]> git.argeo.org Git - lgpl/argeo-commons.git/blobdiff - org.argeo.cms/src/org/argeo/cms/internal/kernel/Kernel.java
Add robots.txt allowing all agents
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / kernel / Kernel.java
index b95c195584d3986734efcef3b81f8fca50453819..3960be687ff91a0ec56408b30d8a167d01b134a9 100644 (file)
@@ -2,45 +2,69 @@ package org.argeo.cms.internal.kernel;
 
 import static bitronix.tm.TransactionManagerServices.getTransactionManager;
 import static bitronix.tm.TransactionManagerServices.getTransactionSynchronizationRegistry;
+import static java.util.Locale.ENGLISH;
 import static org.argeo.cms.internal.kernel.KernelUtils.getFrameworkProp;
-import static org.argeo.cms.internal.kernel.KernelUtils.getOsgiInstancePath;
+import static org.argeo.cms.internal.kernel.KernelUtils.getOsgiInstanceDir;
 import static org.argeo.jcr.ArgeoJcrConstants.ALIAS_NODE;
 import static org.argeo.jcr.ArgeoJcrConstants.JCR_REPOSITORY_ALIAS;
+import static org.argeo.util.LocaleChoice.asLocaleList;
 import static org.osgi.framework.Constants.FRAMEWORK_UUID;
 
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
 import java.io.File;
+import java.io.FileFilter;
+import java.io.IOException;
 import java.lang.management.ManagementFactory;
 import java.security.PrivilegedAction;
 import java.util.HashMap;
 import java.util.Hashtable;
+import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 
+import javax.jcr.ImportUUIDBehavior;
 import javax.jcr.Repository;
 import javax.jcr.RepositoryFactory;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
 import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
 import javax.transaction.TransactionManager;
 import javax.transaction.TransactionSynchronizationRegistry;
 import javax.transaction.UserTransaction;
 
+import org.apache.commons.io.FileUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.jackrabbit.api.JackrabbitRepository;
 import org.apache.jackrabbit.util.TransientFileFactory;
 import org.argeo.ArgeoException;
 import org.argeo.ArgeoLogger;
 import org.argeo.cms.CmsException;
+import org.argeo.cms.maintenance.MaintenanceUi;
 import org.argeo.jackrabbit.OsgiJackrabbitRepositoryFactory;
 import org.argeo.jcr.ArgeoJcrConstants;
+import org.argeo.jcr.ArgeoJcrUtils;
+import org.eclipse.equinox.http.jetty.JettyConfigurator;
+import org.eclipse.equinox.http.jetty.JettyConstants;
 import org.eclipse.equinox.http.servlet.ExtendedHttpService;
+import org.eclipse.rap.rwt.application.ApplicationConfiguration;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.ServiceEvent;
 import org.osgi.framework.ServiceListener;
 import org.osgi.framework.ServiceReference;
 import org.osgi.framework.ServiceRegistration;
+import org.osgi.framework.startlevel.BundleStartLevel;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.service.log.LogReaderService;
 import org.osgi.service.useradmin.UserAdmin;
+import org.osgi.util.tracker.ServiceTracker;
 
 import bitronix.tm.BitronixTransactionManager;
 import bitronix.tm.BitronixTransactionSynchronizationRegistry;
-import bitronix.tm.Configuration;
 import bitronix.tm.TransactionManagerServices;
 
 /**
@@ -55,6 +79,10 @@ import bitronix.tm.TransactionManagerServices;
  * </ul>
  */
 final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
+       /*
+        * SERVICE REFERENCES
+        */
+       private ServiceReference<ConfigurationAdmin> configurationAdmin;
        /*
         * REGISTERED SERVICES
         */
@@ -62,7 +90,7 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
        private ServiceRegistration<TransactionManager> tmReg;
        private ServiceRegistration<UserTransaction> utReg;
        private ServiceRegistration<TransactionSynchronizationRegistry> tsrReg;
-       private ServiceRegistration<Repository> repositoryReg;
+       private ServiceRegistration<? extends Repository> repositoryReg;
        private ServiceRegistration<RepositoryFactory> repositoryFactoryReg;
        private ServiceRegistration<UserAdmin> userAdminReg;
 
@@ -82,9 +110,14 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
        private final BundleContext bc = Activator.getBundleContext();
        private final NodeSecurity nodeSecurity;
        private DataHttp dataHttp;
+       private NodeHttp nodeHttp;
        private KernelThread kernelThread;
 
+       private Locale defaultLocale = null;
+       private List<Locale> locales = null;
+
        public Kernel() {
+               // KernelUtils.logFrameworkProperties(log);
                nodeSecurity = new NodeSecurity();
        }
 
