UpdateSite.java 51.0 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
/*
 * The MIT License
 * 
 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., Seiji Sogabe,
 *                          Andrew Bayer
 * 
 * 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.model;

28
import hudson.ExtensionList;
29
import hudson.PluginManager;
30
import hudson.PluginWrapper;
31
import hudson.Util;
32
import hudson.lifecycle.Lifecycle;
33 34 35
import hudson.model.UpdateCenter.UpdateCenterJob;
import hudson.util.FormValidation;
import hudson.util.FormValidation.Kind;
36
import hudson.util.HttpResponses;
37
import static jenkins.util.MemoryReductionUtil.*;
38
import hudson.util.TextFile;
B
Baptiste Mathus 已提交
39
import static java.util.concurrent.TimeUnit.*;
40 41 42
import hudson.util.VersionNumber;
import java.io.File;
import java.io.IOException;
43
import java.net.URI;
44
import java.net.URL;
45
import java.net.URLEncoder;
46 47
import java.util.ArrayList;
import java.util.Collections;
48
import java.util.HashSet;
49
import java.util.List;
50
import java.util.Locale;
51 52
import java.util.Map;
import java.util.Set;
53
import java.util.TreeMap;
54
import java.util.UUID;
55
import java.util.concurrent.Callable;
56
import java.util.concurrent.Future;
57
import java.util.function.Predicate;
58 59
import java.util.logging.Level;
import java.util.logging.Logger;
60 61
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
62 63
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
64 65
import javax.annotation.Nullable;

66
import io.jenkins.lib.versionnumber.JavaSpecificationVersion;
67
import jenkins.model.Jenkins;
68
import jenkins.plugins.DetachedPluginsUtil;
69
import jenkins.security.UpdateSiteWarningsConfiguration;
70
import jenkins.util.JSONSignatureValidator;
71
import jenkins.util.SystemProperties;
72
import jenkins.util.java.JavaUtils;
73
import net.sf.json.JSONArray;
74 75 76 77
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
78
import org.kohsuke.accmod.restrictions.DoNotUse;
79 80 81 82 83 84
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
85 86

/**
K
Kohsuke Kawaguchi 已提交
87
 * Source of the update center information, like "http://jenkins-ci.org/update-center.json"
88 89
 *
 * <p>
A
alanharder 已提交
90
 * Jenkins can have multiple {@link UpdateSite}s registered in the system, so that it can pick up plugins
91 92 93 94
 * from different locations.
 *
 * @author Andrew Bayer
 * @author Kohsuke Kawaguchi
95
 * @since 1.333
96
 */
97
@ExportedBean
98 99 100
public class UpdateSite {
    /**
     * What's the time stamp of data file?
101
     * 0 means never.
102
     */
103
    private transient volatile long dataTimestamp;
104 105 106

    /**
     * When was the last time we asked a browser to check the data for us?
107
     * 0 means never.
108 109 110
     *
     * <p>
     * There's normally some delay between when we send HTML that includes the check code,
111
     * until we get the data back, so this variable is used to avoid asking too many browsers
112 113
     * all at once.
     */
114
    private transient volatile long lastAttempt;
115

116 117 118 119 120 121
    /**
     * If the attempt to fetch data fails, we progressively use longer time out before retrying,
     * to avoid overloading the server.
     */
    private transient volatile long retryWindow;

122 123 124
    /**
     * Latest data as read from the data file.
     */
125
    private transient Data data;
126

127 128 129 130 131 132
    /**
     * ID string for this update source.
     */
    private final String id;

    /**
133
     * Path to {@code update-center.json}, like {@code http://jenkins-ci.org/update-center.json}.
134 135 136
     */
    private final String url;

137 138 139 140
    /**
     * the prefix for the signature validator name
     */
    private static final String signatureValidatorPrefix = "update site";
141

142
    private static final Set<String> warnedMissing = Collections.synchronizedSet(new HashSet<>());
143

144 145 146 147 148 149 150 151
    public UpdateSite(String id, String url) {
        this.id = id;
        this.url = url;
    }

    /**
     * Get ID string.
     */
152
    @Exported
153 154 155 156
    public String getId() {
        return id;
    }

157
    @Exported
158
    public long getDataTimestamp() {
159
        assert dataTimestamp >= 0;
160 161 162
        return dataTimestamp;
    }

163
    /**
164
     * Update the data file from the given URL if the file
165
     * does not exist, or is otherwise due for update.
166 167
     * Accepted formats are JSONP or HTML with {@code postMessage}, not raw JSON.
     * @param signatureCheck whether to enforce the signature (may be off only for testing!)
168
     * @return null if no updates are necessary, or the future result
169
     * @since 1.502
170
     */
171
    public @CheckForNull Future<FormValidation> updateDirectly(final boolean signatureCheck) {
172
        if (! getDataFile().exists() || isDue()) {
173
            return Jenkins.get().getUpdateCenter().updateService.submit(new Callable<FormValidation>() {
174 175
                @Override public FormValidation call() throws Exception {
                    return updateDirectlyNow(signatureCheck);
176 177
                }
            });
178
        } else {
179
            return null;
180 181 182 183 184 185
        }
    }

    @Restricted(NoExternalUse.class)
    public @Nonnull FormValidation updateDirectlyNow(boolean signatureCheck) throws IOException {
        return updateData(DownloadService.loadJSON(new URL(getUrl() + "?id=" + URLEncoder.encode(getId(), "UTF-8") + "&version=" + URLEncoder.encode(Jenkins.VERSION, "UTF-8"))), signatureCheck);
186 187
    }
    
188
    private FormValidation updateData(String json, boolean signatureCheck)
189 190 191 192
            throws IOException {

        dataTimestamp = System.currentTimeMillis();

193 194
        JSONObject o = JSONObject.fromObject(json);

195 196 197 198 199 200 201 202
        try {
            int v = o.getInt("updateCenterVersion");
            if (v != 1) {
                throw new IllegalArgumentException("Unrecognized update center version: " + v);
            }
        } catch (JSONException x) {
            throw new IllegalArgumentException("Could not find (numeric) updateCenterVersion in " + json, x);
        }
203 204 205

        if (signatureCheck) {
            FormValidation e = verifySignature(o);
206
            if (e.kind!=Kind.OK) {
207
                LOGGER.severe(e.toString());
208 209
                return e;
            }
210 211
        }

212
        LOGGER.finest("Obtained the latest update center data file for UpdateSource " + id);
213
        retryWindow = 0;
214
        getDataFile().write(json);
215
        data = new Data(o);
216 217 218 219 220
        return FormValidation.ok();
    }

