CLICommand.java 7.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/*
 * The MIT License
 *
 * Copyright (c) 2004-2009, Sun Microsystems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package hudson.cli;

26
import hudson.AbortException;
27 28
import hudson.Extension;
import hudson.ExtensionList;
29 30 31
import hudson.ExtensionPoint;
import hudson.cli.declarative.CLIMethod;
import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson;
32
import hudson.model.Hudson;
33 34
import hudson.remoting.Callable;
import hudson.remoting.Channel;
35
import org.kohsuke.args4j.CmdLineException;
36
import org.kohsuke.args4j.CmdLineParser;
37

K
kohsuke 已提交
38
import java.io.BufferedInputStream;
39 40
import java.io.InputStream;
import java.io.PrintStream;
41
import java.util.List;
K
kohsuke 已提交
42
import java.util.Locale;
43 44 45 46

/**
 * Base class for Hudson CLI.
 *
K
kohsuke 已提交
47
 * <h2>How does a CLI command work</h2>
48
 * <p>
K
kohsuke 已提交
49 50 51 52
 * The users starts {@linkplain CLI the "CLI agent"} on a remote system, by specifying arguments, like
 * <tt>"java -jar hudson-cli.jar command arg1 arg2 arg3"</tt>. The CLI agent creates
 * a remoting channel with the server, and it sends the entire arguments to the server, along with
 * the remoted stdin/out/err.
53 54
 *
 * <p>
K
kohsuke 已提交
55
 * The Hudson master then picks the right {@link CLICommand} to execute, clone it, and
56
 * calls {@link #main(List, Locale, InputStream, PrintStream, PrintStream)} method.
K
kohsuke 已提交
57 58
 *
 * <h2>Note for CLI command implementor</h2>
K
kohsuke 已提交
59 60 61
 * Start with <a href="http://wiki.hudson-ci.org/display/HUDSON/Writing+CLI+commands">this document</a>
 * to get the general idea of CLI.
 *
K
kohsuke 已提交
62 63 64 65 66
 * <ul>
 * <li>
 * Put {@link Extension} on your implementation to have it discovered by Hudson.
 *
 * <li>
67
 * Use <a href="http://args4j.dev.java.net/">args4j</a> annotation on your implementation to define
K
kohsuke 已提交
68
 * options and arguments (however, if you don't like that, you could override
69
 * the {@link #main(List, Locale, InputStream, PrintStream, PrintStream)} method directly.
70
 *
K
kohsuke 已提交
71 72 73 74 75 76 77 78
 * <li>
 * stdin, stdout, stderr are remoted, so proper buffering is necessary for good user experience.
 *
 * <li>
 * Send {@link Callable} to a CLI agent by using {@link #channel} to get local interaction,
 * such as uploading a file, asking for a password, etc.
 *
 * </ul>
79 80 81
 *
 * @author Kohsuke Kawaguchi
 * @since 1.302
82
 * @see CLIMethod
83
 */
84
@LegacyInstancesAreScopedToHudson
85 86 87 88 89 90
public abstract class CLICommand implements ExtensionPoint, Cloneable {
    /**
     * Connected to stdout and stderr of the CLI agent that initiated the session.
     * IOW, if you write to these streams, the person who launched the CLI command
     * will see the messages in his terminal.
     *
K
kohsuke 已提交
91
     * <p>
92 93 94
     * (In contrast, calling {@code System.out.println(...)} would print out
     * the message to the server log file, which is probably not what you want.
     */
95
    protected transient PrintStream stdout,stderr;
96

K
kohsuke 已提交
97 98 99 100 101 102
    /**
     * Connected to stdin of the CLI agent.
     *
     * <p>
     * This input stream is buffered to hide the latency in the remoting.
     */
103
    protected transient InputStream stdin;
K
kohsuke 已提交
104

105 106 107 108
    /**
     * {@link Channel} that represents the CLI JVM. You can use this to
     * execute {@link Callable} on the CLI JVM, among other things.
     */
109
    protected transient Channel channel;
110

111 112 113 114 115
    /**
     * The locale of the client. Messages should be formatted with this resource.
     */
    protected transient Locale locale;

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134

    /**
     * Gets the command name.
     *
     * <p>
     * For example, if the CLI is invoked as <tt>java -jar cli.jar foo arg1 arg2 arg4</tt>,
     * on the server side {@link CLICommand} that returns "foo" from {@link #getName()}
     * will be invoked.
     *
     * <p>
     * By default, this method creates "foo-bar-zot" from "FooBarZotCommand".
     */
    public String getName() {
        String name = getClass().getName();
        name = name.substring(name.lastIndexOf('.')+1); // short name
        if(name.endsWith("Command"))
            name = name.substring(0,name.length()-7); // trim off the command

        // convert "FooBarZot" into "foo-bar-zot"
K
kohsuke 已提交
135 136
        // Locale is fixed so that "CreateInstance" always become "create-instance" no matter where this is run.
        return name.replaceAll("([a-z0-9])([A-Z])","$1-$2").toLowerCase(Locale.ENGLISH);
137 138
    }

K
kohsuke 已提交
139 140 141 142 143 144
    /**
     * Gets the quick summary of what this command does.
     * Used by the help command to generate the list of commands.
     */
    public abstract String getShortDescription();

145
    public int main(List<String> args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) {
K
kohsuke 已提交
146
        this.stdin = new BufferedInputStream(stdin);
147 148
        this.stdout = stdout;
        this.stderr = stderr;
149
        this.locale = locale;
150 151 152 153 154 155 156 157 158
        this.channel = Channel.current();
        CmdLineParser p = new CmdLineParser(this);
        try {
            p.parseArgument(args.toArray(new String[args.size()]));
            return run();
        } catch (CmdLineException e) {
            stderr.println(e.getMessage());
            printUsage(stderr, p);
            return -1;
159 160 161 162
        } catch (AbortException e) {
            // signals an error without stack trace
            stderr.println(e.getMessage());
            return -1;
163 164 165
        } catch (Exception e) {
            e.printStackTrace(stderr);
            return -1;
166 167 168 169 170 171 172 173
        }
    }

    /**
     * Executes the command, and return the exit code.
     *
     * @return
     *      0 to indicate a success, otherwise an error code.
174 175 176 177 178 179
     * @throws AbortException
     *      If the processing should be aborted. Hudson will report the error message
     *      without stack trace, and then exits this command.
     * @throws Exception
     *      All the other exceptions cause the stack trace to be dumped, and then
     *      the command exits with an error code.
180
     */
181
    protected abstract int run() throws Exception;
182 183 184 185 186 187

    protected void printUsage(PrintStream stderr, CmdLineParser p) {
        stderr.println("java -jar hudson-cli.jar "+getName()+" args...");
        p.printUsage(stderr);
    }

188 189 190 191 192 193 194 195 196 197 198 199 200
    /**
     * Creates a clone to be used to execute a command.
     */
    protected CLICommand createClone() {
        try {
            return getClass().newInstance();
        } catch (IllegalAccessException e) {
            throw new AssertionError(e);
        } catch (InstantiationException e) {
            throw new AssertionError(e);
        }
    }

201 202 203 204 205 206 207 208 209 210 211
    /**
     * Returns all the registered {@link CLICommand}s.
     */
    public static ExtensionList<CLICommand> all() {
        return Hudson.getInstance().getExtensionList(CLICommand.class);
    }

    /**
     * Obtains a copy of the command for invocation.
     */
    public static CLICommand clone(String name) {
212 213 214
        for (CLICommand cmd : all())
            if(name.equals(cmd.getName()))
                return cmd.createClone();
215 216 217
        return null;
    }
}