UpdateCenter.java 52.4 KB
Newer Older
K
kohsuke 已提交
1 2
/*
 * The MIT License
3
 *
4
 * Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc., Seiji Sogabe
5
 *
K
kohsuke 已提交
6 7 8 9 10 11
 * 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:
12
 *
K
kohsuke 已提交
13 14
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
15
 *
K
kohsuke 已提交
16 17 18 19 20 21 22 23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
24 25
package hudson.model;

26 27
import hudson.BulkChange;
import hudson.Extension;
28
import hudson.ExtensionPoint;
K
kohsuke 已提交
29
import hudson.Functions;
30 31
import hudson.PluginManager;
import hudson.PluginWrapper;
32
import hudson.ProxyConfiguration;
33 34
import hudson.Util;
import hudson.XmlFile;
K
kohsuke 已提交
35
import static hudson.init.InitMilestone.PLUGINS_STARTED;
K
kohsuke 已提交
36
import hudson.init.Initializer;
37
import hudson.lifecycle.Lifecycle;
38
import hudson.lifecycle.RestartNotSupportedException;
39 40
import hudson.model.UpdateSite.Data;
import hudson.model.UpdateSite.Plugin;
41
import hudson.model.listeners.SaveableListener;
42
import hudson.remoting.AtmostOneThreadExecutor;
S
sogabe 已提交
43
import hudson.security.ACL;
44
import hudson.util.DaemonThreadFactory;
45
import hudson.util.FormValidation;
46
import hudson.util.HttpResponses;
47
import hudson.util.NamingThreadFactory;
48
import hudson.util.IOException2;
49
import hudson.util.IOUtils;
50 51
import hudson.util.PersistedList;
import hudson.util.XStream2;
52
import jenkins.RestartRequiredException;
53
import jenkins.model.Jenkins;
54
import jenkins.util.io.OnMaster;
55
import org.acegisecurity.Authentication;
56
import org.acegisecurity.context.SecurityContext;
57
import org.apache.commons.io.input.CountingInputStream;
K
kohsuke 已提交
58
import org.apache.commons.io.output.NullOutputStream;
59
import org.jvnet.localizer.Localizable;
60
import org.kohsuke.stapler.HttpResponse;
61
import org.kohsuke.stapler.StaplerRequest;
K
kohsuke 已提交
62
import org.kohsuke.stapler.StaplerResponse;
63

K
kohsuke 已提交
64
import javax.net.ssl.SSLHandshakeException;
65
import javax.servlet.ServletException;
66
import java.io.File;
67
import java.io.FileOutputStream;
68
import java.io.IOException;
69 70
import java.io.OutputStream;
import java.net.MalformedURLException;
71
import java.net.URL;
72
import java.net.URLConnection;
73
import java.net.UnknownHostException;
74
import java.util.ArrayList;
75
import java.util.Collections;
76
import java.util.HashSet;
77
import java.util.LinkedHashMap;
78
import java.util.List;
79
import java.util.Map;
80
import java.util.Set;
81
import java.util.TreeSet;
82
import java.util.Vector;
83
import java.util.concurrent.ExecutionException;
84
import java.util.concurrent.ExecutorService;
K
kohsuke 已提交
85
import java.util.concurrent.Executors;
K
kohsuke 已提交
86
import java.util.concurrent.Future;
K
kohsuke 已提交
87
import java.util.concurrent.atomic.AtomicInteger;
88
import java.util.jar.Attributes;
89
import java.util.jar.JarFile;
90 91
import java.util.logging.Level;
import java.util.logging.Logger;
92
import javax.annotation.CheckForNull;
S
sogabe 已提交
93
import org.acegisecurity.context.SecurityContextHolder;
94 95
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
96 97
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
98
import org.kohsuke.stapler.interceptor.RequirePOST;
99

100

101 102 103
/**
 * Controls update center capability.
 *
104 105 106
 * <p>
 * The main job of this class is to keep track of the latest update center metadata file, and perform installations.
 * Much of the UI about choosing plugins to install is done in {@link PluginManager}.
107 108 109 110 111
 * <p>
 * The update center can be configured to contact alternate servers for updates
 * and plugins, and to use alternate strategies for downloading, installing
 * and updating components. See the Javadocs for {@link UpdateCenterConfiguration}
 * for more information.
112
 *
113
 * @author Kohsuke Kawaguchi
K
kohsuke 已提交
114
 * @since 1.220
115
 */
116
@ExportedBean
117
public class UpdateCenter extends AbstractModelObject implements Saveable, OnMaster {
118 119
	
    private static final String UPDATE_CENTER_URL = System.getProperty(UpdateCenter.class.getName()+".updateCenterUrl","http://updates.jenkins-ci.org/");
120 121

    /**
122
     * {@linkplain UpdateSite#getId() ID} of the default update site.
123 124 125
     * @since 1.483
     */
    public static final String ID_DEFAULT = "default";
126 127 128

    @Restricted(NoExternalUse.class)
    public static final String ID_UPLOAD = "_upload";
129
	
130 131
    /**
     * {@link ExecutorService} that performs installation.
132
     * @since 1.501
133
     */
134
    private final ExecutorService installerService = new AtmostOneThreadExecutor(
135
        new NamingThreadFactory(new DaemonThreadFactory(), "Update center installer thread"));
136

137 138 139 140
    /**
     * An {@link ExecutorService} for updating UpdateSites.
     */
    protected final ExecutorService updateService = Executors.newCachedThreadPool(
141
        new NamingThreadFactory(new DaemonThreadFactory(), "Update site data downloader"));
142
        
143
    /**
144
     * List of created {@link UpdateCenterJob}s. Access needs to be synchronized.
145
     */
146
    private final Vector<UpdateCenterJob> jobs = new Vector<UpdateCenterJob>();
147

148
    /**
149 150
     * {@link UpdateSite}s from which we've already installed a plugin at least once.
     * This is used to skip network tests.
151
     */
152 153
    private final Set<UpdateSite> sourcesUsed = new HashSet<UpdateSite>();

154
    /**
155
     * List of {@link UpdateSite}s to be used.
156
     */
157 158 159 160 161 162 163
    private final PersistedList<UpdateSite> sites = new PersistedList<UpdateSite>(this);

