]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/internal/runtime/CmsStateImpl.java
Improve CMS start up and status reporting.
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / runtime / CmsStateImpl.java
1 package org.argeo.cms.internal.runtime;
2
3 import java.io.IOException;
4 import java.io.Reader;
5 import java.net.URL;
6 import java.nio.charset.StandardCharsets;
7 import java.nio.file.Files;
8 import java.nio.file.Path;
9 import java.nio.file.Paths;
10 import java.security.KeyStore;
11 import java.util.ArrayList;
12 import java.util.Arrays;
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Locale;
17 import java.util.Map;
18 import java.util.Objects;
19 import java.util.StringJoiner;
20 import java.util.UUID;
21
22 import javax.security.auth.login.Configuration;
23
24 import org.argeo.api.cms.CmsConstants;
25 import org.argeo.api.cms.CmsLog;
26 import org.argeo.api.cms.CmsState;
27 import org.argeo.api.uuid.UuidFactory;
28 import org.argeo.cms.CmsDeployProperty;
29 import org.argeo.cms.auth.ident.IdentClient;
30 import org.argeo.util.FsUtils;
31
32 /**
33 * Implementation of a {@link CmsState}, initialising the required services.
34 */
35 public class CmsStateImpl implements CmsState {
36 private final static CmsLog log = CmsLog.getLog(CmsStateImpl.class);
37
38 // REFERENCES
39 private Long availableSince;
40
41 private UUID uuid;
42 // private final boolean cleanState;
43 // private String hostname;
44
45 private UuidFactory uuidFactory;
46
47 private final Map<CmsDeployProperty, String> deployPropertyDefaults;
48
49 public CmsStateImpl() {
50 Map<CmsDeployProperty, String> deployPropertyDefaults = new HashMap<>();
51 deployPropertyDefaults.put(CmsDeployProperty.NODE_INIT, "../../init");
52 deployPropertyDefaults.put(CmsDeployProperty.LOCALE, Locale.getDefault().toString());
53
54 // certificates
55 deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
56 deployPropertyDefaults.put(CmsDeployProperty.SSL_PASSWORD, PkiUtils.DEFAULT_KEYSTORE_PASSWORD);
57 Path keyStorePath = getDataPath(PkiUtils.DEFAULT_KEYSTORE_PATH);
58 if (keyStorePath != null) {
59 deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORE, keyStorePath.toAbsolutePath().toString());
60 }
61
62 Path trustStorePath = getDataPath(PkiUtils.DEFAULT_TRUSTSTORE_PATH);
63 if (trustStorePath != null) {
64 deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORE, trustStorePath.toAbsolutePath().toString());
65 }
66 deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORETYPE, PkiUtils.PKCS12);
67 deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD, PkiUtils.DEFAULT_KEYSTORE_PASSWORD);
68
69 this.deployPropertyDefaults = Collections.unmodifiableMap(deployPropertyDefaults);
70 }
71
72 public void start() {
73 // Runtime.getRuntime().addShutdownHook(new CmsShutdown());
74
75 try {
76 initSecurity();
77 // initArgeoLogger();
78
79 if (log.isTraceEnabled())
80 log.trace("CMS State started");
81
82 // String stateUuidStr = KernelUtils.getFrameworkProp(Constants.FRAMEWORK_UUID);
83 // this.uuid = UUID.fromString(stateUuidStr);
84 this.uuid = uuidFactory.timeUUID();
85 // this.cleanState = stateUuid.equals(frameworkUuid);
86 // try {
87 // this.hostname = InetAddress.getLocalHost().getHostName();
88 // } catch (UnknownHostException e) {
89 // log.error("Cannot set hostname: " + e);
90 // }
91
92 availableSince = System.currentTimeMillis();
93 if (log.isDebugEnabled()) {
94 // log.debug("## CMS starting... stateUuid=" + this.stateUuid + (cleanState ? "
95 // (clean state) " : " "));
96 StringJoiner sb = new StringJoiner("\n");
97 CmsDeployProperty[] deployProperties = CmsDeployProperty.values();
98 Arrays.sort(deployProperties, (o1, o2) -> o1.name().compareTo(o2.name()));
99 for (CmsDeployProperty deployProperty : deployProperties) {
100 List<String> values = getDeployProperties(deployProperty);
101 for (int i = 0; i < values.size(); i++) {
102 String value = values.get(i);
103 if (value != null) {
104 boolean isDefault = deployPropertyDefaults.containsKey(deployProperty)
105 && value.equals(deployPropertyDefaults.get(deployProperty));
106 String line = deployProperty.getProperty() + (i == 0 ? "" : "." + i) + "=" + value
107 + (isDefault ? " (default)" : "");
108 sb.add(line);
109 }
110 }
111 }
112 log.debug("## CMS starting... (" + uuid + ")\n" + sb + "\n");
113 }
114
115 Path nodeBase = getDataPath(CmsConstants.NODE);
116 if (nodeBase != null && !Files.exists(nodeBase)) {// first init
117 firstInit();
118 }
119
120 } catch (RuntimeException | IOException e) {
121 log.error("## FATAL: CMS state failed", e);
122 }
123 }
124
125 private void initSecurity() {
126 if (getDeployProperty(CmsDeployProperty.JAVA_LOGIN_CONFIG) == null) {
127 String jaasConfig = KernelConstants.JAAS_CONFIG;
128 URL url = getClass().getResource(jaasConfig);
129 // System.setProperty(KernelConstants.JAAS_CONFIG_PROP,
130 // url.toExternalForm());
131 KernelUtils.setJaasConfiguration(url);
132 }
133 // explicitly load JAAS configuration
134 Configuration.getConfiguration();
135
136 boolean initSsl = getDeployProperty(CmsDeployProperty.HTTPS_PORT) != null;
137 if (initSsl) {
138 initCertificates();
139 }
140 }
141
142 private void initCertificates() {
143 // server certificate
144 Path keyStorePath = Paths.get(getDeployProperty(CmsDeployProperty.SSL_KEYSTORE));
145 Path pemKeyPath = getDataPath(PkiUtils.DEFAULT_PEM_KEY_PATH);
146 Path pemCertPath = getDataPath(PkiUtils.DEFAULT_PEM_CERT_PATH);
147 char[] keyStorePassword = getDeployProperty(CmsDeployProperty.SSL_PASSWORD).toCharArray();
148
149 // Keystore
150 // if PEM files both exists, update the PKCS12 file
151 if (Files.exists(pemCertPath) && Files.exists(pemKeyPath)) {
152 // TODO check certificate update time? monitor changes?
153 KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword,
154 getDeployProperty(CmsDeployProperty.SSL_KEYSTORETYPE));
155 try (Reader key = Files.newBufferedReader(pemKeyPath, StandardCharsets.US_ASCII);
156 Reader cert = Files.newBufferedReader(pemCertPath, StandardCharsets.US_ASCII);) {
157 PkiUtils.loadPem(keyStore, key, keyStorePassword, cert);
158 Files.createDirectories(keyStorePath.getParent());
159 PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
160 if (log.isDebugEnabled())
161 log.debug("PEM certificate stored in " + keyStorePath);
162 } catch (IOException e) {
163 log.error("Cannot read PEM files " + pemKeyPath + " and " + pemCertPath, e);
164 }
165 }
166
167 // Truststore
168 Path trustStorePath = Paths.get(getDeployProperty(CmsDeployProperty.SSL_TRUSTSTORE));
169 char[] trustStorePassword = getDeployProperty(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD).toCharArray();
170
171 // IPA CA
172 Path ipaCaCertPath = Paths.get(PkiUtils.IPA_PEM_CA_CERT_PATH);
173 if (Files.exists(ipaCaCertPath)) {
174 KeyStore trustStore = PkiUtils.getKeyStore(trustStorePath, trustStorePassword,
175 getDeployProperty(CmsDeployProperty.SSL_TRUSTSTORETYPE));
176 try (Reader cert = Files.newBufferedReader(ipaCaCertPath, StandardCharsets.US_ASCII);) {
177 PkiUtils.loadPem(trustStore, null, trustStorePassword, cert);
178 Files.createDirectories(keyStorePath.getParent());
179 PkiUtils.saveKeyStore(trustStorePath, trustStorePassword, trustStore);
180 if (log.isDebugEnabled())
181 log.debug("IPA CA certificate stored in " + trustStorePath);
182 } catch (IOException e) {
183 log.error("Cannot trust CA certificate", e);
184 }
185 }
186
187 if (!Files.exists(keyStorePath))
188 PkiUtils.createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
189 // props.put(JettyHttpConstants.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
190 // props.put(JettyHttpConstants.SSL_KEYSTORE, keyStorePath.toString());
191 // props.put(JettyHttpConstants.SSL_PASSWORD, new String(keyStorePassword));
192
193 // props.put(InternalHttpConstants.SSL_KEYSTORETYPE, "PKCS11");
194 // props.put(InternalHttpConstants.SSL_KEYSTORE, "../../nssdb");
195 // props.put(InternalHttpConstants.SSL_PASSWORD, keyStorePassword);
196
197 }
198
199 public void stop() {
200 if (log.isDebugEnabled())
201 log.debug("CMS stopping... (" + this.uuid + ")");
202
203 long duration = ((System.currentTimeMillis() - availableSince) / 1000) / 60;
204 log.info("## ARGEO CMS STOPPED after " + (duration / 60) + "h " + (duration % 60) + "min uptime ##");
205 }
206
207 private void firstInit() throws IOException {
208 log.info("## FIRST INIT ##");
209 List<String> nodeInits = getDeployProperties(CmsDeployProperty.NODE_INIT);
210 // if (nodeInits == null)
211 // nodeInits = "../../init";
212 CmsStateImpl.prepareFirstInitInstanceArea(nodeInits);
213 }
214
215 @Override
216 public String getDeployProperty(String property) {
217 CmsDeployProperty deployProperty = CmsDeployProperty.find(property);
218 if (deployProperty == null) {
219 // legacy
220 if (property.startsWith("argeo.node.")) {
221 return doGetDeployProperty(property);
222 }
223 if (property.equals("argeo.i18n.locales")) {
224 String value = doGetDeployProperty(property);
225 if (value != null) {
226 log.warn("Property " + property + " was ignored (value=" + value + ")");
227
228 }
229 return null;
230 }
231 throw new IllegalArgumentException("Unsupported deploy property " + property);
232 }
233 int index = CmsDeployProperty.getPropertyIndex(property);
234 return getDeployProperty(deployProperty, index);
235 }
236
237 @Override
238 public List<String> getDeployProperties(String property) {
239 CmsDeployProperty deployProperty = CmsDeployProperty.find(property);
240 if (deployProperty == null)
241 return new ArrayList<>();
242 return getDeployProperties(deployProperty);
243 }
244
245 public static List<String> getDeployProperties(CmsState cmsState, CmsDeployProperty deployProperty) {
246 return ((CmsStateImpl) cmsState).getDeployProperties(deployProperty);
247 }
248
249 public List<String> getDeployProperties(CmsDeployProperty deployProperty) {
250 List<String> res = new ArrayList<>(deployProperty.getMaxCount());
251 for (int i = 0; i < deployProperty.getMaxCount(); i++) {
252 // String propertyName = i == 0 ? deployProperty.getProperty() :
253 // deployProperty.getProperty() + "." + i;
254 String value = getDeployProperty(deployProperty, i);
255 res.add(i, value);
256 }
257 return res;
258 }
259
260 public static String getDeployProperty(CmsState cmsState, CmsDeployProperty deployProperty) {
261 return ((CmsStateImpl) cmsState).getDeployProperty(deployProperty);
262 }
263
264 public String getDeployProperty(CmsDeployProperty deployProperty) {
265 String value = getDeployProperty(deployProperty, 0);
266 return value;
267 }
268
269 public String getDeployProperty(CmsDeployProperty deployProperty, int index) {
270 String propertyName = deployProperty.getProperty() + (index == 0 ? "" : "." + index);
271 String value = doGetDeployProperty(propertyName);
272 if (value == null && index == 0) {
273 // try defaults
274 if (deployPropertyDefaults.containsKey(deployProperty)) {
275 value = deployPropertyDefaults.get(deployProperty);
276 if (deployProperty.isSystemPropertyOnly())
277 System.setProperty(deployProperty.getProperty(), value);
278 }
279
280 if (value == null) {
281 // try legacy properties
282 String legacyProperty = switch (deployProperty) {
283 case DIRECTORY -> "argeo.node.useradmin.uris";
284 case DB_URL -> "argeo.node.dburl";
285 case DB_USER -> "argeo.node.dbuser";
286 case DB_PASSWORD -> "argeo.node.dbpassword";
287 case HTTP_PORT -> "org.osgi.service.http.port";
288 case HTTPS_PORT -> "org.osgi.service.http.port.secure";
289 case HOST -> "org.eclipse.equinox.http.jetty.http.host";
290 case LOCALE -> "argeo.i18n.defaultLocale";
291
292 default -> null;
293 };
294 if (legacyProperty != null) {
295 value = doGetDeployProperty(legacyProperty);
296 if (value != null) {
297 log.warn("Retrieved deploy property " + deployProperty.getProperty()
298 + " through deprecated property " + legacyProperty);
299 }
300 }
301 }
302 }
303 if (index == 0 && deployProperty.isSystemPropertyOnly()) {
304 String systemPropertyValue = System.getProperty(deployProperty.getProperty());
305 if (!Objects.equals(value, systemPropertyValue))
306 throw new IllegalStateException(
307 "Property " + deployProperty + " must be a ssystem property, but its value is " + value
308 + ", while the system property value is " + systemPropertyValue);
309 }
310 return value != null ? value.toString() : null;
311 }
312
313 protected String getLegacyProperty(String legacyProperty, CmsDeployProperty deployProperty) {
314 String value = doGetDeployProperty(legacyProperty);
315 if (value != null) {
316 log.warn("Retrieved deploy property " + deployProperty.getProperty() + " through deprecated property "
317 + legacyProperty + ".");
318 }
319 return value;
320 }
321
322 protected String doGetDeployProperty(String property) {
323 return KernelUtils.getFrameworkProp(property);
324 }
325
326 @Override
327 public Path getDataPath(String relativePath) {
328 return KernelUtils.getOsgiInstancePath(relativePath);
329 }
330
331 @Override
332 public Long getAvailableSince() {
333 return availableSince;
334 }
335
336 /*
337 * ACCESSORS
338 */
339 @Override
340 public UUID getUuid() {
341 return uuid;
342 }
343
344 public void setUuidFactory(UuidFactory uuidFactory) {
345 this.uuidFactory = uuidFactory;
346 }
347
348 /**
349 * Called before node initialisation, in order populate OSGi instance are with
350 * some files (typically LDIF, etc).
351 */
352 public static void prepareFirstInitInstanceArea(List<String> nodeInits) {
353
354 for (String nodeInit : nodeInits) {
355 if (nodeInit == null)
356 continue;
357
358 if (nodeInit.startsWith("http")) {
359 // TODO reconnect it
360 // registerRemoteInit(nodeInit);
361 } else {
362
363 // TODO use java.nio.file
364 Path initDir;
365 if (nodeInit.startsWith("."))
366 initDir = KernelUtils.getExecutionDir(nodeInit);
367 else
368 initDir = Paths.get(nodeInit);
369 // TODO also uncompress archives
370 if (Files.exists(initDir)) {
371 Path dataPath = KernelUtils.getOsgiInstancePath("");
372 FsUtils.copyDirectory(initDir, dataPath);
373 log.info("CMS initialized from " + initDir);
374 }
375 }
376 }
377 }
378
379 /*
380 * STATIC
381 */
382 public static IdentClient getIdentClient(String remoteAddr) {
383 if (!IdentClient.isDefaultAuthdPassphraseFileAvailable())
384 return null;
385 // TODO make passphrase more configurable
386 return new IdentClient(remoteAddr);
387 }
388 }