    public FormValidation doVerifySignature() throws IOException {
        return verifySignature(getJSONObject());
221 222
    }

223 224 225 226 227 228 229 230 231 232 233 234 235 236
    /**
     * Extension point to allow implementations of {@link UpdateSite} to create a custom
     * {@link UpdateCenter.InstallationJob}.
     *
     * @param plugin      the plugin to create the {@link UpdateCenter.InstallationJob} for.
     * @param uc          the {@link UpdateCenter}.
     * @param dynamicLoad {@code true} if the plugin should be attempted to be dynamically loaded.
     * @return the {@link UpdateCenter.InstallationJob}.
     * @since 2.9
     */
    protected UpdateCenter.InstallationJob createInstallationJob(Plugin plugin, UpdateCenter uc, boolean dynamicLoad) {
        return uc.new InstallationJob(plugin, this, Jenkins.getAuthentication(), dynamicLoad);
    }

237 238 239
    /**
     * Verifies the signature in the update center data file.
     */
240
    private FormValidation verifySignature(JSONObject o) throws IOException {
241 242 243 244 245 246
        return getJsonSignatureValidator().verifySignature(o);
    }

    /**
     * Let sub-classes of UpdateSite provide their own signature validator.
     * @return the signature validator.
B
Basil Crow 已提交
247
     * @deprecated use {@link #getJsonSignatureValidator(String)} instead.
248
     */
249
    @Deprecated
250 251
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator() {
252 253 254 255 256 257 258 259 260
        return getJsonSignatureValidator(null);
    }

    /**
     * Let sub-classes of UpdateSite provide their own signature validator.
     * @param name, the name for the JSON signature Validator object.
     *              if name is null, then the default name will be used,
     *              which is "update site" followed by the update site id
     * @return the signature validator.
261
     * @since 2.21
262 263 264 265 266 267 268
     */
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator(@CheckForNull String name) {
        if (name == null) {
            name = signatureValidatorPrefix + " '" + id + "'";
        }
        return new JSONSignatureValidator(name);
269 270 271 272 273
    }

    /**
     * Returns true if it's time for us to check for new version.
     */
J
Josh Soref 已提交
274
    public synchronized boolean isDue() {
275
        if(neverUpdate)     return false;
276
        if(dataTimestamp == 0)
277 278
            dataTimestamp = getDataFile().file.lastModified();
        long now = System.currentTimeMillis();
279

280 281 282 283 284 285 286
        retryWindow = Math.max(retryWindow,SECONDS.toMillis(15));
        
        boolean due = now - dataTimestamp > DAY && now - lastAttempt > retryWindow;
        if(due) {
            lastAttempt = now;
            retryWindow = Math.min(retryWindow*2, HOURS.toMillis(1)); // exponential back off but at most 1 hour
        }
287 288 289
        return due;
    }

290 291 292 293 294
    /**
     * Invalidates the cached data and force retrieval.
     *
     * @since 1.432
     */
295
    @RequirePOST
296
    public HttpResponse doInvalidateData() {
297
        Jenkins.get().checkPermission(Jenkins.ADMINISTER);
298
        dataTimestamp = 0;
299
        data = null;
300 301 302
        return HttpResponses.ok();
    }

303
    /**
304
     * Loads the update center data, if any.
305 306 307 308
     *
     * @return  null if no data is available.
     */
    public Data getData() {
309
        if (data == null) {
310
            JSONObject o = getJSONObject();
311
            if (o != null) {
312 313 314 315
                data = new Data(o);
            }
        }
        return data;
316 317
    }

318 319 320
    /**
     * Whether {@link #getData} might be blocking.
     */
321
    // Internal use only
322 323 324 325
    boolean hasUnparsedData() {
        return data == null && getDataFile().exists();
    }

326 327 328 329
    /**
     * Gets the raw update center JSON data.
     */
    public JSONObject getJSONObject() {
330 331
        TextFile df = getDataFile();
        if(df.exists()) {
332
            long start = System.nanoTime();
333
            try {
334
                JSONObject o = JSONObject.fromObject(df.read());
335
                LOGGER.fine(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0));
336
                return o;
337
            } catch (JSONException | IOException e) {
338 339 340 341 342 343 344 345
                LOGGER.log(Level.SEVERE,"Failed to parse "+df,e);
                df.delete(); // if we keep this file, it will cause repeated failures
                return null;
            }
        } else {
            return null;
        }
    }
346

347 348 349 350
    /**
     * Returns a list of plugins that should be shown in the "available" tab.
     * These are "all plugins - installed plugins".
     */
351
    @Exported
352
    public List<Plugin> getAvailables() {
353
        List<Plugin> r = new ArrayList<>();
354
        Data data = getData();
355
        if(data==null)     return Collections.emptyList();
356 357 358 359 360 361
        for (Plugin p : data.plugins.values()) {
            if(p.getInstalled()==null)
                r.add(p);
        }
        return r;
    }
362

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
    /**
     * Gets the information about a specific plugin.
     *
     * @param artifactId
     *      The short name of the plugin. Corresponds to {@link PluginWrapper#getShortName()}.
     *
     * @return
     *      null if no such information is found.
     */
    public Plugin getPlugin(String artifactId) {
        Data dt = getData();
        if(dt==null)    return null;
        return dt.plugins.get(artifactId);
    }

