UpdateSite.java 53.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
/*
 * 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
import java.time.Instant;
47 48
import java.util.ArrayList;
import java.util.Collections;
49
import java.util.Date;
50
import java.util.HashSet;
51
import java.util.List;
52
import java.util.Locale;
53 54
import java.util.Map;
import java.util.Set;
55
import java.util.TreeMap;
56
import java.util.UUID;
57
import java.util.concurrent.Callable;
58
import java.util.concurrent.Future;
59
import java.util.function.Predicate;
60 61
import java.util.logging.Level;
import java.util.logging.Logger;
62 63
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
64 65
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
66 67
import javax.annotation.Nullable;

68
import io.jenkins.lib.versionnumber.JavaSpecificationVersion;
69
import jenkins.model.Jenkins;
70
import jenkins.plugins.DetachedPluginsUtil;
71
import jenkins.security.UpdateSiteWarningsConfiguration;
72
import jenkins.security.UpdateSiteWarningsMonitor;
73
import jenkins.util.JSONSignatureValidator;
74
import jenkins.util.SystemProperties;
75
import jenkins.util.java.JavaUtils;
76
import net.sf.json.JSONArray;
77 78 79 80
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
81
import org.kohsuke.accmod.restrictions.DoNotUse;
82 83 84 85 86 87
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;
88 89

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

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

119 120 121 122 123 124
    /**
     * 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;

125 126 127
    /**
     * Latest data as read from the data file.
     */
128
    private transient Data data;
129

130 131 132 133 134 135
    /**
     * ID string for this update source.
     */
    private final String id;

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

140 141 142 143
    /**
     * the prefix for the signature validator name
     */
    private static final String signatureValidatorPrefix = "update site";
144

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

147 148 149 150 151 152 153 154
    public UpdateSite(String id, String url) {
        this.id = id;
        this.url = url;
    }

    /**
     * Get ID string.
     */
155
    @Exported
156 157 158 159
    public String getId() {
        return id;
    }

160
    @Exported
161
    public long getDataTimestamp() {
162
        assert dataTimestamp >= 0;
163 164 165
        return dataTimestamp;
    }

166 167 168 169 170
    /**
     * Update the data file from the given URL if the file
     * does not exist, or is otherwise due for update.
     * Accepted formats are JSONP or HTML with {@code postMessage}, not raw JSON.
     * @return null if no updates are necessary, or the future result
171
     * @since 2.222
172 173 174 175 176
     */
    public @CheckForNull Future<FormValidation> updateDirectly() {
        return updateDirectly(DownloadService.signatureCheck);
    }

177
    /**
178
     * Update the data file from the given URL if the file
179
     * does not exist, or is otherwise due for update.
180 181
     * 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!)
182
     * @return null if no updates are necessary, or the future result
183
     * @since 1.502
184
     * @deprecated use {@linkplain #updateDirectly()}
185
     */
186
    @Deprecated
187
    public @CheckForNull Future<FormValidation> updateDirectly(final boolean signatureCheck) {
188
        if (! getDataFile().exists() || isDue()) {
189
            return Jenkins.get().getUpdateCenter().updateService.submit(new Callable<FormValidation>() {
190 191
                @Override public FormValidation call() throws Exception {
                    return updateDirectlyNow(signatureCheck);
192 193
                }
            });
194
        } else {
195
            return null;
196 197 198
        }
    }

199 200 201
    /**
     * Forces an update of the data file from the configured URL, irrespective of the last time the data was retrieved.
     * @return A {@code FormValidation} indicating the if the update metadata was successfully downloaded from the configured update site
202
     * @since 2.222
203 204 205 206 207 208
     * @throws IOException if there was an error downloading or saving the file.
     */
    public @Nonnull FormValidation updateDirectlyNow() throws IOException {
        return updateDirectlyNow(DownloadService.signatureCheck);
    }

209 210 211
    @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);
212 213
    }
    
214
    private FormValidation updateData(String json, boolean signatureCheck)
