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

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

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

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

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

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

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

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

141 142 143 144
    /**
     * the prefix for the signature validator name
     */
    private static final String signatureValidatorPrefix = "update site";
145 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
     * Update the data file from the given URL if the file
168
     * does not exist, or is otherwise due for update.
169 170
     * 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!)
171
     * @return null if no updates are necessary, or the future result
172
     * @since 1.502
173
     */
174
    public @CheckForNull Future<FormValidation> updateDirectly(final boolean signatureCheck) {
175 176
        if (! getDataFile().exists() || isDue()) {
            return Jenkins.getInstance().getUpdateCenter().updateService.submit(new Callable<FormValidation>() {
177 178
                @Override public FormValidation call() throws Exception {
                    return updateDirectlyNow(signatureCheck);
179 180
                }
            });
181
        } else {
182
            return null;
183 184 185 186 187 188
        }
    }

    @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);
189 190
    }
    
191 192 193
    /**
     * This is the endpoint that receives the update center data file from the browser.
     */
194
    @RequirePOST
195
    public FormValidation doPostBack(StaplerRequest req) throws IOException, GeneralSecurityException {
196
        DownloadSettings.checkPostBackAccess();
197
        return updateData(IOUtils.toString(req.getInputStream(),"UTF-8"), true);
198 199
    }

200
    private FormValidation updateData(String json, boolean signatureCheck)
201 202 203 204
            throws IOException {

        dataTimestamp = System.currentTimeMillis();

205 206
        JSONObject o = JSONObject.fromObject(json);

207 208 209 210 211 212 213 214
        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);
        }
215 216 217

        if (signatureCheck) {
            FormValidation e = verifySignature(o);
218
            if (e.kind!=Kind.OK) {
219
                LOGGER.severe(e.toString());
220 221
                return e;
            }
222 223
        }

K
bug fix  
Kohsuke Kawaguchi 已提交
224
        LOGGER.info("Obtained the latest update center data file for UpdateSource " + id);
225
        retryWindow = 0;
226
        getDataFile().write(json);
227
        data = new Data(o);
228 229 230 231 232
        return FormValidation.ok();
    }

    public FormValidation doVerifySignature() throws IOException {
        return verifySignature(getJSONObject());
233 234
    }

235 236 237 238 239 240 241 242 243 244 245 246 247 248
    /**
     * 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);
    }

249 250 251
    /**
     * Verifies the signature in the update center data file.
     */
252
    private FormValidation verifySignature(JSONObject o) throws IOException {
253 254 255 256 257 258
        return getJsonSignatureValidator().verifySignature(o);
    }

    /**
     * Let sub-classes of UpdateSite provide their own signature validator.
     * @return the signature validator.
259
     * @deprecated use {@link #getJsonSignatureValidator(@CheckForNull String)} instead.
260
     */
261
    @Deprecated
262 263
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator() {
264 265 266 267 268 269 270 271 272
        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.
273
     * @since 2.21
274 275 276 277 278 279 280
     */
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator(@CheckForNull String name) {
        if (name == null) {
            name = signatureValidatorPrefix + " '" + id + "'";
        }
        return new JSONSignatureValidator(name);
281 282 283 284 285 286 287
    }

    /**
     * Returns true if it's time for us to check for new version.
     */
    public boolean isDue() {
        if(neverUpdate)     return false;
288
        if(dataTimestamp == 0)
289 290
            dataTimestamp = getDataFile().file.lastModified();
        long now = System.currentTimeMillis();
291 292 293 294 295 296 297 298
        
        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
        }
299 300 301
        return due;
    }

302 303 304 305 306
    /**
     * Invalidates the cached data and force retrieval.
     *
     * @since 1.432
     */
307
    @RequirePOST
308 309 310
    public HttpResponse doInvalidateData() {
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
        dataTimestamp = 0;
311
        data = null;
312 313 314
        return HttpResponses.ok();
    }

315
    /**
316
     * Loads the update center data, if any.
317 318 319 320
     *
     * @return  null if no data is available.
     */
    public Data getData() {
321
        if (data == null) {
322
            JSONObject o = getJSONObject();
323
            if (o != null) {
324 325 326 327
                data = new Data(o);
            }
        }
        return data;
328 329 330 331 332 333
    }

    /**
     * Gets the raw update center JSON data.
     */
    public JSONObject getJSONObject() {
334 335 336
        TextFile df = getDataFile();
        if(df.exists()) {
            try {
337
                return JSONObject.fromObject(df.read());
338 339 340 341
            } catch (JSONException e) {
                LOGGER.log(Level.SEVERE,"Failed to parse "+df,e);
                df.delete(); // if we keep this file, it will cause repeated failures
                return null;
342 343 344 345 346 347 348 349 350
            } catch (IOException e) {
                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;
        }
    }
351

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

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
    /**
     * 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);
    }

383 384 385 386
    public Api getApi() {
        return new Api(this);
    }

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

454 455 456 457 458

    /**
     * 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
459
     * @since 2.20
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
     */
    @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;
    }