    /**
     * Update center configuration data
     */
    private UpdateCenterConfiguration config;

164 165
    private boolean requiresRestart;

166
    public UpdateCenter() {
167 168
        configure(new UpdateCenterConfiguration());
    }
169

170 171 172 173
    public Api getApi() {
        return new Api(this);
    }

174 175 176 177
    /**
     * Configures update center to get plugins/updates from alternate servers,
     * and optionally using alternate strategies for downloading, installing
     * and upgrading.
178
     *
179 180 181 182 183 184 185 186
     * @param config Configuration data
     * @see UpdateCenterConfiguration
     */
    public void configure(UpdateCenterConfiguration config) {
        if (config!=null) {
            this.config = config;
        }
    }
187

188
    /**
189
     * Returns the list of {@link UpdateCenterJob} representing scheduled installation attempts.
190 191
     *
     * @return
K
kohsuke 已提交
192
     *      can be empty but never null. Oldest entries first.
193
     */
194
    @Exported
195
    public List<UpdateCenterJob> getJobs() {
K
kohsuke 已提交
196
        synchronized (jobs) {
197
            return new ArrayList<UpdateCenterJob>(jobs);
K
kohsuke 已提交
198
        }
199 200
    }

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    /**
     * Gets a job by its ID.
     *
     * Primarily to make {@link UpdateCenterJob} bound to URL.
     */
    public UpdateCenterJob getJob(int id) {
        synchronized (jobs) {
            for (UpdateCenterJob job : jobs) {
                if (job.id==id)
                    return job;
            }
        }
        return null;
    }

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
    /**
     * Returns latest install/upgrade job for the given plugin.
     * @return InstallationJob or null if not found
     */
    public InstallationJob getJob(Plugin plugin) {
        List<UpdateCenterJob> jobList = getJobs();
        Collections.reverse(jobList);
        for (UpdateCenterJob job : jobList)
            if (job instanceof InstallationJob) {
                InstallationJob ij = (InstallationJob)job;
                if (ij.plugin.name.equals(plugin.name) && ij.plugin.sourceId.equals(plugin.sourceId))
                    return ij;
            }
        return null;
    }

232
    /**
233
     * Returns latest Jenkins upgrade job.
234 235 236 237 238 239 240 241 242 243 244
     * @return HudsonUpgradeJob or null if not found
     */
    public HudsonUpgradeJob getHudsonJob() {
        List<UpdateCenterJob> jobList = getJobs();
        Collections.reverse(jobList);
        for (UpdateCenterJob job : jobList)
            if (job instanceof HudsonUpgradeJob)
                return (HudsonUpgradeJob)job;
        return null;
    }

245
    /**
246 247 248 249 250
     * Returns the list of {@link UpdateSite}s to be used.
     * This is a live list, whose change will be persisted automatically.
     *
     * @return
     *      can be empty but never null.
251
     */
252 253
    public PersistedList<UpdateSite> getSites() {
        return sites;
254 255
    }

256 257 258 259 260 261 262 263
    /**
     * The same as {@link #getSites()} but for REST API.
     */
    @Exported(name="sites")
    public List<UpdateSite> getSiteList() {
        return sites.toList();
    }

J
Jesse Glick 已提交
264 265 266
    /**
     * Alias for {@link #getById}.
     */
267
    public UpdateSite getSite(String id) {
J
Jesse Glick 已提交
268
        return getById(id);
269 270
    }

271
    /**
272 273
     * Gets the string representing how long ago the data was obtained.
     * Will be the newest of all {@link UpdateSite}s.
274
     */
275
    public String getLastUpdatedString() {
276
        long newestTs = 0;
277 278 279 280
        for (UpdateSite s : sites) {
            if (s.getDataTimestamp()>newestTs) {
                newestTs = s.getDataTimestamp();
            }
281
        }
282
        if (newestTs == 0) {
J
Jesse Glick 已提交
283 284
            return Messages.UpdateCenter_n_a();
        }
285
        return Util.getPastTimeString(System.currentTimeMillis()-newestTs);
286 287
    }

288
    /**
289 290
     * Gets {@link UpdateSite} by its ID.
     * Used to bind them to URL.
291
     */
292 293 294 295
    public UpdateSite getById(String id) {
        for (UpdateSite s : sites) {
            if (s.getId().equals(id)) {
                return s;
296
            }
297
        }
298 299
        return null;
    }
300

301
    /**
302
     * Gets the {@link UpdateSite} from which we receive updates for <tt>jenkins.war</tt>.
303 304 305 306 307
     *
     * @return
     *      null if no such update center is provided.
     */
    public UpdateSite getCoreSource() {
K
kohsuke 已提交
308 309 310
        for (UpdateSite s : sites) {
            Data data = s.getData();
            if (data!=null && data.core!=null)
311
                return s;
K
kohsuke 已提交
312
        }
313 314
        return null;
    }
315

316 317 318 319 320 321 322
    /**
     * Gets the default base URL.
     *
     * @deprecated
     *      TODO: revisit tool update mechanism, as that should be de-centralized, too. In the mean time,
     *      please try not to use this method, and instead ping us to get this part completed.
     */
323
    @Deprecated
324 325 326
    public String getDefaultBaseUrl() {
        return config.getUpdateCenterUrl();
    }
327

328 329 330
    /**
     * Gets the plugin with the given name from the first {@link UpdateSite} to contain it.
     */
331
    public @CheckForNull Plugin getPlugin(String artifactId) {
332 333 334
        for (UpdateSite s : sites) {
            Plugin p = s.getPlugin(artifactId);
            if (p!=null) return p;
335
        }
336
        return null;
337 338
    }

339
    /**
340
     * Schedules a Jenkins upgrade.
341
     */
342
    @RequirePOST
343
    public void doUpgrade(StaplerResponse rsp) throws IOException, ServletException {
344 345
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
        HudsonUpgradeJob job = new HudsonUpgradeJob(getCoreSource(), Jenkins.getAuthentication());
346
        if(!Lifecycle.get().canRewriteHudsonWar()) {
347
            sendError("Jenkins upgrade not supported in this running mode");
348 349 350 351 352 353 354 355
            return;
        }

        LOGGER.info("Scheduling the core upgrade");
        addJob(job);
        rsp.sendRedirect2(".");
    }

356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    /**
     * Invalidates the update center JSON data for all the sites and force re-retrieval.
     *
     * @since 1.432
     */
    public HttpResponse doInvalidateData() {
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
        for (UpdateSite site : sites) {
            site.doInvalidateData();
        }

        return HttpResponses.ok();
    }


371 372 373 374
    /**
     * Schedules a Jenkins restart.
     */
    public void doSafeRestart(StaplerRequest request, StaplerResponse response) throws IOException, ServletException {
A
appr 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        synchronized (jobs) {
            if (!isRestartScheduled()) {
                Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
                addJob(new RestartJenkinsJob(getCoreSource()));
                LOGGER.info("Scheduling Jenkins reboot");
            }
        }
        response.sendRedirect2(".");
    }
    