215 216 217 218
            throws IOException {

        dataTimestamp = System.currentTimeMillis();

219 220
        JSONObject o = JSONObject.fromObject(json);

221 222 223 224 225 226 227 228
        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);
        }
229 230 231

        if (signatureCheck) {
            FormValidation e = verifySignature(o);
232
            if (e.kind!=Kind.OK) {
233
                LOGGER.severe(e.toString());
234 235
                return e;
            }
236 237
        }

238
        LOGGER.finest("Obtained the latest update center data file for UpdateSource " + id);
239
        retryWindow = 0;
240
        getDataFile().write(json);
241
        data = new Data(o);
242 243 244 245 246
        return FormValidation.ok();
    }

    public FormValidation doVerifySignature() throws IOException {
        return verifySignature(getJSONObject());
247 248
    }

249 250 251 252 253 254 255 256 257 258 259 260 261 262
    /**
     * 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);
    }

263 264 265
    /**
     * Verifies the signature in the update center data file.
     */
266
    private FormValidation verifySignature(JSONObject o) throws IOException {
267 268 269 270 271 272
        return getJsonSignatureValidator().verifySignature(o);
    }

    /**
     * Let sub-classes of UpdateSite provide their own signature validator.
     * @return the signature validator.
B
Basil Crow 已提交
273
     * @deprecated use {@link #getJsonSignatureValidator(String)} instead.
274
     */
275
    @Deprecated
276 277
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator() {
278 279 280 281 282 283 284 285 286
        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.
287
     * @since 2.21
288 289 290 291 292 293 294
     */
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator(@CheckForNull String name) {
        if (name == null) {
            name = signatureValidatorPrefix + " '" + id + "'";
        }
        return new JSONSignatureValidator(name);
295 296 297 298 299
    }

    /**
     * Returns true if it's time for us to check for new version.
     */
J
Josh Soref 已提交
300
    public synchronized boolean isDue() {
301
        if(neverUpdate)     return false;
302
        if(dataTimestamp == 0)
303 304
            dataTimestamp = getDataFile().file.lastModified();
        long now = System.currentTimeMillis();
305

306 307 308 309 310 311 312
        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
        }
313 314 315
        return due;
    }

316 317 318 319 320
    /**
     * Invalidates the cached data and force retrieval.
     *
     * @since 1.432
     */
321
    @RequirePOST
322
    public HttpResponse doInvalidateData() {
323
        Jenkins.get().checkPermission(Jenkins.ADMINISTER);
324
        dataTimestamp = 0;
325
        data = null;
326 327 328
        return HttpResponses.ok();
    }

329
    /**
330
     * Loads the update center data, if any.
331 332 333 334
     *
     * @return  null if no data is available.
     */
    public Data getData() {
335
        if (data == null) {
336
            JSONObject o = getJSONObject();
337
            if (o != null) {
338 339 340 341
                data = new Data(o);
            }
        }
        return data;
342 343
    }

344 345 346
    /**
     * Whether {@link #getData} might be blocking.
     */
347
    // Internal use only
348 349 350 351
    boolean hasUnparsedData() {
        return data == null && getDataFile().exists();
    }