@@ -101,41 +134,41 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
 
        private void doInit() {
                long begin = System.currentTimeMillis();
-
                // Use CMS bundle classloader
                ClassLoader currentContextCl = Thread.currentThread()
                                .getContextClassLoader();
                Thread.currentThread().setContextClassLoader(
                                Kernel.class.getClassLoader());
-               // KernelUtils.logFrameworkProperties(log);
-
                try {
-                       // Initialise services
-                       logger = new NodeLogger();
-                       // transactionManager = new SimpleTransactionManager();
-                       initBitronixTransactionManager();
-                       repository = new NodeRepository(bc);
-                       repositoryFactory = new OsgiJackrabbitRepositoryFactory();
-                       userAdmin = new NodeUserAdmin(transactionManager, repository);
-
-                       // HTTP
-                       ServiceReference<ExtendedHttpService> sr = bc
-                                       .getServiceReference(ExtendedHttpService.class);
-                       if (sr != null)
-                               addHttpService(sr);
-
-                       // Kernel thread
-                       kernelThread = new KernelThread(this);
-                       kernelThread.setContextClassLoader(Kernel.class.getClassLoader());
-                       kernelThread.start();
-
-                       // Publish services to OSGi
-                       publish();
+                       if (nodeSecurity.isFirstInit())
+                               firstInit();
+
+                       defaultLocale = new Locale(getFrameworkProp(I18N_DEFAULT_LOCALE,
+                                       ENGLISH.getLanguage()));
+                       locales = asLocaleList(getFrameworkProp(I18N_LOCALES));
+
+                       ServiceTracker<LogReaderService, LogReaderService> logReaderService = new ServiceTracker<LogReaderService, LogReaderService>(
+                                       bc, LogReaderService.class, null);
+                       logReaderService.open();
+                       logger = new NodeLogger(logReaderService.getService());
+                       logReaderService.close();
+
+                       if (isMaintenance())
+                               maintenanceInit();
+                       else
+                               normalInit();
                } catch (Exception e) {
                        log.error("Cannot initialize Argeo CMS", e);
                        throw new ArgeoException("Cannot initialize", e);
                } finally {
                        Thread.currentThread().setContextClassLoader(currentContextCl);
+                       // FIXME better manage lifecycle.
+                       try {
+                               new LoginContext(LOGIN_CONTEXT_KERNEL,
+                                               nodeSecurity.getKernelSubject()).logout();
+                       } catch (LoginException e) {
+                               e.printStackTrace();
+                       }
                }
 
                long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
@@ -147,12 +180,140 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
                directorsCut(initDuration);
        }
 
