UpdateSite.java 31.2 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.ClassicPluginStrategy;
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 hudson.util.TextFile;
38
import static hudson.util.TimeUnit2.*;
39 40 41
import hudson.util.VersionNumber;
import java.io.File;
import java.io.IOException;
42
import java.net.URI;
43
import java.net.URL;
44
import java.net.URLEncoder;
45
import java.security.GeneralSecurityException;
46 47
import java.util.ArrayList;
import java.util.Collections;
48
import java.util.HashMap;
49 50 51
import java.util.List;
import java.util.Map;
import java.util.Set;
52
import java.util.TreeMap;
53
import java.util.UUID;
54
import java.util.concurrent.Callable;
55 56 57
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
58 59 60
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.model.Jenkins;
61
import jenkins.model.DownloadSettings;
62 63 64
import jenkins.util.JSONSignatureValidator;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
65
import org.apache.commons.io.IOUtils;
66 67 68 69 70 71 72 73 74
import org.apache.commons.lang.StringUtils;
import org.kohsuke.accmod.Restricted;
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;
75 76

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

    /**
     * When was the last time we asked a browser to check the data for us?
97
     * 0 means never.
98 99 100 101 102 103
     *
     * <p>
     * There's normally some delay between when we send HTML that includes the check code,
     * until we get the data back, so this variable is used to avoid asking too many browseres
     * all at once.
     */
104
    private transient volatile long lastAttempt;
105

106 107 108 109 110 111
    /**
     * 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;

112 113 114 115 116 117 118 119
    /**
     * lastModified time of the data file when it was last read.
     */
    private transient long dataLastReadFromFile;

    /**
     * Latest data as read from the data file.
     */
120
    private transient Data data;
121

122 123 124 125 126 127
    /**
     * ID string for this update source.
     */
    private final String id;

    /**
K
Kohsuke Kawaguchi 已提交
128
     * Path to <tt>update-center.json</tt>, like <tt>http://jenkins-ci.org/update-center.json</tt>.
129 130 131
     */
    private final String url;

132 133


134 135 136 137 138 139 140 141
    public UpdateSite(String id, String url) {
        this.id = id;
        this.url = url;
    }

    /**
     * Get ID string.
     */
142
    @Exported
143 144 145 146
    public String getId() {
        return id;
    }

147
    @Exported
148
    public long getDataTimestamp() {
149
        assert dataTimestamp >= 0;
150 151 152
        return dataTimestamp;
    }

153
    /**
154
     * Update the data file from the given URL if the file
155
     * does not exist, or is otherwise due for update.
156 157
     * 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!)
158
     * @return null if no updates are necessary, or the future result
159
     * @since 1.502
160
     */
161
    public @CheckForNull Future<FormValidation> updateDirectly(final boolean signatureCheck) {
162 163
        if (! getDataFile().exists() || isDue()) {
            return Jenkins.getInstance().getUpdateCenter().updateService.submit(new Callable<FormValidation>() {
164 165
                @Override public FormValidation call() throws Exception {
                    return updateDirectlyNow(signatureCheck);
166 167
                }
            });
168
        } else {
169
            return null;
170 171 172 173 174 175
        }
    }

    @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);
176 177
    }
    
178 179 180
    /**
     * This is the endpoint that receives the update center data file from the browser.
     */
181
    public FormValidation doPostBack(StaplerRequest req) throws IOException, GeneralSecurityException {
182
        DownloadSettings.checkPostBackAccess();
183
        return updateData(IOUtils.toString(req.getInputStream(),"UTF-8"), true);
184 185
    }

186
    private FormValidation updateData(String json, boolean signatureCheck)
187 188 189 190
            throws IOException {

        dataTimestamp = System.currentTimeMillis();

191 192
        JSONObject o = JSONObject.fromObject(json);

193 194 195 196 197 198 199 200
        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);
        }
201 202 203

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

K
bug fix  
Kohsuke Kawaguchi 已提交
210
        LOGGER.info("Obtained the latest update center data file for UpdateSource " + id);
211
        retryWindow = 0;
212
        getDataFile().write(json);
213 214 215 216 217
        return FormValidation.ok();
    }

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

    /**
     * Verifies the signature in the update center data file.
     */