352 353 354 355
    /**
     * Gets the raw update center JSON data.
     */
    public JSONObject getJSONObject() {
356 357
        TextFile df = getDataFile();
        if(df.exists()) {
358
            long start = System.nanoTime();
359
            try {
360
                JSONObject o = JSONObject.fromObject(df.read());
361
                LOGGER.fine(() -> String.format("Loaded and parsed %s in %.01fs", df, (System.nanoTime() - start) / 1_000_000_000.0));
362
                return o;
363
            } catch (JSONException | IOException e) {
364 365 366 367 368 369 370 371
                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;
        }
    }
372

373 374 375 376
    /**
     * Returns a list of plugins that should be shown in the "available" tab.
     * These are "all plugins - installed plugins".
     */
377
    @Exported
378
    public List<Plugin> getAvailables() {
379
        List<Plugin> r = new ArrayList<>();
380
        Data data = getData();
381
        if(data==null)     return Collections.emptyList();
382 383 384 385 386 387
        for (Plugin p : data.plugins.values()) {
            if(p.getInstalled()==null)
                r.add(p);
        }
        return r;
    }
388

389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    /**
     * 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);
    }

404 405 406 407
    public Api getApi() {
        return new Api(this);
    }

408
    /**
409 410
     * 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.
411
     */
412
    @Exported
413
    @CheckForNull
414 415 416 417 418 419 420 421 422 423
    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() {
424
        return new TextFile(new File(Jenkins.get().getRootDir(),
425 426 427 428 429 430 431 432 433
                                     "updates/" + getId()+".json"));
    }
    
    /**
     * Returns the list of plugins that are updates to currently installed ones.
     *
     * @return
     *      can be empty but never null.
     */
434
    @Exported
435 436 437 438
    public List<Plugin> getUpdates() {
        Data data = getData();
        if(data==null)      return Collections.emptyList(); // fail to determine
        
439
        List<Plugin> r = new ArrayList<>();
440
        for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) {
441 442 443 444 445 446 447 448 449 450
            Plugin p = pw.getUpdateInfo();
            if(p!=null) r.add(p);
        }
        
        return r;
    }
    
    /**
     * Does any of the plugin has updates?
     */
451
    @Exported
452 453 454 455
    public boolean hasUpdates() {
        Data data = getData();
        if(data==null)      return false;
        
456
        for (PluginWrapper pw : Jenkins.get().getPluginManager().getPlugins()) {
457 458
            if(!pw.isBundled() && pw.getUpdateInfo()!=null)
                // do not advertize updates to bundled plugins, since we generally want users to get them
A
alanharder 已提交
459
                // as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins. 
460 461 462 463 464 465 466 467 468 469
                return true;
        }
        return false;
    }
    
    
    /**
     * Exposed to get rid of hardcoding of the URL that serves up update-center.json
     * in Javascript.
     */
470
    @Exported
471 472 473 474
    public String getUrl() {
        return url;
    }

475 476 477 478 479

    /**
     * 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
480
     * @since 2.20
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
     */
    @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;
    }

497 498 499 500 501 502
    /**
     * Where to actually download the update center?
     *
     * @deprecated
     *      Exposed only for UI.
     */
503
    @Deprecated
504 505 506 507
    public String getDownloadUrl() {
        return url;
    }

K
kohsuke 已提交
508 509 510 511
    /**
     * Is this the legacy default update center site?
     */
    public boolean isLegacyDefault() {
512 513 514 515 516 517 518 519 520
        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 已提交
521 522
    }

523 524 525 526 527 528 529 530 531 532
    /**
     * In-memory representation of the update center data.
     */
    public final class Data {
        /**
         * The {@link UpdateSite} ID.
         */
        public final String sourceId;

        /**
A
alanharder 已提交
533
         * The latest jenkins.war.
534 535 536 537 538
         */
        public final Entry core;
        /**
         * Plugins in the repository, keyed by their artifact IDs.
         */
539
        public final Map<String,Plugin> plugins = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
540 541 542
        /**
         * List of warnings (mostly security) published with the update site.
         *
543
         * @since 2.40
544
         */
545
        private final Set<Warning> warnings = new HashSet<>();
546 547

        /**
A
alanharder 已提交
548
         * If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
549 550 551 552 553
         * the network connection is up. Null to skip the check.
         */
        public final String connectionCheckUrl;

        Data(JSONObject o) {
554
            this.sourceId = Util.intern((String)o.get("id"));
555 556 557 558
            JSONObject c = o.optJSONObject("core");
            if (c!=null) {
                core = new Entry(sourceId, c, url);
            } else {
559 560
                core = null;
            }
561 562 563 564 565 566 567 568 569 570 571 572

            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);
                    }
                }
            }