378 379 380 381
    public Api getApi() {
        return new Api(this);
    }

382
    /**
383 384
     * Gets a URL for the Internet connection check.
     * @return  an "always up" server for Internet connectivity testing, or {@code null} if we are going to skip the test.
385
     */
386
    @Exported
387
    @CheckForNull
388 389 390 391 392 393 394 395 396 397
    public String getConnectionCheckUrl() {
        Data dt = getData();
        if(dt==null)    return "http://www.google.com/";
        return dt.connectionCheckUrl;
    }

    /**
     * This is where we store the update center data.
     */
    private TextFile getDataFile() {
398
        return new TextFile(new File(Jenkins.get().getRootDir(),
399 400 401 402 403 404 405 406 407
                                     "updates/" + getId()+".json"));
    }
    
    /**
     * Returns the list of plugins that are updates to currently installed ones.
     *
     * @return
     *      can be empty but never null.
     */
408
    @Exported
409 410 411 412
    public List<Plugin> getUpdates() {
        Data data = getData();
        if(data==null)      return Collections.emptyList(); // fail to determine
        
413
        List<Plugin> r = new ArrayList<>();
414
        for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) {
415 416 417 418 419 420 421 422 423 424
            Plugin p = pw.getUpdateInfo();
            if(p!=null) r.add(p);
        }
        
        return r;
    }
    
    /**
     * Does any of the plugin has updates?
     */
425
    @Exported
426 427 428 429
    public boolean hasUpdates() {
        Data data = getData();
        if(data==null)      return false;
        
430
        for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) {
431 432
            if(!pw.isBundled() && pw.getUpdateInfo()!=null)
                // do not advertize updates to bundled plugins, since we generally want users to get them
A
alanharder 已提交
433
                // as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins. 
434 435 436 437 438 439 440 441 442 443
                return true;
        }
        return false;
    }
    
    
    /**
     * Exposed to get rid of hardcoding of the URL that serves up update-center.json
     * in Javascript.
     */
444
    @Exported
445 446 447 448
    public String getUrl() {
        return url;
    }

449 450 451 452 453

    /**
     * URL which exposes the metadata location in a specific update site.
     * @param downloadable, the downloadable id of a specific metatadata json (e.g. hudson.tasks.Maven.MavenInstaller.json)
     * @return the location
454
     * @since 2.20
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
     */
    @CheckForNull
    @Restricted(NoExternalUse.class)
    public String getMetadataUrlForDownloadable(String downloadable) {
        String siteUrl = getUrl();
        String updateSiteMetadataUrl = null;
        int baseUrlEnd = siteUrl.indexOf("update-center.json");
        if (baseUrlEnd != -1) {
            String siteBaseUrl = siteUrl.substring(0, baseUrlEnd);
            updateSiteMetadataUrl = siteBaseUrl + "updates/" + downloadable;
        } else {
            LOGGER.log(Level.WARNING, "Url {0} does not look like an update center:", siteUrl);
        }
        return updateSiteMetadataUrl;
    }

471 472 473 474 475 476
    /**
     * Where to actually download the update center?
     *
     * @deprecated
     *      Exposed only for UI.
     */
477
    @Deprecated
478 479 480 481
    public String getDownloadUrl() {
        return url;
    }

K
kohsuke 已提交
482 483 484 485
    /**
     * Is this the legacy default update center site?
     */
    public boolean isLegacyDefault() {
486 487 488 489 490 491 492 493 494
        return isHudsonCI() || isUpdatesFromHudsonLabs();
    }

    private boolean isHudsonCI() {
        return url != null && UpdateCenter.PREDEFINED_UPDATE_SITE_ID.equals(id) && url.startsWith("http://hudson-ci.org/");
    }

    private boolean isUpdatesFromHudsonLabs() {
        return url != null && url.startsWith("http://updates.hudson-labs.org/");
K
kohsuke 已提交
495 496
    }

497 498 499 500 501 502 503 504 505 506
    /**
     * In-memory representation of the update center data.
     */
    public final class Data {
        /**
         * The {@link UpdateSite} ID.
         */
        public final String sourceId;

        /**
A
alanharder 已提交
507
         * The latest jenkins.war.
508 509 510 511 512
         */
        public final Entry core;
        /**
         * Plugins in the repository, keyed by their artifact IDs.
         */
513
        public final Map<String,Plugin> plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
514 515 516
        /**
         * List of warnings (mostly security) published with the update site.
         *
517
         * @since 2.40
518
         */
519
        private final Set<Warning> warnings = new HashSet<>();
520 521

        /**
A
alanharder 已提交
522
         * If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
523 524 525 526 527
         * the network connection is up. Null to skip the check.
         */
        public final String connectionCheckUrl;

        Data(JSONObject o) {
528
            this.sourceId = Util.intern((String)o.get("id"));
529 530 531 532
            JSONObject c = o.optJSONObject("core");
            if (c!=null) {
                core = new Entry(sourceId, c, url);
            } else {
533 534
                core = null;
            }
535 536 537 538 539 540 541 542 543 544 545 546

            JSONArray w = o.optJSONArray("warnings");
            if (w != null) {
                for (int i = 0; i < w.size(); i++) {
                    try {
                        warnings.add(new Warning(w.getJSONObject(i)));
                    } catch (JSONException ex) {
                        LOGGER.log(Level.WARNING, "Failed to parse JSON for warning", ex);
                    }
                }
            }

547
            for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) {
548 549
                Plugin p = new Plugin(sourceId, e.getValue());
                // JENKINS-33308 - include implied dependencies for older plugins that may need them
550
                List<PluginWrapper.Dependency> implicitDeps = DetachedPluginsUtil.getImpliedDependencies(p.name, p.requiredCore);
551 552 553 554 555 556 557
                if(!implicitDeps.isEmpty()) {
                    for(PluginWrapper.Dependency dep : implicitDeps) {
                        if(!p.dependencies.containsKey(dep.shortName)) {
                            p.dependencies.put(dep.shortName, dep.version);
                        }
                    }
                }
558
                plugins.put(Util.intern(e.getKey()), p);
559 560 561 562 563
            }

            connectionCheckUrl = (String)o.get("connectionCheckUrl");
        }