223
    private FormValidation verifySignature(JSONObject o) throws IOException {
224 225 226 227 228 229 230 231 232 233
        return getJsonSignatureValidator().verifySignature(o);
    }

    /**
     * Let sub-classes of UpdateSite provide their own signature validator.
     * @return the signature validator.
     */
    @Nonnull
    protected JSONSignatureValidator getJsonSignatureValidator() {
        return new JSONSignatureValidator("update site '"+id+"'");
234 235 236 237 238 239 240
    }

    /**
     * Returns true if it's time for us to check for new version.
     */
    public boolean isDue() {
        if(neverUpdate)     return false;
241
        if(dataTimestamp == 0)
242 243
            dataTimestamp = getDataFile().file.lastModified();
        long now = System.currentTimeMillis();
244 245 246 247 248 249 250 251
        
        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
        }
252 253 254
        return due;
    }

255 256 257 258 259
    /**
     * Invalidates the cached data and force retrieval.
     *
     * @since 1.432
     */
260
    @RequirePOST
261 262 263 264 265 266
    public HttpResponse doInvalidateData() {
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
        dataTimestamp = 0;
        return HttpResponses.ok();
    }

267
    /**
268
     * Loads the update center data, if any and if modified since last read.
269 270 271 272
     *
     * @return  null if no data is available.
     */
    public Data getData() {
273 274 275 276 277 278 279 280 281 282 283
        TextFile df = getDataFile();
        if (df.exists() && dataLastReadFromFile != df.file.lastModified()) {
            JSONObject o = getJSONObject();
            if (o!=null) {
                data = new Data(o);
                dataLastReadFromFile = df.file.lastModified();
            } else {
                data = null;
            }
        }
        return data;
284 285 286 287 288 289
    }

    /**
     * Gets the raw update center JSON data.
     */
    public JSONObject getJSONObject() {
290 291 292
        TextFile df = getDataFile();
        if(df.exists()) {
            try {
293
                return JSONObject.fromObject(df.read());
294 295 296 297
            } 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;
298 299 300 301 302 303 304 305 306
            } 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;
        }
    }
307

308 309 310 311
    /**
     * Returns a list of plugins that should be shown in the "available" tab.
     * These are "all plugins - installed plugins".
     */
312
    @Exported
313 314 315
    public List<Plugin> getAvailables() {
        List<Plugin> r = new ArrayList<Plugin>();
        Data data = getData();
316
        if(data==null)     return Collections.emptyList();
317 318 319 320 321 322
        for (Plugin p : data.plugins.values()) {
            if(p.getInstalled()==null)
                r.add(p);
        }
        return r;
    }
323

324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    /**
     * 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);
    }

339 340 341 342
    public Api getApi() {
        return new Api(this);
    }

343 344 345
    /**
     * Returns an "always up" server for Internet connectivity testing, or null if we are going to skip the test.
     */
346
    @Exported
347 348 349 350 351 352 353 354 355 356
    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() {
357
        return new TextFile(new File(Jenkins.getInstance().getRootDir(),
358 359 360 361 362 363 364 365 366
                                     "updates/" + getId()+".json"));
    }
    
    /**
     * Returns the list of plugins that are updates to currently installed ones.
     *
     * @return
     *      can be empty but never null.
     */
367
    @Exported
368 369 370 371 372
    public List<Plugin> getUpdates() {
        Data data = getData();
        if(data==null)      return Collections.emptyList(); // fail to determine
        
        List<Plugin> r = new ArrayList<Plugin>();
373
        for (PluginWrapper pw : Jenkins.getInstance().getPluginManager().getPlugins()) {
374 375 376 377 378 379 380 381 382 383
            Plugin p = pw.getUpdateInfo();
            if(p!=null) r.add(p);
        }
        
        return r;
    }
    
    /**
     * Does any of the plugin has updates?
     */
384
    @Exported
385 386 387 388
    public boolean hasUpdates() {
        Data data = getData();
        if(data==null)      return false;
        
389
        for (PluginWrapper pw : Jenkins.getInstance().getPluginManager().getPlugins()) {
390 391
            if(!pw.isBundled() && pw.getUpdateInfo()!=null)
                // do not advertize updates to bundled plugins, since we generally want users to get them
A
alanharder 已提交
392
                // as a part of jenkins.war updates. This also avoids unnecessary pinning of plugins. 
393 394 395 396 397 398 399 400 401 402
                return true;
        }
        return false;
    }
    
    
    /**
     * Exposed to get rid of hardcoding of the URL that serves up update-center.json
     * in Javascript.
     */
403
    @Exported
404 405 406 407
    public String getUrl() {
        return url;
    }

