]> git.argeo.org Git - gpl/argeo-slc.git/blobdiff - runtime/org.argeo.slc.launcher/src/main/java/org/argeo/slc/cli/SlcMain.java
Working command line SLC
[gpl/argeo-slc.git] / runtime / org.argeo.slc.launcher / src / main / java / org / argeo / slc / cli / SlcMain.java
index 2df18bf24c5597af383b4fd18881f44b4ad4d126..90ca7411f9ad23cdfb205c7a0e03b4a951f42f7f 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007-2012 Mathieu Baudier
+ * Copyright (C) 2007-2012 Argeo GmbH
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  */
 package org.argeo.slc.cli;
 
-import java.io.FileInputStream;
-import java.util.Properties;
-
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.GnuParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.OptionBuilder;
-import org.apache.commons.cli.Options;
-import org.apache.commons.cli.ParseException;
-import org.apache.commons.io.IOUtils;
-import org.argeo.slc.SlcException;
-
-@SuppressWarnings("static-access")
-public class SlcMain {
-       public enum Type {
-               standalone, agent, server
+import java.io.File;
+import java.lang.reflect.Method;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.UUID;
+
+import javax.security.auth.Subject;
+import javax.security.auth.login.LoginContext;
+
+import org.argeo.osgi.boot.OsgiBoot;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.launch.Framework;
+import org.osgi.framework.launch.FrameworkFactory;
+import org.osgi.util.tracker.ServiceTracker;
+
+/** Configures an SLC runtime and runs a process. */
+public class SlcMain implements Runnable {
+       private final String[] args;
+
+       // private static String bundlesToInstall = "/usr/share/osgi;in=*.jar";
+       private String bundlesToInstall = System.getProperty("user.home")
+                       + "/dev/src/slc/dep/org.argeo.slc.dep.minimal/target/dependency;in=*.jar,"
+                       + System.getProperty("user.home")
+                       + "/dev/src/slc/demo/modules;in=*;ex=pom.xml;ex=.svn";
+
+       private final List<String> bundlesToStart = new ArrayList<String>();
+
+       public SlcMain(String[] args) {
+               this.args = args;
+               bundlesToStart.add("org.springframework.osgi.extender");
+               bundlesToStart.add("org.argeo.node.repo.jackrabbit");
+               bundlesToStart.add("org.argeo.security.dao.os");
+               bundlesToStart.add("org.argeo.slc.node.jackrabbit");
+               bundlesToStart.add("org.argeo.slc.agent");
+               bundlesToStart.add("org.argeo.slc.agent.jcr");
        }
 
-       private static Boolean debug = true;
-
-       // private final static String BOOTSTRAP_LOG4J_CONFIG =
-       // "org/argeo/slc/cli/bootstrapLog4j.properties";
-       // private final static String DEFAULT_AGENT_CONTEXT =
-       // "classpath:org/argeo/slc/cli/spring-agent-default.xml";
-
-       private final static Option typeOpt = OptionBuilder.withLongOpt("mode")
-                       .withArgName("mode").hasArg()
-                       .withDescription("Execution type, one of: " + listTypeValues())
-                       .create('t');
-
-       private final static Option propertyOpt = OptionBuilder
-                       .withLongOpt("property").withArgName("prop1=val1,prop2=val2")
-                       .hasArgs().withValueSeparator(',')
-                       .withDescription("use value for given property").create('p');
-
-       private final static Option propertiesOpt = OptionBuilder
-                       .withLongOpt("properties").withArgName("properties file").hasArgs()
-                       .withValueSeparator(',')
-                       .withDescription("load properties from file (-p has priority)")
-                       .create('P');
-
-       private final static Option moduleOpt = OptionBuilder.withLongOpt("module")
-                       .withArgName("module").hasArg().withDescription("Execution module")
-                       .create('m');
-
-       private final static Option flowsOpt = OptionBuilder.withLongOpt("flows")
-                       .withArgName("flows").hasArg().withDescription("Flows to execute")
-                       .create('f');
-
-       private final static Option runtimeOpt = OptionBuilder
-                       .withLongOpt("runtime").withArgName("runtime").hasArg()
-                       .withDescription("Runtime URL").create('r');
-
-       private final static Options options;
-
-       private final static String commandName = "slc";
-
-       static {
-               options = new Options();
-               options.addOption(typeOpt);
-               options.addOption(moduleOpt);
-               options.addOption(flowsOpt);
-               options.addOption(propertyOpt);
-               options.addOption(propertiesOpt);
-               options.addOption(runtimeOpt);
-       }
-
-       public static void main(String[] args) {
-               Type type = null;
-               Properties properties = new Properties();
-               String module = null;
-               String flows = null;
-               String urlStr = null;
-
+       public void run() {
+               final LoginContext lc;
                try {
-
-                       CommandLineParser clParser = new GnuParser();
-                       CommandLine cl = clParser.parse(options, args);
-
-                       // Mode
-                       String typeStr = cl.getOptionValue(typeOpt.getOpt());
-                       if (typeStr == null) {
-                               type = Type.standalone;
-                       } else {
-                               try {
-                                       type = Type.valueOf(typeStr);
-                               } catch (IllegalArgumentException e) {
-                                       throw new SlcException("Unrecognized mode '" + typeStr
-                                                       + "'", e);
-                               }
-                       }
-
-                       // Script
-                       if (type.equals(Type.standalone)) {
-                               if (!cl.hasOption(moduleOpt.getOpt()))
-                                       throw new SlcException("Type " + Type.standalone
-                                                       + " requires option '" + moduleOpt.getLongOpt()
-                                                       + "'");
-                               module = cl.getOptionValue(moduleOpt.getOpt());
-
-                               // Targets
-                               if (cl.hasOption(flowsOpt.getOpt()))
-                                       flows = cl.getOptionValue(flowsOpt.getOpt());
-                       }
-
-                       // Properties
-                       if (cl.hasOption(propertiesOpt.getOpt())) {
-                               for (String propertyFile : cl.getOptionValues(propertiesOpt
-                                               .getOpt())) {
-                                       loadPropertyFile(properties, propertyFile);
-                               }
-                       }
-                       if (cl.hasOption(propertyOpt.getOpt())) {
-                               for (String property : cl.getOptionValues(propertyOpt.getOpt())) {
-                                       addProperty(properties, property);
-                               }
-                       }
-
-                       // Runtime
-                       if (cl.hasOption(runtimeOpt.getOpt())) {
-                               urlStr = cl.getOptionValue(runtimeOpt.getOpt());
-                       }
-               } catch (ParseException e) {
-                       System.err.println("Problem with command line arguments. "
-                                       + e.getMessage());
-                       badExit();
-               } catch (SlcException e) {
-                       System.err.println(e.getMessage());
-                       badExit();
+                       // Authenticate
+                       lc = new LoginContext("NIX");
+                       lc.login();
+
+                       // Prepare directories
+                       String executionDir = System.getProperty("user.dir");
+                       File slcDir = new File(executionDir, "target/.slc");
+                       File tempDir = new File(System.getProperty("java.io.tmpdir"));
+
+                       File dataDir = new File(tempDir, "slc-data-"
+                                       + UUID.randomUUID().toString());
+                       if (!dataDir.exists())
+                               dataDir.mkdirs();
+
+                       File confDir = new File(slcDir, "conf");
+                       if (!confDir.exists())
+                               confDir.mkdirs();
+
+                       System.setProperty("log4j.configuration", "file:./log4j.properties");
+                       System.setProperty("argeo.node.repo.configuration",
+                                       "osgibundle:repository-memory.xml");
+
+                       // Start Equinox
+                       ServiceLoader<FrameworkFactory> ff = ServiceLoader
+                                       .load(FrameworkFactory.class);
+                       FrameworkFactory frameworkFactory = ff.iterator().next();
+                       Map<String, String> configuration = new HashMap<String, String>();
+                       configuration.put("osgi.configuration.area",
+                                       confDir.getCanonicalPath());
+                       configuration.put("osgi.instance.area", dataDir.getCanonicalPath());
+                       configuration.put("osgi.clean", "true");
+
+                       // Spring configs currently require System properties
+                       System.getProperties().putAll(configuration);
+
+                       Framework framework = frameworkFactory.newFramework(configuration);
+                       framework.start();
+                       BundleContext bundleContext = framework.getBundleContext();
+                       // String[] osgiRuntimeArgs = { "-configuration",
+                       // confDir.getCanonicalPath(), "-data",
+                       // dataDir.getCanonicalPath(), "-clean" };
+                       // BundleContext bundleContext = EclipseStarter.startup(
+                       // osgiRuntimeArgs, null);
+
+                       // OSGi bootstrap
+                       OsgiBoot osgiBoot = new OsgiBoot(bundleContext);
+                       osgiBoot.installUrls(osgiBoot.getBundlesUrls(bundlesToInstall));
+
+                       // Start runtime
+                       osgiBoot.startBundles(bundlesToStart);
+
+                       // Find SLC Agent
+                       ServiceTracker agentTracker = new ServiceTracker(bundleContext,
+                                       "org.argeo.slc.execution.SlcAgentCli", null);
+                       agentTracker.open();
+                       final Object agentCli = agentTracker.waitForService(30 * 1000);
+
+                       // Run as a privileged action
+                       Subject.doAs(Subject.getSubject(AccessController.getContext()),
+                                       new PrivilegedAction<String>() {
+
+                                               public String run() {
+                                                       try {
+                                                               Class<?>[] parameterTypes = { String[].class };
+                                                               Method method = agentCli.getClass().getMethod(
+                                                                               "process", parameterTypes);
+                                                               Object[] methodArgs = { args };
+                                                               Object ret = method
+                                                                               .invoke(agentCli, methodArgs);
+                                                               return ret.toString();
+                                                       } catch (Exception e) {
+                                                               throw new RuntimeException("Cannot run "
+                                                                               + Arrays.toString(args) + " on "
+                                                                               + agentCli, e);
+                                                       }
+                                               }
+
+                                       });
+
+                       // Shutdown OSGi runtime
+                       framework.stop();
+                       framework.waitForStop(60 * 1000);
+
+                       System.exit(0);
                } catch (Exception e) {
-                       System.err.println("Unexpected exception when bootstrapping.");
                        e.printStackTrace();
-                       badExit();
-               }
-
-               if (debug) {
-                       debug("Mode: " + type);
-                       if (urlStr != null)
-                               debug("Runtime: " + urlStr);
-                       debug("User properties: " + properties);
-                       if (module != null)
-                               debug("Module: " + module);
-                       if (flows != null)
-                               debug("Flows: " + flows);
-               }
-
-               // Standalone
-               if (type.equals(Type.standalone)) {
-               }
-               // Agent
-               else if (type.equals(Type.agent)) {
+                       System.exit(1);
                }
        }
 
-       public static void printUsage() {
-               new HelpFormatter().printHelp(commandName, options, true);
-       }
-
-       private static String listTypeValues() {
-               StringBuffer buf = new StringBuffer("");
-               for (Type mode : Type.values()) {
-                       buf.append(mode).append(", ");
-               }
-               String str = buf.toString();
-               // unsafe, but there will be at least one value in the enum
-               return str.substring(0, str.length() - 2);
-       }
-
-       protected static void addProperty(Properties properties, String property) {
-               int eqIndex = property.indexOf('=');
-               if (eqIndex == 0)
-                       throw new SlcException("Badly formatted property " + property);
-
-               if (eqIndex > 0) {
-                       String key = property.substring(0, eqIndex);
-                       String value = property.substring(eqIndex + 1);
-                       properties.setProperty(key, value);
-
-               } else {
-                       properties.setProperty(property, "true");
-               }
-       }
-
-       protected static void loadPropertyFile(Properties properties,
-                       String propertyFile) {
-               FileInputStream in = null;
-               try {
-                       in = new FileInputStream(propertyFile);
-                       properties.load(in);
-               } catch (Exception e) {
-                       throw new SlcException("Could not load proeprty file "
-                                       + propertyFile);
-               } finally {
-                       IOUtils.closeQuietly(in);
-               }
-       }
-
-       private static void badExit() {
-               printUsage();
-               System.exit(1);
+       public static void main(String[] args) {
+               new SlcMain(args).run();
        }
 
        protected static void info(Object msg) {
@@ -226,4 +162,5 @@ public class SlcMain {
        protected static void debug(Object msg) {
                System.out.println(msg);
        }
+
 }