573
            for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) {
574 575
                Plugin p = new Plugin(sourceId, e.getValue());
                // JENKINS-33308 - include implied dependencies for older plugins that may need them
576
                List<PluginWrapper.Dependency> implicitDeps = DetachedPluginsUtil.getImpliedDependencies(p.name, p.requiredCore);
577 578 579 580 581 582 583
                if(!implicitDeps.isEmpty()) {
                    for(PluginWrapper.Dependency dep : implicitDeps) {
                        if(!p.dependencies.containsKey(dep.shortName)) {
                            p.dependencies.put(dep.shortName, dep.version);
                        }
                    }
                }
584
                plugins.put(Util.intern(e.getKey()), p);
585 586 587 588 589
            }

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

590 591 592
        /**
         * Returns the set of warnings
         * @return the set of warnings
593
         * @since 2.40
594 595 596 597 598 599
         */
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
            return this.warnings;
        }

600 601 602 603
        /**
         * Is there a new version of the core?
         */
        public boolean hasCoreUpdates() {
604
            return core != null && core.isNewerThan(Jenkins.VERSION);
605 606 607 608 609 610 611 612 613 614
        }

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

615
    @ExportedBean
616 617 618 619
    public static class Entry {
        /**
         * {@link UpdateSite} ID.
         */
620
        @Exported
621 622 623 624 625
        public final String sourceId;

        /**
         * Artifact ID.
         */
626
        @Exported
627 628 629 630
        public final String name;
        /**
         * The version.
         */
631
        @Exported
632 633 634 635
        public final String version;
        /**
         * Download URL.
         */
636
        @Exported
637 638
        public final String url;

639 640 641 642

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

644 645 646 647 648 649
        @Restricted(NoExternalUse.class)
        /* final */ String sha256;

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

650
        public Entry(String sourceId, JSONObject o) {
651 652 653 654
            this(sourceId, o, null);
        }

        Entry(String sourceId, JSONObject o, String baseURL) {
655
            this.sourceId = sourceId;
656 657
            this.name = Util.intern(o.getString("name"));
            this.version = Util.intern(o.getString("version"));
658 659 660

            // 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.
661
            this.sha1 = Util.fixEmptyAndTrim(o.optString("sha1"));
662 663
            this.sha256 = Util.fixEmptyAndTrim(o.optString("sha256"));
            this.sha512 = Util.fixEmptyAndTrim(o.optString("sha512"));
664

665 666 667 668 669 670 671 672
            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;
673 674
        }

675 676 677
        /**
         * The base64 encoded binary SHA-1 checksum of the file.
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
678
         * @since 1.641 (and 1.625.3 LTS)
679 680 681 682 683 684
         */
        // TODO @Exported assuming we want this in the API
        public String getSha1() {
            return sha1;
        }

685
        /**
686
         * The base64 encoded SHA-256 checksum of the file.
687
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
688
         * @since 2.130
689 690 691 692 693 694
         */
        public String getSha256() {
            return sha256;
        }

        /**
695
         * The base64 encoded SHA-512 checksum of the file.
696
         * Can be null if not provided by the update site.
D
Daniel Beck 已提交
697
         * @since 2.130
698 699 700 701 702
         */
        public String getSha512() {
            return sha512;
        }

703 704 705 706 707 708 709 710 711 712 713
        /**
         * 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 {
714
                return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
715 716 717 718 719
            } catch (IllegalArgumentException e) {
                // couldn't parse as the version number.
                return false;
            }
        }
720

721 722 723 724
        public Api getApi() {
            return new Api(this);
        }

725 726
    }

727 728 729 730 731 732 733 734
    /**
     * 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.
     *
735
     * @since 2.40
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
     */
    @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"));
765 766
            this.firstVersion = Util.intern(Util.fixEmpty(o.optString("firstVersion")));
            this.lastVersion = Util.intern(Util.fixEmpty(o.optString("lastVersion")));
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
            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
     *
788
     * @since 2.40
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 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
     */
    @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");
863
            this.component = Util.intern(o.getString("name"));
864 865 866 867 868
            this.message = o.getString("message");
            this.url = o.getString("url");

            if (o.has("versions")) {
                JSONArray versions = o.getJSONArray("versions");
869
                List<WarningVersionRange> ranges = new ArrayList<>(versions.size());
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 895 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
                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
921
                    PluginWrapper plugin = Jenkins.get().getPluginManager().getPlugin(this.component);
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
                    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;
        }
    }

