CLIAction.java 8.9 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 26 27 28 29 30 31 32 33
/*
 * The MIT License
 *
 * Copyright (c) 2013 Red Hat, 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;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

34
import hudson.model.UnprotectedRootAction;
35 36
import jenkins.model.Jenkins;

K
Kohsuke Kawaguchi 已提交
37
import org.jenkinsci.Symbol;
38 39
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
K
Kohsuke Kawaguchi 已提交
40 41
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerProxy;
42 43 44 45 46 47
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

import hudson.Extension;
import hudson.model.FullDuplexHttpChannel;
import hudson.remoting.Channel;
48 49 50 51 52 53 54 55 56 57 58 59 60
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.util.FullDuplexHttpService;
61 62

/**
K
Kohsuke Kawaguchi 已提交
63 64
 * Shows usage of CLI and commands.
 *
65 66
 * @author ogondza
 */
K
Kohsuke Kawaguchi 已提交
67
@Extension @Symbol("cli")
68
@Restricted(NoExternalUse.class)
69
public class CLIAction implements UnprotectedRootAction, StaplerProxy {
70

71 72 73
    private static final Logger LOGGER = Logger.getLogger(CLIAction.class.getName());

    private transient final Map<UUID, FullDuplexHttpService> duplexServices = new HashMap<>();
74 75 76 77 78 79 80 81 82 83

    public String getIconFileName() {
        return null;
    }

    public String getDisplayName() {
        return "Jenkins CLI";
    }

    public String getUrlName() {
84
        return jenkins.CLI.DISABLED ? null : "cli";
85 86 87
    }

    public void doCommand(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException {
88
        final Jenkins jenkins = Jenkins.getActiveInstance();
89 90 91 92 93 94
        jenkins.checkPermission(Jenkins.READ);

        // Strip trailing slash
        final String commandName = req.getRestOfPath().substring(1);
        CLICommand command = CLICommand.clone(commandName);
        if (command == null) {
95
            rsp.sendError(HttpServletResponse.SC_NOT_FOUND, "No such command");
96 97 98 99 100 101 102
            return;
        }

        req.setAttribute("command", command);
        req.getView(this, "command.jelly").forward(req, rsp);
    }

K
Kohsuke Kawaguchi 已提交
103 104 105 106 107 108 109 110
    @Override
    public Object getTarget() {
        StaplerRequest req = Stapler.getCurrentRequest();
        if (req.getRestOfPath().length()==0 && "POST".equals(req.getMethod())) {
            // CLI connection request
            throw new CliEndpointResponse();
        } else {
            return this;
111
        }
K
Kohsuke Kawaguchi 已提交
112
    }
113

K
Kohsuke Kawaguchi 已提交
114 115 116
    /**
     * Serves CLI-over-HTTP response.
     */
117 118 119 120 121 122
    private class CliEndpointResponse extends FullDuplexHttpService.Response {

        CliEndpointResponse() {
            super(duplexServices);
        }

K
Kohsuke Kawaguchi 已提交
123
        @Override
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        protected FullDuplexHttpService createService(StaplerRequest req, UUID uuid) throws IOException {
            // do not require any permission to establish a CLI connection
            // the actual authentication for the connecting Channel is done by CLICommand

            if ("false".equals(req.getParameter("remoting"))) {
                return new FullDuplexHttpService(uuid) {
                    @Override
                    protected void run(InputStream upload, OutputStream download) throws IOException, InterruptedException {
                        class ServerSideImpl extends PlainCLIProtocol.ServerSide {
                            List<String> args = new ArrayList<>();
                            Locale locale = Locale.getDefault();
                            Charset encoding = Charset.defaultCharset();
                            final PipedInputStream stdin = new PipedInputStream();
                            final PipedOutputStream stdinMatch = new PipedOutputStream();
                            ServerSideImpl(InputStream is, OutputStream os) throws IOException {
                                super(is, os);
                                stdinMatch.connect(stdin);
                            }
                            @Override
                            protected void onArg(String text) {
                                args.add(text);
                            }
                            @Override
                            protected void onLocale(String text) {
                                // TODO what is the opposite of Locale.toString()?
                            }
                            @Override
                            protected void onEncoding(String text) {
                                try {
                                    encoding = Charset.forName(text);
                                } catch (UnsupportedCharsetException x) {
                                    LOGGER.log(Level.WARNING, "unknown client charset {0}", text);
                                }
                            }
                            @Override
                            protected synchronized void onStart() {
160
                                notifyAll();
161 162 163 164 165 166 167 168 169
                            }
                            @Override
                            protected void onStdin(byte[] chunk) throws IOException {
                                stdinMatch.write(chunk);
                            }
                            @Override
                            protected void onEndStdin() throws IOException {
                                stdinMatch.close();
                            }
K
Kohsuke Kawaguchi 已提交
170
                        }
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
                        ServerSideImpl connection = new ServerSideImpl(upload, download);
                        connection.begin();
                        synchronized (connection) {
                            connection.wait(); // TODO this can wait indefinitely even when the connection is broken
                        }
                        PrintStream stdout = new PrintStream(connection.streamStdout(), false, connection.encoding.name());
                        PrintStream stderr = new PrintStream(connection.streamStderr(), true, connection.encoding.name());
                        String commandName = connection.args.get(0);
                        CLICommand command = CLICommand.clone(commandName);
                        if (command == null) {
                            stderr.println("No such command " + commandName);
                            connection.sendExit(2);
                            return;
                        }
                        command.setTransportAuth(Jenkins.getAuthentication());
                        command.setClientCharset(connection.encoding);
                        CLICommand orig = CLICommand.setCurrent(command);
                        try {
                            int exit = command.main(connection.args.subList(1, connection.args.size()), connection.locale, connection.stdin, stdout, stderr);
                            stdout.flush();
                            connection.sendExit(exit);
                        } finally {
                            CLICommand.setCurrent(orig);
                        }
                    }
                };
            } else {
                return new FullDuplexHttpChannel(uuid, !Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
199
                    @SuppressWarnings("deprecation")
200 201 202 203 204
                    @Override
                    protected void main(Channel channel) throws IOException, InterruptedException {
                        // capture the identity given by the transport, since this can be useful for SecurityRealm.createCliAuthenticator()
                        channel.setProperty(CLICommand.TRANSPORT_AUTHENTICATION, Jenkins.getAuthentication());
                        channel.setProperty(CliEntryPoint.class.getName(), new CliManagerImpl(channel));
K
Kohsuke Kawaguchi 已提交
205
                    }
206
                };
207 208 209 210
            }
        }
    }
}