Search in sources :

Example 26 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class HeartbeatTest method testVotingLoop.

/**
     * SLING-5027 : test to reproduce the voting loop
     * (and verify that it's fixed)
     */
@Test
public void testVotingLoop() throws Throwable {
    logger.info("testVotingLoop: creating slowMachine1...");
    FullJR2VirtualInstanceBuilder slowBuilder1 = newBuilder();
    slowBuilder1.setDebugName("slow1").newRepository("/var/discovery/impl/", true).setConnectorPingTimeout(600).setConnectorPingInterval(999).setMinEventDelay(0);
    FullJR2VirtualInstance slowMachine1 = slowBuilder1.fullBuild();
    instances.add(slowMachine1);
    SimpleTopologyEventListener slowListener1 = new SimpleTopologyEventListener("slow1");
    slowMachine1.bindTopologyEventListener(slowListener1);
    logger.info("testVotingLoop: creating slowMachine2...");
    FullJR2VirtualInstanceBuilder slowBuilder2 = newBuilder();
    slowBuilder2.setDebugName("slow2").useRepositoryOf(slowMachine1).setConnectorPingTimeout(600).setConnectorPingInterval(999).setMinEventDelay(0);
    FullJR2VirtualInstance slowMachine2 = slowBuilder2.fullBuild();
    instances.add(slowMachine2);
    SimpleTopologyEventListener slowListener2 = new SimpleTopologyEventListener("slow2");
    slowMachine2.bindTopologyEventListener(slowListener2);
    logger.info("testVotingLoop: creating fastMachine...");
    FullJR2VirtualInstanceBuilder fastBuilder = newBuilder();
    fastBuilder.setDebugName("fast").useRepositoryOf(slowMachine1).setConnectorPingTimeout(600).setConnectorPingInterval(999).setMinEventDelay(0);
    FullJR2VirtualInstance fastMachine = fastBuilder.fullBuild();
    instances.add(fastMachine);
    SimpleTopologyEventListener fastListener = new SimpleTopologyEventListener("fast");
    fastMachine.bindTopologyEventListener(fastListener);
    HeartbeatHandler hhSlow1 = slowMachine1.getHeartbeatHandler();
    HeartbeatHandler hhSlow2 = slowMachine2.getHeartbeatHandler();
    HeartbeatHandler hhFast = fastMachine.getHeartbeatHandler();
    Thread.sleep(1000);
    logger.info("testVotingLoop: after some initial 1sec sleep no event should yet have been sent");
    assertFalse(fastMachine.getDiscoveryService().getTopology().isCurrent());
    assertFalse(slowMachine1.getDiscoveryService().getTopology().isCurrent());
    assertFalse(slowMachine2.getDiscoveryService().getTopology().isCurrent());
    assertNull(fastListener.getLastEvent());
    assertNull(slowListener1.getLastEvent());
    assertNull(slowListener2.getLastEvent());
    // prevent the slow machine from voting
    logger.info("testVotingLoop: stopping voting of slowMachine1...");
    slowMachine1.stopVoting();
    // now let all issue a heartbeat
    logger.info("testVotingLoop: letting slow1, slow2 and fast all issue 1 heartbeat");
    hhSlow1.issueHeartbeat();
    hhSlow2.issueHeartbeat();
    hhFast.issueHeartbeat();
    // now let the fast one start a new voting, to which
    // only the fast one will vote, the slow one doesn't.
    // that will cause a voting loop
    logger.info("testVotingLoop: let the fast one do a checkView, thus initiate a voting");
    hhFast.doCheckView();
    Calendar previousVotedAt = null;
    for (int i = 0; i < 5; i++) {
        logger.info("testVotingLoop: sleeping 1sec...");
        Thread.sleep(1000);
        logger.info("testVotingLoop: check to see that there is no voting loop...");
        // now check the ongoing votings
        ResourceResolverFactory factory = fastMachine.getResourceResolverFactory();
        ResourceResolver resourceResolver = factory.getServiceResourceResolver(null);
        try {
            List<VotingView> ongoingVotings = VotingHelper.listOpenNonWinningVotings(resourceResolver, fastMachine.getFullConfig());
            assertNotNull(ongoingVotings);
            assertEquals(1, ongoingVotings.size());
            VotingView ongoingVote = ongoingVotings.get(0);
            assertFalse(ongoingVote.isWinning());
            assertFalse(ongoingVote.hasVotedYes(slowMachine1.getSlingId()));
            assertTrue(ongoingVote.hasVotedYes(slowMachine2.getSlingId()));
            final Resource memberResource = ongoingVote.getResource().getChild("members").getChild(slowMachine2.getSlingId());
            final ModifiableValueMap memberMap = memberResource.adaptTo(ModifiableValueMap.class);
            Property vote = (Property) memberMap.get("vote");
            assertEquals(Boolean.TRUE, vote.getBoolean());
            Property votedAt = (Property) memberMap.get("votedAt");
            if (previousVotedAt == null) {
                previousVotedAt = votedAt.getDate();
            } else {
                assertEquals(previousVotedAt, votedAt.getDate());
            }
        } catch (Exception e) {
            resourceResolver.close();
            fail("Exception: " + e);
        }
    }
}
Also used : FullJR2VirtualInstance(org.apache.sling.discovery.impl.setup.FullJR2VirtualInstance) Calendar(java.util.Calendar) Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) FullJR2VirtualInstanceBuilder(org.apache.sling.discovery.impl.setup.FullJR2VirtualInstanceBuilder) ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) VotingView(org.apache.sling.discovery.impl.cluster.voting.VotingView) Property(javax.jcr.Property) Test(org.junit.Test)