953 954 955 956 957 958 959 960 961 962
    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"));

963 964 965 966
    public final class Plugin extends Entry {
        /**
         * Optional URL to the Wiki page that discusses this plugin.
         */
967
        @Exported
968 969 970 971 972 973 974 975
        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
         */
976
        @Exported
977 978 979 980
        public final String title;
        /**
         * Optional excerpt string.
         */
981
        @Exported
982 983 984 985
        public final String excerpt;
        /**
         * Optional version # from which this plugin release is configuration-compatible.
         */
986
        @Exported
987
        public final String compatibleSinceVersion;
988
        /**
A
alanharder 已提交
989
         * Version of Jenkins core this plugin was compiled against.
990
         */
991
        @Exported
992
        public final String requiredCore;
993 994 995
        /**
         * Version of Java this plugin requires to run.
         *
996
         * @since 2.158
997 998
         */
        @Exported
999
        public final String minimumJavaVersion;
1000 1001 1002 1003
        /**
         * Categories for grouping plugins, taken from labels assigned to wiki page.
         * Can be null.
         */
1004
        @Exported
1005
        public final String[] categories;
1006

1007
        /**
1008
         * Dependencies of this plugin, a name -&gt; version mapping.
1009
         */
1010
        @Exported
1011
        public final Map<String,String> dependencies;
1012
        
1013 1014 1015 1016
        /**
         * Optional dependencies of this plugin.
         */
        @Exported
1017
        public final Map<String,String> optionalDependencies;
1018

1019 1020 1021 1022 1023
        /**
         * Set of plugins, this plugin is a incompatible dependency to.
         */
        private Set<Plugin> incompatibleParentPlugins;

1024 1025
        /**
         * Date when this plugin was released.
1026
         * @since 2.224
1027 1028 1029 1030
         */
        @Exported
        public final Date releaseTimestamp;

1031 1032
        @DataBoundConstructor
        public Plugin(String sourceId, JSONObject o) {
1033
            super(sourceId, o, UpdateSite.this.url);
1034 1035 1036
            this.wiki = get(o,"wiki");
            this.title = get(o,"title");
            this.excerpt = get(o,"excerpt");
1037
            this.compatibleSinceVersion = Util.intern(get(o,"compatibleSinceVersion"));
1038
            this.minimumJavaVersion = Util.intern(get(o, "minimumJavaVersion"));
1039
            this.requiredCore = Util.intern(get(o,"requiredCore"));
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
            final String releaseTimestamp = get(o, "releaseTimestamp");
            Date date = null;
            if (releaseTimestamp != null) {
                try {
                    date = Date.from(Instant.parse(releaseTimestamp));
                } catch (Exception ex) {
                    LOGGER.log(Level.FINE, "Failed to parse releaseTimestamp for " + title + " from " + sourceId, ex);
                }
            }
            this.releaseTimestamp = date;
1050 1051 1052 1053 1054 1055
            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);
1056

1057 1058
            for(Object jo : o.getJSONArray("dependencies")) {
                JSONObject depObj = (JSONObject) jo;
1059
                // Make sure there's a name attribute and that the optional value isn't true.
1060 1061
                String depName = Util.intern(get(depObj,"name"));
                if (depName!=null) {
1062
                    if (get(depObj, "optional").equals("false")) {
1063
                        dependencies.put(depName, Util.intern(get(depObj, "version")));
1064
                    } else {
1065
                        optionalDependencies.put(depName, Util.intern(get(depObj, "version")));
1066
                    }
1067 1068 1069
                }
            }

1070 1071
        }

1072