564 565 566
        /**
         * Returns the set of warnings
         * @return the set of warnings
567
         * @since 2.40
568 569 570 571 572 573
         */
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
            return this.warnings;
        }

574 575 576 577
        /**
         * Is there a new version of the core?
         */
        public boolean hasCoreUpdates() {
578
            return core != null && core.isNewerThan(Jenkins.VERSION);
579 580 581 582 583 584 585 586 587 588
        }

        /**
         * Do we support upgrade?
         */
        public boolean canUpgrade() {
            return Lifecycle.get().canRewriteHudsonWar();
        }
    }

589
    @ExportedBean
590 591 592 593
    public static class Entry {
        /**
         * {@link UpdateSite} ID.
         */
594
        @Exported
595 596 597 598 599
        public final String sourceId;

        /**
         * Artifact ID.
         */
600
        @Exported
601 602 603 604
        public final String name;
        /**
         * The version.
         */
605
        @Exported
606 607 608 609
        public final String version;
        /**
         * Download URL.
         */
610
        @Exported
611 612
        public final String url;

613 614 615 616

        // non-private, non-final for test
        @Restricted(NoExternalUse.class)
        /* final */ String sha1;
617

618 619 620 621 622 623
        @Restricted(NoExternalUse.class)
        /* final */ String sha256;

        @Restricted(NoExternalUse.class)
        /* final */ String sha512;

624
        public Entry(String sourceId, JSONObject o) {
625 626 627 628
            this(sourceId, o, null);
        }

        Entry(String sourceId, JSONObject o, String baseURL) {
629
            this.sourceId = sourceId;
630 631
            this.name = Util.intern(o.getString("name"));
            this.version = Util.intern(o.getString("version"));
632 633 634

            // Trim this to prevent issues when the other end used Base64.encodeBase64String that added newlines
            // to the end in old commons-codec. Not the case on updates.jenkins-ci.org, but let's be safe.
635
            this.sha1 = Util.fixEmptyAndTrim(o.optString("sha1"));
636 637
            this.sha256 = Util.fixEmptyAndTrim(o.optString("sha256"));
            this.sha512 = Util.fixEmptyAndTrim(o.optString("sha512"));
638

639 640 641 642 643 644 645 646
            String url = o.getString("url");
            if (!URI.create(url).isAbsolute()) {
                if (baseURL == null) {
                    throw new IllegalArgumentException("Cannot resolve " + url + " without a base URL");
                }
                url = URI.create(baseURL).resolve(url).toString();
            }
            this.url = url;
647 648
        }

649 650 651
        /**
         * The base64 encoded binary SHA-1 checksum of the file.
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
652
         * @since 1.641 (and 1.625.3 LTS)
653 654 655 656 657 658
         */
        // TODO @Exported assuming we want this in the API
        public String getSha1() {
            return sha1;
        }

659
        /**
660
         * The base64 encoded SHA-256 checksum of the file.
661
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
662
         * @since 2.130
663 664 665 666 667 668
         */
        public String getSha256() {
            return sha256;
        }

        /**
669
         * The base64 encoded SHA-512 checksum of the file.
670
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
671
         * @since 2.130
672 673 674 675 676
         */
        public String getSha512() {
            return sha512;
        }

677 678 679 680 681 682 683 684 685 686 687
        /**
         * Checks if the specified "current version" is older than the version of this entry.
         *
         * @param currentVersion
         *      The string that represents the version number to be compared.
         * @return
         *      true if the version listed in this entry is newer.
         *      false otherwise, including the situation where the strings couldn't be parsed as version numbers.
         */
        public boolean isNewerThan(String currentVersion) {
            try {
688
                return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
689 690 691 692 693
            } catch (IllegalArgumentException e) {
                // couldn't parse as the version number.
                return false;
            }
        }
694

695 696 697 698
        public Api getApi() {
            return new Api(this);
        }

699 700
    }

