package com.amazon.jenkins.ec2fleet;

import hudson.Extension;
import hudson.model.PeriodicWork;
import hudson.slaves.Cloud;
import hudson.widgets.Widget;
import jenkins.model.Jenkins;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * User: cyberax
 * Date: 1/11/16
 * Time: 13:21
 */
@Extension
@SuppressWarnings("unused")
public class CloudNanny extends PeriodicWork
{
    private static final Logger LOGGER = Logger.getLogger(CloudNanny.class.getName());

    @Override public long getRecurrencePeriod() {
        return 10000L;
    }

    @Override protected void doRun() throws Exception {

        // Trigger reprovisioning as well
        Jenkins.getActiveInstance().unlabeledNodeProvisioner.suggestReviewNow();

        final List<FleetStateStats> stats = new ArrayList<FleetStateStats>();
        for(final Cloud cloud : Jenkins.getActiveInstance().clouds) {
            if (!(cloud instanceof EC2FleetCloud))
                continue;

            // Update the cluster states
            final EC2FleetCloud fleetCloud =(EC2FleetCloud) cloud;
            LOGGER.log(Level.FINE, "Checking cloud: " + fleetCloud.getLabelString() );
            stats.add(fleetCloud.updateStatus());
        }

        for (final Widget w : Jenkins.getInstance().getWidgets()) {
            if (!(w instanceof FleetStatusWidget))
                continue;

            ((FleetStatusWidget)w).setStatusList(stats);
        }
    }
}

@@ -90,16 +90,43 @@
 icWork;%0A
+import hudson.model.Queue;%0A
 import h
@@ -253,24 +253,62 @@
 .util.List;%0A
+import java.util.concurrent.Callable;%0A
 import java.
@@ -1300,32 +1300,273 @@
 add(
-fleetCloud.updateStatus(
+Queue.withLock(new Callable%3CFleetStateStats%3E() %7B%0A                @Override%0A                public FleetStateStats call()%0A                        throws Exception%0A                %7B%0A                    return fleetCloud.updateStatus();%0A                %7D%0A            %7D
 ));%0A

Fix potential deadlock