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= {"non-interactive"})
104        @Usage("non interactive mode, the JVM io will not be used")
105        Boolean nonInteractive,
106        @Option(names={"c","cmd"})
107        @Usage("adds a dir to the command path")
108        List<String> cmds,
109        @Option(names={"conf"})
110        @Usage("adds a dir to the conf path")
111        List<String> confs,
112        @Option(names={"p","property"})
113        @Usage("set a property of the form a=b")
114        List<String> properties,
115        @Option(names = {"cmd-mode"})
116        @Usage("the cmd mode (read or copy), copy mode requires at least one cmd path to be specified")
117        ResourceMode cmdMode,
118        @Option(names = {"conf-mode"})
119        @Usage("the conf mode (read of copy), copy mode requires at least one conf path to be specified")
120        ResourceMode confMode,
121        @Argument(name = "pid")
122        @Usage("the optional JVM process id to attach to")
123        Integer pid) throws Exception {
124    
125        //
126        boolean copyCmd = cmdMode != ResourceMode.read && cmds != null && cmds.size() > 0;
127        boolean copyConf = confMode != ResourceMode.read && confs != null && confs.size() > 0;
128    
129        //
130        if (copyCmd) {
131          File dst = new File(cmds.get(0));
132          if (!dst.isDirectory()) {
133            throw new Exception("Directory " + dst.getAbsolutePath() + " does not exist");
134          }
135          FS fs = new FS();
136          fs.mount(Thread.currentThread().getContextClassLoader(), Path.get("/crash/commands/"));
137          org.crsh.vfs.File f = fs.get(Path.get("/"));
138          log.info("Copying command classpath resources");
139          copy(f, dst);
140        }
141    
142        //
143        if (copyConf) {
144          File dst = new File(confs.get(0));
145          if (!dst.isDirectory()) {
146            throw new Exception("Directory " + dst.getAbsolutePath() + " does not exist");
147          }
148          FS fs = new FS();
149          fs.mount(Thread.currentThread().getContextClassLoader(), Path.get("/crash/"));
150          org.crsh.vfs.File f = fs.get(Path.get("/"));
151          log.info("Copying conf classpath resources");
152          for (org.crsh.vfs.File child : f.children()) {
153            if (!child.isDir()) {
154              copy(child, new File(dst, child.getName()));
155            }
156          }
157        }
158    
159        //
160        CloseableList closeable = new CloseableList();
161        Shell shell;
162        if (pid != null) {
163    
164          // Standalone
165          log.log(Level.INFO, "Attaching to remote process " + pid);
166          final VirtualMachine vm = VirtualMachine.attach("" + pid);
167    
168          // Compute classpath
169          String classpath = System.getProperty("java.class.path");
170          String sep = System.getProperty("path.separator");
171          StringBuilder buffer = new StringBuilder();
172          for (String path : classpath.split(Pattern.quote(sep))) {
173            File file = new File(path);
174            if (file.exists()) {
175              if (buffer.length() > 0) {
176                buffer.append(' ');
177              }
178              buffer.append(file.getCanonicalPath());
179            }
180          }
181    
182          // Create manifest
183          Manifest manifest = new Manifest();
184          Attributes attributes = manifest.getMainAttributes();
185          attributes.putValue("Agent-Class", Agent.class.getName());
186          attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
187          attributes.put(Attributes.Name.CLASS_PATH, buffer.toString());
188    
189          // Create jar file
190          File agentFile = File.createTempFile("agent", ".jar");
191          agentFile.deleteOnExit();
192          JarOutputStream out = new JarOutputStream(new FileOutputStream(agentFile), manifest);
193          out.close();
194          log.log(Level.INFO, "Created agent jar " + agentFile.getCanonicalPath());
195    
196          //
197          RemoteServer server = new RemoteServer(0);
198          int port = server.bind();
199          log.log(Level.INFO, "Callback server set on port " + port);
200    
201          // Build the options
202          StringBuilder sb = new StringBuilder();
203    
204          // Rewrite canonical path
205          if (copyCmd) {
206            sb.append("--cmd-mode copy ");
207          } else {
208            sb.append("--cmd-mode read ");
209          }
210          if (cmds != null) {
211            for (String cmd : cmds) {
212              File cmdPath = new File(cmd);
213              if (cmdPath.exists()) {
214                sb.append("--cmd ");
215                Delimiter.EMPTY.escape(cmdPath.getCanonicalPath(), sb);
216                sb.append(' ');
217              }
218            }
219          }
220    
221          // Rewrite canonical path
222          if (copyCmd) {
223            sb.append("--conf-mode copy ");
224          } else {
225            sb.append("--conf-mode read ");
226          }
227          if (confs != null) {
228            for (String conf : confs) {
229              File confPath = new File(conf);
230              if (confPath.exists()) {
231                sb.append("--conf ");
232                Delimiter.EMPTY.escape(confPath.getCanonicalPath(), sb);
233                sb.append(' ');
234              }
235            }
236          }
237    
238          // Propagate canonical config
239          if (properties != null) {
240            for (String property : properties) {
241              sb.append("--property ");
242              Delimiter.EMPTY.escape(property, sb);
243              sb.append(' ');
244            }
245          }
246    
247          // Append callback port
248          sb.append(port);
249    
250          //
251          String options = sb.toString();
252          log.log(Level.INFO, "Loading agent with command " + options + " as agent " + agentFile.getCanonicalPath());
253          vm.loadAgent(agentFile.getCanonicalPath(), options);
254    
255          //
256          server.accept();
257    
258          //
259          shell = server.getShell();
260          closeable.add(new Closeable() {
261            public void close() throws IOException {
262              vm.detach();
263            }
264          });
265        } else {
266          final Bootstrap bootstrap = new Bootstrap(Thread.currentThread().getContextClassLoader());
267    
268          //
269          if (!copyCmd) {
270            bootstrap.addToCmdPath(Path.get("/crash/commands/"));
271          }
272          if (cmds != null) {
273            for (String cmd : cmds) {
274              File cmdPath = new File(cmd);
275              bootstrap.addToCmdPath(cmdPath);
276            }
277          }
278    
279          //
280          if (!copyConf) {
281            bootstrap.addToConfPath(Path.get("/crash/"));
282          }
283          if (confs != null) {
284            for (String conf : confs) {
285              File confPath = new File(conf);
286              bootstrap.addToConfPath(confPath);
287            }
288          }
289    
290          //
291          if (properties != null) {
292            Properties config = new Properties();
293            for (String property : properties) {
294              int index = property.indexOf('=');
295              if (index == -1) {
296                config.setProperty(property, "");
297              } else {
298                config.setProperty(property.substring(0, index), property.substring(index + 1));
299              }
300            }
301            bootstrap.setConfig(config);
302          }
303    
304          // Register shutdown hook
305          Runtime.getRuntime().addShutdownHook(new Thread() {
306            @Override
307            public void run() {
308              // Should trigger some kind of run interruption
309            }
310          });
311    
312          // Do bootstrap
313          bootstrap.bootstrap();
314          Runtime.getRuntime().addShutdownHook(new Thread(){
315            @Override
316            public void run() {
317              bootstrap.shutdown();
318            }
319          });
320    
321          //
322          ShellFactory factory = bootstrap.getContext().getPlugin(ShellFactory.class);
323          shell = factory.create(null);
324          closeable = null;
325        }
326    
327        //
328        if (nonInteractive == null || !nonInteractive) {
329    
330          // Start crash for this command line
331          final Terminal term = TerminalFactory.create();
332          term.init();
333          ConsoleReader reader = new ConsoleReader(null, new FileInputStream(FileDescriptor.in), System.out, term);
334          Runtime.getRuntime().addShutdownHook(new Thread(){
335            @Override
336            public void run() {
337              try {
338                term.restore();
339              }
340              catch (Exception ignore) {
341              }
342            }
343          });
344    
345          AnsiConsole.systemInstall();
346    
347          final PrintWriter out = new PrintWriter(AnsiConsole.out);
348          final JLineProcessor processor = new JLineProcessor(
349              shell,
350              reader,
351              out
352          );
353          reader.addCompleter(processor);
354    
355          // Install signal handler
356          InterruptHandler ih = new InterruptHandler(new Runnable() {
357            public void run() {
358              processor.cancel();
359            }
360          });
361          ih.install();
362    
363          //
364          try {
365            processor.run();
366          }
367          catch (Throwable t) {
368            t.printStackTrace();
369          }
370          finally {
371    
372            //
373            AnsiConsole.systemUninstall();
374    
375            //
376            if (closeable != null) {
377              Safe.close(closeable);
378            }
379    
380            // Force exit
381            System.exit(0);
382          }
383        }
384      }
385    
386      public static void main(String[] args) throws Exception {
387    
388        StringBuilder line = new StringBuilder();
389        for (int i = 0;i < args.length;i++) {
390          if (i  > 0) {
391            line.append(' ');
392          }
393          Delimiter.EMPTY.escape(args[i], line);
394        }
395    
396        //
397        CRaSH main = new CRaSH();
398        InvocationMatcher<CRaSH> matcher = main.descriptor.invoker("main");
399        InvocationMatch<CRaSH> match = matcher.match(line.toString());
400        match.invoke(new CRaSH());
401      }
402    }