    /**
     * Cancel all scheduled jenkins restarts
     */
    public void doCancelRestart(StaplerResponse response) throws IOException, ServletException {
        synchronized (jobs) {
            for (UpdateCenterJob job : jobs) {
                if (job instanceof RestartJenkinsJob) {
                    if (((RestartJenkinsJob) job).cancel()) {
                        LOGGER.info("Scheduled Jenkins reboot unscheduled");
                    }
                }
            }
        }
398 399
        response.sendRedirect2(".");
    }
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

    /**
     * If any of the executed {@link UpdateCenterJob}s requires a restart
     * to take effect, this method returns true.
     *
     * <p>
     * This doesn't necessarily mean the user has scheduled or initiated
     * the restart operation.
     *
     * @see #isRestartScheduled()
     */
    @Exported
    public boolean isRestartRequiredForCompletion() {
        return requiresRestart;
    }

A
appr 已提交
416
    /**
417 418 419 420
     * Checks if the restart operation is scheduled
     * (which means in near future Jenkins will restart by itself)
     *
     * @see #isRestartRequiredForCompletion()
A
appr 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433
     */
    public boolean isRestartScheduled() {
        for (UpdateCenterJob job : getJobs()) {
            if (job instanceof RestartJenkinsJob) {
                RestartJenkinsJob.RestartJenkinsJobStatus status = ((RestartJenkinsJob) job).status;
                if (status instanceof RestartJenkinsJob.Pending
                        || status instanceof RestartJenkinsJob.Running) {
                    return true;
                }
            }
        }
        return false;
    }
434

435
    /**
436
     * Returns true if backup of jenkins.war exists on the hard drive
437 438 439 440 441 442 443 444
     */
    public boolean isDowngradable() {
        return new File(Lifecycle.get().getHudsonWar() + ".bak").exists();
    }

    /**
     * Performs hudson downgrade.
     */
445
    @RequirePOST
446
    public void doDowngrade(StaplerResponse rsp) throws IOException, ServletException {
447
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
448
        if(!isDowngradable()) {
449
            sendError("Jenkins downgrade is not possible, probably backup does not exist");
450 451 452
            return;
        }

453
        HudsonDowngradeJob job = new HudsonDowngradeJob(getCoreSource(), Jenkins.getAuthentication());
454 455 456 457 458
        LOGGER.info("Scheduling the core downgrade");
        addJob(job);
        rsp.sendRedirect2(".");
    }

459 460 461 462
    /**
     * Performs hudson downgrade.
     */
    public void doRestart(StaplerResponse rsp) throws IOException, ServletException {
463 464
        Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
        HudsonDowngradeJob job = new HudsonDowngradeJob(getCoreSource(), Jenkins.getAuthentication());
465 466 467 468 469 470
        LOGGER.info("Scheduling the core downgrade");

        addJob(job);
        rsp.sendRedirect2(".");
    }

471 472 473 474
    /**
     * Returns String with version of backup .war file,
     * if the file does not exists returns null
     */
475
    public String getBackupVersion() {
476
        try {
477
            JarFile backupWar = new JarFile(new File(Lifecycle.get().getHudsonWar() + ".bak"));
478 479 480 481 482 483 484 485
            try {
                Attributes attrs = backupWar.getManifest().getMainAttributes();
                String v = attrs.getValue("Jenkins-Version");
                if (v==null)    v = attrs.getValue("Hudson-Version");
                return v;
            } finally {
                backupWar.close();
            }
486 487 488 489 490 491
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to read backup version ", e);
            return null;}

    }

492
    /*package*/ synchronized Future<UpdateCenterJob> addJob(UpdateCenterJob job) {
493
        // the first job is always the connectivity check
494 495
        if (sourcesUsed.add(job.site))
            new ConnectionCheckJob(job.site).submit();
K
kohsuke 已提交
496
        return job.submit();
497 498
    }

499 500 501 502 503 504
    public String getDisplayName() {
        return "Update center";
    }

    public String getSearchUrl() {
        return "updateCenter";
505 506
    }

507
    /**
508
     * Saves the configuration info to the disk.
509
     */
510 511 512 513
    public synchronized void save() {
        if(BulkChange.contains(this))   return;
        try {
            getConfigFile().write(sites);
514
            SaveableListener.fireOnChange(this, getConfigFile());
515 516
        } catch (IOException e) {
            LOGGER.log(Level.WARNING, "Failed to save "+getConfigFile(),e);
517 518 519
        }
    }

520
    /**
521
     * Loads the data from the disk into this object.
522
     */
523
    public synchronized void load() throws IOException {
524
        UpdateSite defaultSite = new UpdateSite(ID_DEFAULT, config.getUpdateCenterUrl() + "update-center.json");
525 526 527 528 529 530 531
        XmlFile file = getConfigFile();
        if(file.exists()) {
            try {
                sites.replaceBy(((PersistedList)file.unmarshal(sites)).toList());
            } catch (IOException e) {
                LOGGER.log(Level.WARNING, "Failed to load "+file, e);
            }
K
kohsuke 已提交
532 533 534 535 536 537 538 539
            for (UpdateSite site : sites) {
                // replace the legacy site with the new site
                if (site.isLegacyDefault()) {
                    sites.remove(site);
                    sites.add(defaultSite);
                    break;
                }
            }
540 541
        } else {
            if (sites.isEmpty()) {
K
kohsuke 已提交
542
                // If there aren't already any UpdateSources, add the default one.
543
                // to maintain compatibility with existing UpdateCenterConfiguration, create the default one as specified by UpdateCenterConfiguration
K
kohsuke 已提交
544
                sites.add(defaultSite);
545 546
            }
        }
547 548
    }

549
    private XmlFile getConfigFile() {
550
        return new XmlFile(XSTREAM,new File(Jenkins.getInstance().root,
551
                                    UpdateCenter.class.getName()+".xml"));
552 553
    }

554
    public List<Plugin> getAvailables() {
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
        Map<String,Plugin> pluginMap = new LinkedHashMap<String, Plugin>();
        for (UpdateSite site : sites) {
            for (Plugin plugin: site.getAvailables()) {
                final Plugin existing = pluginMap.get(plugin.name);
                if (existing == null) {
                    pluginMap.put(plugin.name, plugin);
                } else if (!existing.version.equals(plugin.version)) {
                    // allow secondary update centers to publish different versions
                    // TODO refactor to consolidate multiple versions of the same plugin within the one row
                    final String altKey = plugin.name + ":" + plugin.version;
                    if (!pluginMap.containsKey(altKey)) {
                        pluginMap.put(altKey, plugin);
                    }
                }
            }
570 571
        }

572
        return new ArrayList<Plugin>(pluginMap.values());
573 574
    }

575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
    /**
     * Returns a list of plugins that should be shown in the "available" tab, grouped by category.
     * A plugin with multiple categories will appear multiple times in the list.
     */
    public PluginEntry[] getCategorizedAvailables() {
        TreeSet<PluginEntry> entries = new TreeSet<PluginEntry>();
        for (Plugin p : getAvailables()) {
            if (p.categories==null || p.categories.length==0)
                entries.add(new PluginEntry(p, getCategoryDisplayName(null)));
            else
                for (String c : p.categories)
                    entries.add(new PluginEntry(p, getCategoryDisplayName(c)));
        }
        return entries.toArray(new PluginEntry[entries.size()]);
    }