Example 27 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class JobManagerImpl method findJobs.

/**
     * @see org.apache.sling.event.jobs.JobManager#findJobs(org.apache.sling.event.jobs.JobManager.QueryType, java.lang.String, long, java.util.Map[])
     */
@Override
public Collection<Job> findJobs(final QueryType type, final String topic, final long limit, final Map<String, Object>... templates) {
    final boolean isHistoryQuery = type == QueryType.HISTORY || type == QueryType.SUCCEEDED || type == QueryType.CANCELLED || type == QueryType.DROPPED || type == QueryType.ERROR || type == QueryType.GIVEN_UP || type == QueryType.STOPPED;
    final List<Job> result = new ArrayList<>();
    final ResourceResolver resolver = this.configuration.createResourceResolver();
    final StringBuilder buf = new StringBuilder(64);
    try {
        buf.append("/jcr:root");
        buf.append(this.configuration.getJobsBasePathWithSlash());
        buf.append("/element(*,");
        buf.append(ResourceHelper.RESOURCE_TYPE_JOB);
        buf.append(")[@");
        buf.append(ISO9075.encode(ResourceHelper.PROPERTY_JOB_TOPIC));
        if (topic != null) {
            buf.append(" = '");
            buf.append(topic);
            buf.append("'");
        }
        // restricting on the type - history or unfinished
        if (isHistoryQuery) {
            buf.append(" and @");
            buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
            if (type == QueryType.SUCCEEDED || type == QueryType.DROPPED || type == QueryType.ERROR || type == QueryType.GIVEN_UP || type == QueryType.STOPPED) {
                buf.append(" = '");
                buf.append(type.name());
                buf.append("'");
            } else if (type == QueryType.CANCELLED) {
                buf.append(" and (@");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.DROPPED.name());
                buf.append("' or @");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.ERROR.name());
                buf.append("' or @");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.GIVEN_UP.name());
                buf.append("' or @");
                buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
                buf.append(" = '");
                buf.append(QueryType.STOPPED.name());
                buf.append("')");
            }
        } else {
            buf.append(" and not(@");
            buf.append(ISO9075.encode(JobImpl.PROPERTY_FINISHED_STATE));
            buf.append(")");
            if (type == QueryType.ACTIVE) {
                buf.append(" and @");
                buf.append(ISO9075.encode(Job.PROPERTY_JOB_STARTED_TIME));
            } else if (type == QueryType.QUEUED) {
                buf.append(" and not(@");
                buf.append(ISO9075.encode(Job.PROPERTY_JOB_STARTED_TIME));
                buf.append(")");
            }
        }
        if (templates != null && templates.length > 0) {
            int index = 0;
            for (final Map<String, Object> template : templates) {
                // skip empty templates
                if (template.size() == 0) {
                    continue;
                }
                if (index == 0) {
                    buf.append(" and (");
                } else {
                    buf.append(" or ");
                }
                buf.append('(');
                final Iterator<Map.Entry<String, Object>> i = template.entrySet().iterator();
                boolean first = true;
                while (i.hasNext()) {
                    final Map.Entry<String, Object> current = i.next();
                    final String key = ISO9075.encode(current.getKey());
                    final char firstChar = key.length() > 0 ? key.charAt(0) : 0;
                    final String propName;
                    final Operation op;
                    if (firstChar == '=') {
                        propName = key.substring(1);
                        op = Operation.EQUALS;
                    } else if (firstChar == '<') {
                        final char secondChar = key.length() > 1 ? key.charAt(1) : 0;
                        if (secondChar == '=') {
                            op = Operation.LESS_OR_EQUALS;
                            propName = key.substring(2);
                        } else {
                            op = Operation.LESS;
                            propName = key.substring(1);
                        }
                    } else if (firstChar == '>') {
                        final char secondChar = key.length() > 1 ? key.charAt(1) : 0;
                        if (secondChar == '=') {
                            op = Operation.GREATER_OR_EQUALS;
                            propName = key.substring(2);
                        } else {
                            op = Operation.GREATER;
                            propName = key.substring(1);
                        }
                    } else {
                        propName = key;
                        op = Operation.EQUALS;
                    }
                    if (first) {
                        first = false;
                        buf.append('@');
                    } else {
                        buf.append(" and @");
                    }
                    buf.append(propName);
                    buf.append(' ');
                    switch(op) {
                        case EQUALS:
                            buf.append('=');
                            break;
                        case LESS:
                            buf.append('<');
                            break;
                        case LESS_OR_EQUALS:
                            buf.append("<=");
                            break;
                        case GREATER:
                            buf.append('>');
                            break;
                        case GREATER_OR_EQUALS:
                            buf.append(">=");
                            break;
                    }
                    buf.append(" '");
                    buf.append(current.getValue());
                    buf.append("'");
                }
                buf.append(')');
                index++;
            }
            if (index > 0) {
                buf.append(')');
            }
        }
        buf.append("] order by @");
        if (isHistoryQuery) {
            buf.append(JobImpl.PROPERTY_FINISHED_DATE);
            buf.append(" descending");
        } else {
            buf.append(Job.PROPERTY_JOB_CREATED);
            buf.append(" ascending");
        }
        final Iterator<Resource> iter = resolver.findResources(buf.toString(), "xpath");
        long count = 0;
        while (iter.hasNext() && (limit < 1 || count < limit)) {
            final Resource jobResource = iter.next();
            // sanity check for the path
            if (this.configuration.isJob(jobResource.getPath())) {
                final JobImpl job = Utility.readJob(logger, jobResource);
                if (job != null) {
                    count++;
                    result.add(job);
                }
            }
        }
    } catch (final QuerySyntaxException qse) {
        logger.warn("Query syntax wrong " + buf.toString(), qse);
    } finally {
        resolver.close();
    }
    return result;
}
Also used : ArrayList(java.util.ArrayList) Resource(org.apache.sling.api.resource.Resource) QuerySyntaxException(org.apache.sling.api.resource.QuerySyntaxException) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Job(org.apache.sling.event.jobs.Job) Map(java.util.Map) HashMap(java.util.HashMap)