701 702 703 704 705 706 707 708
    /**
     * A version range for {@code Warning}s indicates which versions of a given plugin are affected
     * by it.
     *
     * {@link #name}, {@link #firstVersion} and {@link #lastVersion} fields are only used for administrator notices.
     *
     * The {@link #pattern} is used to determine whether a given warning applies to the current installation.
     *
709
     * @since 2.40
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
     */
    @Restricted(NoExternalUse.class)
    public static final class WarningVersionRange {
        /**
         * Human-readable English name for this version range, e.g. 'regular', 'LTS', '2.6 line'.
         */
        @Nullable
        public final String name;

        /**
         * First version in this version range to be subject to the warning.
         */
        @Nullable
        public final String firstVersion;

        /**
         * Last version in this version range to be subject to the warning.
         */
        @Nullable
        public final String lastVersion;

        /**
         * Regular expression pattern for this version range that matches all included version numbers.
         */
        @Nonnull
        private final Pattern pattern;

        public WarningVersionRange(JSONObject o) {
            this.name = Util.fixEmpty(o.optString("name"));
739 740
            this.firstVersion = Util.intern(Util.fixEmpty(o.optString("firstVersion")));
            this.lastVersion = Util.intern(Util.fixEmpty(o.optString("lastVersion")));
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
            Pattern p;
            try {
                p = Pattern.compile(o.getString("pattern"));
            } catch (PatternSyntaxException ex) {
                LOGGER.log(Level.WARNING, "Failed to compile pattern '" + o.getString("pattern") + "', using '.*' instead", ex);
                p = Pattern.compile(".*");
            }
            this.pattern = p;
        }

        public boolean includes(VersionNumber number) {
            return pattern.matcher(number.toString()).matches();
        }
    }

    /**
     * Represents a warning about a certain component, mostly related to known security issues.
     *
     * @see UpdateSiteWarningsConfiguration
     * @see jenkins.security.UpdateSiteWarningsMonitor
     *
762
     * @since 2.40
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
     */
    @Restricted(NoExternalUse.class)
    public static final class Warning {

        public enum Type {
            CORE,
            PLUGIN,
            UNKNOWN
        }

        /**
         * The type classifier for this warning.
         */
        @Nonnull
        public /* final */ Type type;

        /**
         * The globally unique ID of this warning.
         *
         * <p>This is typically the CVE identifier or SECURITY issue (Jenkins project);
         * possibly with a unique suffix (e.g. artifactId) if either applies to multiple components.</p>
         */
        @Exported
        @Nonnull
        public final String id;

        /**
         * The name of the affected component.
         * <ul>
         *   <li>If type is 'core', this is 'core' by convention.
         *   <li>If type is 'plugin', this is the artifactId of the affected plugin
         * </ul>
         */
        @Exported
        @Nonnull
        public final String component;

        /**
         * A short, English language explanation for this warning.
         */
        @Exported
        @Nonnull
        public final String message;

        /**
         * A URL with more information about this, typically a security advisory. For use in administrator notices
         * only, so
         */
        @Exported
        @Nonnull
        public final String url;

        /**
         * A list of named version ranges specifying which versions of the named component this warning applies to.
         *
         * If this list is empty, all versions of the component are considered to be affected by this warning.
         */
        @Exported
        @Nonnull
        public final List<WarningVersionRange> versionRanges;

        /**
         *
         * @param o the {@link JSONObject} representing the warning
         * @throws JSONException if the argument does not match the expected format
         */
        @Restricted(NoExternalUse.class)
        public Warning(JSONObject o) {
            try {
                this.type = Type.valueOf(o.getString("type").toUpperCase(Locale.US));
            } catch (IllegalArgumentException ex) {
                this.type = Type.UNKNOWN;
            }
            this.id = o.getString("id");
837
            this.component = Util.intern(o.getString("name"));
838 839 840 841 842
            this.message = o.getString("message");
            this.url = o.getString("url");

            if (o.has("versions")) {
                JSONArray versions = o.getJSONArray("versions");
843
                List<WarningVersionRange> ranges = new ArrayList<>(versions.size());
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894
                for (int i = 0; i < versions.size(); i++) {
                    WarningVersionRange range = new WarningVersionRange(versions.getJSONObject(i));
                    ranges.add(range);
                }
                this.versionRanges = Collections.unmodifiableList(ranges);
            } else {
                this.versionRanges = Collections.emptyList();
            }
        }

        /**
         * Two objects are considered equal if they are the same type and have the same ID.
         *
         * @param o the other object
         * @return true iff this object and the argument are considered equal
         */
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (!(o instanceof Warning)) return false;

            Warning warning = (Warning) o;

            return id.equals(warning.id);
        }

        @Override
        public int hashCode() {
            return id.hashCode();
        }

        public boolean isPluginWarning(@Nonnull String pluginName) {
            return type == Type.PLUGIN && pluginName.equals(this.component);
        }

        /**
         * Returns true if this warning is relevant to the current configuration
         * @return true if this warning is relevant to the current configuration
         */
        public boolean isRelevant() {
            switch (this.type) {
                case CORE:
                    VersionNumber current = Jenkins.getVersion();

                    if (!isRelevantToVersion(current)) {
                        return false;
                    }
                    return true;
                case PLUGIN:

                    // check whether plugin is installed
895
                    PluginWrapper plugin = Jenkins.get().getPluginManager().getPlugin(this.component);
896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
                    if (plugin == null) {
                        return false;
                    }

                    // check whether warning is relevant to installed version
                    VersionNumber currentCore = plugin.getVersionNumber();
                    if (!isRelevantToVersion(currentCore)) {
                        return false;
                    }
                    return true;
                case UNKNOWN:
                default:
                    return false;
            }
        }

        public boolean isRelevantToVersion(@Nonnull VersionNumber version) {
            if (this.versionRanges.isEmpty()) {
                // no version ranges specified, so all versions are affected
                return true;
            }

            for (UpdateSite.WarningVersionRange range : this.versionRanges) {
                if (range.includes(version)) {
                    return true;
                }
            }
            return false;
        }
    }

927 928 929 930 931 932 933 934 935 936
    private static String get(JSONObject o, String prop) {
        if(o.has(prop))
            return o.getString(prop);
        else
            return null;
    }

    static final Predicate<Object> IS_DEP_PREDICATE = x -> x instanceof JSONObject && get(((JSONObject)x), "name") != null;
    static final Predicate<Object> IS_NOT_OPTIONAL = x-> "false".equals(get(((JSONObject)x), "optional"));