-       private void initBitronixTransactionManager() {
-               Configuration tmConf = TransactionManagerServices.getConfiguration();
+       private void normalInit() {
+               ConfigurationAdmin conf = findConfigurationAdmin();
+               // Initialise services
+               initTransactionManager();
+               if (repository == null)
+                       repository = new NodeRepository();
+               if (repositoryFactory == null)
+                       repositoryFactory = new OsgiJackrabbitRepositoryFactory();
+               userAdmin = new NodeUserAdmin(transactionManager, repository);
+
+               // HTTP
+               initWebServer(conf);
+               ServiceReference<ExtendedHttpService> sr = bc
+                               .getServiceReference(ExtendedHttpService.class);
+               if (sr != null)
+                       addHttpService(sr);
+
+               // ADMIN UIs
+               UserUi userUi = new UserUi();
+               Hashtable<String, String> props = new Hashtable<String, String>();
+               props.put("contextName", "user");
+               bc.registerService(ApplicationConfiguration.class, userUi, props);
+
+               // Kernel thread
+               kernelThread = new KernelThread(this);
+               kernelThread.setContextClassLoader(Kernel.class.getClassLoader());
+               kernelThread.start();
+
+               // Publish services to OSGi
+               publish();
+       }
+
+       private boolean isMaintenance() {
+               String startLevel = KernelUtils.getFrameworkProp("osgi.startLevel");
+               if (startLevel == null)
+                       return false;
+               int bundleStartLevel = bc.getBundle().adapt(BundleStartLevel.class)
+                               .getStartLevel();
+               // int frameworkStartLevel =
+               // bc.getBundle(0).adapt(BundleStartLevel.class)
+               // .getStartLevel();
+               int frameworkStartLevel = Integer.parseInt(startLevel);
+               // int frameworkStartLevel = bc.getBundle(0)
+               // .adapt(FrameworkStartLevel.class).getStartLevel();
+               return bundleStartLevel == frameworkStartLevel;
+       }
+
+       private void maintenanceInit() {
+               log.info("## MAINTENANCE ##");
+               bc.addServiceListener(Kernel.this);
+               initWebServer(null);
+               MaintenanceUi maintenanceUi = new MaintenanceUi();
+               Hashtable<String, String> props = new Hashtable<String, String>();
+               props.put("contextName", "maintenance");
+               bc.registerService(ApplicationConfiguration.class, maintenanceUi, props);
+       }
+
+       private void firstInit() {
+               log.info("## FIRST INIT ##");
+               String nodeInit = getFrameworkProp(NODE_INIT);
+               if (nodeInit == null)
+                       nodeInit = "../../init";
+               if (nodeInit.startsWith("http")) {
+                       remoteFirstInit(nodeInit);
+                       return;
+               }
+               File initDir;
+               if (nodeInit.startsWith("."))
+                       initDir = KernelUtils.getExecutionDir(nodeInit);
+               else
+                       initDir = new File(nodeInit);
+               // TODO also uncompress archives
+               if (initDir.exists())
+                       try {
+                               FileUtils.copyDirectory(initDir, getOsgiInstanceDir(),
+                                               new FileFilter() {
+
+                                                       @Override
+                                                       public boolean accept(File pathname) {
+                                                               if (pathname.getName().equals(".svn")
+                                                                               || pathname.getName().equals(".git"))
+                                                                       return false;
+                                                               return true;
+                                                       }
+                                               });
+                               log.info("CMS initialized from " + initDir.getCanonicalPath());
+                       } catch (IOException e) {
+                               throw new CmsException("Cannot initialize from " + initDir, e);
+                       }
+       }
+
+       private void remoteFirstInit(String uri) {
+               try {
+                       repository = new NodeRepository();
+                       repositoryFactory = new OsgiJackrabbitRepositoryFactory();
+                       Repository remoteRepository = ArgeoJcrUtils.getRepositoryByUri(
+                                       repositoryFactory, uri);
+                       Session remoteSession = remoteRepository
+                                       .login(new SimpleCredentials("root", "demo".toCharArray()),
+                                                       "main");
+                       Session localSession = this.repository.login();
+                       // FIXME register node type
+                       // if (false)
+                       // CndImporter.registerNodeTypes(null, localSession);
+                       ByteArrayOutputStream out = new ByteArrayOutputStream();
+                       remoteSession.exportSystemView("/", out, true, false);
+                       ByteArrayInputStream in = new ByteArrayInputStream(
+                                       out.toByteArray());
+                       localSession.importXML("/", in,
+                                       ImportUUIDBehavior.IMPORT_UUID_COLLISION_THROW);
+                       // JcrUtils.copy(remoteSession.getRootNode(),
+                       // localSession.getRootNode());
+               } catch (Exception e) {
+                       throw new CmsException("Cannot first init from " + uri, e);
+               }
+       }
+
+       /** Can be null */
+       private ConfigurationAdmin findConfigurationAdmin() {
+               configurationAdmin = bc.getServiceReference(ConfigurationAdmin.class);
+               if (configurationAdmin == null) {
+                       return null;
+               }
+               return bc.getService(configurationAdmin);
+       }
+
+       private void initTransactionManager() {
+               bitronix.tm.Configuration tmConf = TransactionManagerServices
+                               .getConfiguration();
                tmConf.setServerId(getFrameworkProp(FRAMEWORK_UUID));
 
-               File tmBaseDir = new File(getFrameworkProp(TRANSACTIONS_HOME,
-                               getOsgiInstancePath("transactions")));
+               // File tmBaseDir = new File(getFrameworkProp(TRANSACTIONS_HOME,
+               // getOsgiInstancePath(DIR_TRANSACTIONS)));
+               File tmBaseDir = bc.getDataFile(DIR_TRANSACTIONS);
                File tmDir1 = new File(tmBaseDir, "btm1");
                tmDir1.mkdirs();
                tmConf.setLogPart1Filename(new File(tmDir1, tmDir1.getName() + ".tlog")
@@ -165,6 +326,45 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
                transactionSynchronizationRegistry = getTransactionSynchronizationRegistry();
        }
 
+       private void initWebServer(ConfigurationAdmin conf) {
+               String httpPort = getFrameworkProp("org.osgi.service.http.port");
+               String httpsPort = getFrameworkProp("org.osgi.service.http.port.secure");
+               try {
+                       if (httpPort != null || httpsPort != null) {
+                               Hashtable<String, Object> jettyProps = new Hashtable<String, Object>();
+                               if (httpPort != null) {
+                                       jettyProps.put(JettyConstants.HTTP_PORT, httpPort);
+                                       jettyProps.put(JettyConstants.HTTP_ENABLED, true);
+                               }
+                               if (httpsPort != null) {
+                                       jettyProps.put(JettyConstants.HTTPS_PORT, httpsPort);
+                                       jettyProps.put(JettyConstants.HTTPS_ENABLED, true);
+                                       jettyProps.put(JettyConstants.SSL_KEYSTORETYPE, "PKCS12");
+                                       jettyProps.put(JettyConstants.SSL_KEYSTORE, nodeSecurity
+                                                       .getHttpServerKeyStore().getCanonicalPath());
+                                       jettyProps.put(JettyConstants.SSL_PASSWORD, "changeit");
+                                       jettyProps.put(JettyConstants.SSL_WANTCLIENTAUTH, true);
+                               }
+                               if (conf != null) {
+                                       // TODO make filter more generic
+                                       String filter = "(" + JettyConstants.HTTP_PORT + "="
+                                                       + httpPort + ")";
+                                       if (conf.listConfigurations(filter) != null)
+                                               return;
+                                       Configuration jettyConf = conf.createFactoryConfiguration(
+                                                       JETTY_FACTORY_PID, null);
+                                       jettyConf.update(jettyProps);
+                               } else {
+                                       JettyConfigurator.startServer("default", jettyProps);
+                               }
+                       }
+               } catch (Exception e) {
+                       throw new CmsException("Cannot initialize web server on "
+                                       + httpPortsMsg(httpPort, httpsPort), e);
+               }
+       }
+
+       @SuppressWarnings("unchecked")
        private void publish() {
                // Listen to service publication (also ours)
                bc.addServiceListener(Kernel.this);
@@ -184,8 +384,10 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
                // JCR
                Hashtable<String, String> regProps = new Hashtable<String, String>();
                regProps.put(JCR_REPOSITORY_ALIAS, ALIAS_NODE);
-               repositoryReg = bc.registerService(Repository.class, repository,
-                               regProps);
+               repositoryReg = (ServiceRegistration<? extends Repository>) bc
+                               .registerService(new String[] { Repository.class.getName(),
+                                               JackrabbitRepository.class.getName() }, repository,
+                                               regProps);
                repositoryFactoryReg = bc.registerService(RepositoryFactory.class,
                                repositoryFactory, null);
        }
@@ -198,6 +400,8 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
 
                if (dataHttp != null)
                        dataHttp.destroy();
+               if (nodeHttp != null)
+                       nodeHttp.destroy();
                if (userAdmin != null)
                        userAdmin.destroy();
                if (repository != null)
@@ -273,29 +477,27 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
                // TODO find constants
                Object httpPort = sr.getProperty("http.port");
                Object httpsPort = sr.getProperty("https.port");
-               dataHttp = new DataHttp(httpService, repository);
+               dataHttp = new DataHttp(httpService);
+               nodeHttp = new NodeHttp(httpService, repository);
                if (log.isDebugEnabled())
-                       log.debug("HTTP " + httpPort
-                                       + (httpsPort != null ? " - HTTPS " + httpsPort : ""));
+                       log.debug(httpPortsMsg(httpPort, httpsPort));
+       }
+
+       private String httpPortsMsg(Object httpPort, Object httpsPort) {
+               return "HTTP " + httpPort
+                               + (httpsPort != null ? " - HTTPS " + httpsPort : "");
+       }
+
+       @Override
+       public Locale getDefaultLocale() {
+               return defaultLocale;
        }
 
-       // private ExtendedHttpService waitForHttpService() {
-       // final ServiceTracker<ExtendedHttpService, ExtendedHttpService> st = new
-       // ServiceTracker<ExtendedHttpService, ExtendedHttpService>(
-       // bc, ExtendedHttpService.class, null);
-       // st.open();
-       // ExtendedHttpService httpService;
-       // try {
-       // httpService = st.waitForService(1000);
-       // } catch (InterruptedException e) {
-       // httpService = null;
-       // }
-       //
-       // if (httpService == null)
-       // throw new CmsException("Could not find "
-       // + ExtendedHttpService.class + " service.");
-       // return httpService;
-       // }
+       /** Can be null. */
+       @Override
+       public List<Locale> getLocales() {
+               return locales;
+       }
 
        final private static void directorsCut(long initDuration) {
                // final long ms = 128l + (long) (Math.random() * 128d);
@@ -360,7 +562,7 @@ final class Kernel implements KernelHeader, KernelConstants, ServiceListener {
                rootThreadGroup.enumerate(threads);
                int nonDameonCount = 0;
                for (Thread t : threads)
-                       if (!t.isDaemon())
+                       if (t != null && !t.isDaemon())
                                nonDameonCount++;
                return nonDameonCount;
        }