476 477 478 479 480 481
    /**
     * Where to actually download the update center?
     *
     * @deprecated
     *      Exposed only for UI.
     */
482
    @Deprecated
483 484 485 486
    public String getDownloadUrl() {
        return url;
    }

K
kohsuke 已提交
487 488 489 490
    /**
     * Is this the legacy default update center site?
     */
    public boolean isLegacyDefault() {
491 492 493 494 495 496 497 498 499
        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 已提交
500 501
    }

502 503 504 505 506 507 508 509 510 511
    /**
     * In-memory representation of the update center data.
     */
    public final class Data {
        /**
         * The {@link UpdateSite} ID.
         */
        public final String sourceId;

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

        /**
A
alanharder 已提交
527
         * If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
528 529 530 531 532
         * the network connection is up. Null to skip the check.
         */
        public final String connectionCheckUrl;

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

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

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

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

569 570 571
        /**
         * Returns the set of warnings
         * @return the set of warnings
572
         * @since 2.40
573 574 575 576 577 578
         */
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
            return this.warnings;
        }

579 580 581 582
        /**
         * Is there a new version of the core?
         */
        public boolean hasCoreUpdates() {
583
            return core != null && core.isNewerThan(Jenkins.VERSION);
584 585 586 587 588 589 590 591 592 593
        }

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

594
    @ExportedBean
595 596 597 598
    public static class Entry {
        /**
         * {@link UpdateSite} ID.
         */
599
        @Exported
600 601 602 603 604
        public final String sourceId;

        /**
         * Artifact ID.
         */
605
        @Exported
606 607 608 609
        public final String name;
        /**
         * The version.
         */
610
        @Exported
611 612 613 614
        public final String version;
        /**
         * Download URL.
         */
615
        @Exported
616 617
        public final String url;

618 619 620 621

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

623 624 625 626 627 628
        @Restricted(NoExternalUse.class)
        /* final */ String sha256;

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

629
        public Entry(String sourceId, JSONObject o) {
630 631 632 633
            this(sourceId, o, null);
        }

        Entry(String sourceId, JSONObject o, String baseURL) {
634
            this.sourceId = sourceId;
635 636
            this.name = Util.intern(o.getString("name"));
            this.version = Util.intern(o.getString("version"));
637 638 639

            // 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.
640
            this.sha1 = Util.fixEmptyAndTrim(o.optString("sha1"));
641 642
            this.sha256 = Util.fixEmptyAndTrim(o.optString("sha256"));
            this.sha512 = Util.fixEmptyAndTrim(o.optString("sha512"));
643

644 645 646 647 648 649 650 651
            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;
652 653
        }

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

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

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

682 683 684 685 686 687 688 689 690 691 692
        /**
         * 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 {
693
                return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
694 695 696 697 698
            } catch (IllegalArgumentException e) {
                // couldn't parse as the version number.
                return false;
            }
        }
699

700 701 702 703
        public Api getApi() {
            return new Api(this);
        }

704 705
    }

706 707 708 709 710 711 712 713
    /**
     * 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.
     *
714
     * @since 2.40
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
     */
    @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"));
744 745
            this.firstVersion = Util.intern(Util.fixEmpty(o.optString("firstVersion")));
            this.lastVersion = Util.intern(Util.fixEmpty(o.optString("lastVersion")));
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
            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
     *
767
     * @since 2.40
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 837 838 839 840 841
     */
    @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");
842
            this.component = Util.intern(o.getString("name"));
843 844 845 846 847
            this.message = o.getString("message");
            this.url = o.getString("url");

            if (o.has("versions")) {
                JSONArray versions = o.getJSONArray("versions");
848
                List<WarningVersionRange> ranges = new ArrayList<>(versions.size());
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 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 921 922 923 924 925 926 927 928 929 930 931
                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
                    PluginWrapper plugin = Jenkins.getInstance().getPluginManager().getPlugin(this.component);
                    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;
        }
    }

932 933 934 935 936 937 938 939 940 941
    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"));

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

986
        /**
987
         * Dependencies of this plugin, a name -&gt; version mapping.
988
         */
