BuildCommand.java 9.3 KB
Newer Older
K
kohsuke 已提交
1 2 3
/*
 * The MIT License
 *
4
 * Copyright (c) 2004-2010, Sun Microsystems, Inc.
K
kohsuke 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
 *
 * 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.
 */
24 25
package hudson.cli;

26
import hudson.console.ModelHyperlinkNote;
27 28
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
29
import hudson.model.Cause.UserIdCause;
30 31 32 33
import hudson.model.ParametersAction;
import hudson.model.ParameterValue;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.ParameterDefinition;
34
import hudson.Extension;
35
import hudson.AbortException;
36
import hudson.model.Item;
37
import hudson.model.Result;
38
import hudson.model.TaskListener;
39
import hudson.model.queue.QueueTaskFuture;
40
import hudson.scm.PollingResult.Change;
41
import hudson.util.EditDistance;
42
import hudson.util.StreamTaskListener;
43 44 45
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

46 47 48 49 50
import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map.Entry;
E
Esa Laine 已提交
51
import java.io.FileNotFoundException;
52 53
import java.io.PrintStream;

54 55
import jenkins.model.Jenkins;

56 57 58 59 60 61 62 63 64
/**
 * Builds a job, and optionally waits until its completion.
 *
 * @author Kohsuke Kawaguchi
 */
@Extension
public class BuildCommand extends CLICommand {
    @Override
    public String getShortDescription() {
65
        return Messages.BuildCommand_ShortDescription();
66 67 68 69 70
    }

    @Argument(metaVar="JOB",usage="Name of the job to build",required=true)
    public AbstractProject<?,?> job;

71 72 73 74
    @Option(name="-f", usage="Follow the build progress. Like -s only interrupts are not passed through to the build.")
    public boolean follow = false;

    @Option(name="-s",usage="Wait until the completion/abortion of the command. Interrupts are passed through to the build.")
75 76
    public boolean sync = false;

77 78 79
    @Option(name="-w",usage="Wait until the start of the command")
    public boolean wait = false;

80 81 82
    @Option(name="-c",usage="Check for SCM changes before starting the build, and if there's no change, exit without doing a build")
    public boolean checkSCM = false;

83 84 85
    @Option(name="-p",usage="Specify the build parameters in the key=value format.")
    public Map<String,String> parameters = new HashMap<String, String>();

86 87 88
    @Option(name="-v",usage="Prints out the console output of the build. Use with -s")
    public boolean consoleOutput = false;

89 90
    @Option(name="-r") @Deprecated
    public int retryCnt = 10;
E
Esa Laine 已提交
91

92 93
    protected static final String BUILD_SCHEDULING_REFUSED = "Build scheduling Refused by an extension, hence not in Queue";

94
    protected int run() throws Exception {
95
        job.checkPermission(Item.BUILD);
96

97
        ParametersAction a = null;
98 99 100 101 102
        if (!parameters.isEmpty()) {
            ParametersDefinitionProperty pdp = job.getProperty(ParametersDefinitionProperty.class);
            if (pdp==null)
                throw new AbortException(job.getFullDisplayName()+" is not parameterized but the -p option was specified");

103
            List<ParameterValue> values = new ArrayList<ParameterValue>();
104 105 106 107 108 109 110 111 112

            for (Entry<String, String> e : parameters.entrySet()) {
                String name = e.getKey();
                ParameterDefinition pd = pdp.getParameterDefinition(name);
                if (pd==null)
                    throw new AbortException(String.format("\'%s\' is not a valid parameter. Did you mean %s?",
                            name, EditDistance.findNearest(name, pdp.getParameterDefinitionNames())));
                values.add(pd.createValue(this,e.getValue()));
            }
113 114 115 116 117 118 119 120 121 122

            // handle missing parameters by adding as default values ISSUE JENKINS-7162
            for(ParameterDefinition pd :  pdp.getParameterDefinitions()) {
                if (parameters.containsKey(pd.getName()))
                    continue;

                // not passed in use default
                values.add(pd.getDefaultParameterValue());
            }

123 124 125
            a = new ParametersAction(values);
        }

126
        if (checkSCM) {
127
            if (job.poll(new StreamTaskListener(stdout, getClientCharset())).change == Change.NONE) {
128 129 130 131
                return 0;
            }
        }

132
        if (!job.isBuildable()) {
133
            String msg = Messages.BuildCommand_CLICause_CannotBuildUnknownReasons(job.getFullDisplayName());
134
            if (job.isDisabled()) {
135
                msg = Messages.BuildCommand_CLICause_CannotBuildDisabled(job.getFullDisplayName());
136
            } else if (job.isHoldOffBuildUntilSave()){
137
                msg = Messages.BuildCommand_CLICause_CannotBuildConfigNotSaved(job.getFullDisplayName());
138
            }
139
            stderr.println(msg);
140
            return -1;
141
        }
142

143 144
        QueueTaskFuture<? extends AbstractBuild> f = job.scheduleBuild2(0, new CLICause(Jenkins.getAuthentication().getName()), a);
        
145
        if (wait || sync || follow) {
146
            if (f == null) {
147
                stderr.println(BUILD_SCHEDULING_REFUSED);
148 149
                return -1;
            }
150
            AbstractBuild b = f.waitForStart();    // wait for the start
151 152
            stdout.println("Started "+b.getFullDisplayName());

153
            if (sync || follow) {
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
                try {
                    if (consoleOutput) {
                        // read output in a retry loop, by default try only once
                        // writeWholeLogTo may fail with FileNotFound
                        // exception on a slow/busy machine, if it takes
                        // longish to create the log file
                        int retryInterval = 100;
                        for (int i=0;i<=retryCnt;) {
                            try {
                                b.writeWholeLogTo(stdout);
                                break;
                            }
                            catch (FileNotFoundException e) {
                                if ( i == retryCnt ) {
                                    throw e;
                                }
                                i++;
                                Thread.sleep(retryInterval);
E
Esa Laine 已提交
172 173 174
                            }
                        }
                    }
175 176 177 178
                    f.get();    // wait for the completion
                    stdout.println("Completed "+b.getFullDisplayName()+" : "+b.getResult());
                    return b.getResult().ordinal;
                } catch (InterruptedException e) {
179 180 181 182 183 184 185
                    if (follow) {
                        return 125;
                    } else {
                        // if the CLI is aborted, try to abort the build as well
                        f.cancel(true);
                        throw e;
                    }
186 187
                }
            }
188
        }
189

190
        return 0;
191 192 193 194 195 196 197 198 199
    }

