TaskScheduler.java 21.5 KB
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Properties
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.LoginException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.apache.sling.commons.scheduler.Job
 *  org.apache.sling.commons.scheduler.JobContext
 *  org.apache.sling.commons.scheduler.ScheduleOptions
 *  org.apache.sling.commons.scheduler.Scheduler
 *  org.apache.sling.discovery.InstanceDescription
 *  org.apache.sling.discovery.TopologyEvent
 *  org.apache.sling.discovery.TopologyEvent$Type
 *  org.apache.sling.discovery.TopologyEventListener
 *  org.apache.sling.discovery.TopologyView
 *  org.apache.sling.event.jobs.Job
 *  org.apache.sling.event.jobs.JobManager
 *  org.apache.sling.hc.api.HealthCheck
 *  org.apache.sling.launchpad.api.StartupListener
 *  org.apache.sling.launchpad.api.StartupMode
 *  org.osgi.framework.BundleContext
 *  org.osgi.framework.Filter
 *  org.osgi.framework.InvalidSyntaxException
 *  org.osgi.framework.ServiceReference
 *  org.osgi.framework.ServiceRegistration
 *  org.osgi.service.event.Event
 *  org.osgi.service.event.EventHandler
 *  org.osgi.util.tracker.ServiceTracker
 *  org.osgi.util.tracker.ServiceTrackerCustomizer
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.maintenance.impl;

