]> git.argeo.org Git - lgpl/argeo-commons.git/blobdiff - org.argeo.cms/src/org/argeo/cms/internal/kernel/Kernel.java
Simplify authentication
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / internal / kernel / Kernel.java
index 848206f5c5248833707a99838b92bceb3210d031..68b3fa2891bf784ab5be47a33c254e1fa67fdc33 100644 (file)
@@ -1,16 +1,47 @@
 package org.argeo.cms.internal.kernel;
 
+import static bitronix.tm.TransactionManagerServices.getTransactionManager;
+import static bitronix.tm.TransactionManagerServices.getTransactionSynchronizationRegistry;
+import static org.argeo.cms.internal.kernel.KernelUtils.getFrameworkProp;
+import static org.argeo.cms.internal.kernel.KernelUtils.getOsgiInstancePath;
+import static org.argeo.jcr.ArgeoJcrConstants.ALIAS_NODE;
+import static org.argeo.jcr.ArgeoJcrConstants.JCR_REPOSITORY_ALIAS;
+import static org.osgi.framework.Constants.FRAMEWORK_UUID;
+
+import java.io.File;
+import java.lang.management.ManagementFactory;
+import java.security.PrivilegedAction;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.jcr.Repository;
 import javax.jcr.RepositoryFactory;
+import javax.security.auth.Subject;
+import javax.transaction.TransactionManager;
+import javax.transaction.TransactionSynchronizationRegistry;
+import javax.transaction.UserTransaction;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
+import org.apache.jackrabbit.util.TransientFileFactory;
 import org.argeo.ArgeoException;
+import org.argeo.ArgeoLogger;
+import org.argeo.cms.CmsException;
 import org.argeo.jackrabbit.OsgiJackrabbitRepositoryFactory;
-import org.argeo.security.core.InternalAuthentication;
-import org.eclipse.rap.rwt.application.ApplicationConfiguration;
+import org.argeo.jcr.ArgeoJcrConstants;
+import org.eclipse.equinox.http.servlet.ExtendedHttpService;
 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.springframework.security.core.context.SecurityContextHolder;
+import org.osgi.service.useradmin.UserAdmin;
+
+import bitronix.tm.BitronixTransactionManager;
+import bitronix.tm.BitronixTransactionSynchronizationRegistry;
+import bitronix.tm.Configuration;
+import bitronix.tm.TransactionManagerServices;
 
 /**
  * Argeo CMS Kernel. Responsible for :
@@ -23,86 +54,251 @@ import org.springframework.security.core.context.SecurityContextHolder;
  * <li>OS access</li>
  * </ul>
  */
