CLICommand.java 12.8 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 hudson.remoting.ChannelProperty;
36
import hudson.security.CliAuthenticator;
37
import hudson.security.SecurityRealm;
38 39 40 41
import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.kohsuke.args4j.ClassParser;
42
import org.kohsuke.args4j.CmdLineException;
43
import org.kohsuke.args4j.CmdLineParser;
44

K
kohsuke 已提交
45
import java.io.BufferedInputStream;
46
import java.io.IOException;
47 48
import java.io.InputStream;
import java.io.PrintStream;
49
import java.util.List;
K
kohsuke 已提交
50
import java.util.Locale;
51
import java.util.logging.Logger;
52 53 54 55

/**
 * Base class for Hudson CLI.
 *
K
kohsuke 已提交
56
 * <h2>How does a CLI command work</h2>
57
 * <p>
K
kohsuke 已提交
58 59 60 61
 * 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.
62 63
 *
 * <p>
K
kohsuke 已提交
64
 * The Hudson master then picks the right {@link CLICommand} to execute, clone it, and
65
 * calls {@link #main(List, Locale, InputStream, PrintStream, PrintStream)} method.
K
kohsuke 已提交
66 67
 *
 * <h2>Note for CLI command implementor</h2>
K
kohsuke 已提交
68 69 70
 * 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 已提交
71 72 73 74 75
 * <ul>
 * <li>
 * Put {@link Extension} on your implementation to have it discovered by Hudson.
 *
 * <li>
76
 * Use <a href="http://args4j.dev.java.net/">args4j</a> annotation on your implementation to define
K
kohsuke 已提交
77
 * options and arguments (however, if you don't like that, you could override
78
 * the {@link #main(List, Locale, InputStream, PrintStream, PrintStream)} method directly.
79
 *
K
kohsuke 已提交
80 81 82 83 84 85 86 87
 * <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>
88 89 90
 *
 * @author Kohsuke Kawaguchi
 * @since 1.302
91
 * @see CLIMethod
92
 */
93
@LegacyInstancesAreScopedToHudson
94 95 96 97 98 99
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 已提交
100
     * <p>