989
        @Exported
990
        public final Map<String,String> dependencies;
991
        
992 993 994 995
        /**
         * Optional dependencies of this plugin.
         */
        @Exported
996
        public final Map<String,String> optionalDependencies;
997

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.getInstance().getPluginManager();
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
            return pm.getPlugin(name);
        }

        /**
         * 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.
         */
1057
        @Exported
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
        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;
        }

1071 1072 1073
        /**
         * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work.
         */
1074
        @Exported
1075 1076 1077
        public List<Plugin> getNeededDependencies() {
            List<Plugin> deps = new ArrayList<Plugin>();

1078
            for(Map.Entry<String,String> e : dependencies.entrySet()) {
1079
                VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
1080
                Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey(), requiredVersion);
1081 1082 1083 1084
                if (depPlugin == null) {
                    LOGGER.log(Level.WARNING, "Could not find dependency {0} of {1}", new Object[] {e.getKey(), name});
                    continue;
                }
1085

1086
                // Is the plugin installed already? If not, add it.
1087 1088 1089
                PluginWrapper current = depPlugin.getInstalled();

                if (current ==null) {
1090 1091 1092 1093
                    deps.add(depPlugin);
                }
                // If the dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
1094
                else if (current.isOlderThan(requiredVersion)) {
1095 1096
                    deps.add(depPlugin);
                }
1097 1098 1099 1100
                // JENKINS-34494 - or if the plugin is disabled, this will allow us to enable it
                else if (!current.isEnabled()) {
                    deps.add(depPlugin);
                }
1101 1102
            }

1103
            for(Map.Entry<String,String> e : optionalDependencies.entrySet()) {
1104
                VersionNumber requiredVersion = e.getValue() != null ? new VersionNumber(e.getValue()) : null;
1105
                Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey(), requiredVersion);
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
                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);
                }
            }

1119 1120 1121
            return deps;
        }
        
1122
        public boolean isForNewerHudson() {
1123 1124
            try {
                return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
1125
                  new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
1126 1127 1128
            } catch (NumberFormatException nfe) {
                return true;  // If unable to parse version
            }
1129
        }
1130

1131
        /**
D
Daniel Beck 已提交
1132
         * Returns true iff the plugin declares a minimum Java version and it's newer than what the Jenkins master is running on.
1133 1134 1135 1136
         * @since TODO
         */
        public boolean isForNewerJava() {
            try {
1137 1138
                final JavaSpecificationVersion currentRuntimeJavaVersion = JavaUtils.getCurrentJavaRuntimeVersionNumber();
                return minimumJavaVersion != null && new JavaSpecificationVersion(minimumJavaVersion).isNewerThan(
1139
                        currentRuntimeJavaVersion);
1140
            } catch (NumberFormatException nfe) {
1141
                logBadMinJavaVersion();
1142
                return false; // treat this as undeclared minimum Java version
1143 1144 1145
            }
        }

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
        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;
        }

1160
        /**
D
Daniel Beck 已提交
1161
         * Returns the minimum Java version needed to use the plugin and all its dependencies.
1162
         * @since TODO
B
Baptiste Mathus 已提交
1163
         * @return the minimum Java version needed to use the plugin and all its dependencies, or null if unspecified.
1164
         */
1165 1166
        @CheckForNull
        public VersionNumber getNeededDependenciesMinimumJavaVersion() {
1167 1168
            VersionNumber versionNumber = null;
            try {
1169
                versionNumber = minimumJavaVersion == null ? null : new VersionNumber(minimumJavaVersion);
1170
            } catch (NumberFormatException nfe) {
1171
                logBadMinJavaVersion();
1172 1173
            }
            for (Plugin p: getNeededDependencies()) {
1174
                VersionNumber v = p.getNeededDependenciesMinimumJavaVersion();
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
                if (v == null) {
                    continue;
                }
                if (versionNumber == null || v.isNewerThan(versionNumber)) {
                    versionNumber = v;
                }
            }
            return versionNumber;
        }

1185
        private void logBadMinJavaVersion() {
1186
            LOGGER.log(Level.WARNING, "minimumJavaVersion was specified for plugin {0} but unparseable (received {1})",
1187
                       new String[]{this.name, this.minimumJavaVersion});
1188 1189
        }

1190
        public boolean isNeededDependenciesForNewerJenkins() {
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
            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;
            });
1204 1205
        }

D
Daniel Beck 已提交
1206
        /**
1207
         * Returns true iff any of the plugin dependencies require a newer Java than Jenkins is running on.
D
Daniel Beck 已提交
1208 1209 1210
         *
         * @since TODO
         */