408 409 410 411 412 413
    /**
     * Where to actually download the update center?
     *
     * @deprecated
     *      Exposed only for UI.
     */
414
    @Deprecated
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    public String getDownloadUrl() {
        /*
            HACKISH:

            Loading scripts in HTTP from HTTPS pages cause browsers to issue a warning dialog.
            The elegant way to solve the problem is to always load update center from HTTPS,
            but our backend mirroring scheme isn't ready for that. So this hack serves regular
            traffic in HTTP server, and only use HTTPS update center for Jenkins in HTTPS.

            We'll monitor the traffic to see if we can sustain this added traffic.
         */
        if (url.equals("http://updates.jenkins-ci.org/update-center.json") && Jenkins.getInstance().isRootUrlSecure())
            return "https"+url.substring(4);
        return url;
    }

K
kohsuke 已提交
431 432 433 434
    /**
     * Is this the legacy default update center site?
     */
    public boolean isLegacyDefault() {
435
        return id.equals(UpdateCenter.ID_DEFAULT) && url.startsWith("http://hudson-ci.org/") || url.startsWith("http://updates.hudson-labs.org/");
K
kohsuke 已提交
436 437
    }

438 439 440 441 442 443 444 445 446 447
    /**
     * In-memory representation of the update center data.
     */
    public final class Data {
        /**
         * The {@link UpdateSite} ID.
         */
        public final String sourceId;

        /**
A
alanharder 已提交
448
         * The latest jenkins.war.
449 450 451 452 453 454 455 456
         */
        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);

        /**
A
alanharder 已提交
457
         * If this is non-null, Jenkins is going to check the connectivity to this URL to make sure
458 459 460 461 462 463
         * the network connection is up. Null to skip the check.
         */
        public final String connectionCheckUrl;

        Data(JSONObject o) {
            this.sourceId = (String)o.get("id");
464 465 466 467
            JSONObject c = o.optJSONObject("core");
            if (c!=null) {
                core = new Entry(sourceId, c, url);
            } else {
468 469 470
                core = null;
            }
            for(Map.Entry<String,JSONObject> e : (Set<Map.Entry<String,JSONObject>>)o.getJSONObject("plugins").entrySet()) {
471 472 473 474 475 476 477 478 479 480 481
                Plugin p = new Plugin(sourceId, e.getValue());
                // JENKINS-33308 - include implied dependencies for older plugins that may need them
                List<PluginWrapper.Dependency> implicitDeps = ClassicPluginStrategy.getImpliedDependencies(p.name, p.requiredCore);
                if(!implicitDeps.isEmpty()) {
                    for(PluginWrapper.Dependency dep : implicitDeps) {
                        if(!p.dependencies.containsKey(dep.shortName)) {
                            p.dependencies.put(dep.shortName, dep.version);
                        }
                    }
                }
                plugins.put(e.getKey(), p);
482 483 484 485 486 487 488 489 490
            }

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

        /**
         * Is there a new version of the core?
         */
        public boolean hasCoreUpdates() {
491
            return core != null && core.isNewerThan(Jenkins.VERSION);
492 493 494 495 496 497 498 499 500 501
        }

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

502
    @ExportedBean
503 504 505 506
    public static class Entry {
        /**
         * {@link UpdateSite} ID.
         */
507
        @Exported
508 509 510 511 512
        public final String sourceId;

        /**
         * Artifact ID.
         */
513
        @Exported
514 515 516 517
        public final String name;
        /**
         * The version.
         */
518
        @Exported
519 520 521 522
        public final String version;
        /**
         * Download URL.
         */
523
        @Exported
524 525
        public final String url;

526 527 528 529

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

531
        public Entry(String sourceId, JSONObject o) {
532 533 534 535
            this(sourceId, o, null);
        }

        Entry(String sourceId, JSONObject o, String baseURL) {
536 537 538
            this.sourceId = sourceId;
            this.name = o.getString("name");
            this.version = o.getString("version");
539 540 541

            // 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.
542
            this.sha1 = Util.fixEmptyAndTrim(o.optString("sha1"));
543

544 545 546 547 548 549 550 551
            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;
552 553
        }

554 555 556 557 558 559 560 561 562 563
        /**
         * The base64 encoded binary SHA-1 checksum of the file.
         * Can be null if not provided by the update site.
         * @since TODO
         */
        // TODO @Exported assuming we want this in the API
        public String getSha1() {
            return sha1;
        }

564 565 566 567 568 569 570 571 572 573 574
        /**
         * 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 {
575
                return new VersionNumber(currentVersion).compareTo(new VersionNumber(version)) < 0;
576 577 578 579 580
            } catch (IllegalArgumentException e) {
                // couldn't parse as the version number.
                return false;
            }
        }
581

582 583 584 585
        public Api getApi() {
            return new Api(this);
        }

586 587 588 589 590 591
    }

    public final class Plugin extends Entry {
        /**
         * Optional URL to the Wiki page that discusses this plugin.
         */
592
        @Exported
593 594 595 596 597 598 599 600
        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
         */
601
        @Exported
602 603 604 605
        public final String title;
        /**
         * Optional excerpt string.
         */
606
        @Exported
607 608 609 610
        public final String excerpt;
        /**
         * Optional version # from which this plugin release is configuration-compatible.
         */
611
        @Exported
612
        public final String compatibleSinceVersion;
613
        /**
A
alanharder 已提交
614
         * Version of Jenkins core this plugin was compiled against.
615
         */
616
        @Exported
617
        public final String requiredCore;
618 619 620 621
        /**
         * Categories for grouping plugins, taken from labels assigned to wiki page.
         * Can be null.
         */
622
        @Exported
623
        public final String[] categories;
624

625
        /**
626
         * Dependencies of this plugin, a name -&gt; version mapping.
627
         */
628
        @Exported
629 630
        public final Map<String,String> dependencies = new HashMap<String,String>();
        
631 632 633 634 635 636
        /**
         * Optional dependencies of this plugin.
         */
        @Exported
        public final Map<String,String> optionalDependencies = new HashMap<String,String>();

637 638
        @DataBoundConstructor
        public Plugin(String sourceId, JSONObject o) {
639
            super(sourceId, o, UpdateSite.this.url);
640 641 642 643
            this.wiki = get(o,"wiki");
            this.title = get(o,"title");
            this.excerpt = get(o,"excerpt");
            this.compatibleSinceVersion = get(o,"compatibleSinceVersion");
644
            this.requiredCore = get(o,"requiredCore");
645
            this.categories = o.has("labels") ? (String[])o.getJSONArray("labels").toArray(new String[0]) : null;
646 647
            for(Object jo : o.getJSONArray("dependencies")) {
                JSONObject depObj = (JSONObject) jo;
648 649
                // Make sure there's a name attribute and that the optional value isn't true.
                if (get(depObj,"name")!=null) {
650 651 652 653 654
                    if (get(depObj, "optional").equals("false")) {
                        dependencies.put(get(depObj, "name"), get(depObj, "version"));
                    } else {
                        optionalDependencies.put(get(depObj, "name"), get(depObj, "version"));
                    }
655 656 657 658
                }
                
            }

659 660 661 662 663 664 665 666 667 668
        }

        private String get(JSONObject o, String prop) {
            if(o.has(prop))
                return o.getString(prop);
            else
                return null;
        }

        public String getDisplayName() {
669 670 671 672 673 674
            String displayName;
            if(title!=null)
                displayName = title;
            else
                displayName = name;
            return StringUtils.removeStart(displayName, "Jenkins ");
675 676 677 678 679 680
        }

        /**
         * If some version of this plugin is currently installed, return {@link PluginWrapper}.
         * Otherwise null.
         */
681
        @Exported
682
        public PluginWrapper getInstalled() {
683
            PluginManager pm = Jenkins.getInstance().getPluginManager();
684 685 686 687 688 689 690 691 692 693
            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.
         */
694
        @Exported
695 696 697 698 699 700 701 702 703 704 705 706 707
        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;
        }

708 709 710
        /**
         * Returns a list of dependent plugins which need to be installed or upgraded for this plugin to work.
         */
711
        @Exported
712 713 714
        public List<Plugin> getNeededDependencies() {
            List<Plugin> deps = new ArrayList<Plugin>();

715
            for(Map.Entry<String,String> e : dependencies.entrySet()) {
716
                Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey());
717 718 719 720
                if (depPlugin == null) {
                    LOGGER.log(Level.WARNING, "Could not find dependency {0} of {1}", new Object[] {e.getKey(), name});
                    continue;
                }
721
                VersionNumber requiredVersion = new VersionNumber(e.getValue());
722 723
                
                // Is the plugin installed already? If not, add it.
724 725 726
                PluginWrapper current = depPlugin.getInstalled();

                if (current ==null) {
727 728 729 730
                    deps.add(depPlugin);
                }
                // If the dependency plugin is installed, is the version we depend on newer than
                // what's installed? If so, upgrade.
731
                else if (current.isOlderThan(requiredVersion)) {
732 733 734 735
                    deps.add(depPlugin);
                }
            }

736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
            for(Map.Entry<String,String> e : optionalDependencies.entrySet()) {
                Plugin depPlugin = Jenkins.getInstance().getUpdateCenter().getPlugin(e.getKey());
                if (depPlugin == null) {
                    continue;
                }
                VersionNumber requiredVersion = new VersionNumber(e.getValue());

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

752 753 754
            return deps;
        }
        
755
        public boolean isForNewerHudson() {
756 757
            try {
                return requiredCore!=null && new VersionNumber(requiredCore).isNewerThan(
758
                  new VersionNumber(Jenkins.VERSION.replaceFirst("SHOT *\\(private.*\\)", "SHOT")));
759 760 761
            } catch (NumberFormatException nfe) {
                return true;  // If unable to parse version
            }
762
        }
763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

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

        public boolean isNeededDependenciesForNewerJenkins() {
            for (Plugin p: getNeededDependencies()) {
                if (p.isForNewerHudson() || p.isNeededDependenciesForNewerJenkins()) return true;
            }
            return false;
        }

        /**
         * 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() {
            for (Plugin p: getNeededDependencies()) {
                if (!p.isCompatibleWithInstalledVersion() || !p.isNeededDependenciesCompatibleWithInstalledVersion())
                    return false;
            }
            return true;
        }
800

801 802 803 804
        /**
         * @deprecated as of 1.326
         *      Use {@link #deploy()}.
         */
805
        @Deprecated
806 807 808 809
        public void install() {
            deploy();
        }

810 811 812 813
        public Future<UpdateCenterJob> deploy() {
            return deploy(false);
        }

814 815 816 817 818 819
        /**
         * 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.
820 821 822 823
         *
         * @param dynamicLoad
         *      If true, the plugin will be dynamically loaded into this Jenkins. If false,
         *      the plugin will only take effect after the reboot.
824
         *      See {@link UpdateCenter#isRestartRequiredForCompletion()}
825
         */
826
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad) {
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
            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.
         */
843
        @Restricted(NoExternalUse.class)
844
        public Future<UpdateCenterJob> deploy(boolean dynamicLoad, @CheckForNull UUID correlationId) {
845 846
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
847
            for (Plugin dep : getNeededDependencies()) {
848 849 850 851 852 853 854
                UpdateCenter.InstallationJob job = uc.getJob(dep);
                if (job == null || job.status instanceof UpdateCenter.DownloadJob.Failure) {
                    LOGGER.log(Level.WARNING, "Adding dependent install of " + dep.name + " for plugin " + name);
                    dep.deploy(dynamicLoad);
                } else {
                    LOGGER.log(Level.WARNING, "Dependent install of " + dep.name + " for plugin " + name + " already added, skipping");
                }
855
            }
856 857 858
            UpdateCenter.InstallationJob job = uc.new InstallationJob(this, UpdateSite.this, Jenkins.getAuthentication(), dynamicLoad);
            job.setCorrelationId(correlationId);
            return uc.addJob(job);
859 860
        }

861 862 863 864
        /**
         * Schedules the downgrade of this plugin.
         */
        public Future<UpdateCenterJob> deployBackup() {
865 866 867
            Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
            UpdateCenter uc = Jenkins.getInstance().getUpdateCenter();
            return uc.addJob(uc.new PluginDowngradeJob(this, UpdateSite.this, Jenkins.getAuthentication()));
868
        }
869 870 871
        /**
         * Making the installation web bound.
         */
872
        @RequirePOST
873 874 875 876 877
        public HttpResponse doInstall() throws IOException {
            deploy(false);
            return HttpResponses.redirectTo("../..");
        }

878
        @RequirePOST
879 880 881
        public HttpResponse doInstallNow() throws IOException {
            deploy(true);
            return HttpResponses.redirectTo("../..");
882
        }
883 884 885 886

        /**
         * Performs the downgrade of the plugin.
         */
887
        @RequirePOST
888
        public HttpResponse doDowngrade() throws IOException {
889
            deployBackup();
890
            return HttpResponses.redirectTo("../..");
891
        }
892 893 894 895 896 897
    }

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

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

898
    // The name uses UpdateCenter for compatibility reason.
899
    public static boolean neverUpdate = Boolean.getBoolean(UpdateCenter.class.getName()+".never");
900 901

}