    private static String getCategoryDisplayName(String category) {
        if (category==null)
            return Messages.UpdateCenter_PluginCategory_misc();
        try {
            return (String)Messages.class.getMethod(
                    "UpdateCenter_PluginCategory_" + category.replace('-', '_')).invoke(null);
        } catch (Exception ex) {
            return Messages.UpdateCenter_PluginCategory_unrecognized(category);
        }
    }

602
    public List<Plugin> getUpdates() {
603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
        Map<String,Plugin> pluginMap = new LinkedHashMap<String, Plugin>();
        for (UpdateSite site : sites) {
            for (Plugin plugin: site.getUpdates()) {
                final Plugin existing = pluginMap.get(plugin.name);
                if (existing == null) {
                    pluginMap.put(plugin.name, plugin);
                } else if (!existing.version.equals(plugin.version)) {
                    // allow secondary update centers to publish different versions
                    // TODO refactor to consolidate multiple versions of the same plugin within the one row
                    final String altKey = plugin.name + ":" + plugin.version;
                    if (!pluginMap.containsKey(altKey)) {
                        pluginMap.put(altKey, plugin);
                    }
                }
            }
618
        }
K
kohsuke 已提交
619

620
        return new ArrayList<Plugin>(pluginMap.values());
621
    }
622 623 624 625 626 627 628 629 630 631 632 633 634 635
    
    /**
     * Ensure that all UpdateSites are up to date, without requiring a user to
     * browse to the instance.
     * 
     * @return a list of {@link FormValidation} for each updated Update Site
     * @throws ExecutionException 
     * @throws InterruptedException 
     * @since 1.501
     * 
     */
    public List<FormValidation> updateAllSites() throws InterruptedException, ExecutionException {
        List <Future<FormValidation>> futures = new ArrayList<Future<FormValidation>>();
        for (UpdateSite site : getSites()) {
636
            Future<FormValidation> future = site.updateDirectly(DownloadService.signatureCheck);
637 638 639 640 641 642 643 644 645 646 647
            if (future != null) {
                futures.add(future);
            }
        }
        
        List<FormValidation> results = new ArrayList<FormValidation>(); 
        for (Future<FormValidation> f : futures) {
            results.add(f.get());
        }
        return results;
    }
648

649 650

    /**
651
     * {@link AdministrativeMonitor} that checks if there's Jenkins update.
652
     */
653 654
    @Extension
    public static final class CoreUpdateMonitor extends AdministrativeMonitor {
655 656 657 658 659 660
        public boolean isActivated() {
            Data data = getData();
            return data!=null && data.hasCoreUpdates();
        }

        public Data getData() {
661
            UpdateSite cs = Jenkins.getInstance().getUpdateCenter().getCoreSource();
662 663
            if (cs!=null)   return cs.getData();
            return null;
664 665 666
        }
    }

667

668
    /**
669 670 671
     * Strategy object for controlling the update center's behaviors.
     *
     * <p>
672
     * Until 1.333, this extension point used to control the configuration of
673 674 675 676 677 678 679 680
     * where to get updates (hence the name of this class), but with the introduction
     * of multiple update center sites capability, that functionality is achieved by
     * simply installing another {@link UpdateSite}.
     *
     * <p>
     * See {@link UpdateSite} for how to manipulate them programmatically.
     *
     * @since 1.266
681
     */
682 683
    @SuppressWarnings({"UnusedDeclaration"})
    public static class UpdateCenterConfiguration implements ExtensionPoint {
K
kohsuke 已提交
684
        /**
685
         * Creates default update center configuration - uses settings for global update center.
K
kohsuke 已提交
686
         */
687
        public UpdateCenterConfiguration() {
K
kohsuke 已提交
688
        }
689

690 691 692
        /**
         * Check network connectivity by trying to establish a connection to
         * the host in connectionCheckUrl.
693
         *
694 695 696 697 698 699 700 701
         * @param job The connection checker that is invoking this strategy.
         * @param connectionCheckUrl A string containing the URL of a domain
         *          that is assumed to be always available.
         * @throws IOException if a connection can't be established
         */
        public void checkConnection(ConnectionCheckJob job, String connectionCheckUrl) throws IOException {
            testConnection(new URL(connectionCheckUrl));
        }
702

703 704
        /**
         * Check connection to update center server.
705
         *
706 707 708 709 710 711 712
         * @param job The connection checker that is invoking this strategy.
         * @param updateCenterUrl A sting containing the URL of the update center host.
         * @throws IOException if a connection to the update center server can't be established.
         */
        public void checkUpdateCenter(ConnectionCheckJob job, String updateCenterUrl) throws IOException {
            testConnection(new URL(updateCenterUrl + "?uctest"));
        }
713

714
        /**
715 716
         * Validate the URL of the resource before downloading it.
         *
717 718 719 720 721 722 723
         * @param job The download job that is invoking this strategy. This job is
         *          responsible for managing the status of the download and installation.
         * @param src The location of the resource on the network
         * @throws IOException if the validation fails
         */
        public void preValidate(DownloadJob job, URL src) throws IOException {
        }
724

725 726 727
        /**
         * Validate the resource after it has been downloaded, before it is
         * installed. The default implementation does nothing.
728
         *
729 730 731 732 733 734 735
         * @param job The download job that is invoking this strategy. This job is
         *          responsible for managing the status of the download and installation.
         * @param src The location of the downloaded resource.
         * @throws IOException if the validation fails.
         */
        public void postValidate(DownloadJob job, File src) throws IOException {
        }
736

737 738 739 740 741
        /**
         * Download a plugin or core upgrade in preparation for installing it
         * into its final location. Implementations will normally download the
         * resource into a temporary location and hand off a reference to this
         * location to the install or upgrade strategy to move into the final location.
742
         *
743 744 745 746 747 748 749 750
         * @param job The download job that is invoking this strategy. This job is
         *          responsible for managing the status of the download and installation.
         * @param src The URL to the resource to be downloaded.
         * @return A File object that describes the downloaded resource.
         * @throws IOException if there were problems downloading the resource.
         * @see DownloadJob
         */
        public File download(DownloadJob job, URL src) throws IOException {
S
Steven Post 已提交
751 752
            CountingInputStream in = null;
            OutputStream out = null;
753
            URLConnection con = null;
754
            try {
755
                con = connect(job,src);
756
                int total = con.getContentLength();
S
Steven Post 已提交
757
                in = new CountingInputStream(con.getInputStream());
758 759 760 761 762
                byte[] buf = new byte[8192];
                int len;

                File dst = job.getDestination();
                File tmp = new File(dst.getPath()+".tmp");
S
Steven Post 已提交
763
                out = new FileOutputStream(tmp);
764 765

                LOGGER.info("Downloading "+job.getName());
766 767 768
                Thread t = Thread.currentThread();
                String oldName = t.getName();
                t.setName(oldName + ": " + src);
769 770 771 772 773 774
                try {
                    while((len=in.read(buf))>=0) {
                        out.write(buf,0,len);
                        job.status = job.new Installing(total==-1 ? -1 : in.getCount()*100/total);
                    }
                } catch (IOException e) {
775
                    throw new IOException("Failed to load "+src+" to "+tmp,e);
776 777
                } finally {
                    t.setName(oldName);
778
                }
779

780 781 782 783 784 785
                if (total!=-1 && total!=tmp.length()) {
                    // don't know exactly how this happens, but report like
                    // http://www.ashlux.com/wordpress/2009/08/14/hudson-and-the-sonar-plugin-fail-maveninstallation-nosuchmethoderror/
                    // indicates that this kind of inconsistency can happen. So let's be defensive
                    throw new IOException("Inconsistent file length: expected "+total+" but only got "+tmp.length());
                }
786

787 788
                return tmp;
            } catch (IOException e) {
789 790 791 792 793 794 795 796 797
                // assist troubleshooting in case of e.g. "too many redirects" by printing actual URL
                String extraMessage = "";
                if (con != null && con.getURL() != null && !src.toString().equals(con.getURL().toString())) {
                    // Two URLs are considered equal if different hosts resolve to same IP. Prefer to log in case of string inequality,
                    // because who knows how the server responds to different host name in the request header?
                    // Also, since it involved name resolution, it'd be an expensive operation.
                    extraMessage = " (redirected to: " + con.getURL() + ")";
                }
                throw new IOException2("Failed to download from "+src+extraMessage,e);
798 799 800
            } finally {
                IOUtils.closeQuietly(in);
                IOUtils.closeQuietly(out);
801
            }
802
        }
803

804 805 806 807 808 809 810 811
        /**
         * Connects to the given URL for downloading the binary. Useful for tweaking
         * how the connection gets established.
         */
        protected URLConnection connect(DownloadJob job, URL src) throws IOException {
            return ProxyConfiguration.open(src);
        }

812 813 814
        /**
         * Called after a plugin has been downloaded to move it into its final
         * location. The default implementation is a file rename.
815
         *
816 817 818 819 820 821 822 823
         * @param job The install job that is invoking this strategy.
         * @param src The temporary location of the plugin.
         * @param dst The final destination to install the plugin to.
         * @throws IOException if there are problems installing the resource.
         */
        public void install(DownloadJob job, File src, File dst) throws IOException {
            job.replace(dst, src);
        }
824

825 826 827
        /**
         * Called after an upgrade has been downloaded to move it into its final
         * location. The default implementation is a file rename.
828
         *
829 830 831 832 833 834 835
         * @param job The upgrade job that is invoking this strategy.
         * @param src The temporary location of the upgrade.
         * @param dst The final destination to install the upgrade to.
         * @throws IOException if there are problems installing the resource.
         */
        public void upgrade(DownloadJob job, File src, File dst) throws IOException {
            job.replace(dst, src);
836
        }
837 838