1211 1212 1213 1214 1215 1216 1217 1218 1219
        public boolean isNeededDependenciesForNewerJava() {
            for (Plugin p: getNeededDependencies()) {
                if (p.isForNewerJava() || p.isNeededDependenciesForNewerJava()) {
                    return true;
                }
            }
            return false;
        }

1220 1221 1222 1223 1224 1225 1226 1227 1228
        /**
         * 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() {
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
            return isNeededDependenciesCompatibleWithInstalledVersion(new PluginManager.MetadataCache());
        }

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

1244
        /**
1245
         * @since 2.40
1246 1247 1248 1249
         */
        @CheckForNull
        @Restricted(NoExternalUse.class)
        public Set<Warning> getWarnings() {
1250
            UpdateSiteWarningsConfiguration configuration = ExtensionList.lookupSingleton(UpdateSiteWarningsConfiguration.class);
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
            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;
        }

        /**
1274
         * @since 2.40
1275 1276 1277 1278 1279 1280
         */
        @Restricted(DoNotUse.class)
        public boolean hasWarnings() {
            return getWarnings().size() > 0;
        }

1281 1282 1283 1284
        /**
         * @deprecated as of 1.326
         *      Use {@link #deploy()}.
         */
1285
        @Deprecated
1286 1287 1288 1289
        public void install() {
            deploy();
        }

1290 1291 1292 1293
        public Future<UpdateCenterJob> deploy() {
            return deploy(false);
        }

1294 1295 1296 1297 1298 1299
        /**
         * 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.
1300 1301 1302 1303
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
1304
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
1305
         */
1306
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad) {
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322
            return deploy(dynamicLoad, null);
        }

        /**
         * 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.
         */
1323
        @Restricted(NoExternalUse.class)
1324
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) {
1325 1326
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
1327
            for (Plugin dep : getNeededDependencies()) {
1328 1329
                UpdateCenter.InstallationJob job = uc.getJob(dep);
                if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) {
1330
                    LOGGER.log(Level.INFO, "Adding dependent install of " + dep.name + " for plugin " + name);
1331 1332
                    dep.deploy(dynamicLoad);
                } else {
1333
                    LOGGER.log(Level.INFO, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping");
1334
                }
1335
            }
1336 1337 1338 1339
            PluginWrapper pw = getInstalled();
            if(pw != null) { // JENKINS-34494 - check for this plugin being disabled
                Future<UpdateCenterJob> enableJob = null;
                if(!pw.isEnabled()) {
1340
                    UpdateCenter.EnableJob job = uc.new EnableJob(UpdateSite.this, null, this, dynamicLoad);
1341 1342 1343 1344
                    job.setCorrelationId(correlationId);
                    enableJob = uc.addJob(job);
                }
                if(pw.getVersionNumber().equals(new VersionNumber(version))) {
1345
                    return enableJob != null ? enableJob : uc.addJob(uc.new NoOpJob(UpdateSite.this, null, this));
1346
                }
1347
            }
1348
            UpdateCenter.InstallationJob job = createInstallationJob(this, uc, dynamicLoad);
1349 1350
            job.setCorrelationId(correlationId);
            return uc.addJob(job);
1351 1352
        }

1353 1354 1355 1356
        /**
         * Schedules the downgrade of this plugin.
         */
        public Future<UpdateCenterJob> deployBackup() {
1357 1358 1359
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
            return uc.addJob(uc.new PluginDowngradeJob(this, UpdateSite.this, Jenkins.getAuthentication()));
1360
        }
1361 1362 1363
        /**
         * Making the installation web bound.
         */
1364
        @RequirePOST
1365 1366 1367 1368 1369
        public HttpResponse doInstall() throws IOException {
            deploy(false);
            return HttpResponses.redirectTo("../..");
        }

1370
        @RequirePOST
1371 1372 1373
        public HttpResponse doInstallNow() throws IOException {
            deploy(true);
            return HttpResponses.redirectTo("../..");
1374
        }
1375 1376 1377 1378

        /**
         * Performs the downgrade of the plugin.
         */
1379
        @RequirePOST
1380
        public HttpResponse doDowngrade() throws IOException {
1381
            deployBackup();
1382
            return HttpResponses.redirectTo("../..");
1383
        }
1384 1385 1386 1387 1388 1389
    }

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

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

1390
    // The name uses UpdateCenter for compatibility reason.
1391
    public static boolean neverUpdate = SystemProperties.getBoolean(UpdateCenter.class.getName()+".never");
1392 1393

}