937 938 939 940
    public final class Plugin extends Entry {
        /**
         * Optional URL to the Wiki page that discusses this plugin.
         */
941
        @Exported
942 943 944 945 946 947 948 949
        public final String wiki;
        /**
         * Human readable title of the plugin, taken from Wiki page.
         * Can be null.
         *
         * <p>
         * beware of XSS vulnerability since this data comes from Wiki
         */
950
        @Exported
951 952 953 954
        public final String title;
        /**
         * Optional excerpt string.
         */
955
        @Exported
956 957 958 959
        public final String excerpt;
        /**
         * Optional version # from which this plugin release is configuration-compatible.
         */
960
        @Exported
961
        public final String compatibleSinceVersion;
962
        /**
A
alanharder 已提交
963
         * Version of Jenkins core this plugin was compiled against.
964
         */
965
        @Exported
966
        public final String requiredCore;
967 968 969
        /**
         * Version of Java this plugin requires to run.
         *
970
         * @since 2.158
971 972
         */
        @Exported
973
        public final String minimumJavaVersion;
974 975 976 977
        /**
         * Categories for grouping plugins, taken from labels assigned to wiki page.
         * Can be null.
         */
978
        @Exported
979
        public final String[] categories;
980

981
        /**
982
         * Dependencies of this plugin, a name -&gt; version mapping.
983
         */
984
        @Exported
985
        public final Map<String,String> dependencies;
986
        
987 988 989 990
        /**
         * Optional dependencies of this plugin.
         */
        @Exported
991
        public final Map<String,String> optionalDependencies;
992

993 994 995 996 997
        /**
         * Set of plugins, this plugin is a incompatible dependency to.
         */
        private Set<Plugin> incompatibleParentPlugins;

998 999
        @DataBoundConstructor
        public Plugin(String sourceId, JSONObject o) {
1000
            super(sourceId, o, UpdateSite.this.url);
1001 1002 1003
            this.wiki = get(o,"wiki");
            this.title = get(o,"title");
            this.excerpt = get(o,"excerpt");
1004
            this.compatibleSinceVersion = Util.intern(get(o,"compatibleSinceVersion"));
1005
            this.minimumJavaVersion = Util.intern(get(o, "minimumJavaVersion"));
1006 1007 1008 1009 1010 1011 1012
            this.requiredCore = Util.intern(get(o,"requiredCore"));
            this.categories = o.has("labels") ? internInPlace((String[])o.getJSONArray("labels").toArray(EMPTY_STRING_ARRAY)) : null;
            JSONArray ja = o.getJSONArray("dependencies");
            int depCount = (int)(ja.stream().filter(IS_DEP_PREDICATE.and(IS_NOT_OPTIONAL)).count());
            int optionalDepCount = (int)(ja.stream().filter(IS_DEP_PREDICATE.and(IS_NOT_OPTIONAL.negate())).count());
            dependencies = getPresizedMutableMap(depCount);
            optionalDependencies = getPresizedMutableMap(optionalDepCount);
1013

1014 1015
            for(Object jo : o.getJSONArray("dependencies")) {
                JSONObject depObj = (JSONObject) jo;
1016
                // Make sure there's a name attribute and that the optional value isn't true.
1017 1018
                String depName = Util.intern(get(depObj,"name"));
                if (depName!=null) {
1019
                    if (get(depObj, "optional").equals("false")) {
1020
                        dependencies.put(depName, Util.intern(get(depObj, "version")));
1021
                    } else {
1022
                        optionalDependencies.put(depName, Util.intern(get(depObj, "version")));
1023
                    }
1024 1025 1026
                }
            }

1027 1028
        }

1029

1030 1031

        public String getDisplayName() {
1032 1033 1034 1035 1036 1037
            String displayName;
            if(title!=null)
                displayName = title;
            else
                displayName = name;
            return StringUtils.removeStart(displayName, "Jenkins ");
1038 1039 1040 1041 1042 1043
        }

        /**
         * If some version of this plugin is currently installed, return {@link PluginWrapper}.
         * Otherwise null.
         */
1044
        @Exported
1045
        public PluginWrapper getInstalled() {
1046
            PluginManager pm = Jenkins.get().getPluginManager();
1047 1048 1049
            return pm.getPlugin(name);
        }

1050 1051 1052 1053
        /**
         * Returns true if the plugin and its dependencies are fully compatible with the current installation
         * This is set to restricted for now, since it is only being used by Jenkins UI at the moment.
         *
1054
         * @since 2.175
1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
         */
        @Restricted(NoExternalUse.class)
        public boolean isCompatible() {
            return isCompatible(new PluginManager.MetadataCache());
        }

        @Restricted(NoExternalUse.class) // table.jelly
        public boolean isCompatible(PluginManager.MetadataCache cache) {
            return isCompatibleWithInstalledVersion() && !isForNewerHudson() &&  !isForNewerJava() &&
                    isNeededDependenciesCompatibleWithInstalledVersion(cache) &&
                    !isNeededDependenciesForNewerJenkins(cache) && !isNeededDependenciesForNewerJava();
        }

1068 1069 1070 1071 1072 1073 1074
        /**
         * If the plugin is already installed, and the new version of the plugin has a "compatibleSinceVersion"
         * value (i.e., it's only directly compatible with that version or later), this will check to
         * see if the installed version is older than the compatible-since version. If it is older, it'll return false.
         * If it's not older, or it's not installed, or it's installed but there's no compatibleSinceVersion
         * specified, it'll return true.
         */
1075
        @Exported
1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
        public boolean isCompatibleWithInstalledVersion() {
            PluginWrapper installedVersion = getInstalled();
            if (installedVersion != null) {
                if (compatibleSinceVersion != null) {
                    if (new VersionNumber(installedVersion.getVersion())
                            .isOlderThan(new VersionNumber(compatibleSinceVersion))) {
                        return false;
                    }
                }
            }
            return true;
        }

1089 1090 1091
        /**
         * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work.
         */
1092
        @Exported
1093
        public List<Plugin> getNeededDependencies() {
1094
            List<Plugin> deps = new ArrayList<>();
1095

1096
            for(Map.Entry<String,String> e : dependencies.entrySet()) {
1097
                VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
1098
                Plugin depPlugin = Jenkins.get().getUpdateCenter().getPlugin(e.getKey(), requiredVersion);
1099
                if (depPlugin == null) {
1100
                    LOGGER.log(warnedMissing.add(e.getKey()) ? Level.WARNING : Level.FINE, "Could not find dependency {0} of {1}", new Object[] {e.getKey(), name});
1101 1102
                    continue;
                }
1103

1104
                // Is the plugin installed already? If not, add it.
1105 1106 1107
                PluginWrapper current = depPlugin.getInstalled();

                if (current ==null) {
1108 1109 1110 1111
                    deps.add(depPlugin);
                }
                // If the dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
1112
                else if (current.isOlderThan(requiredVersion)) {
1113 1114
                    deps.add(depPlugin);
                }
1115 1116 1117 1118
                // JENKINS-34494 - or if the plugin is disabled, this will allow us to enable it
                else if (!current.isEnabled()) {
                    deps.add(depPlugin);
                }
1119 1120
            }

1121
            for(Map.Entry<String,String> e : optionalDependencies.entrySet()) {
1122
                VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
1123
                Plugin depPlugin = Jenkins.get().getUpdateCenter().getPlugin(e.getKey(), requiredVersion);
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
                if (depPlugin == null) {
                    continue;
                }

                PluginWrapper current = depPlugin.getInstalled();

                // If the optional dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
                if (current != null && current.isOlderThan(requiredVersion)) {
                    deps.add(depPlugin);
                }
            }

1137 1138 1139
            return deps;
        }
        
1140
        public boolean isForNewerHudson() {
1141 1142
            try {
                return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
1143
                  new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
1144 1145 1146
            } catch (NumberFormatException nfe) {
                return true;  // If unable to parse version
            }
1147
        }
1148

1149
        /**
D
Daniel Beck 已提交
1150
         * Returns true iff the plugin declares a minimum Java version and it's newer than what the Jenkins master is running on.
1151
         * @since 2.158
1152 1153 1154
         */
        public boolean isForNewerJava() {
            try {
1155 1156
                final JavaSpecificationVersion currentRuntimeJavaVersion = JavaUtils.getCurrentJavaRuntimeVersionNumber();
                return minimumJavaVersion != null && new JavaSpecificationVersion(minimumJavaVersion).isNewerThan(
1157
                        currentRuntimeJavaVersion);
1158
            } catch (NumberFormatException nfe) {
1159
                logBadMinJavaVersion();
1160
                return false; // treat this as undeclared minimum Java version
1161 1162 1163
            }
        }

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
        public VersionNumber getNeededDependenciesRequiredCore() {
            VersionNumber versionNumber = null;
            try {
                versionNumber = requiredCore == null ? null : new VersionNumber(requiredCore);
            } catch (NumberFormatException nfe) {
                // unable to parse version
            }
            for (Plugin p: getNeededDependencies()) {
                VersionNumber v = p.getNeededDependenciesRequiredCore();
                if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v;
            }
            return versionNumber;
        }

1178
        /**
D
Daniel Beck 已提交
1179
         * Returns the minimum Java version needed to use the plugin and all its dependencies.
1180
         * @since 2.158
B
Baptiste Mathus 已提交
1181
         * @return the minimum Java version needed to use the plugin and all its dependencies, or null if unspecified.
1182
         */
1183 1184
        @CheckForNull
        public VersionNumber getNeededDependenciesMinimumJavaVersion() {
1185 1186
            VersionNumber versionNumber = null;
            try {
1187
                versionNumber = minimumJavaVersion == null ? null : new VersionNumber(minimumJavaVersion);
1188
            } catch (NumberFormatException nfe) {
1189
                logBadMinJavaVersion();
1190 1191
            }
            for (Plugin p: getNeededDependencies()) {
1192
                VersionNumber v = p.getNeededDependenciesMinimumJavaVersion();
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
                if (v == null) {
                    continue;
                }
                if (versionNumber == null || v.isNewerThan(versionNumber)) {
                    versionNumber = v;
                }
            }
            return versionNumber;
        }

1203
        private void logBadMinJavaVersion() {
1204
            LOGGER.log(Level.WARNING, "minimumJavaVersion was specified for plugin {0} but unparseable (received {1})",
1205
                       new String[]{this.name, this.minimumJavaVersion});
1206 1207
        }

1208
        public boolean isNeededDependenciesForNewerJenkins() {
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
            return isNeededDependenciesForNewerJenkins(new PluginManager.MetadataCache());
        }

        @Restricted(NoExternalUse.class) // table.jelly
        public boolean isNeededDependenciesForNewerJenkins(PluginManager.MetadataCache cache) {
            return cache.of("isNeededDependenciesForNewerJenkins:" + name, Boolean.class, () -> {
                for (Plugin p : getNeededDependencies()) {
                    if (p.isForNewerHudson() || p.isNeededDependenciesForNewerJenkins()) {
                        return true;
                    }
                }
                return false;
            });
1222 1223
        }

D
Daniel Beck 已提交
1224
        /**
1225
         * Returns true iff any of the plugin dependencies require a newer Java than Jenkins is running on.
D
Daniel Beck 已提交
1226
         *
1227
         * @since 2.158
D
Daniel Beck 已提交
1228
         */
1229 1230 1231 1232 1233 1234 1235 1236 1237
        public boolean isNeededDependenciesForNewerJava() {
            for (Plugin p: getNeededDependencies()) {
                if (p.isForNewerJava() || p.isNeededDependenciesForNewerJava()) {
                    return true;
                }
            }
            return false;
        }

1238 1239 1240 1241 1242 1243 1244 1245 1246
        /**
         * If at least some of the plugin's needed dependencies are already installed, and the new version of the
         * needed dependencies plugin have a "compatibleSinceVersion"
         * value (i.e., it's only directly compatible with that version or later), this will check to
         * see if the installed version is older than the compatible-since version. If it is older, it'll return false.
         * If it's not older, or it's not installed, or it's installed but there's no compatibleSinceVersion
         * specified, it'll return true.
         */
        public boolean isNeededDependenciesCompatibleWithInstalledVersion() {
1247 1248 1249 1250 1251
            return isNeededDependenciesCompatibleWithInstalledVersion(new PluginManager.MetadataCache());
        }

        @Restricted(NoExternalUse.class) // table.jelly
        public boolean isNeededDependenciesCompatibleWithInstalledVersion(PluginManager.MetadataCache cache) {
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264
            return getDependenciesIncompatibleWithInstalledVersion(cache).isEmpty();
        }

        /**
         * Get the list of incompatible dependencies (if there are any, as determined by isNeededDependenciesCompatibleWithInstalledVersion)
         *
         * @since TODO
         */
        @Restricted(NoExternalUse.class) // table.jelly
        @SuppressWarnings("unchecked")
        public List<Plugin> getDependenciesIncompatibleWithInstalledVersion(PluginManager.MetadataCache cache) {
            return cache.of("getDependenciesIncompatibleWithInstalledVersion:" + name, List.class, () -> {
                List<Plugin> incompatiblePlugins = new ArrayList<>();
1265 1266
                for (Plugin p : getNeededDependencies()) {
                    if (!p.isCompatibleWithInstalledVersion() || !p.isNeededDependenciesCompatibleWithInstalledVersion()) {
1267
                        incompatiblePlugins.add(p);
1268 1269
                    }
                }
1270
                return incompatiblePlugins;
1271
            });
1272
        }
1273

1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
        public void setIncompatibleParentPlugins(Set<Plugin> incompatibleParentPlugins) {
            this.incompatibleParentPlugins = incompatibleParentPlugins;
        }

        @Restricted(NoExternalUse.class) // table.jelly
        public Set<Plugin> getIncompatibleParentPlugins() {
            return this.incompatibleParentPlugins;
        }

        @Restricted(NoExternalUse.class) // table.jelly
        public boolean hasIncompatibleParentPlugins() {
            return this.incompatibleParentPlugins != null && !this.incompatibleParentPlugins.isEmpty();
        }

1288
        /**
1289
         * @since 2.40
1290 1291 1292 1293
         */
        @CheckForNull
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
1294
            UpdateSiteWarningsConfiguration configuration = ExtensionList.lookupSingleton(UpdateSiteWarningsConfiguration.class);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
            Set<Warning> warnings = new HashSet<>();

            for (Warning warning: configuration.getAllWarnings()) {
                if (configuration.isIgnored(warning)) {
                    // warning is currently being ignored
                    continue;
                }
                if (!warning.isPluginWarning(this.name)) {
                    // warning is not about this plugin
                    continue;
                }

                if (!warning.isRelevantToVersion(new VersionNumber(this.version))) {
                    // warning is not relevant to this version
                    continue;
                }
                warnings.add(warning);
            }

            return warnings;
        }

        /**
1318
         * @since 2.40
1319 1320 1321 1322 1323 1324
         */
        @Restricted(DoNotUse.class)
        public boolean hasWarnings() {
            return getWarnings().size() > 0;
        }

