Fix first init
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / runtime / CmsStateImpl.java
index 902fe793b7a28ea98b377d65fb717c19d41f1274..d364620f56f09118a99cd36564146c1f61919a8f 100644 (file)
@@ -1,8 +1,11 @@
 package org.argeo.cms.internal.runtime;
 
+import java.io.BufferedInputStream;
 import java.io.IOException;
 import java.io.Reader;
+import java.net.InetAddress;
 import java.net.URL;
+import java.net.UnknownHostException;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -21,6 +24,11 @@ import java.util.Objects;
 import java.util.Set;
 import java.util.StringJoiner;
 import java.util.UUID;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.ForkJoinTask;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 
 import javax.security.auth.login.Configuration;
 
@@ -30,7 +38,7 @@ import org.argeo.api.cms.CmsState;
 import org.argeo.api.uuid.UuidFactory;
 import org.argeo.cms.CmsDeployProperty;
 import org.argeo.cms.auth.ident.IdentClient;
-import org.argeo.util.FsUtils;
+import org.argeo.cms.util.FsUtils;
 
 /**
  * Implementation of a {@link CmsState}, initialising the required services.
@@ -43,7 +51,7 @@ public class CmsStateImpl implements CmsState {
 
        private UUID uuid;
 //     private final boolean cleanState;
-//     private String hostname;
+       private String hostname;
 
        private UuidFactory uuidFactory;
 
@@ -59,19 +67,19 @@ public class CmsStateImpl implements CmsState {
                deployPropertyDefaults.put(CmsDeployProperty.LOCALE, Locale.getDefault().toString());
 
                // certificates
-               deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
-               deployPropertyDefaults.put(CmsDeployProperty.SSL_PASSWORD, PkiUtils.DEFAULT_KEYSTORE_PASSWORD);
-               Path keyStorePath = getDataPath(PkiUtils.DEFAULT_KEYSTORE_PATH);
+               deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORETYPE, KernelConstants.PKCS12);
+               deployPropertyDefaults.put(CmsDeployProperty.SSL_PASSWORD, KernelConstants.DEFAULT_KEYSTORE_PASSWORD);
+               Path keyStorePath = getDataPath(KernelConstants.DEFAULT_KEYSTORE_PATH);
                if (keyStorePath != null) {
                        deployPropertyDefaults.put(CmsDeployProperty.SSL_KEYSTORE, keyStorePath.toAbsolutePath().toString());
                }
 
-               Path trustStorePath = getDataPath(PkiUtils.DEFAULT_TRUSTSTORE_PATH);
+               Path trustStorePath = getDataPath(KernelConstants.DEFAULT_TRUSTSTORE_PATH);
                if (trustStorePath != null) {
                        deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORE, trustStorePath.toAbsolutePath().toString());
                }
-               deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORETYPE, PkiUtils.PKCS12);
-               deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD, PkiUtils.DEFAULT_KEYSTORE_PASSWORD);
+               deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTORETYPE, KernelConstants.PKCS12);
+               deployPropertyDefaults.put(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD, KernelConstants.DEFAULT_KEYSTORE_PASSWORD);
 
                // SSH
                Path authorizedKeysPath = getDataPath(KernelConstants.NODE_SSHD_AUTHORIZED_KEYS_PATH);
@@ -83,24 +91,42 @@ public class CmsStateImpl implements CmsState {
        }
 
        public void start() {
-//             Runtime.getRuntime().addShutdownHook(new CmsShutdown());
-
                try {
+                       // First init check
+                       Path privateBase = getDataPath(KernelConstants.DIR_PRIVATE);
+                       if (privateBase != null && !Files.exists(privateBase)) {// first init
+                               firstInit();
+                               Files.createDirectories(privateBase);
+                       }
+
                        initSecurity();
 //                     initArgeoLogger();
 
                        if (log.isTraceEnabled())
                                log.trace("CMS State started");
 
-//                     String stateUuidStr = KernelUtils.getFrameworkProp(Constants.FRAMEWORK_UUID);
-//                     this.uuid = UUID.fromString(stateUuidStr);
                        this.uuid = uuidFactory.timeUUID();
-//             this.cleanState = stateUuid.equals(frameworkUuid);
-//                     try {
-//                             this.hostname = InetAddress.getLocalHost().getHostName();
-//                     } catch (UnknownHostException e) {
-//                             log.error("Cannot set hostname: " + e);
-//                     }
+
+                       // hostname
+                       this.hostname = getDeployProperty(CmsDeployProperty.HOST);
+                       // TODO verify we have access to the IP address
+                       if (hostname == null) {
+                               final String LOCALHOST_IP = "::1";
+                               ForkJoinTask<String> hostnameFJT = ForkJoinPool.commonPool().submit(() -> {
+                                       try {
+                                               String hostname = InetAddress.getLocalHost().getHostName();
+                                               return hostname;
+                                       } catch (UnknownHostException e) {
+                                               throw new IllegalStateException("Cannot get local hostname", e);
+                                       }
+                               });
+                               try {
+                                       this.hostname = hostnameFJT.get(5, TimeUnit.SECONDS);
+                               } catch (InterruptedException | ExecutionException | TimeoutException e) {
+                                       this.hostname = LOCALHOST_IP;
+                                       log.warn("Could not get local hostname, using " + this.hostname);
+                               }
+                       }
 
                        availableSince = System.currentTimeMillis();
                        if (log.isDebugEnabled()) {
@@ -125,11 +151,6 @@ public class CmsStateImpl implements CmsState {
                                log.debug("## CMS starting... (" + uuid + ")\n" + sb + "\n");
                        }
 
-                       Path nodeBase = getDataPath(KernelConstants.DIR_PRIVATE);
-                       if (nodeBase != null && !Files.exists(nodeBase)) {// first init
-                               firstInit();
-                       }
-
                } catch (RuntimeException | IOException e) {
                        log.error("## FATAL: CMS state failed", e);
                }
@@ -137,7 +158,7 @@ public class CmsStateImpl implements CmsState {
 
        private void initSecurity() {
                // private directory permissions
-               Path privateDir = KernelUtils.getOsgiInstancePath(KernelConstants.DIR_PRIVATE);
+               Path privateDir = getDataPath(KernelConstants.DIR_PRIVATE);
                if (privateDir != null) {
                        // TODO rather check whether we can read and write
                        Set<PosixFilePermission> posixPermissions = new HashSet<>();
@@ -145,9 +166,11 @@ public class CmsStateImpl implements CmsState {
                        posixPermissions.add(PosixFilePermission.OWNER_WRITE);
                        posixPermissions.add(PosixFilePermission.OWNER_EXECUTE);
                        try {
+                               if (!Files.exists(privateDir))
+                                       Files.createDirectories(privateDir);
                                Files.setPosixFilePermissions(privateDir, posixPermissions);
                        } catch (IOException e) {
-                               log.error("Cannot set permissions on " + privateDir);
+                               log.error("Cannot set permissions on " + privateDir, e);
                        }
                }
 
@@ -170,8 +193,8 @@ public class CmsStateImpl implements CmsState {
        private void initCertificates() {
                // server certificate
                Path keyStorePath = Paths.get(getDeployProperty(CmsDeployProperty.SSL_KEYSTORE));
-               Path pemKeyPath = getDataPath(PkiUtils.DEFAULT_PEM_KEY_PATH);
-               Path pemCertPath = getDataPath(PkiUtils.DEFAULT_PEM_CERT_PATH);
+               Path pemKeyPath = getDataPath(KernelConstants.DEFAULT_PEM_KEY_PATH);
+               Path pemCertPath = getDataPath(KernelConstants.DEFAULT_PEM_CERT_PATH);
                char[] keyStorePassword = getDeployProperty(CmsDeployProperty.SSL_PASSWORD).toCharArray();
 
                // Keystore
@@ -181,7 +204,7 @@ public class CmsStateImpl implements CmsState {
                        KeyStore keyStore = PkiUtils.getKeyStore(keyStorePath, keyStorePassword,
                                        getDeployProperty(CmsDeployProperty.SSL_KEYSTORETYPE));
                        try (Reader key = Files.newBufferedReader(pemKeyPath, StandardCharsets.US_ASCII);
-                                       Reader cert = Files.newBufferedReader(pemCertPath, StandardCharsets.US_ASCII);) {
+                                       BufferedInputStream cert = new BufferedInputStream(Files.newInputStream(pemCertPath));) {
                                PkiUtils.loadPrivateCertificatePem(keyStore, CmsConstants.NODE, key, keyStorePassword, cert);
                                Files.createDirectories(keyStorePath.getParent());
                                PkiUtils.saveKeyStore(keyStorePath, keyStorePassword, keyStore);
@@ -197,11 +220,11 @@ public class CmsStateImpl implements CmsState {
                char[] trustStorePassword = getDeployProperty(CmsDeployProperty.SSL_TRUSTSTOREPASSWORD).toCharArray();
 
                // IPA CA
-               Path ipaCaCertPath = Paths.get(PkiUtils.IPA_PEM_CA_CERT_PATH);
+               Path ipaCaCertPath = Paths.get(KernelConstants.IPA_PEM_CA_CERT_PATH);
                if (Files.exists(ipaCaCertPath)) {
                        KeyStore trustStore = PkiUtils.getKeyStore(trustStorePath, trustStorePassword,
                                        getDeployProperty(CmsDeployProperty.SSL_TRUSTSTORETYPE));
-                       try (Reader cert = Files.newBufferedReader(ipaCaCertPath, StandardCharsets.US_ASCII);) {
+                       try (BufferedInputStream cert = new BufferedInputStream(Files.newInputStream(ipaCaCertPath));) {
                                PkiUtils.loadTrustedCertificatePem(trustStore, trustStorePassword, cert);
                                Files.createDirectories(keyStorePath.getParent());
                                PkiUtils.saveKeyStore(trustStorePath, trustStorePassword, trustStore);
@@ -212,16 +235,8 @@ public class CmsStateImpl implements CmsState {
                        }
                }
 
-               if (!Files.exists(keyStorePath))
-                       PkiUtils.createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
-//             props.put(JettyHttpConstants.SSL_KEYSTORETYPE, PkiUtils.PKCS12);
-//             props.put(JettyHttpConstants.SSL_KEYSTORE, keyStorePath.toString());
-//             props.put(JettyHttpConstants.SSL_PASSWORD, new String(keyStorePassword));
-
-//             props.put(InternalHttpConstants.SSL_KEYSTORETYPE, "PKCS11");
-//             props.put(InternalHttpConstants.SSL_KEYSTORE, "../../nssdb");
-//             props.put(InternalHttpConstants.SSL_PASSWORD, keyStorePassword);
-
+//             if (!Files.exists(keyStorePath))
+//                     PkiUtils.createSelfSignedKeyStore(keyStorePath, keyStorePassword, PkiUtils.PKCS12);
        }
 
        public void stop() {
@@ -373,6 +388,10 @@ public class CmsStateImpl implements CmsState {
                this.uuidFactory = uuidFactory;
        }
 
+       public String getHostname() {
+               return hostname;
+       }
+
        /**
         * Called before node initialisation, in order populate OSGi instance are with
         * some files (typically LDIF, etc).