AgentManagerImpl.java 16.8 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Node
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Deactivate
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.ReferenceCardinality
 *  org.apache.felix.scr.annotations.ReferencePolicy
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.jackrabbit.commons.JcrUtils
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.commons.scheduler.Scheduler
 *  org.apache.sling.event.jobs.Job
 *  org.apache.sling.event.jobs.JobManager
 *  org.apache.sling.event.jobs.consumer.JobExecutionContext
 *  org.apache.sling.event.jobs.consumer.JobExecutionContext$ResultBuilder
 *  org.apache.sling.event.jobs.consumer.JobExecutionResult
 *  org.apache.sling.event.jobs.consumer.JobExecutor
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.apache.sling.serviceusermapping.ServiceUserMapped
 *  org.osgi.framework.BundleContext
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.replication.impl;

import com.day.cq.replication.Agent;
import com.day.cq.replication.AgentConfig;
import com.day.cq.replication.AgentConfigGroup;
import com.day.cq.replication.AgentManager;
import com.day.cq.replication.ConfigManager;
import com.day.cq.replication.ReplicationAction;
import com.day.cq.replication.ReplicationActionType;
import com.day.cq.replication.ReplicationContentFactory;
import com.day.cq.replication.ReplicationContentFilter;
import com.day.cq.replication.ReplicationContentFilterFactory;
import com.day.cq.replication.ReplicationQueue;
import com.day.cq.replication.impl.AgentImpl;
import com.day.cq.replication.impl.ReplicationContentFactoryProvider;
import com.day.cq.replication.impl.ServiceTracker;
import com.day.cq.replication.impl.distribution.DistributionQueueImpl;
import com.day.cq.replication.impl.queue.QueueListener;
import com.day.cq.replication.impl.queue.ReplicationJob;
import com.day.cq.replication.impl.queue.ReplicationQueueImpl;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
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.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.Service;
import org.apache.jackrabbit.commons.JcrUtils;
import org.apache.sling.api.resource.ResourceResolverFactory;
import org.apache.sling.commons.scheduler.Scheduler;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.JobManager;
import org.apache.sling.event.jobs.consumer.JobExecutionContext;
import org.apache.sling.event.jobs.consumer.JobExecutionResult;
import org.apache.sling.event.jobs.consumer.JobExecutor;
import org.apache.sling.jcr.api.SlingRepository;
import org.apache.sling.serviceusermapping.ServiceUserMapped;
import org.osgi.framework.BundleContext;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(metatype=1)
@Service(value={AgentManager.class, JobExecutor.class})
@org.apache.felix.scr.annotations.Property(name="job.topics", value={"com/day/cq/replication/job/*"})
@Reference(name="contentFilterFactory", referenceInterface=ReplicationContentFilterFactory.class, cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE, policy=ReferencePolicy.DYNAMIC)
public class AgentManagerImpl
implements AgentManager,
JobExecutor,
ConfigManager.ConfigEventListener {
    private static final Logger log = LoggerFactory.getLogger(AgentManagerImpl.class);
    private static final String CONTENT_PATH = "/var/replication/data";
    private ComponentContext componentContext;
    @Reference
    private JobManager jobManager = null;
    @Reference
    private Scheduler scheduler = null;
    @Reference
    private SlingRepository repository = null;
    @Reference
    private ServiceTracker serviceTracker = null;
    @Reference
    private ReplicationContentFactoryProvider factoryProvider = null;
    @Reference
    private ConfigManager configManager = null;
    @org.apache.felix.scr.annotations.Property(name="serviceUser.target", value={"(subServiceName=replicationService)"})
    @Reference(name="serviceUser")
    private ServiceUserMapped serviceUserMapped;
    @Reference
    private ResourceResolverFactory resourceResolverFactory = null;
    private final Map<String, ReplicationContentFilterFactory> filterFactoryCache = new ConcurrentHashMap<String, ReplicationContentFilterFactory>();
    private final ReadWriteLock lock = new ReentrantReadWriteLock();
    private Map<String, AgentImpl> agents = new LinkedHashMap<String, AgentImpl>();
    private Map<String, Agent> cachedAgents;

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    @Activate
    protected void activate(ComponentContext ctx) throws RepositoryException {
        this.componentContext = ctx;
        this.lock.writeLock().lock();
        Session session = null;
        try {
            for (String cfgId : this.configManager.getConfigurations().keySet()) {
                try {
                    this.update(cfgId);
                }
                catch (RepositoryException e) {
                    log.error("Error while initializing replication agent.", (Throwable)e);
                }
            }
            this.cacheAgents();
            this.configManager.registerListener(this);
            session = this.repository.loginService("replicationService", null);
            JcrUtils.getOrCreateByPath((String)"/var/replication/data", (String)"sling:Folder", (String)"sling:Folder", (Session)session, (boolean)false);
            session.save();
            log.info("AgentManager service activated");
        }
        finally {
            if (session != null) {
                session.logout();
            }
            this.lock.writeLock().unlock();
        }
    }

    @Deactivate
    protected void deactivate() {
        this.componentContext = null;
        this.configManager.unregisterListener(this);
        this.lock.writeLock().lock();
        try {
            for (AgentImpl agent : this.agents.values()) {
                agent.destroy(false);
            }
            this.agents.clear();
            this.cachedAgents = Collections.emptyMap();
        }
        finally {
            this.lock.writeLock().unlock();
        }
        this.filterFactoryCache.clear();
    }

    @Override
    public Map<String, Agent> getAgents() {
        return this.cachedAgents;
    }

    private void cacheAgents() {
        this.cachedAgents = new LinkedHashMap<String, Agent>();
        for (Agent agent : this.agents.values()) {
            this.cachedAgents.put(agent.getId(), agent);
        }
        this.cachedAgents = Collections.unmodifiableMap(this.cachedAgents);
    }

    @Override
    public void onConfigEvent(ConfigManager.ConfigEvent evt) {
        this.lock.writeLock().lock();
        try {
            switch (evt.getType()) {
                case ADDED: 
                case UPDATED: {
                    this.update(evt.getId());
                    break;
                }
                case REMOVED: {
                    this.remove(evt.getId());
                }
            }
            this.cacheAgents();
        }
        catch (RepositoryException e) {
            log.error("Error while adding/updating agent: {}", (Object)evt.getId(), (Object)e);
        }
        finally {
            this.lock.writeLock().unlock();
        }
    }

    private void update(String cfgId) throws RepositoryException {
        AgentConfig config = this.configManager.getConfigurations().get(cfgId);
        if (config == null || !config.getConfigGroup().isActive()) {
            this.remove(cfgId);
        } else {
            AgentImpl agent = this.agents.remove(cfgId);
            if (agent == null) {
                String id = config.getAgentId();
                log.info("AgentConfig at {} added.", (Object)cfgId);
                ReplicationContentFactory factory = this.factoryProvider.create(id);
                agent = new AgentImpl(id, config, this.serviceTracker, this, factory);
                agent.init(this.componentContext.getBundleContext());
            } else {
                log.info("AgentConfig at {} updated.", (Object)cfgId);
                agent.update(config);
            }
            this.agents.put(cfgId, agent);
        }
    }

    private void remove(String path) {
        AgentImpl agent = this.agents.remove(path);
        if (agent != null) {
            log.info("AgentConfig at {} removed.", (Object)path);
            agent.destroy();
        }
    }

    private Node getOutboxNode(Session session, String agentId) throws RepositoryException {
        String path = "/var/replication/data/" + agentId;
        return JcrUtils.getOrCreateByPath((String)path, (String)"sling:Folder", (String)"sling:Folder", (Session)session, (boolean)true);
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected Calendar getLastPollTime(String agentId) {
        this.lock.writeLock().lock();
        try {
            Session session = null;
            try {
                session = this.repository.loginService("replicationService", null);
                Node ob = this.getOutboxNode(session, agentId);
                if (ob.hasProperty("cq:lastPoll")) {
                    Calendar calendar = ob.getProperty("cq:lastPoll").getDate();
                    return calendar;
                }
            }
            catch (RepositoryException e) {
                log.error("Error while fetching last poll time for agent {}", (Object)agentId, (Object)e);
            }
            finally {
                if (session != null) {
                    session.logout();
                }
            }
            Calendar e = null;
            return e;
        }
        finally {
            this.lock.writeLock().unlock();
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    protected void setLastPollTime(String agentId, Calendar time) {
        this.lock.writeLock().lock();
        Session session = null;
        try {
            session = this.repository.loginService("replicationService", null);
            Node ob = this.getOutboxNode(session, agentId);
            ob.setProperty("cq:lastPoll", time);
            session.save();
        }
        catch (RepositoryException e) {
            log.error("Error while fetching last poll time for agent {}", (Object)agentId, (Object)e);
        }
        finally {
            this.lock.writeLock().unlock();
            if (session != null) {
                session.logout();
            }
        }
    }

    public JobExecutionResult process(Job newJob, JobExecutionContext context) {
        ReplicationJob job = new ReplicationJob(newJob, context);
        String queueName = job.getQueueName();
        Agent a = this.getAgents().get(queueName);
        if (a == null) {
            log.error("Job contains unknown agent: {}. Discarding Job {}", (Object)queueName, (Object)job);
            return context.result().cancelled();
        }
        ReplicationQueueImpl queue = (ReplicationQueueImpl)a.getQueue();
        if (queue == null) {
            log.error("Job contains agent which is not started: {}. waiting {}", (Object)queueName, (Object)job);
            return context.result().failed();
        }
        QueueListener.JobStatus result = a.getConfiguration().isBatchMode() && ReplicationActionType.ACTIVATE.equals((Object)job.getAction().getType()) ? queue.batchProcess(job, a.getConfiguration()) : queue.process(job);
        if (result == null) {
            return null;
        }
        if (result == QueueListener.JobStatus.CANCELLED) {
            return context.result().cancelled();
        }
        if (result == QueueListener.JobStatus.FAILED) {
            return context.result().failed();
        }
        return context.result().succeeded();
    }

    public ReplicationQueueImpl createQueue(String name, QueueListener listener) {
        ReplicationQueueImpl q = new ReplicationQueueImpl(this.jobManager, this.scheduler, name);
        q.open(listener);
        return q;
    }

    public DistributionQueueImpl createDistributionQueue(String distributionAgentName) {
        return new DistributionQueueImpl(this.resourceResolverFactory, distributionAgentName);
    }

    protected void bindContentFilterFactory(ReplicationContentFilterFactory factory, Map<String, Object> properties) {
        String key = (String)properties.get("service.pid");
        this.filterFactoryCache.put(key, factory);
        log.info("bound new filter factory [{}]. got [{}] factories.", (Object)key, (Object)this.filterFactoryCache.size());
    }

    protected void unbindContentFilterFactory(ReplicationContentFilterFactory factory, Map<String, Object> properties) {
        String key = (String)properties.get("service.pid");
        this.filterFactoryCache.remove(key);
        log.info("unbound filter factory [{}]. got [{}] factories.", (Object)key, (Object)this.filterFactoryCache.size());
    }

    public List<ReplicationContentFilter> createContentFilterChain(ReplicationAction action) {
        ArrayList<ReplicationContentFilter> filters = new ArrayList<ReplicationContentFilter>();
        Collection<ReplicationContentFilterFactory> factories = this.filterFactoryCache.values();
        for (ReplicationContentFilterFactory factory : factories) {
            ReplicationContentFilter filter = factory.createFilter(action);
            if (null == filter) continue;
            filters.add(filter);
        }
        return filters;
    }

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

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

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

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

    protected void bindRepository(SlingRepository slingRepository) {
        this.repository = slingRepository;
    }

    protected void unbindRepository(SlingRepository slingRepository) {
        if (this.repository == slingRepository) {
            this.repository = null;
        }
    }

    protected void bindServiceTracker(ServiceTracker serviceTracker) {
        this.serviceTracker = serviceTracker;
    }

    protected void unbindServiceTracker(ServiceTracker serviceTracker) {
        if (this.serviceTracker == serviceTracker) {
            this.serviceTracker = null;
        }
    }

    protected void bindFactoryProvider(ReplicationContentFactoryProvider replicationContentFactoryProvider) {
        this.factoryProvider = replicationContentFactoryProvider;
    }

    protected void unbindFactoryProvider(ReplicationContentFactoryProvider replicationContentFactoryProvider) {
        if (this.factoryProvider == replicationContentFactoryProvider) {
            this.factoryProvider = null;
        }
    }

    protected void bindConfigManager(ConfigManager configManager) {
        this.configManager = configManager;
    }

    protected void unbindConfigManager(ConfigManager configManager) {
        if (this.configManager == configManager) {
            this.configManager = null;
        }
    }

    protected void bindServiceUser(ServiceUserMapped serviceUserMapped) {
        this.serviceUserMapped = serviceUserMapped;
    }

    protected void unbindServiceUser(ServiceUserMapped serviceUserMapped) {
        if (this.serviceUserMapped == serviceUserMapped) {
            this.serviceUserMapped = null;
        }
    }

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

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

}