101 102 103
     * (In contrast, calling {@code System.out.println(...)} would print out
     * the message to the server log file, which is probably not what you want.
     */
104
    public transient PrintStream stdout,stderr;
105

K
kohsuke 已提交
106 107 108 109 110 111
    /**
     * Connected to stdin of the CLI agent.
     *
     * <p>
     * This input stream is buffered to hide the latency in the remoting.
     */
112
    public transient InputStream stdin;
K
kohsuke 已提交
113

114 115 116 117
    /**
     * {@link Channel} that represents the CLI JVM. You can use this to
     * execute {@link Callable} on the CLI JVM, among other things.
     */
118
    public transient Channel channel;
119

120 121 122
    /**
     * The locale of the client. Messages should be formatted with this resource.
     */
123
    public transient Locale locale;
124

125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

    /**
     * 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
140
        name = name.substring(name.lastIndexOf('$')+1);
141 142 143 144
        if(name.endsWith("Command"))
            name = name.substring(0,name.length()-7); // trim off the command

        // convert "FooBarZot" into "foo-bar-zot"
K
kohsuke 已提交
145 146
        // 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);
147 148
    }

K
kohsuke 已提交
149 150 151 152 153 154
    /**
     * Gets the quick summary of what this command does.
     * Used by the help command to generate the list of commands.
     */
    public abstract String getShortDescription();

155
    public int main(List<String> args, Locale locale, InputStream stdin, PrintStream stdout, PrintStream stderr) {
K
kohsuke 已提交
156
        this.stdin = new BufferedInputStream(stdin);
157 158
        this.stdout = stdout;
        this.stderr = stderr;
159
        this.locale = locale;
160 161
        this.channel = Channel.current();
        CmdLineParser p = new CmdLineParser(this);
162 163 164 165 166

        // add options from the authenticator
        SecurityContext sc = SecurityContextHolder.getContext();
        Authentication old = sc.getAuthentication();

167
        CliAuthenticator authenticator = Hudson.getInstance().getSecurityRealm().createCliAuthenticator(this);
168
        new ClassParser().parse(authenticator,p);
169

170 171
        try {
            p.parseArgument(args.toArray(new String[args.size()]));
172 173 174 175
            Authentication auth = authenticator.authenticate();
            if (auth==Hudson.ANONYMOUS)
                auth = loadStoredAuthentication();
            sc.setAuthentication(auth); // run the CLI with the right credential
176 177 178 179 180
            return run();
        } catch (CmdLineException e) {
            stderr.println(e.getMessage());
            printUsage(stderr, p);
            return -1;
181 182 183 184
        } catch (AbortException e) {
            // signals an error without stack trace
            stderr.println(e.getMessage());
            return -1;
185 186 187
        } catch (Exception e) {
            e.printStackTrace(stderr);
            return -1;
188 189
        } finally {
            sc.setAuthentication(old); // restore
190 191 192
        }
    }

193 194 195 196 197 198 199 200 201 202 203 204 205
    /**
     * Loads the persisted authentication information from {@link ClientAuthenticationCache}.
     */
    protected Authentication loadStoredAuthentication() throws InterruptedException {
        try {
            return new ClientAuthenticationCache(channel).get();
        } catch (IOException e) {
            stderr.println("Failed to access the stored credential");
            e.printStackTrace(stderr);  // recover
            return Hudson.ANONYMOUS;
        }
    }

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    /**
     * Determines if the user authentication is attempted through CLI before running this command.
     *
     * <p>
     * If your command doesn't require any authentication whatsoever, and if you don't even want to let the user
     * authenticate, then override this method to always return false &mdash; doing so will result in all the commands
     * running as anonymous user credential.
     *
     * <p>
     * Note that even if this method returns true, the user can still skip aut 
     *
     * @param auth
     *      Always non-null.
     *      If the underlying transport had already performed authentication, this object is something other than
     *      {@link Hudson#ANONYMOUS}.
     */
    protected boolean shouldPerformAuthentication(Authentication auth) {
        return auth==Hudson.ANONYMOUS;
    }

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
    /**
     * Returns the identity of the client as determined at the CLI transport level.
     *
     * <p>
     * When the CLI connection to the server is tunneled over HTTP, that HTTP connection
     * can authenticate the client, just like any other HTTP connections to the server
     * can authenticate the client. This method returns that information, if one is available.
     * By generalizing it, this method returns the identity obtained at the transport-level authentication.
     *
     * <p>
     * For example, imagine if the current {@link SecurityRealm} is doing Kerberos authentication,
     * then this method can return a valid identity of the client.
     *
     * <p>
     * If the transport doesn't do authentication, this method returns {@link Hudson#ANONYMOUS}.
     */
    public Authentication getTransportAuthentication() {
        Authentication a = channel.getProperty(TRANSPORT_AUTHENTICATION);
        if (a==null)    a = Hudson.ANONYMOUS;
        return a;
    }

248 249 250 251 252
    /**
     * Executes the command, and return the exit code.
     *
     * @return
     *      0 to indicate a success, otherwise an error code.
253 254 255 256 257 258
     * @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.
259
     */
260
    protected abstract int run() throws Exception;
261 262 263

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

268 269 270 271 272 273 274 275 276
    /**
     * Called while producing usage. This is a good method to override
     * to render the general description of the command that goes beyond
     * a single-line summary. 
     */
    protected void printUsageSummary(PrintStream stderr) {
        stderr.println(getShortDescription());
    }

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
    /**
     * Convenience method for subtypes to obtain the system property of the client.
     */
    protected String getClientSystemProperty(String name) throws IOException, InterruptedException {
        return channel.call(new GetSystemProperty(name));
    }

    private static final class GetSystemProperty implements Callable<String, IOException> {
        private final String name;

        private GetSystemProperty(String name) {
            this.name = name;
        }

        public String call() throws IOException {
            return System.getProperty(name);
        }

        private static final long serialVersionUID = 1L;
    }

298 299 300 301 302 303 304 305 306 307 308 309 310
    /**
     * 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);
        }
    }

311 312
    

313 314 315 316 317 318 319 320 321 322 323
    /**
     * 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) {
324 325 326
        for (CLICommand cmd : all())
            if(name.equals(cmd.getName()))
                return cmd.createClone();
327 328
        return null;
    }
329 330

    private static final Logger LOGGER = Logger.getLogger(CLICommand.class.getName());
J
jpederzolli 已提交
331

332 333 334 335 336
    /**
     * Key for {@link Channel#getProperty(Object)} that links to the {@link Authentication} object
     * which captures the identity of the client given by the transport layer.
     */
    public static final ChannelProperty<Authentication> TRANSPORT_AUTHENTICATION = new ChannelProperty<Authentication>(Authentication.class,"transportAuthentication");
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351

    private static final ThreadLocal<CLICommand> CURRENT_COMMAND = new ThreadLocal<CLICommand>();

    /*package*/ static CLICommand setCurrent(CLICommand cmd) {
        CLICommand old = getCurrent();
        CURRENT_COMMAND.set(cmd);
        return old;
    }

    /**
     * If the calling thread is in the middle of executing a CLI command, return it. Otherwise null.
     */
    public static CLICommand getCurrent() {
        return CURRENT_COMMAND.get();
    }
352
}