OffloadingAgentManager.java 19.3 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.crypto.CryptoSupport
 *  org.apache.felix.scr.annotations.Component
 *  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.ModifiableValueMap
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceResolverFactory
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.apache.sling.commons.threads.ThreadPool
 *  org.apache.sling.commons.threads.ThreadPoolManager
 *  org.apache.sling.discovery.ClusterView
 *  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.discovery.commons.InstancesDiff
 *  org.apache.sling.discovery.commons.InstancesDiff$InstanceCollection
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.granite.offloading.impl.transporter;

import com.adobe.granite.crypto.CryptoSupport;
import com.adobe.granite.offloading.impl.util.OffloadingUtil;
import java.net.InetAddress;
import java.util.Collection;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.felix.scr.annotations.Component;
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.ModifiableValueMap;
import org.apache.sling.api.resource.PersistenceException;
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.commons.osgi.PropertiesUtil;
import org.apache.sling.commons.threads.ThreadPool;
import org.apache.sling.commons.threads.ThreadPoolManager;
import org.apache.sling.discovery.ClusterView;
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.discovery.commons.InstancesDiff;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(immediate=1, label="%offloading.agentmanager.label", description="%offloading.agentmanager.description", metatype=1)
@Service(value={TopologyEventListener.class})
@Properties(value={@Property(name="offloading.agentmanager.enabled", boolValue={0}, label="Automatic Agent Management", description="Allows to enable/disable the automatic creation replication agents for offloading")})
public class OffloadingAgentManager
implements TopologyEventListener {
    private static final Logger LOG = LoggerFactory.getLogger(OffloadingAgentManager.class);
    static final String SCR_PROP_NAME_ENABLED = "offloading.agentmanager.enabled";
    static final boolean SCR_PROP_DEFAULT_ENABLED = false;
    private static final String SUB_SERVICE_NAME = "agentmanager";
    private boolean enabled = false;
    private static final String AGENTS_ROOT_PATH = "/etc/replication/agents.author";
    private static final String REPLICATION_AGENT_NAME = "Offloading Replication Agent";
    private static final String REVERSE_REPLICATION_AGENT_NAME = "Offloading Reverse Replication Agent";
    private static final String REPLICATION_AGENT_NAME_FORMAT = "offloading_%s";
    private static final String REVERSE_REPLICATION_AGENT_NAME_FORMAT = "offloading_reverse_%s";
    private static final String OUTBOX_REPLICATION_AGENT_NAME = "Offloading Outbox Replication Agent";
    private static final String OUTBOX_REPLICATION_AGENT_RESOURCE_NAME = "offloading_outbox";
    private static final String REPLICATION_AGENT_SLING_RESOURCE_TYPE = "cq/replication/components/agent";
    private static final String REVERSE_REPLICATION_AGENT_SLING_RESOURCE_TYPE = "cq/replication/components/revagent";
    private static final String REPLICATION_AGENT_HTTP_METHOD = "POST";
    private static final String REVERSE_REPLICATION_AGENT_HTTP_METHOD = "GET";
    private static final int NETWORK_TEST_TIMEOUT_SECONDS = 3;
    private static final String USER = "admin";
    private static final String PASSWORD = "admin";
    private ThreadPool eventProcessingThreadPool;
    @Reference
    private ThreadPoolManager threadPoolManager;
    @Reference
    private ResourceResolverFactory rrf;
    @Reference
    private CryptoSupport cryptoSupport;

    public void handleTopologyEvent(TopologyEvent topologyEvent) {
        this.processTopologyEvent(topologyEvent);
    }

    private void processTopologyEvent(final TopologyEvent topologyEvent) {
        if (this.enabled && TopologyEvent.Type.TOPOLOGY_CHANGING != topologyEvent.getType() && (TopologyEvent.Type.TOPOLOGY_CHANGED == topologyEvent.getType() || TopologyEvent.Type.TOPOLOGY_INIT == topologyEvent.getType())) {
            Runnable task = new Runnable(){

                @Override
                public void run() {
                    InstancesDiff instancesDiff = new InstancesDiff(topologyEvent);
                    InstancesDiff.InstanceCollection removed = instancesDiff.removed();
                    InstancesDiff.InstanceCollection added = instancesDiff.added();
                    added.isNotInClusterView(topologyEvent.getNewView().getLocalInstance().getClusterView());
                    for (InstanceDescription instance2 : removed.get()) {
                        LOG.info("Instance {} was removed from the topology.", (Object)instance2.getSlingId());
                        OffloadingAgentManager.this.configureAgentsEnablement(instance2, false);
                    }
                    for (InstanceDescription instance2 : added.get()) {
                        LOG.info("Instance {} was added to the topology.", (Object)instance2.getSlingId());
                        OffloadingAgentManager.this.createReplicationAgentsForInstance(instance2);
                        OffloadingAgentManager.this.configureAgentsEnablement(instance2, true);
                    }
                }
            };
            this.eventProcessingThreadPool.execute(task);
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void createReplicationAgentsForInstance(InstanceDescription instanceDescription) {
        if (instanceDescription != null) {
            ResourceResolver rr = null;
            try {
                rr = this.getServiceResolver();
                Resource agentsRoot = rr.getResource("/etc/replication/agents.author");
                if (agentsRoot != null) {
                    this.createReplicationAgent(AgentType.REPLICATION, rr, agentsRoot, instanceDescription);
                    this.createReplicationAgent(AgentType.REVERSE_REPLICATION, rr, agentsRoot, instanceDescription);
                }
            }
            catch (LoginException e) {
                LOG.error("Cannot obtain service resolver.", (Throwable)e);
            }
            finally {
                if (rr != null) {
                    rr.close();
                }
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void configureAgentsEnablement(InstanceDescription instanceDescription, boolean agentEnablement) {
        if (instanceDescription != null) {
            ResourceResolver rr = null;
            try {
                rr = this.getServiceResolver();
                Resource agentsRoot = rr.getResource("/etc/replication/agents.author");
                if (agentsRoot != null) {
                    ModifiableValueMap agentConfig;
                    ModifiableValueMap agentConfig2;
                    String slingID = instanceDescription.getSlingId();
                    Resource replicationAgent = agentsRoot.getChild(String.format("offloading_%s", slingID) + "/" + "jcr:content");
                    if (replicationAgent != null && (agentConfig2 = (ModifiableValueMap)replicationAgent.adaptTo(ModifiableValueMap.class)) != null) {
                        agentConfig2.put((Object)"enabled", (Object)agentEnablement);
                        LOG.info("Deactivated agent {} for instance {}.", (Object)replicationAgent.getParent().getPath(), (Object)slingID);
                    }
                    Resource reverseReplicationAgent = agentsRoot.getChild(String.format("offloading_reverse_%s", slingID) + "/" + "jcr:content");
                    if (replicationAgent != null && (agentConfig = (ModifiableValueMap)reverseReplicationAgent.adaptTo(ModifiableValueMap.class)) != null) {
                        agentConfig.put((Object)"enabled", (Object)agentEnablement);
                        LOG.info("Deactivated agent {} for instance {}.", (Object)reverseReplicationAgent.getParent().getPath(), (Object)slingID);
                    }
                    rr.commit();
                }
            }
            catch (LoginException e) {
                LOG.error("Cannot obtain service resolver.", (Throwable)e);
            }
            catch (PersistenceException e) {
                LOG.error("Cannot commit changes for replication agents for instance " + instanceDescription.getSlingId(), (Throwable)e);
            }
            finally {
                if (rr != null) {
                    rr.close();
                }
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void createOutboxReplicationAgent() {
        ResourceResolver rr = null;
        try {
            rr = this.getServiceResolver();
            Resource agentsRoot = rr.getResource("/etc/replication/agents.author");
            if (agentsRoot != null && rr.getResource(agentsRoot, "offloading_outbox") == null) {
                HashMap<String, Object> agentResourceProperties = new HashMap<String, Object>();
                agentResourceProperties.put("jcr:primaryType", "cq:Page");
                agentResourceProperties.put("jcr:createdBy", rr.getUserID());
                agentResourceProperties.put("jcr:created", new Date());
                Resource agentResource = rr.create(agentsRoot, "offloading_outbox", agentResourceProperties);
                HashMap<String, Object> agentProperties = new HashMap<String, Object>();
                agentProperties.put("enabled", true);
                agentProperties.put("jcr:title", "Offloading Outbox Replication Agent");
                agentProperties.put("noVersioning", true);
                agentProperties.put("transportUri", "repo://var/replication/outbox");
                agentProperties.put("triggerSpecific", true);
                agentProperties.put("agentType", "default");
                agentProperties.put("sling:resourceType", "cq/replication/components/agent");
                rr.create(agentResource, "jcr:content", agentProperties);
                rr.commit();
                LOG.info("Created outbox replication agent {}.", (Object)agentResource.getPath());
            }
        }
        catch (Exception e) {
            LOG.error("Cannot create an outbox replication agent.", (Throwable)e);
        }
        finally {
            if (rr != null) {
                rr.close();
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    private void configureOutboxAgentEnablement(boolean agentEnablement) {
        ResourceResolver rr = null;
        try {
            Resource outboxAgent;
            rr = this.getServiceResolver();
            Resource agentsRoot = rr.getResource("/etc/replication/agents.author");
            if (agentsRoot != null && (outboxAgent = rr.getResource(agentsRoot, "offloading_outbox/jcr:content")) != null) {
                ModifiableValueMap agentProperties = (ModifiableValueMap)outboxAgent.adaptTo(ModifiableValueMap.class);
                agentProperties.put((Object)"enabled", (Object)agentEnablement);
                rr.commit();
            }
        }
        catch (Exception e) {
            LOG.error("Cannot " + (agentEnablement ? "enable" : "disable") + " outbox replication agent.", (Throwable)e);
        }
        finally {
            if (rr != null) {
                rr.close();
            }
        }
    }

    private void createReplicationAgent(AgentType type, ResourceResolver rr, Resource parent, InstanceDescription instanceDescription) {
        String agentResourceName = null;
        if (type == AgentType.REPLICATION) {
            agentResourceName = String.format("offloading_%s", instanceDescription.getSlingId());
        } else if (type == AgentType.REVERSE_REPLICATION) {
            agentResourceName = String.format("offloading_reverse_%s", instanceDescription.getSlingId());
        }
        if (rr.getResource(parent, agentResourceName) == null) {
            HashMap<String, Object> agentProperties = new HashMap<String, Object>();
            String jcrTitle = null;
            String protocolHTTPMethod = null;
            String endpoint = null;
            String slingResourceType = null;
            boolean reverseReplication = false;
            boolean triggerSpecific = false;
            String agentType = null;
            Set<String> endpoints = OffloadingUtil.expandCSV(instanceDescription.getProperty("org.apache.sling.instance.endpoints"));
            for (String s : endpoints) {
                String address = OffloadingUtil.getHostFromEndpoint(s);
                try {
                    if (!InetAddress.getByName(address).isReachable(3000)) continue;
                    endpoint = s;
                    break;
                }
                catch (Exception e) {
                    LOG.error("Unknown host " + address + " for instance " + instanceDescription.getSlingId());
                    continue;
                }
            }
            if (endpoint == null) {
                LOG.warn("Skipping creating replication agent for instance " + instanceDescription.getSlingId() + ": no accessible endpoint " + "detected.");
                return;
            }
            switch (type) {
                case REPLICATION: {
                    jcrTitle = "Offloading Replication Agent";
                    protocolHTTPMethod = "POST";
                    slingResourceType = "cq/replication/components/agent";
                    reverseReplication = false;
                    agentType = "default";
                    triggerSpecific = true;
                    break;
                }
                case REVERSE_REPLICATION: {
                    jcrTitle = "Offloading Reverse Replication Agent";
                    protocolHTTPMethod = "GET";
                    slingResourceType = "cq/replication/components/revagent";
                    reverseReplication = true;
                    agentType = "reverse";
                    triggerSpecific = false;
                    break;
                }
            }
            agentProperties.put("enabled", true);
            agentProperties.put("jcr:title", jcrTitle);
            agentProperties.put("protocolHTTPMethod", protocolHTTPMethod);
            agentProperties.put("sling:resourceType", slingResourceType);
            agentProperties.put("transportUri", endpoint + "bin/receive?sling:authRequestLogin=1");
            agentProperties.put("transportUser", "admin");
            agentProperties.put("jcr:primaryType", "nt:unstructured");
            agentProperties.put("reverseReplication", reverseReplication);
            agentProperties.put("agentType", agentType);
            agentProperties.put("triggerSpecific", triggerSpecific);
            try {
                agentProperties.put("transportPassword", this.cryptoSupport.protect("admin"));
                HashMap<String, Object> agentResourceProperties = new HashMap<String, Object>();
                agentResourceProperties.put("jcr:primaryType", "cq:Page");
                agentResourceProperties.put("jcr:createdBy", rr.getUserID());
                agentResourceProperties.put("jcr:created", new Date());
                Resource agentResource = rr.create(parent, agentResourceName, agentResourceProperties);
                rr.create(agentResource, "jcr:content", agentProperties);
                rr.commit();
                LOG.info("Created {} agent for instance {}.", (Object)type.value(), (Object)instanceDescription.getSlingId());
            }
            catch (Exception e) {
                LOG.error("Cannot create replication agent.", (Throwable)e);
            }
        }
    }

    private ResourceResolver getServiceResolver() throws LoginException {
        HashMap<String, String> authenticationInfo = new HashMap<String, String>();
        authenticationInfo.put("sling.service.subservice", "agentmanager");
        return this.rrf.getServiceResourceResolver(authenticationInfo);
    }

    protected void activate(ComponentContext componentContext) {
        Dictionary properties = componentContext.getProperties();
        this.enabled = PropertiesUtil.toBoolean(properties.get("offloading.agentmanager.enabled"), (boolean)false);
        if (this.enabled) {
            this.eventProcessingThreadPool = this.threadPoolManager.get("Offloading Agent Manager event processing");
            this.createOutboxReplicationAgent();
            this.configureOutboxAgentEnablement(true);
        }
    }

    protected void deactivate(ComponentContext componentContext) {
        if (this.enabled) {
            this.configureOutboxAgentEnablement(false);
            if (this.eventProcessingThreadPool != null) {
                this.threadPoolManager.release(this.eventProcessingThreadPool);
                this.eventProcessingThreadPool = null;
            }
        }
    }

    protected void bindThreadPoolManager(ThreadPoolManager threadPoolManager) {
        this.threadPoolManager = threadPoolManager;
    }

    protected void unbindThreadPoolManager(ThreadPoolManager threadPoolManager) {
        if (this.threadPoolManager == threadPoolManager) {
            this.threadPoolManager = null;
        }
    }

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

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

    protected void bindCryptoSupport(CryptoSupport cryptoSupport) {
        this.cryptoSupport = cryptoSupport;
    }

    protected void unbindCryptoSupport(CryptoSupport cryptoSupport) {
        if (this.cryptoSupport == cryptoSupport) {
            this.cryptoSupport = null;
        }
    }

    private static enum AgentType {
        REPLICATION("replication"),
        REVERSE_REPLICATION("reverse replication");
        
        private String type;

        private AgentType(String type) {
            this.type = type;
        }

        public String value() {
            return this.type;
        }
    }

}