Example 28 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class JobManagerConfiguration method createResourceResolver.

/**
     * Create a new resource resolver for reading and writing the resource tree.
     * The resolver needs to be closed by the client.
     * @return A resource resolver or {@code null} if the component is already deactivated.
     * @throws RuntimeException if the resolver can't be created.
     */
public ResourceResolver createResourceResolver() {
    ResourceResolver resolver = null;
    final ResourceResolverFactory factory = this.resourceResolverFactory;
    if (factory != null) {
        try {
            resolver = this.resourceResolverFactory.getServiceResourceResolver(null);
        } catch (final LoginException le) {
            logger.error("Unable to create new resource resolver: " + le.getMessage(), le);
            throw new RuntimeException(le);
        }
    }
    return resolver;
}
Also used : ResourceResolverFactory(org.apache.sling.api.resource.ResourceResolverFactory) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) LoginException(org.apache.sling.api.resource.LoginException)

Example 29 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class JobManagerImpl method addJobInternal.

/**
     * Persist the job in the resource tree
     * @param jobTopic The required job topic
     * @param jobName The optional job name
     * @param passedJobProperties The optional job properties
     * @return The persisted job or <code>null</code>.
     */
private Job addJobInternal(final String jobTopic, final Map<String, Object> jobProperties, final List<String> errors) {
    final QueueInfo info = this.configuration.getQueueConfigurationManager().getQueueInfo(jobTopic);
    final TopologyCapabilities caps = this.configuration.getTopologyCapabilities();
    info.targetId = (caps == null ? null : caps.detectTarget(jobTopic, jobProperties, info));
    if (logger.isDebugEnabled()) {
        if (info.targetId != null) {
            logger.debug("Persisting job {} into queue {}, target={}", new Object[] { Utility.toString(jobTopic, jobProperties), info.queueName, info.targetId });
        } else {
            logger.debug("Persisting job {} into queue {}", Utility.toString(jobTopic, jobProperties), info.queueName);
        }
    }
    final ResourceResolver resolver = this.configuration.createResourceResolver();
    try {
        final JobImpl job = this.writeJob(resolver, jobTopic, jobProperties, info);
        if (info.targetId != null) {
            this.configuration.getAuditLogger().debug("ASSIGN OK {} : {}", info.targetId, job.getId());
        } else {
            this.configuration.getAuditLogger().debug("UNASSIGN OK : {}", job.getId());
        }
        return job;
    } catch (final PersistenceException re) {
        // something went wrong, so let's log it
        this.logger.error("Exception during persisting new job '" + Utility.toString(jobTopic, jobProperties) + "'", re);
    } finally {
        resolver.close();
    }
    if (errors != null) {
        errors.add("Unable to persist new job.");
    }
    return null;
}
Also used : QueueInfo(org.apache.sling.event.impl.jobs.config.QueueConfigurationManager.QueueInfo) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) TopologyCapabilities(org.apache.sling.event.impl.jobs.config.TopologyCapabilities)