        /**
839 840
         * Returns an "always up" server for Internet connectivity testing.
         *
841
         * @deprecated as of 1.333
842 843
         *      With the introduction of multiple update center capability, this information
         *      is now a part of the <tt>update-center.json</tt> file. See
K
Kohsuke Kawaguchi 已提交
844
         *      <tt>http://jenkins-ci.org/update-center.json</tt> as an example.
845
         */
846
        @Deprecated
847 848 849
        public String getConnectionCheckUrl() {
            return "http://www.google.com";
        }
850

851 852 853
        /**
         * Returns the URL of the server that hosts the update-center.json
         * file.
K
kohsuke 已提交
854
         *
855
         * @deprecated as of 1.333
856 857
         *      With the introduction of multiple update center capability, this information
         *      is now moved to {@link UpdateSite}.
K
kohsuke 已提交
858 859
         * @return
         *      Absolute URL that ends with '/'.
860
         */
861
        @Deprecated
862
        public String getUpdateCenterUrl() {
863
            return UPDATE_CENTER_URL;
864
        }
865

866 867
        /**
         * Returns the URL of the server that hosts plugins and core updates.
868
         *
869
         * @deprecated as of 1.333
870 871
         *      <tt>update-center.json</tt> is now signed, so we don't have to further make sure that
         *      we aren't downloading from anywhere unsecure.
872
         */
873
        @Deprecated
874
        public String getPluginRepositoryBaseUrl() {
K
Kohsuke Kawaguchi 已提交
875
            return "http://jenkins-ci.org/";
876
        }
877

878

879
        private void testConnection(URL url) throws IOException {
K
kohsuke 已提交
880
            try {
K
kohsuke 已提交
881
                Util.copyStreamAndClose(ProxyConfiguration.open(url).getInputStream(),new NullOutputStream());
K
kohsuke 已提交
882 883 884
            } catch (SSLHandshakeException e) {
                if (e.getMessage().contains("PKIX path building failed"))
                   // fix up this crappy error message from JDK
885
                    throw new IOException("Failed to validate the SSL certificate of "+url,e);
K
kohsuke 已提交
886
            }
887
        }
888
    }
889

890 891 892 893 894
    /**
     * Things that {@link UpdateCenter#installerService} executes.
     *
     * This object will have the <tt>row.jelly</tt> which renders the job on UI.
     */
895
    @ExportedBean
896
    public abstract class UpdateCenterJob implements Runnable {
897 898 899 900 901 902 903 904
        /**
         * Unique ID that identifies this job.
         *
         * @see UpdateCenter#getJob(int)
         */
        @Exported
        public final int id = iota.incrementAndGet();

905 906 907 908 909
        /**
         * Which {@link UpdateSite} does this belong to?
         */
        public final UpdateSite site;

910 911 912 913 914
        /**
         * If this job fails, set to the error.
         */
        protected Throwable error;

915 916 917 918
        protected UpdateCenterJob(UpdateSite site) {
            this.site = site;
        }

919 920 921 922
        public Api getApi() {
            return new Api(this);
        }

K
kohsuke 已提交
923 924 925 926
        /**
         * @deprecated as of 1.326
         *      Use {@link #submit()} instead.
         */
927
        @Deprecated
928
        public void schedule() {
K
kohsuke 已提交
929 930 931
            submit();
        }

932 933 934 935 936
        @Exported
        public String getType() {
            return getClass().getSimpleName();
        }

K
kohsuke 已提交
937 938 939 940 941 942
        /**
         * Schedules this job for an execution
         * @return
         *      {@link Future} to keeps track of the status of the execution.
         */
        public Future<UpdateCenterJob> submit() {
943
            LOGGER.fine("Scheduling "+this+" to installerService");
944
            jobs.add(this);
K
kohsuke 已提交
945
            return installerService.submit(this,this);
946
        }
947

948
        @Exported
949 950 951 952
        public String getErrorMessage() {
            return error != null ? error.getMessage() : null;
        }
        
953 954 955
        public Throwable getError() {
            return error;
        }
956 957
    }

958 959 960 961
    /**
     * Restarts jenkins.
     */
    public class RestartJenkinsJob extends UpdateCenterJob {
A
appr 已提交
962 963 964
         /**
         * Immutable state of this job.
         */
965
         @Exported(inline=true)
A
appr 已提交
966 967 968 969 970 971 972 973 974 975 976 977 978
        public volatile RestartJenkinsJobStatus status = new Pending();
        