1073 1074

        public String getDisplayName() {
1075 1076 1077 1078 1079 1080
            String displayName;
            if(title!=null)
                displayName = title;
            else
                displayName = name;
            return StringUtils.removeStart(displayName, "Jenkins ");
1081 1082 1083 1084 1085 1086
        }

        /**
         * If some version of this plugin is currently installed, return {@link PluginWrapper}.
         * Otherwise null.
         */
1087
        @Exported
1088
        public PluginWrapper getInstalled() {
1089
            PluginManager pm = Jenkins.get().getPluginManager();
1090 1091 1092
            return pm.getPlugin(name);
        }

1093 1094
        /**
         * Returns true if the plugin and its dependencies are fully compatible with the current installation
1095
         * This is set to restricted for now, since it is only being used by Jenkins UI or Restful API at the moment.
1096
         *
1097
         * @since 2.175
1098 1099
         */
        @Restricted(NoExternalUse.class)
1100
        @Exported
1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
        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();
        }

1112 1113 1114 1115 1116 1117 1118
        /**
         * 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.
         */
1119
        @Exported
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
        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;
        }

1133 1134 1135
        /**
         * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work.
         */
1136
        @Exported
1137
        public List<Plugin> getNeededDependencies() {
1138
            List<Plugin> deps = new ArrayList<>();
1139

1140
            for(Map.Entry<String,String> e : dependencies.entrySet()) {
1141
                VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
1142
                Plugin depPlugin = Jenkins.get().getUpdateCenter().getPlugin(e.getKey(), requiredVersion);
1143
                if (depPlugin == null) {
1144
                    LOGGER.log(warnedMissing.add(e.getKey()) ? Level.WARNING : Level.FINE, "Could not find dependency {0} of {1}", new Object[] {e.getKey(), name});
1145 1146
                    continue;
                }
1147

1148
                // Is the plugin installed already? If not, add it.
1149 1150 1151
                PluginWrapper current = depPlugin.getInstalled();

                if (current ==null) {
1152 1153 1154 1155
                    deps.add(depPlugin);
                }
                // If the dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
1156
                else if (current.isOlderThan(requiredVersion)) {
1157 1158
                    deps.add(depPlugin);
                }
1159 1160 1161 1162
                // JENKINS-34494 - or if the plugin is disabled, this will allow us to enable it
                else if (!current.isEnabled()) {
                    deps.add(depPlugin);
                }
1163 1164
            }

1165
            for(Map.Entry<String,String> e : optionalDependencies.entrySet()) {
1166
                VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
1167
                Plugin depPlugin = Jenkins.get().getUpdateCenter().getPlugin(e.getKey(), requiredVersion);
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180
                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);
                }
            }

1181 1182
            return deps;
        }
1183

1184
        public boolean isForNewerHudson() {
1185 1186
            try {
                return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
1187
                  new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
1188 1189 1190
            } catch (NumberFormatException nfe) {
                return true;  // If unable to parse version
            }
1191
        }
1192

1193
        /**
D
Daniel Beck 已提交
1194
         * Returns true iff the plugin declares a minimum Java version and it's newer than what the Jenkins master is running on.
1195
         * @since 2.158
1196 1197 1198
         */
        public boolean isForNewerJava() {
            try {
1199 1200
                final JavaSpecificationVersion currentRuntimeJavaVersion = JavaUtils.getCurrentJavaRuntimeVersionNumber();
                return minimumJavaVersion != null && new JavaSpecificationVersion(minimumJavaVersion).isNewerThan(
1201
                        currentRuntimeJavaVersion);
1202
            } catch (NumberFormatException nfe) {
1203
                logBadMinJavaVersion();
1204
                return false; // treat this as undeclared minimum Java version
1205 1206 1207
            }
        }

1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
        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;
        }

1222
        /**
D
Daniel Beck 已提交
1223
         * Returns the minimum Java version needed to use the plugin and all its dependencies.
1224
         * @since 2.158
B
Baptiste Mathus 已提交
1225
         * @return the minimum Java version needed to use the plugin and all its dependencies, or null if unspecified.
1226
         */