-final class Kernel {
-       private final static Log log = LogFactory.getLog(Kernel.class);
-//     private static final String PROP_WORKBENCH_AUTOSTART = "org.eclipse.rap.workbenchAutostart";
+final class Kernel implements KernelConstants, ServiceListener {
+       /*
+        * REGISTERED SERVICES
+        */
+       private ServiceRegistration<ArgeoLogger> loggerReg;
+       private ServiceRegistration<TransactionManager> tmReg;
+       private ServiceRegistration<UserTransaction> utReg;
+       private ServiceRegistration<TransactionSynchronizationRegistry> tsrReg;
+       private ServiceRegistration<Repository> repositoryReg;
+       private ServiceRegistration<RepositoryFactory> repositoryFactoryReg;
+       private ServiceRegistration<UserAdmin> userAdminReg;
 
-       private final BundleContext bundleContext;
+       /*
+        * SERVICES IMPLEMENTATIONS
+        */
+       private NodeLogger logger;
+       private BitronixTransactionManager transactionManager;
+       private BitronixTransactionSynchronizationRegistry transactionSynchronizationRegistry;
+       private OsgiJackrabbitRepositoryFactory repositoryFactory;
+       NodeRepository repository;
+       private NodeUserAdmin userAdmin;
 
-       private JackrabbitNode node;
-       private RepositoryFactory repositoryFactory;
-       private NodeSecurity nodeSecurity;
-       private NodeHttp nodeHttp;
+       // Members
+       private final static Log log = LogFactory.getLog(Kernel.class);
+       ThreadGroup threadGroup = new ThreadGroup(Kernel.class.getSimpleName());
+       private final BundleContext bc = Activator.getBundleContext();
+       private final NodeSecurity nodeSecurity;
+       private DataHttp dataHttp;
+       private KernelThread kernelThread;
 
-       private ServiceRegistration<ApplicationConfiguration> workbenchReg;
+       public Kernel() {
+               nodeSecurity = new NodeSecurity();
+       }
 
-       Kernel(BundleContext bundleContext) {
-               this.bundleContext = bundleContext;
+       final void init() {
+               Subject.doAs(nodeSecurity.getKernelSubject(),
+                               new PrivilegedAction<Void>() {
+                                       @Override
+                                       public Void run() {
+                                               doInit();
+                                               return null;
+                                       }
+                               });
        }
 
-       void init() {
+       private void doInit() {
+               ClassLoader currentContextCl = Thread.currentThread()
+                               .getContextClassLoader();
+               Thread.currentThread().setContextClassLoader(
+                               Kernel.class.getClassLoader());
                long begin = System.currentTimeMillis();
-               InternalAuthentication initAuth = new InternalAuthentication(
-                               KernelConstants.DEFAULT_SECURITY_KEY);
-               SecurityContextHolder.getContext().setAuthentication(initAuth);
+
+               // KernelUtils.logFrameworkProperties(log);
 
                try {
-                       node = new JackrabbitNode(bundleContext);
+                       // Initialise services
+                       logger = new NodeLogger();
+                       // transactionManager = new SimpleTransactionManager();
+                       initBitronixTransactionManager();
+                       repository = new NodeRepository(bc);
                        repositoryFactory = new OsgiJackrabbitRepositoryFactory();
-                       nodeSecurity = new NodeSecurity(bundleContext, node);
-                       nodeHttp = new NodeHttp(bundleContext, node, nodeSecurity);
+                       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
-                       nodeSecurity.publish();
-                       node.publish();
-                       bundleContext.registerService(RepositoryFactory.class,
-                                       repositoryFactory, null);
-                       nodeHttp.publish();
-
-//                     if ("false".equals(bundleContext
-//                                     .getProperty(PROP_WORKBENCH_AUTOSTART))) {
-//                             WorkbenchApplicationConfiguration wac = new WorkbenchApplicationConfiguration();
-//                             registerWorkbench(wac);
-//                     }
+                       publish();
                } catch (Exception e) {
                        log.error("Cannot initialize Argeo CMS", e);
                        throw new ArgeoException("Cannot initialize", e);
+               } finally {
+                       Thread.currentThread().setContextClassLoader(currentContextCl);
                }
 
-               long duration = System.currentTimeMillis() - begin;
-               log.info("## ARGEO CMS UP in " + (duration / 1000) + "."
-                               + (duration % 1000) + "s ##");
-               directorsCut();
+               long jvmUptime = ManagementFactory.getRuntimeMXBean().getUptime();
+               log.info("## ARGEO CMS UP in " + (jvmUptime / 1000) + "."
+                               + (jvmUptime % 1000) + "s ##");
+               long initDuration = System.currentTimeMillis() - begin;
+               if (log.isTraceEnabled())
+                       log.trace("Kernel initialization took " + initDuration + "ms");
+               directorsCut(initDuration);
+       }
+
+       private void initBitronixTransactionManager() {
+               Configuration tmConf = TransactionManagerServices.getConfiguration();
+               tmConf.setServerId(getFrameworkProp(FRAMEWORK_UUID));
+
+               File tmBaseDir = new File(getFrameworkProp(TRANSACTIONS_HOME,
+                               getOsgiInstancePath("transactions")));
+               File tmDir1 = new File(tmBaseDir, "btm1");
+               tmDir1.mkdirs();
+               tmConf.setLogPart1Filename(new File(tmDir1, tmDir1.getName() + ".tlog")
+                               .getAbsolutePath());
+               File tmDir2 = new File(tmBaseDir, "btm2");
+               tmDir2.mkdirs();
+               tmConf.setLogPart2Filename(new File(tmDir2, tmDir2.getName() + ".tlog")
+                               .getAbsolutePath());
+               transactionManager = getTransactionManager();
+               transactionSynchronizationRegistry = getTransactionSynchronizationRegistry();
+       }
+
+       private void publish() {
+               // Listen to service publication (also ours)
+               bc.addServiceListener(Kernel.this);
+
+               // Logging
+               loggerReg = bc.registerService(ArgeoLogger.class, logger, null);
+               // Transaction
+               tmReg = bc.registerService(TransactionManager.class,
+                               transactionManager, null);
+               utReg = bc.registerService(UserTransaction.class, transactionManager,
+                               null);
+               tsrReg = bc.registerService(TransactionSynchronizationRegistry.class,
+                               transactionSynchronizationRegistry, null);
+               // User admin
+               userAdminReg = bc.registerService(UserAdmin.class, userAdmin,
+                               userAdmin.currentState());
+               // JCR
+               Hashtable<String, String> regProps = new Hashtable<String, String>();
+               regProps.put(JCR_REPOSITORY_ALIAS, ALIAS_NODE);
+               repositoryReg = bc.registerService(Repository.class, repository,
+                               regProps);
+               repositoryFactoryReg = bc.registerService(RepositoryFactory.class,
+                               repositoryFactory, null);
        }
 
        void destroy() {
                long begin = System.currentTimeMillis();
+               unpublish();
 
-               // OSGi
-               workbenchReg.unregister();
+               kernelThread.destroyAndJoin();
 
-               nodeHttp = null;
-               nodeSecurity.destroy();
-               node.destroy();
+               if (dataHttp != null)
+                       dataHttp.destroy();
+               if (userAdmin != null)
+                       userAdmin.destroy();
+               if (repository != null)
+                       repository.destroy();
+               if (transactionManager != null)
+                       transactionManager.shutdown();
+
+               bc.removeServiceListener(this);
+
+               // Clean hanging threads from Jackrabbit
+               TransientFileFactory.shutdown();
 
+               // Clean hanging Gogo shell thread
+               new GogoShellKiller().start();
+
+               nodeSecurity.destroy();
                long duration = System.currentTimeMillis() - begin;
                log.info("## ARGEO CMS DOWN in " + (duration / 1000) + "."
                                + (duration % 1000) + "s ##");
        }
 
-//     private void registerWorkbench(final WorkbenchApplicationConfiguration wac) {
-//             new Thread("Worbench Launcher") {
-//                     public void run() {
-//                             Hashtable<String, String> props = new Hashtable<String, String>();
-//                             props.put(ApplicationLauncher.PROPERTY_CONTEXT_NAME, "ui");
-//                             workbenchReg = bundleContext.registerService(
-//                                             ApplicationConfiguration.class, wac, props);
-//                     }
-//             }.start();
-//     }
-
-       private void directorsCut() {
-               final long ms = 128l + (long) (Math.random() * 128d);
+       private void unpublish() {
+               userAdminReg.unregister();
+               repositoryFactoryReg.unregister();
+               repositoryReg.unregister();
+               tmReg.unregister();
+               utReg.unregister();
+               tsrReg.unregister();
+               loggerReg.unregister();
+       }
+
+       @Override
+       public void serviceChanged(ServiceEvent event) {
+               ServiceReference<?> sr = event.getServiceReference();
+               Object service = bc.getService(sr);
+               if (service instanceof Repository) {
+                       Object jcrRepoAlias = sr
+                                       .getProperty(ArgeoJcrConstants.JCR_REPOSITORY_ALIAS);
+                       if (jcrRepoAlias != null) {// JCR repository
+                               String alias = jcrRepoAlias.toString();
+                               Repository repository = (Repository) bc.getService(sr);
+                               Map<String, Object> props = new HashMap<String, Object>();
+                               for (String key : sr.getPropertyKeys())
+                                       props.put(key, sr.getProperty(key));
+                               if (ServiceEvent.REGISTERED == event.getType()) {
+                                       try {
+                                               repositoryFactory.register(repository, props);
+                                               dataHttp.registerRepositoryServlets(alias, repository);
+                                       } catch (Exception e) {
+                                               throw new CmsException(
+                                                               "Could not publish JCR repository " + alias, e);
+                                       }
+                               } else if (ServiceEvent.UNREGISTERING == event.getType()) {
+                                       repositoryFactory.unregister(repository, props);
+                                       dataHttp.unregisterRepositoryServlets(alias);
+                               }
+                       }
+               } else if (service instanceof ExtendedHttpService) {
+                       if (ServiceEvent.REGISTERED == event.getType()) {
+                               addHttpService(sr);
+                       } else if (ServiceEvent.UNREGISTERING == event.getType()) {
+                               dataHttp.destroy();
+                               dataHttp = null;
+                       }
+               }
+       }
+
+       private void addHttpService(ServiceReference<?> sr) {
+               // for (String key : sr.getPropertyKeys())
+               // log.debug(key + "=" + sr.getProperty(key));
+               ExtendedHttpService httpService = (ExtendedHttpService) bc
+                               .getService(sr);
+               // TODO find constants
+               Object httpPort = sr.getProperty("http.port");
+               Object httpsPort = sr.getProperty("https.port");
+               dataHttp = new DataHttp(httpService, repository);
+               if (log.isDebugEnabled())
+                       log.debug("HTTP " + httpPort
+                                       + (httpsPort != null ? " - HTTPS " + httpsPort : ""));
+       }
+
+       // 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;
+       // }
+
+       final private static void directorsCut(long initDuration) {
+               // final long ms = 128l + (long) (Math.random() * 128d);
+               long ms = initDuration / 100;
                log.info("Spend " + ms + "ms"
                                + " reflecting on the progress brought to mankind"
                                + " by Free Software...");
@@ -117,7 +313,65 @@ final class Kernel {
                double sleepAccuracy = ((double) durationNano) / (ms * M);
                if (log.isDebugEnabled())
                        log.debug("Sleep accuracy: "
-                                       + String.format("%.2f", sleepAccuracy * 100) + " %");
+                                       + String.format("%.2f", 100 - (sleepAccuracy * 100 - 100))
+                                       + " %");
+       }
+
+       /** Workaround for blocking Gogo shell by system shutdown. */
+       private class GogoShellKiller extends Thread {
+
+               public GogoShellKiller() {
+                       super("Gogo shell killer");
+                       setDaemon(true);
+               }
+
+               @Override
+               public void run() {
+                       ThreadGroup rootTg = getRootThreadGroup(null);
+                       Thread gogoShellThread = findGogoShellThread(rootTg);
+                       if (gogoShellThread == null)
+                               return;
+                       while (getNonDaemonCount(rootTg) > 2) {
+                               try {
+                                       Thread.sleep(100);
+                               } catch (InterruptedException e) {
+                                       // silent
+                               }
+                       }
+                       gogoShellThread = findGogoShellThread(rootTg);
+                       if (gogoShellThread == null)
+                               return;
+                       System.exit(0);
+               }
+       }
+
+       private static ThreadGroup getRootThreadGroup(ThreadGroup tg) {
+               if (tg == null)
+                       tg = Thread.currentThread().getThreadGroup();
+               if (tg.getParent() == null)
+                       return tg;
+               else
+                       return getRootThreadGroup(tg.getParent());
+       }
+
+       private static int getNonDaemonCount(ThreadGroup rootThreadGroup) {
+               Thread[] threads = new Thread[rootThreadGroup.activeCount()];
+               rootThreadGroup.enumerate(threads);
+               int nonDameonCount = 0;
+               for (Thread t : threads)
+                       if (!t.isDaemon())
+                               nonDameonCount++;
+               return nonDameonCount;
+       }
+
+       private static Thread findGogoShellThread(ThreadGroup rootThreadGroup) {
+               Thread[] threads = new Thread[rootThreadGroup.activeCount()];
+               rootThreadGroup.enumerate(threads, true);
+               for (Thread thread : threads) {
+                       if (thread.getName().equals("Gogo shell"))
+                               return thread;
+               }
+               return null;
        }
 
-}
+}
\ No newline at end of file