        /**
         * Cancel job
         */     
        public synchronized boolean cancel() {
            if (status instanceof Pending) {
                status = new Canceled();
                return true;
            }
            return false;
        }
        
979 980 981 982
        public RestartJenkinsJob(UpdateSite site) {
            super(site);
        }

A
appr 已提交
983 984 985 986 987
        public synchronized void run() {
            if (!(status instanceof Pending)) {
                return;
            }
            status = new Running();
988
            try {
989
                Jenkins.getInstance().safeRestart();
990
            } catch (RestartNotSupportedException exception) {
991
                // ignore if restart is not allowed
A
appr 已提交
992
                status = new Failure();
993
                error = exception;
994 995
            }
        }
996 997

        @ExportedBean
A
appr 已提交
998
        public abstract class RestartJenkinsJobStatus {
999
            @Exported
A
appr 已提交
1000 1001 1002 1003 1004
            public final int id = iota.incrementAndGet();
   
        }
        
        public class Pending extends RestartJenkinsJobStatus {
1005 1006 1007 1008
            @Exported
            public String getType() {
                return getClass().getSimpleName();
            }
A
appr 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
        }
        
        public class Running extends RestartJenkinsJobStatus {
            
        }
        
        public class Failure extends RestartJenkinsJobStatus {
            
        }
        
        public class Canceled extends RestartJenkinsJobStatus {
            
        }
1022 1023
    }

1024 1025 1026 1027 1028 1029
    /**
     * Tests the internet connectivity.
     */
    public final class ConnectionCheckJob extends UpdateCenterJob {
        private final Vector<String> statuses= new Vector<String>();

1030 1031 1032 1033
        public ConnectionCheckJob(UpdateSite site) {
            super(site);
        }

1034
        public void run() {
1035 1036 1037
            if (ID_UPLOAD.equals(site.getId())) {
                return;
            }
1038
            LOGGER.fine("Doing a connectivity check");
1039
            try {
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
                String connectionCheckUrl = site.getConnectionCheckUrl();
                if (connectionCheckUrl!=null) {
                    statuses.add(Messages.UpdateCenter_Status_CheckingInternet());
                    try {
                        config.checkConnection(this, connectionCheckUrl);
                    } catch (IOException e) {
                        if(e.getMessage().contains("Connection timed out")) {
                            // Google can't be down, so this is probably a proxy issue
                            statuses.add(Messages.UpdateCenter_Status_ConnectionFailed(connectionCheckUrl));
                            return;
                        }
1051 1052
                    }
                }
1053

1054
                statuses.add(Messages.UpdateCenter_Status_CheckingJavaNet());
1055
                config.checkUpdateCenter(this, site.getUrl());
1056

1057
                statuses.add(Messages.UpdateCenter_Status_Success());
1058
            } catch (UnknownHostException e) {
1059
                statuses.add(Messages.UpdateCenter_Status_UnknownHostException(e.getMessage()));
1060
                addStatus(e);
1061
                error = e;
1062 1063
            } catch (IOException e) {
                statuses.add(Functions.printThrowable(e));
1064
                error = e;
1065 1066 1067
            }
        }

1068 1069 1070 1071
        private void addStatus(UnknownHostException e) {
            statuses.add("<pre>"+ Functions.xmlEscape(Functions.printThrowable(e))+"</pre>");
        }

1072 1073 1074 1075 1076 1077 1078
        public String[] getStatuses() {
            synchronized (statuses) {
                return statuses.toArray(new String[statuses.size()]);
            }
        }
    }

1079
    /**
1080
     * Base class for a job that downloads a file from the Jenkins project.
1081
     */
1082
    public abstract class DownloadJob extends UpdateCenterJob {
K
kohsuke 已提交
1083 1084 1085
        /**
         * Immutable object representing the current state of this job.
         */
1086
        @Exported(inline=true)
K
kohsuke 已提交
1087
        public volatile InstallationStatus status = new Pending();
1088

1089 1090 1091 1092 1093 1094 1095 1096 1097 1098
        /**
         * Where to download the file from.
         */
        protected abstract URL getURL() throws MalformedURLException;

        /**
         * Where to download the file to.
         */
        protected abstract File getDestination();

1099
        @Exported
K
kohsuke 已提交
1100
        public abstract String getName();
1101 1102 1103 1104 1105

        /**
         * Called when the whole thing went successfully.
         */
        protected abstract void onSuccess();
1106

1107

1108
        private Authentication authentication;
1109

1110 1111 1112
        /**
         * Get the user that initiated this job
         */
1113
        public Authentication getUser() {
1114 1115
            return this.authentication;
        }
1116 1117 1118