1227 1228
        @CheckForNull
        public VersionNumber getNeededDependenciesMinimumJavaVersion() {
1229 1230
            VersionNumber versionNumber = null;
            try {
1231
                versionNumber = minimumJavaVersion == null ? null : new VersionNumber(minimumJavaVersion);
1232
            } catch (NumberFormatException nfe) {
1233
                logBadMinJavaVersion();
1234 1235
            }
            for (Plugin p: getNeededDependencies()) {
1236
                VersionNumber v = p.getNeededDependenciesMinimumJavaVersion();
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246
                if (v == null) {
                    continue;
                }
                if (versionNumber == null || v.isNewerThan(versionNumber)) {
                    versionNumber = v;
                }
            }
            return versionNumber;
        }

1247
        private void logBadMinJavaVersion() {
1248
            LOGGER.log(Level.WARNING, "minimumJavaVersion was specified for plugin {0} but unparseable (received {1})",
1249
                       new String[]{this.name, this.minimumJavaVersion});
1250 1251
        }

1252
        public boolean isNeededDependenciesForNewerJenkins() {
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
            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;
            });
1266 1267
        }

D
Daniel Beck 已提交
1268
        /**
1269
         * Returns true iff any of the plugin dependencies require a newer Java than Jenkins is running on.
D
Daniel Beck 已提交
1270
         *
1271
         * @since 2.158
D
Daniel Beck 已提交
1272
         */
1273 1274 1275 1276 1277 1278 1279 1280 1281
        public boolean isNeededDependenciesForNewerJava() {
            for (Plugin p: getNeededDependencies()) {
                if (p.isForNewerJava() || p.isNeededDependenciesForNewerJava()) {
                    return true;
                }
            }
            return false;
        }

1282 1283 1284 1285 1286 1287 1288 1289 1290
        /**
         * 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() {
1291 1292 1293 1294 1295
            return isNeededDependenciesCompatibleWithInstalledVersion(new PluginManager.MetadataCache());
        }

        @Restricted(NoExternalUse.class) // table.jelly
        public boolean isNeededDependenciesCompatibleWithInstalledVersion(PluginManager.MetadataCache cache) {
1296 1297 1298
            return getDependenciesIncompatibleWithInstalledVersion(cache).isEmpty();
        }

1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
        /**
         * Returns true if and only if this update addressed a currently active security vulnerability.
         *
         * @return true if and only if this update addressed a currently active security vulnerability.
         */
        @Restricted(NoExternalUse.class) // Jelly
        public boolean fixesSecurityVulnerabilities() {
            final PluginWrapper installed = getInstalled();
            if (installed == null) {
                return false;
            }
            boolean allWarningsStillApply = true;
            for (Warning warning : ExtensionList.lookupSingleton(UpdateSiteWarningsMonitor.class).getActivePluginWarningsByPlugin().getOrDefault(installed, Collections.emptyList())) {
                boolean thisWarningApplies = false;
                for (WarningVersionRange range : warning.versionRanges) {
                    if (range.includes(new VersionNumber(version))) {
                        thisWarningApplies = true;
                    }
                }
                if (!thisWarningApplies) {
                    allWarningsStillApply = false;
                }
            }
            return !allWarningsStillApply;
        }

1325 1326 1327
        /**
         * Get the list of incompatible dependencies (if there are any, as determined by isNeededDependenciesCompatibleWithInstalledVersion)
         *
1328
         * @since 2.203
1329 1330 1331 1332 1333 1334
         */
        @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<>();
1335 1336
                for (Plugin p : getNeededDependencies()) {
                    if (!p.isCompatibleWithInstalledVersion() || !p.isNeededDependenciesCompatibleWithInstalledVersion()) {
1337
                        incompatiblePlugins.add(p);
1338 1339
                    }
                }
1340
                return incompatiblePlugins;
1341
            });
1342
        }
1343

1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
        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();
        }