1325 1326 1327 1328
        /**
         * @deprecated as of 1.326
         *      Use {@link #deploy()}.
         */
1329
        @Deprecated
1330 1331 1332 1333
        public void install() {
            deploy();
        }

1334 1335 1336 1337
        public Future<UpdateCenterJob> deploy() {
            return deploy(false);
        }

1338 1339 1340 1341 1342 1343
        /**
         * Schedules the installation of this plugin.
         *
         * <p>
         * This is mainly intended to be called from the UI. The actual installation work happens
         * asynchronously in another thread.
1344 1345 1346 1347
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
1348
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
1349
         */
1350
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad) {
1351
            return deploy(dynamicLoad, null, null);
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        }

        /**
         * Schedules the installation of this plugin.
         *
         * <p>
         * This is mainly intended to be called from the UI. The actual installation work happens
         * asynchronously in another thread.
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
         * @param correlationId A correlation ID to be set on the job.
1366
         * @param batch if defined, a list of plugins to add to, which will be started later
1367
         */
1368
        @Restricted(NoExternalUse.class)
1369
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId, @CheckForNull List<PluginWrapper> batch) {
1370 1371
            Jenkins.get().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.get().getUpdateCenter();
1372
            for (Plugin dep : getNeededDependencies()) {
1373 1374
                UpdateCenter.InstallationJob job = uc.getJob(dep);
                if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) {
1375
                    LOGGER.log(Level.INFO, "Adding dependent install of " + dep.name + " for plugin " + name);
1376
                    dep.deploy(dynamicLoad, /* UpdateCenterPluginInstallTest.test_installKnownPlugins specifically asks that these not be correlated */ null, batch);
1377
                } else {
1378
                    LOGGER.log(Level.FINE, "Dependent install of {0} for plugin {1} already added, skipping", new Object[] {dep.name, name});
1379
                }
1380
            }