        protected DownloadJob(UpdateSite site, Authentication authentication) {
            super(site);
1119 1120
            this.authentication = authentication;
        }
1121

K
kohsuke 已提交
1122 1123
        public void run() {
            try {
1124
                LOGGER.info("Starting the installation of "+getName()+" on behalf of "+getUser().getName());
1125

1126
                _run();
1127

1128
                LOGGER.info("Installation successful: "+getName());
K
kohsuke 已提交
1129
                status = new Success();
1130
                onSuccess();
1131 1132 1133
            } catch (InstallationStatus e) {
                status = e;
                if (status.isSuccess()) onSuccess();
1134
                requiresRestart |= status.requiresRestart();
1135
            } catch (Throwable e) {
1136
                LOGGER.log(Level.SEVERE, "Failed to install "+getName(),e);
K
kohsuke 已提交
1137
                status = new Failure(e);
1138
                error = e;
K
kohsuke 已提交
1139
            }
1140 1141
        }

1142
        protected void _run() throws IOException, InstallationStatus {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
            URL src = getURL();

            config.preValidate(this, src);

            File dst = getDestination();
            File tmp = config.download(this, src);

            config.postValidate(this, tmp);
            config.install(this, tmp, dst);
        }

1154 1155 1156 1157 1158
        /**
         * Called when the download is completed to overwrite
         * the old file with the new file.
         */
        protected void replace(File dst, File src) throws IOException {
1159 1160 1161 1162
            File bak = Util.changeExtension(dst,".bak");
            bak.delete();
            dst.renameTo(bak);
            dst.delete(); // any failure up to here is no big deal
1163 1164 1165 1166 1167
            if(!src.renameTo(dst)) {
                throw new IOException("Failed to rename "+src+" to "+dst);
            }
        }

K
kohsuke 已提交
1168 1169 1170 1171 1172
        /**
         * Indicates the status or the result of a plugin installation.
         * <p>
         * Instances of this class is immutable.
         */
1173
        @ExportedBean
1174
        public abstract class InstallationStatus extends Throwable {
K
kohsuke 已提交
1175
            public final int id = iota.incrementAndGet();
1176
            @Exported
1177 1178 1179
            public boolean isSuccess() {
                return false;
            }
1180 1181 1182 1183
            @Exported
            public final String getType() {
                return getClass().getSimpleName();
            }
1184 1185 1186 1187 1188 1189 1190

            /**
             * Indicates that a restart is needed to complete the tasks.
             */
            public boolean requiresRestart() {
                return false;
            }
K
kohsuke 已提交
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
        }

        /**
         * Indicates that the installation of a plugin failed.
         */
        public class Failure extends InstallationStatus {
            public final Throwable problem;

            public Failure(Throwable problem) {
                this.problem = problem;
            }

1203
            public String getProblemStackTrace() {
K
kohsuke 已提交
1204 1205
                return Functions.printThrowable(problem);
            }
1206
        }
1207

1208 1209 1210
        /**
         * Indicates that the installation was successful but a restart is needed.
         */
1211
        public class SuccessButRequiresRestart extends Success {
1212 1213 1214 1215 1216 1217 1218 1219 1220
            private final Localizable message;

            public SuccessButRequiresRestart(Localizable message) {
                this.message = message;
            }

            public String getMessage() {
                return message.toString();
            }
1221 1222 1223 1224 1225

            @Override
            public boolean requiresRestart() {
                return true;
            }
1226 1227
        }

1228
        /**
K
kohsuke 已提交
1229
         * Indicates that the plugin was successfully installed.
1230
         */
K
kohsuke 已提交
1231
        public class Success extends InstallationStatus {
1232 1233 1234
            @Override public boolean isSuccess() {
                return true;
            }
K
kohsuke 已提交
1235
        }
1236

K
kohsuke 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
        /**
         * Indicates that the plugin is waiting for its turn for installation.
         */
        public class Pending extends InstallationStatus {
        }

        /**
         * Installation of a plugin is in progress.
         */
        public class Installing extends InstallationStatus {
            /**
             * % completed download, or -1 if the percentage is not known.
             */
            public final int percentage;

            public Installing(int percentage) {
                this.percentage = percentage;
            }
1255 1256 1257
        }
    }

1258 1259 1260 1261 1262 1263 1264
    /**
     * Represents the state of the installation activity of one plugin.
     */
    public final class InstallationJob extends DownloadJob {
        /**
         * What plugin are we trying to install?
         */
1265
        @Exported
1266 1267
        public final Plugin plugin;

1268
        private final PluginManager pm = Jenkins.getInstance().getPluginManager();
1269

1270 1271 1272 1273 1274 1275
        /**
         * True to load the plugin into this Jenkins, false to wait until restart.
         */
        private final boolean dynamicLoad;

        /**
K
Kohsuke Kawaguchi 已提交
1276
         * @deprecated as of 1.442
1277
         */
1278
        @Deprecated
1279
        public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth) {
1280 1281 1282 1283
            this(plugin,site,auth,false);
        }

        public InstallationJob(Plugin plugin, UpdateSite site, Authentication auth, boolean dynamicLoad) {
1284
            super(site, auth);
1285
            this.plugin = plugin;
1286
            this.dynamicLoad = dynamicLoad;
1287 1288 1289 1290 1291 1292 1293
        }

        protected URL getURL() throws MalformedURLException {
            return new URL(plugin.url);
        }

        protected File getDestination() {
I
imod 已提交
1294 1295 1296 1297 1298
            File baseDir = pm.rootDir;
            return new File(baseDir, plugin.name + ".jpi");
        }
        
        private File getLegacyDestination() {
1299 1300 1301 1302
            File baseDir = pm.rootDir;
            return new File(baseDir, plugin.name + ".hpi");
        }

K
kohsuke 已提交
1303 1304
        public String getName() {
            return plugin.getDisplayName();
1305 1306
        }

1307
        @Override
1308
        public void _run() throws IOException, InstallationStatus {
K
kohsuke 已提交
1309
            super._run();
1310 1311 1312

            // if this is a bundled plugin, make sure it won't get overwritten
            PluginWrapper pw = plugin.getInstalled();
1313 1314
            if (pw!=null && pw.isBundled()) {
                SecurityContext oldContext = ACL.impersonate(ACL.SYSTEM);
S
sogabe 已提交
1315 1316 1317
                try {
                    pw.doPin();
                } finally {
1318
                    SecurityContextHolder.setContext(oldContext);
S
sogabe 已提交
1319
                }
1320
            }
1321 1322 1323 1324 1325

            if (dynamicLoad) {
                try {
                    pm.dynamicLoad(getDestination());
                } catch (RestartRequiredException e) {
1326
                    throw new SuccessButRequiresRestart(e.message);
1327
                } catch (Exception e) {
1328
                    throw new IOException("Failed to dynamically deploy this plugin",e);
1329
                }
1330 1331
            } else {
                throw new SuccessButRequiresRestart(Messages._UpdateCenter_DownloadButNotActivated());
1332
            }
1333 1334
        }

1335 1336 1337
        protected void onSuccess() {
            pm.pluginUploaded = true;
        }
1338 1339 1340 1341 1342

        @Override
        public String toString() {
            return super.toString()+"[plugin="+plugin.title+"]";
        }
I
imod 已提交
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365
        