1358
        /**
1359
         * @since 2.40
1360 1361 1362 1363
         */
        @CheckForNull
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
1364
            UpdateSiteWarningsConfiguration configuration = ExtensionList.lookupSingleton(UpdateSiteWarningsConfiguration.class);
1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387
            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;
        }

        /**
1388
         * @since 2.40
1389 1390 1391 1392 1393 1394
         */
        @Restricted(DoNotUse.class)
        public boolean hasWarnings() {
            return getWarnings().size() > 0;
        }

1395 1396 1397 1398
        /**
         * @deprecated as of 1.326
         *      Use {@link #deploy()}.
         */
1399
        @Deprecated
1400 1401 1402 1403
        public void install() {
            deploy();
        }

1404 1405 1406 1407
        public Future<UpdateCenterJob> deploy() {
            return deploy(false);
        }

1408 1409 1410 1411 1412 1413
        /**
         * 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.
1414 1415 1416 1417
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
1418
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
1419
         */
1420
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad) {
1421
            return deploy(dynamicLoad, null, null);
1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
        }

        /**
         * 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.
1436
         * @param batch if defined, a list of plugins to add to, which will be started later
1437
         */
1438
        @Restricted(NoExternalUse.class)
1439
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId, @CheckForNull List<PluginWrapper> batch) {
1440 1441
            Jenkins.get().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.get().getUpdateCenter();
1442
            for (Plugin dep : getNeededDependencies()) {
1443 1444
                UpdateCenter.InstallationJob job = uc.getJob(dep);
                if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) {
1445
                    LOGGER.log(Level.INFO, "Adding dependent install of " + dep.name + " for plugin " + name);
1446
                    dep.deploy(dynamicLoad, /* UpdateCenterPluginInstallTest.test_installKnownPlugins specifically asks that these not be correlated */ null, batch);
1447
                } else {
1448
                    LOGGER.log(Level.FINE, "Dependent install of {0} for plugin {1} already added, skipping", new Object[] {dep.name, name});
1449
                }
1450
            }
1451 1452 1453 1454
            PluginWrapper pw = getInstalled();
            if(pw != null) { // JENKINS-34494 - check for this plugin being disabled
                Future<UpdateCenterJob> enableJob = null;
                if(!pw.isEnabled()) {
1455
                    UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad);
1456 1457 1458 1459
                    job.setCorrelationId(correlationId);
                    enableJob = uc.addJob(job);
                }
                if(pw.getVersionNumber().equals(new VersionNumber(version))) {
1460
                    return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this));
1461
                }
1462
            }
1463
            UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad);
1464
            job.setCorrelationId(correlationId);
1465
            job.setBatch(batch);
1466
            return uc.addJob(job);
1467 1468
        }

1469 1470 1471 1472
        /**
         * Schedules the downgrade of this plugin.
         */
        public Future<UpdateCenterJob> deployBackup() {
1473 1474
            Jenkins.get().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.get().getUpdateCenter();
1475
            return uc.addJob(uc.new PluginDowngradeJob(this, UpdateSite.this, Jenkins.getAuthentication()));
1476
        }
1477 1478 1479
        /**
         * Making the installation web bound.
         */
1480
        @RequirePOST
1481 1482 1483 1484 1485
        public HttpResponse doInstall() throws IOException {
            deploy(false);
            return HttpResponses.redirectTo("../..");
        }

1486
        @RequirePOST
1487 1488 1489
        public HttpResponse doInstallNow() throws IOException {
            deploy(true);
            return HttpResponses.redirectTo("../..");
1490
        }
1491 1492 1493 1494

        /**
         * Performs the downgrade of the plugin.
         */
1495
        @RequirePOST
1496
        public HttpResponse doDowngrade() throws IOException {
1497
            deployBackup();
1498
            return HttpResponses.redirectTo("../..");
1499
        }
1500 1501 1502 1503 1504 1505
    }

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

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

1506
    // The name uses UpdateCenter for compatibility reason.
1507
    public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName()+".never");
1508 1509

}