001    /*
002     * Copyright (C) 2012 eXo Platform SAS.
003     *
004     * This is free software; you can redistribute it and/or modify it
005     * under the terms of the GNU Lesser General Public License as
006     * published by the Free Software Foundation; either version 2.1 of
007     * the License, or (at your option) any later version.
008     *
009     * This software is distributed in the hope that it will be useful,
010     * but WITHOUT ANY WARRANTY; without even the implied warranty of
011     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012     * Lesser General Public License for more details.
013     *
014     * You should have received a copy of the GNU Lesser General Public
015     * License along with this software; if not, write to the Free
016     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
017     * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
018     */
019    
020    package org.crsh.standalone;
021    
022    import com.sun.tools.attach.VirtualMachine;
023    import org.crsh.cli.impl.descriptor.CommandDescriptorImpl;
024    import jline.Terminal;
025    import jline.TerminalFactory;
026    import jline.console.ConsoleReader;
027    import org.crsh.cli.impl.Delimiter;
028    import org.crsh.cli.impl.descriptor.IntrospectionException;
029    import org.crsh.cli.Argument;
030    import org.crsh.cli.Command;
031    import org.crsh.cli.Option;
032    import org.crsh.cli.Usage;
033    import org.crsh.cli.impl.lang.CommandFactory;
034    import org.crsh.cli.impl.invocation.InvocationMatch;
035    import org.crsh.cli.impl.invocation.InvocationMatcher;
036    import org.crsh.processor.jline.JLineProcessor;
037    import org.crsh.shell.Shell;
038    import org.crsh.shell.ShellFactory;
039    import org.crsh.shell.impl.remoting.RemoteServer;
040    import org.crsh.util.CloseableList;
041    import org.crsh.util.IO;
042    import org.crsh.util.InterruptHandler;
043    import org.crsh.util.Safe;
044    import org.crsh.vfs.FS;
045    import org.crsh.vfs.Path;
046    import org.crsh.vfs.Resource;
047    import org.fusesource.jansi.AnsiConsole;
048    
049    import java.io.ByteArrayInputStream;
050    import java.io.Closeable;
051    import java.io.File;
052    import java.io.FileDescriptor;
053    import java.io.FileInputStream;
054    import java.io.FileOutputStream;
055    import java.io.IOException;
056    import java.io.PrintWriter;
057    import java.util.List;
058    import java.util.Properties;
059    import java.util.jar.Attributes;
060    import java.util.jar.JarOutputStream;
061    import java.util.jar.Manifest;
062    import java.util.logging.Level;
063    import java.util.logging.Logger;
064    import java.util.regex.Pattern;
065    
066    public class CRaSH {
067    
068      /** . */
069      private static Logger log = Logger.getLogger(CRaSH.class.getName());
070    
071      /** . */
072      private final CommandDescriptorImpl<CRaSH> descriptor;
073    
074      public CRaSH() throws IntrospectionException {
075        this.descriptor = CommandFactory.DEFAULT.create(CRaSH.class);
076      }
077    
078      private void copy(org.crsh.vfs.File src, File dst) throws IOException {
079        if (src.isDir()) {
080          if (!dst.exists()) {
081            if (dst.mkdir()) {
082              log.fine("Could not create dir " + dst.getCanonicalPath());
083            }
084          }
085          if (dst.exists() && dst.isDirectory()) {
086            for (org.crsh.vfs.File child : src.children()) {
087              copy(child, new File(dst, child.getName()));
088            }
089          }
090        } else {
091          if (!dst.exists()) {
092            Resource resource = src.getResource();
093            if (resource != null) {
094              log.info("Copied resource " + src.getPath().getValue() + " to " + dst.getCanonicalPath());
095              IO.copy(new ByteArrayInputStream(resource.getContent()), new FileOutputStream(dst));
096            }
097          }
098        }
099      }
100    
101      @Command
102      public void main(
103        @Option(names={"c","cmd"})
104        @Usage("adds a dir to the command path")
105        List<String> cmds,
106        @Option(names={"conf"})
107        @Usage("adds a dir to the conf path")
108        List<String> confs,
109        @Option(names={"p","property"})
110        @Usage("set a property of the form a=b")
111        List<String> properties,
112        @Option(names = {"cmd-mode"})
113        @Usage("the cmd mode (read or copy), copy mode requires at least one cmd path to be specified")
114        ResourceMode cmdMode,
115        @Option(names = {"conf-mode"})
116        @Usage("the conf mode (read of copy), copy mode requires at least one conf path to be specified")
117        ResourceMode confMode,
118        @Argument(name = "pid")
119        @Usage("the optional JVM process id to attach to")
120        Integer pid) throws Exception {
121    
122        //
123        boolean copyCmd = cmdMode != ResourceMode.read && cmds != null && cmds.size() > 0;
124        boolean copyConf = confMode != ResourceMode.read && confs != null && confs.size() > 0;
125    
126        //
127        if (copyCmd) {
128          File dst = new File(cmds.get(0));
129          if (!dst.isDirectory()) {
130            throw new Exception("Directory " + dst.getAbsolutePath() + " does not exist");
131          }
132          FS fs = new FS();
133          fs.mount(Thread.currentThread().getContextClassLoader(), Path.get("/crash/commands/"));
134          org.crsh.vfs.File f = fs.get(Path.get("/"));
135          log.info("Copying command classpath resources");
136          copy(f, dst);
137        }
138    
139        //
140        if (copyConf) {
141          File dst = new File(confs.get(0));
142          if (!dst.isDirectory()) {
143            throw new Exception("Directory " + dst.getAbsolutePath() + " does not exist");
144          }
145          FS fs = new FS();
146          fs.mount(Thread.currentThread().getContextClassLoader(), Path.get("/crash/"));
147          org.crsh.vfs.File f = fs.get(Path.get("/"));
148          log.info("Copying conf classpath resources");
149          for (org.crsh.vfs.File child : f.children()) {
150            if (!child.isDir()) {
151              copy(child, new File(dst, child.getName()));
152            }
153          }
154        }
155    
156        //
157        CloseableList closeable = new CloseableList();
158        Shell shell;
159        if (pid != null) {
160    
161          // Standalone
162          log.log(Level.INFO, "Attaching to remote process " + pid);
163          final VirtualMachine vm = VirtualMachine.attach("" + pid);
164    
165          // Compute classpath
166          String classpath = System.getProperty("java.class.path");
167          String sep = System.getProperty("path.separator");
168          StringBuilder buffer = new StringBuilder();
169          for (String path : classpath.split(Pattern.quote(sep))) {
170            File file = new File(path);
171            if (file.exists()) {
172              if (buffer.length() > 0) {
173                buffer.append(' ');
174              }
175              buffer.append(file.getCanonicalPath());
176            }
177          }
178    
179          // Create manifest
180          Manifest manifest = new Manifest();
181          Attributes attributes = manifest.getMainAttributes();
182          attributes.putValue("Agent-Class", Agent.class.getName());
183          attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
184          attributes.put(Attributes.Name.CLASS_PATH, buffer.toString());
185    
186          // Create jar file
187          File agentFile = File.createTempFile("agent", ".jar");
188          agentFile.deleteOnExit();
189          JarOutputStream out = new JarOutputStream(new FileOutputStream(agentFile), manifest);
190          out.close();
191          log.log(Level.INFO, "Created agent jar " + agentFile.getCanonicalPath());
192    
193          //
194          RemoteServer server = new RemoteServer(0);
195          int port = server.bind();
196          log.log(Level.INFO, "Callback server set on port " + port);
197    
198          // Build the options
199          StringBuilder sb = new StringBuilder();
200    
201          // Rewrite canonical path
202          if (copyCmd) {
203            sb.append("--cmd-mode copy ");
204          } else {
205            sb.append("--cmd-mode read ");
206          }
207          if (cmds != null) {
208            for (String cmd : cmds) {
209              File cmdPath = new File(cmd);
210              if (cmdPath.exists()) {
211                sb.append("--cmd ");
212                Delimiter.EMPTY.escape(cmdPath.getCanonicalPath(), sb);
213                sb.append(' ');
214              }
215            }
216          }
217    
218          // Rewrite canonical path
219          if (copyCmd) {
220            sb.append("--conf-mode copy ");
221          } else {
222            sb.append("--conf-mode read ");
223          }
224          if (confs != null) {
225            for (String conf : confs) {
226              File confPath = new File(conf);
227              if (confPath.exists()) {
228                sb.append("--conf ");
229                Delimiter.EMPTY.escape(confPath.getCanonicalPath(), sb);
230                sb.append(' ');
231              }
232            }
233          }
234    
235          // Propagate canonical config
236          if (properties != null) {
237            for (String property : properties) {
238              sb.append("--property ");
239              Delimiter.EMPTY.escape(property, sb);
240              sb.append(' ');
241            }
242          }
243    
244          // Append callback port
245          sb.append(port);
246    
247          //
248          String options = sb.toString();
249          log.log(Level.INFO, "Loading agent with command " + options + " as agent " + agentFile.getCanonicalPath());
250          vm.loadAgent(agentFile.getCanonicalPath(), options);
251    
252          //
253          server.accept();
254    
255          //
256          shell = server.getShell();
257          closeable.add(new Closeable() {
258            public void close() throws IOException {
259              vm.detach();
260            }
261          });
262        } else {
263          final Bootstrap bootstrap = new Bootstrap(Thread.currentThread().getContextClassLoader());
264    
265          //
266          if (!copyCmd) {
267            bootstrap.addToCmdPath(Path.get("/crash/commands/"));
268          }
269          if (cmds != null) {
270            for (String cmd : cmds) {
271              File cmdPath = new File(cmd);
272              bootstrap.addToCmdPath(cmdPath);
273            }
274          }
275    
276          //
277          if (!copyConf) {
278            bootstrap.addToConfPath(Path.get("/crash/"));
279          }
280          if (confs != null) {
281            for (String conf : confs) {
282              File confPath = new File(conf);
283              bootstrap.addToConfPath(confPath);
284            }
285          }
286    
287          //
288          if (properties != null) {
289            Properties config = new Properties();
290            for (String property : properties) {
291              int index = property.indexOf('=');
292              if (index == -1) {
293                config.setProperty(property, "");
294              } else {
295                config.setProperty(property.substring(0, index), property.substring(index + 1));
296              }
297            }
298            bootstrap.setConfig(config);
299          }
300    
301          // Register shutdown hook
302          Runtime.getRuntime().addShutdownHook(new Thread() {
303            @Override
304            public void run() {
305              // Should trigger some kind of run interruption
306            }
307          });
308    
309          // Do bootstrap
310          bootstrap.bootstrap();
311          Runtime.getRuntime().addShutdownHook(new Thread(){
312            @Override
313            public void run() {
314              bootstrap.shutdown();
315            }
316          });
317    
318          //
319          ShellFactory factory = bootstrap.getContext().getPlugin(ShellFactory.class);
320          shell = factory.create(null);
321          closeable = null;
322        }
323    
324        // Start crash for this command line
325        final Terminal term = TerminalFactory.create();
326        term.init();
327        ConsoleReader reader = new ConsoleReader(null, new FileInputStream(FileDescriptor.in), System.out, term);
328        Runtime.getRuntime().addShutdownHook(new Thread(){
329          @Override
330          public void run() {
331            try {
332              term.restore();
333            }
334            catch (Exception ignore) {
335            }
336          }
337        });
338    
339        AnsiConsole.systemInstall();
340    
341        final PrintWriter out = new PrintWriter(AnsiConsole.out);
342        final JLineProcessor processor = new JLineProcessor(
343            shell,
344            reader,
345            out
346        );
347        reader.addCompleter(processor);
348    
349        // Install signal handler
350        InterruptHandler ih = new InterruptHandler(new Runnable() {
351          public void run() {
352            processor.cancel();
353          }
354        });
355        ih.install();
356    
357        //
358        try {
359          processor.run();
360        }
361        catch (Throwable t) {
362          t.printStackTrace();
363        }
364        finally {
365    
366          //
367          AnsiConsole.systemUninstall();
368    
369          //
370          if (closeable != null) {
371            Safe.close(closeable);
372          }
373    
374          // Force exit
375          System.exit(0);
376        }
377      }
378    
379      public static void main(String[] args) throws Exception {
380    
381        StringBuilder line = new StringBuilder();
382        for (int i = 0;i < args.length;i++) {
383          if (i  > 0) {
384            line.append(' ');
385          }
386          Delimiter.EMPTY.escape(args[i], line);
387        }
388    
389        //
390        CRaSH main = new CRaSH();
391        InvocationMatcher<CRaSH> matcher = main.descriptor.invoker("main");
392        InvocationMatch<CRaSH> match = matcher.match(line.toString());
393        match.invoke(new CRaSH());
394      }
395    }