        /**
         * Called when the download is completed to overwrite
         * the old file with the new file.
         */
        @Override
        protected void replace(File dst, File src) throws IOException {
        	File bak = Util.changeExtension(dst,".bak");
        	
            bak.delete();
            final File legacy = getLegacyDestination();
			if(legacy.exists()){
            	legacy.renameTo(bak);
            }else{
            	dst.renameTo(bak);
            }
            legacy.delete();
            dst.delete(); // any failure up to here is no big deal
            
            if(!src.renameTo(dst)) {
                throw new IOException("Failed to rename "+src+" to "+dst);
            }
        }
1366 1367
    }

1368 1369 1370 1371 1372 1373 1374 1375 1376
    /**
     * Represents the state of the downgrading activity of plugin.
     */
    public final class PluginDowngradeJob extends DownloadJob {
        /**
         * What plugin are we trying to install?
         */
        public final Plugin plugin;

1377
        private final PluginManager pm = Jenkins.getInstance().getPluginManager();
1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

        public PluginDowngradeJob(Plugin plugin, UpdateSite site, Authentication auth) {
            super(site, auth);
            this.plugin = plugin;
        }

        protected URL getURL() throws MalformedURLException {
            return new URL(plugin.url);
        }

        protected File getDestination() {
            File baseDir = pm.rootDir;
I
imod 已提交
1390 1391 1392 1393 1394
            final File legacy = new File(baseDir, plugin.name + ".hpi");
            if(legacy.exists()){
            	return legacy;
            }
            return new File(baseDir, plugin.name + ".jpi");
1395 1396
        }

1397
        protected File getBackup() {
1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
            File baseDir = pm.rootDir;
            return new File(baseDir, plugin.name + ".bak");
        }

        public String getName() {
            return plugin.getDisplayName();
        }

        @Override
        public void run() {
            try {
                LOGGER.info("Starting the downgrade of "+getName()+" on behalf of "+getUser().getName());

                _run();

                LOGGER.info("Downgrade successful: "+getName());
                status = new Success();
                onSuccess();
            } catch (Throwable e) {
                LOGGER.log(Level.SEVERE, "Failed to downgrade "+getName(),e);
                status = new Failure(e);
1419
                error = e;
1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452
            }
        }

        @Override
        protected void _run() throws IOException {
            File dst = getDestination();
            File backup = getBackup();

            config.install(this, backup, dst);
        }

        /**
         * Called to overwrite
         * current version with backup file
         */
        @Override
        protected void replace(File dst, File backup) throws IOException {
            dst.delete(); // any failure up to here is no big deal
            if(!backup.renameTo(dst)) {
                throw new IOException("Failed to rename "+backup+" to "+dst);
            }
        }

        protected void onSuccess() {
            pm.pluginUploaded = true;
        }

        @Override
        public String toString() {
            return super.toString()+"[plugin="+plugin.title+"]";
        }
    }

1453
    /**
1454
     * Represents the state of the upgrade activity of Jenkins core.
1455 1456
     */
    public final class HudsonUpgradeJob extends DownloadJob {
1457 1458
        public HudsonUpgradeJob(UpdateSite site, Authentication auth) {
            super(site, auth);
1459 1460 1461
        }

        protected URL getURL() throws MalformedURLException {
1462
            return new URL(site.getData().core.url);
1463 1464 1465 1466 1467 1468
        }

        protected File getDestination() {
            return Lifecycle.get().getHudsonWar();
        }

K
kohsuke 已提交
1469
        public String getName() {
1470
            return "jenkins.war";
1471 1472 1473
        }

        protected void onSuccess() {
1474
            status = new Success();
K
kohsuke 已提交
1475 1476
        }

1477 1478 1479 1480
        @Override
        protected void replace(File dst, File src) throws IOException {
            Lifecycle.get().rewriteHudsonWar(src);
        }
1481 1482
    }

1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
    public final class HudsonDowngradeJob extends DownloadJob {
        public HudsonDowngradeJob(UpdateSite site, Authentication auth) {
            super(site, auth);
        }

        protected URL getURL() throws MalformedURLException {
            return new URL(site.getData().core.url);
        }

        protected File getDestination() {
            return Lifecycle.get().getHudsonWar();
        }

        public String getName() {
1497
            return "jenkins.war";
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
        }
        protected void onSuccess() {
            status = new Success();
        }
        @Override
        public void run() {
            try {
                LOGGER.info("Starting the downgrade of "+getName()+" on behalf of "+getUser().getName());

                _run();

                LOGGER.info("Downgrading successful: "+getName());
                status = new Success();
                onSuccess();
            } catch (Throwable e) {
                LOGGER.log(Level.SEVERE, "Failed to downgrade "+getName(),e);
                status = new Failure(e);
1515
                error = e;
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533
            }
        }

        @Override
        protected void _run() throws IOException {

            File backup = new File(Lifecycle.get().getHudsonWar() + ".bak");
            File dst = getDestination();

            config.install(this, backup, dst);
        }

        @Override
        protected void replace(File dst, File src) throws IOException {
            Lifecycle.get().rewriteHudsonWar(src);
        }
    }

1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
    public static final class PluginEntry implements Comparable<PluginEntry> {
        public Plugin plugin;
        public String category;
        private PluginEntry(Plugin p, String c) { plugin = p; category = c; }

        public int compareTo(PluginEntry o) {
            int r = category.compareTo(o.category);
            if (r==0) r = plugin.name.compareToIgnoreCase(o.plugin.name);
            return r;
        }
    }

1546 1547 1548
    /**
     * Adds the update center data retriever to HTML.
     */
1549
    @Extension
1550 1551 1552
    public static class PageDecoratorImpl extends PageDecorator {
    }

K
kohsuke 已提交
1553 1554 1555 1556 1557
    /**
     * Initializes the update center.
     *
     * This has to wait until after all plugins load, to let custom UpdateCenterConfiguration take effect first.
     */
1558
    @Initializer(after=PLUGINS_STARTED, fatal=false)
1559
    public static void init(Jenkins h) throws IOException {
K
kohsuke 已提交
1560 1561 1562
        h.getUpdateCenter().load();
    }

K
kohsuke 已提交
1563 1564 1565 1566 1567
    /**
     * Sequence number generator.
     */
    private static final AtomicInteger iota = new AtomicInteger();

1568
    private static final Logger LOGGER = Logger.getLogger(UpdateCenter.class.getName());
1569

1570 1571 1572 1573
    /**
     * @deprecated as of 1.333
     *      Use {@link UpdateSite#neverUpdate}
     */
1574
    @Deprecated
1575
    public static boolean neverUpdate = Boolean.getBoolean(UpdateCenter.class.getName()+".never");
1576

1577
    public static final XStream2 XSTREAM = new XStream2();
K
kohsuke 已提交
1578

1579 1580 1581 1582
    static {
        XSTREAM.alias("site",UpdateSite.class);
        XSTREAM.alias("sites",PersistedList.class);
    }
1583
}