1381 1382 1383 1384
            PluginWrapper pw = getInstalled();
            if(pw != null) { // JENKINS-34494 - check for this plugin being disabled
                Future<UpdateCenterJob> enableJob = null;
                if(!pw.isEnabled()) {
1385
                    UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad);
1386 1387 1388 1389
                    job.setCorrelationId(correlationId);
                    enableJob = uc.addJob(job);
                }
                if(pw.getVersionNumber().equals(new VersionNumber(version))) {
1390
                    return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this));
1391
                }
1392
            }
1393
            UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad);
1394
            job.setCorrelationId(correlationId);
1395
            job.setBatch(batch);
1396
            return uc.addJob(job);
1397 1398
        }

1399 1400 1401 1402
        /**
         * Schedules the downgrade of this plugin.
         */
        public Future<UpdateCenterJob> deployBackup() {
1403 1404
            Jenkins.get().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.get().getUpdateCenter();
1405
            return uc.addJob(uc.new PluginDowngradeJob(this, UpdateSite.this, Jenkins.getAuthentication()));
1406
        }
1407 1408 1409
        /**
         * Making the installation web bound.
         */
1410
        @RequirePOST
1411 1412 1413 1414 1415
        public HttpResponse doInstall() throws IOException {
            deploy(false);
            return HttpResponses.redirectTo("../..");
        }

1416
        @RequirePOST
1417 1418 1419
        public HttpResponse doInstallNow() throws IOException {
            deploy(true);
            return HttpResponses.redirectTo("../..");
1420
        }
1421 1422 1423 1424

        /**
         * Performs the downgrade of the plugin.
         */
1425
        @RequirePOST
1426
        public HttpResponse doDowngrade() throws IOException {
1427
            deployBackup();
1428
            return HttpResponses.redirectTo("../..");
1429
        }
1430 1431 1432 1433 1434 1435
    }

    private static final long DAY = DAYS.toMillis(1);

    private static final Logger LOGGER = Logger.getLogger(UpdateSite.class.getName());

1436
    // The name uses UpdateCenter for compatibility reason.
1437
    public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName()+".never");
1438 1439

}