    @Override
    protected void printUsageSummary(PrintStream stderr) {
        stderr.println(
            "Starts a build, and optionally waits for a completion.\n" +
            "Aside from general scripting use, this command can be\n" +
            "used to invoke another job from within a build of one job.\n" +
            "With the -s option, this command changes the exit code based on\n" +
200 201 202 203 204 205
            "the outcome of the build (exit code 0 indicates a success)\n" +
            "and interrupting the command will interrupt the job.\n" +
            "With the -f option, this command changes the exit code based on\n" +
            "the outcome of the build (exit code 0 indicates a success)\n" +
            "however, unlike -s, interrupting the command will not interrupt\n" +
            "the job (exit code 125 indicates the command was interrupted)\n" +
206 207
            "With the -c option, a build will only run if there has been\n" +
            "an SCM change"
208 209 210
        );
    }

211
    public static class CLICause extends UserIdCause {
212

213
    	private String startedBy;
214

215
    	public CLICause(){
216
    		startedBy = "unknown";
217
    	}
218

219 220 221
    	public CLICause(String startedBy){
    		this.startedBy = startedBy;
    	}
222

223
        @Override
224
        public String getShortDescription() {
225 226 227 228 229 230 231
            return Messages.BuildCommand_CLICause_ShortDescription(startedBy);
        }

        @Override
        public void print(TaskListener listener) {
            listener.getLogger().println(Messages.BuildCommand_CLICause_ShortDescription(
                    ModelHyperlinkNote.encodeTo("/user/" + startedBy, startedBy)));
232
        }
233 234 235 236 237 238 239 240 241 242

        @Override
        public boolean equals(Object o) {
            return o instanceof CLICause;
        }

        @Override
        public int hashCode() {
            return 7;
        }
243 244 245
    }
}