Example 30 with ResourceResolver

use of org.apache.sling.api.resource.ResourceResolver in project sling by apache.

the class OakVirtualInstanceBuilder method resetRepo.

@Override
protected void resetRepo() throws Exception {
    leaseCollection.reset();
    ResourceResolver rr = null;
    Session l = null;
    try {
        rr = factory.getServiceResourceResolver(null);
        l = rr.adaptTo(Session.class);
        l.removeItem("/var");
        l.save();
        l.logout();
    } catch (Exception e) {
        l.refresh(false);
        l.logout();
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Session(javax.jcr.Session)

Aggregations

ResourceResolver (org.apache.sling.api.resource.ResourceResolver)339 Resource (org.apache.sling.api.resource.Resource)168 Test (org.junit.Test)131 HashMap (java.util.HashMap)65 LoginException (org.apache.sling.api.resource.LoginException)53 PersistenceException (org.apache.sling.api.resource.PersistenceException)52 Session (javax.jcr.Session)31 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)29 ValueMap (org.apache.sling.api.resource.ValueMap)27 SyntheticResource (org.apache.sling.api.resource.SyntheticResource)26 ArrayList (java.util.ArrayList)23 DistributionRequest (org.apache.sling.distribution.DistributionRequest)23 DistributionPackage (org.apache.sling.distribution.packaging.DistributionPackage)21 Map (java.util.Map)19 Before (org.junit.Before)19 IOException (java.io.IOException)17 NonExistingResource (org.apache.sling.api.resource.NonExistingResource)17 ChildResource (org.apache.sling.validation.model.ChildResource)17 HashSet (java.util.HashSet)16 ResourceResolverFactory (org.apache.sling.api.resource.ResourceResolverFactory)15