import com.adobe.granite.maintenance.MaintenanceTaskInfo;
import com.adobe.granite.maintenance.MaintenanceTaskManager;
import com.adobe.granite.maintenance.impl.MaintenanceTaskHealthCheck;
import com.adobe.granite.maintenance.impl.MaintenanceWindowImpl;
import com.adobe.granite.operations.OperationsService;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.scheduler.JobContext;
import org.apache.sling.commons.scheduler.ScheduleOptions;
import org.apache.sling.commons.scheduler.Scheduler;
import org.apache.sling.discovery.InstanceDescription;
import org.apache.sling.discovery.TopologyEvent;
import org.apache.sling.discovery.TopologyEventListener;
import org.apache.sling.discovery.TopologyView;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.hc.api.HealthCheck;
import org.apache.sling.launchpad.api.StartupListener;
import org.apache.sling.launchpad.api.StartupMode;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Filter;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1, metatype=1, label="Adobe Granite Maintenance Scheduler", description="Scheduler for the maintenance tasks.")
@Service(value={EventHandler.class, TopologyEventListener.class, StartupListener.class})
@Properties(value={@Property(name="event.topics", value={"org/apache/sling/api/resource/Resource/ADDED", "org/apache/sling/api/resource/Resource/REMOVED", "org/apache/sling/api/resource/Resource/CHANGED", "org/apache/sling/event/notification/job/CANCELLED"}, propertyPrivate=1)})
public class TaskScheduler
implements org.apache.sling.commons.scheduler.Job,
EventHandler,
TopologyEventListener,
StartupListener {
    private final Logger logger;
    private static final String DEFAULT_PATH = "/mnt/overlay";
    @Property(value={"/mnt/overlay"}, label="Base Path", description="Resource base path to the window definitions. The configuration path is appended to the base path.")
    private static final String PROPERTY_PATH = "resourcePath";
    private static final String DEFAULT_CONFIG = "granite/operations/config/maintenance";
    @Property(value={"granite/operations/config/maintenance"}, label="Config Path", description="Configuration path to the window definitions. This is relative to the base path and must not start with a slash.")
    private static final String PROPERTY_CONFIG = "config";
    @Reference
    private Scheduler scheduler;
    @Reference
    private ResourceResolverFactory rrFactory;
    @Reference
    private MaintenanceTaskManager mtManager;
    @Reference
    private JobManager jobManager;
    @Reference
    private OperationsService operationsService;
    private String resourcePath;
    private String[] resourcePathPrefix;
    private List<MaintenanceWindowImpl> maintenanceWindows;
    private final List<ServiceRegistration> registrations;
    private final BlockingQueue<Boolean> updateQueue;
    private volatile boolean isActive;
    private volatile boolean startupFinished;
    private volatile boolean isLeader;
    private BundleContext bundleContext;
    private ServiceTracker taskTracker;
    private static final String KEY_WINDOW = "window";
    private static final String KEY_JOBS = "jobs";
    private static final String KEY_END = "end";

    public TaskScheduler() {
        this.logger = LoggerFactory.getLogger(this.getClass());
        this.maintenanceWindows = Collections.emptyList();
        this.registrations = new ArrayList<ServiceRegistration>();
        this.updateQueue = new LinkedBlockingQueue<Boolean>();
        this.isActive = false;
        this.startupFinished = false;
        this.isLeader = false;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Activate
    protected void activate(BundleContext bundleContext, Map<String, Object> props) throws LoginException, InvalidSyntaxException {
        this.bundleContext = bundleContext;
        String basePath = PropertiesUtil.toString((Object)props.get("resourcePath"), (String)"/mnt/overlay");
        String configPath = PropertiesUtil.toString((Object)props.get("config"), (String)"granite/operations/config/maintenance");
        this.resourcePath = basePath + '/' + configPath;
        ResourceResolver resolver = null;
        try {
            resolver = this.rrFactory.getAdministrativeResourceResolver(null);
            String[] paths = resolver.getSearchPath();
            this.resourcePathPrefix = new String[paths.length];
            for (int i = 0; i < this.resourcePathPrefix.length; ++i) {
                this.resourcePathPrefix[i] = paths[i] + configPath;
            }
        }
        finally {
            if (resolver != null) {
                resolver.close();
            }
        }
        this.taskTracker = new ServiceTracker(bundleContext, this.createFilter(bundleContext), new ServiceTrackerCustomizer(){

            public void removedService(ServiceReference reference, Object service) {
                TaskScheduler.this.updateQueue.offer(true);
            }

            public void modifiedService(ServiceReference reference, Object service) {
                TaskScheduler.this.updateQueue.offer(true);
            }

            public Object addingService(ServiceReference reference) {
                TaskScheduler.this.updateQueue.offer(true);
                return reference;
            }
        });
        this.taskTracker.open();
    }

    private Filter createFilter(BundleContext btx) throws InvalidSyntaxException {
        return btx.createFilter(String.format("(&(%s=*)(%s=*)(%s=*))", "granite.maintenance.name", "granite.maintenance.title", "job.topics"));
    }

    @Deactivate
    protected void deactivate() {
        this.stop();
        if (this.taskTracker != null) {
            this.taskTracker.close();
            this.taskTracker = null;
        }
        this.bundleContext = null;
    }

    private void start() {
        this.isActive = true;
        Thread updateThread = new Thread(new Runnable(){

            @Override
            public void run() {
                TaskScheduler.this.processUpdateQueue();
            }
        }, "Adobe Granite Maintenance Scheduler Update Task");
        updateThread.setDaemon(true);
        updateThread.start();
        this.updateQueue.offer(true);
    }

    private void stop() {
        this.isActive = false;
        this.updateQueue.offer(true);
        this.unscheduleWindows();
    }

    public void inform(StartupMode mode, boolean finished) {
        if (finished) {
            this.startupFinished = true;
            this.checkActive();
        }
    }

    public void startupFinished(StartupMode arg0) {
        this.startupFinished = true;
        this.checkActive();
    }

    public void startupProgress(float p) {
    }

    private synchronized void checkActive() {
        if (this.startupFinished && this.isLeader) {
            if (!this.isActive) {
                this.start();
            }
        } else if (this.isActive) {
            this.stop();
        }
    }

    public void handleTopologyEvent(TopologyEvent event) {
        if (event.getType() == TopologyEvent.Type.TOPOLOGY_INIT || event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGED) {
            this.isLeader = event.getNewView().getLocalInstance().isLeader();
            this.checkActive();
        } else if (event.getType() == TopologyEvent.Type.TOPOLOGY_CHANGING) {
            this.isLeader = false;
            this.checkActive();
        }
    }

    private void processUpdateQueue() {
        while (this.isActive) {
            Boolean object = null;
            try {
                object = this.updateQueue.take();
                if (object != null) {
                    this.updateQueue.clear();
                }
            }
            catch (InterruptedException ie) {
                // empty catch block
            }
            if (object == null || !this.isActive) continue;
            this.updateSchedule();
        }
    }

    private synchronized void unscheduleWindows() {
        for (MaintenanceWindowImpl window : this.maintenanceWindows) {
            this.scheduler.unschedule(window.getStartScheduleName());
            this.scheduler.unschedule(window.getEndScheduleName());
        }
        this.maintenanceWindows = Collections.emptyList();
        for (ServiceRegistration reg : this.registrations) {
            reg.unregister();
        }
        this.registrations.clear();
    }

    /*
     * Enabled force condition propagation
     * Lifted jumps to return sites
     */
    public void handleEvent(Event event) {
        if (!this.isActive) return;
        if (event.getTopic().equals("org/apache/sling/event/notification/job/CANCELLED")) {
            String[] log;
            String jobId;
            Job job;
            String topic = (String)event.getProperty("event.job.topic");
            if (topic == null || !topic.startsWith("com/adobe/granite/maintenance/job/") || (job = this.jobManager.getJobById(jobId = (String)event.getProperty("slingevent:eventId"))) == null) return;
            StringBuilder sb = new StringBuilder();
            sb.append("Maintenance task ");
            sb.append(topic.substring("com/adobe/granite/maintenance/job/".length()));
            sb.append(" failed");
            String msg = job.getResultMessage();
            if (msg != null) {
                sb.append(" with message: ");
                sb.append(msg);
            }
            if ((log = job.getProgressLog()) != null && log.length > 0) {
                sb.append("\nFull log:");
                for (String m : log) {
                    sb.append("  ");
                    sb.append(m);
                    sb.append("\n");
                }
            }
            this.logger.error(sb.toString());
            return;
        } else {
            String path = (String)event.getProperty("path");
            if (path == null) return;
            String[] arr$ = this.resourcePathPrefix;
            int len$ = arr$.length;
            int i$ = 0;
            while (i$ < len$) {
                String prefix = arr$[i$];
                if (path.startsWith(prefix)) {
                    this.updateQueue.offer(true);
                    return;
                }
                ++i$;
            }
            return;
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private synchronized void updateSchedule() {
        ArrayList<MaintenanceWindowImpl> windows;
        block13 : {
            this.logger.debug("Unscheduling previous maintenance schedule");
            this.unscheduleWindows();
            this.logger.debug("Updating maintenance schedule");
            windows = new ArrayList<MaintenanceWindowImpl>();
            ResourceResolver resolver = null;
            try {
                resolver = this.rrFactory.getAdministrativeResourceResolver(null);
                Resource parent = resolver.getResource(this.resourcePath);
                if (parent == null) break block13;
                for (Resource windowResource : parent.getChildren()) {
                    MaintenanceWindowImpl window = null;
                    try {
                        window = new MaintenanceWindowImpl(windowResource);
                    }
                    catch (IllegalArgumentException iae) {
                        this.logger.error("Unable to read maintenance window definition from " + windowResource.getPath(), (Throwable)iae);
                    }
                    if (window == null) continue;
                    ArrayList<MaintenanceTaskInfo> infos = new ArrayList<MaintenanceTaskInfo>();
                    for (Resource taskResource : windowResource.getChildren()) {
                        String taskName;
                        ValueMap tvm = ResourceUtil.getValueMap((Resource)taskResource);
                        if (!this.operationsService.isEnabled(tvm) || (taskName = (String)tvm.get("granite.maintenance.name", String.class)) == null) continue;
                        MaintenanceTaskInfo info = this.mtManager.getMaintenanceTaskInfo(taskName);
                        if (info != null) {
                            infos.add(info);
                            continue;
                        }
                        this.logger.error("No maintenance task found with name {} for window {}", (Object)taskName, (Object)window.getTitle());
                    }
                    if (infos.size() == 0) {
                        this.logger.info("No maintenance tasks found for window {}", (Object)window.getTitle());
                        continue;
                    }
                    window.setTasks(infos);
                    windows.add(window);
                }
            }
            catch (LoginException le) {
                this.logger.error("Unable to get resource resolver.", (Throwable)le);
            }
            finally {
                if (resolver != null) {
                    resolver.close();
                }
            }
        }
        if (windows.size() == 0) {
            this.logger.error("No maintenance windows found at {}", (Object)this.resourcePath);
        }
        this.maintenanceWindows = windows;
        this.startMaintenanceWindows();
        this.registerHealthChecks();
        this.logger.debug("Maintenance schedule updated");
    }

    private void registerHealthChecks() {
        HashSet<String> configuredTaskNames = new HashSet<String>();
        for (MaintenanceWindowImpl window : this.maintenanceWindows) {
            for (MaintenanceTaskInfo info : window.getMaintenanceTaskInfos()) {
                String taskName = info.getName();
                if (!configuredTaskNames.add(taskName)) continue;
                this.registerHealthCheck(taskName, window.getSchedule());
            }
        }
        for (MaintenanceTaskInfo info : this.mtManager.getMaintenanceTaskInfos()) {
            String taskName;
            if (!info.isMandatory() || !configuredTaskNames.add(taskName = info.getName())) continue;
            this.registerHealthCheck(taskName, null);
        }
    }

    private void registerHealthCheck(String taskName, MaintenanceTaskInfo.TaskSchedule schedule) {
        Hashtable<String, String> regProps = new Hashtable<String, String>();
        regProps.put("hc.name", "Maintenance Task " + taskName);
        regProps.put("hc.mbean.name", "MaintenanceTask" + taskName);
        regProps.put("hc.tags", "system");
        ServiceRegistration reg = this.bundleContext.registerService(HealthCheck.class.getName(), (Object)new MaintenanceTaskHealthCheck(this.mtManager, schedule, taskName), regProps);
        this.registrations.add(reg);
    }

    private void startMaintenanceWindows() {
        for (MaintenanceWindowImpl window : this.maintenanceWindows) {
            this.logger.debug("Starting maintenance window {} from {} to {}", new Object[]{window.getTitle(), window.getStartCronExpression(), window.getEndCronExpression()});
            ArrayList windowJobList = new ArrayList();
            HashMap<String, Serializable> startConfig = new HashMap<String, Serializable>();
            startConfig.put("window", window);
            startConfig.put("end", (Boolean)false);
            startConfig.put("jobs", windowJobList);
            this.scheduler.schedule((Object)this, this.scheduler.EXPR(window.getStartCronExpression()).name(window.getStartScheduleName()).canRunConcurrently(false).onLeaderOnly(true).config(startConfig));
            HashMap<String, Serializable> endConfig = new HashMap<String, Serializable>();
            endConfig.put("window", window);
            endConfig.put("end", (Boolean)true);
            endConfig.put("jobs", windowJobList);
            this.scheduler.schedule((Object)this, this.scheduler.EXPR(window.getEndCronExpression()).name(window.getEndScheduleName()).canRunConcurrently(false).onLeaderOnly(true).config(endConfig));
        }
    }

    public void execute(JobContext context) {
        Map config = context.getConfiguration();
        MaintenanceWindowImpl window = (MaintenanceWindowImpl)config.get("window");
        List jobs = (List)config.get("jobs");
        Boolean isEnd = (Boolean)config.get("end");
        if (isEnd.booleanValue()) {
            for (String jobId : jobs) {
                this.jobManager.stopJobById(jobId);
                Job currentJob = this.jobManager.getJobById(jobId);
                if (currentJob == null || currentJob.getFinishedDate() != null) continue;
                this.jobManager.removeJobById(jobId);
            }
            jobs.clear();
        } else {
            HashMap<String, String> jobProperties = new HashMap<String, String>();
            jobProperties.put("window", window.getTitle());
            for (MaintenanceTaskInfo info : window.getMaintenanceTaskInfos()) {
                Job job = this.jobManager.addJob(info.getTaskTopic(), jobProperties);
                if (job == null) continue;
                jobs.add(job.getId());
            }
        }
    }

    protected void bindScheduler(Scheduler scheduler) {
        this.scheduler = scheduler;
    }

    protected void unbindScheduler(Scheduler scheduler) {
        if (this.scheduler == scheduler) {
            this.scheduler = null;
        }
    }

    protected void bindRrFactory(ResourceResolverFactory resourceResolverFactory) {
        this.rrFactory = resourceResolverFactory;
    }

    protected void unbindRrFactory(ResourceResolverFactory resourceResolverFactory) {
        if (this.rrFactory == resourceResolverFactory) {
            this.rrFactory = null;
        }
    }

    protected void bindMtManager(MaintenanceTaskManager maintenanceTaskManager) {
        this.mtManager = maintenanceTaskManager;
    }

    protected void unbindMtManager(MaintenanceTaskManager maintenanceTaskManager) {
        if (this.mtManager == maintenanceTaskManager) {
            this.mtManager = null;
        }
    }

    protected void bindJobManager(JobManager jobManager) {
        this.jobManager = jobManager;
    }

    protected void unbindJobManager(JobManager jobManager) {
        if (this.jobManager == jobManager) {
            this.jobManager = null;
        }
    }

    protected void bindOperationsService(OperationsService operationsService) {
        this.operationsService = operationsService;
    }

    protected void unbindOperationsService(OperationsService operationsService) {
        if (this.operationsService == operationsService) {
            this.operationsService = null;
        }
    }

}