Search in sources :

Example 16 with PersistenceException

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

the class VotingHandler method handleEvent.

/**
     * handle repository changes and react to ongoing votings
     */
@Override
public void handleEvent(final Event event) {
    if (!activated) {
        return;
    }
    String resourcePath = (String) event.getProperty("path");
    String ongoingVotingsPath = config.getOngoingVotingsPath();
    if (resourcePath == null) {
        // not of my business
        return;
    }
    if (!resourcePath.startsWith(ongoingVotingsPath)) {
        // not of my business
        return;
    }
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = resolverFactory.getServiceResourceResolver(null);
    } catch (LoginException e) {
        logger.error("handleEvent: could not log in administratively: " + e, e);
        return;
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("handleEvent: path = " + resourcePath + ", event = " + event);
        }
        analyzeVotings(resourceResolver);
    } catch (PersistenceException e) {
        logger.error("handleEvent: got a PersistenceException during votings analysis: " + e, e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException)

Example 17 with PersistenceException

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

the class HeartbeatHandler method doCheckView.

/** Check whether the established view matches the reality, ie matches the
     * heartbeats
     */
@Override
protected void doCheckView() {
    super.doCheckView();
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = getResourceResolver();
        doCheckViewWith(resourceResolver);
    } catch (LoginException e) {
        logger.error("checkView: could not log in administratively: " + e, e);
    } catch (PersistenceException e) {
        logger.error("checkView: encountered a persistence exception during view check: " + e, e);
    } catch (RuntimeException e) {
        logger.error("checkView: encountered a runtime exception during view check: " + e, e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException)

Example 18 with PersistenceException

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

the class HeartbeatHandler method doCheckViewWith.

/** do the established-against-heartbeat view check using the given resourceResolver.
     */
private void doCheckViewWith(final ResourceResolver resourceResolver) throws PersistenceException {
    if (votingHandler == null) {
        logger.info("doCheckViewWith: votingHandler is null! slingId=" + slingId);
    } else {
        votingHandler.analyzeVotings(resourceResolver);
        try {
            votingHandler.cleanupTimedoutVotings(resourceResolver);
        } catch (Exception e) {
            logger.warn("doCheckViewWith: Exception occurred while cleaning up votings: " + e, e);
        }
    }
    final VotingView winningVoting = VotingHelper.getWinningVoting(resourceResolver, config);
    int numOpenNonWinningVotes = VotingHelper.listOpenNonWinningVotings(resourceResolver, config).size();
    if (winningVoting != null || (numOpenNonWinningVotes > 0)) {
        // then there are votings pending and I shall wait for them to
        // settle
        // but first: make sure we sent the TOPOLOGY_CHANGING
        logger.info("doCheckViewWith: there are pending votings, marking topology as changing...");
        invalidateCurrentEstablishedView();
        discoveryServiceImpl.handleTopologyChanging();
        if (logger.isDebugEnabled()) {
            logger.debug("doCheckViewWith: " + numOpenNonWinningVotes + " ongoing votings, no one winning yet - I shall wait for them to settle.");
        }
        return;
    }
    final Resource clusterNodesRes = ResourceHelper.getOrCreateResource(resourceResolver, config.getClusterInstancesPath());
    final Set<String> liveInstances = ViewHelper.determineLiveInstances(clusterNodesRes, config);
    final View establishedView = ViewHelper.getEstablishedView(resourceResolver, config);
    lastEstablishedViewId = establishedView == null ? null : establishedView.getResource().getName();
    boolean establishedViewMatches;
    if (lastEstablishedViewId != null && failedEstablishedViewId != null && lastEstablishedViewId.equals(failedEstablishedViewId)) {
        // SLING-5195 : heartbeat-self-check caused this establishedViewId
        // to be declared as failed - so we must now cause a new voting
        logger.info("doCheckView: current establishedViewId ({}) was declared as failed earlier already.", lastEstablishedViewId);
        establishedViewMatches = false;
    } else {
        if (establishedView == null) {
            establishedViewMatches = false;
        } else {
            String mismatchDetails;
            try {
                mismatchDetails = establishedView.matches(liveInstances);
            } catch (Exception e) {
                logger.error("doCheckViewWith: could not compare established view with live ones: " + e, e);
                invalidateCurrentEstablishedView();
                discoveryServiceImpl.handleTopologyChanging();
                return;
            }
            if (mismatchDetails != null) {
                logger.info("doCheckView: established view does not match. (details: " + mismatchDetails + ")");
            } else {
                logger.debug("doCheckView: established view matches with expected.");
            }
            establishedViewMatches = mismatchDetails == null;
        }
    }
    if (establishedViewMatches) {
        // that's the normal case. the established view matches what we're
        // seeing.
        // all happy and fine
        logger.debug("doCheckViewWith: no pending nor winning votes. view is fine. we're all happy.");
        return;
    }
    // immediately send a TOPOLOGY_CHANGING - could already be sent, but just to be sure
    logger.info("doCheckViewWith: no matching established view, marking topology as changing");
    invalidateCurrentEstablishedView();
    discoveryServiceImpl.handleTopologyChanging();
    List<VotingView> myYesVotes = VotingHelper.getYesVotingsOf(resourceResolver, config, slingId);
    if (myYesVotes != null && myYesVotes.size() > 0) {
        logger.info("doCheckViewWith: I have voted yes (" + myYesVotes.size() + "x)- the vote was not yet promoted but expecting it to be soon. Not voting again in the meantime. My yes vote was for: " + myYesVotes);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("doCheckViewWith: no pending nor winning votes. But: view does not match established or no established yet. Initiating a new voting");
        Iterator<String> it = liveInstances.iterator();
        while (it.hasNext()) {
            logger.debug("doCheckViewWith: one of the live instances is: " + it.next());
        }
    }
    // we seem to be the first to realize that the currently established
    // view doesnt match
    // the currently live instances.
    // initiate a new voting
    doStartNewVoting(resourceResolver, liveInstances);
}
Also used : Resource(org.apache.sling.api.resource.Resource) VotingView(org.apache.sling.discovery.impl.cluster.voting.VotingView) VotingView(org.apache.sling.discovery.impl.cluster.voting.VotingView) View(org.apache.sling.discovery.impl.common.View) PersistenceException(org.apache.sling.api.resource.PersistenceException) BundleException(org.osgi.framework.BundleException) LoginException(org.apache.sling.api.resource.LoginException)

Example 19 with PersistenceException

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

the class DiscoveryServiceImpl method doUpdateProperties.

/**
     * Update the properties by inquiring the PropertyProvider's current values.
     * <p>
     * This method is invoked regularly by the heartbeatHandler.
     * The properties are stored in the repository under Config.getClusterInstancesPath()
     * and announced in the topology.
     * <p>
     * @see Config#getClusterInstancesPath()
     */
private void doUpdateProperties() {
    if (resourceResolverFactory == null) {
        // cannot update the properties then..
        logger.debug("doUpdateProperties: too early to update the properties. resourceResolverFactory not yet set.");
        return;
    } else {
        logger.debug("doUpdateProperties: updating properties now..");
    }
    final Map<String, String> newProps = new HashMap<String, String>();
    for (final ProviderInfo info : this.providerInfos) {
        info.refreshProperties();
        newProps.putAll(info.properties);
    }
    ResourceResolver resourceResolver = null;
    try {
        resourceResolver = resourceResolverFactory.getServiceResourceResolver(null);
        Resource myInstance = ResourceHelper.getOrCreateResource(resourceResolver, config.getClusterInstancesPath() + "/" + slingId + "/properties");
        // SLING-2879 - revert/refresh resourceResolver here to work
        // around a potential issue with jackrabbit in a clustered environment
        resourceResolver.revert();
        resourceResolver.refresh();
        final ModifiableValueMap myInstanceMap = myInstance.adaptTo(ModifiableValueMap.class);
        final Set<String> keys = new HashSet<String>(myInstanceMap.keySet());
        for (final String key : keys) {
            if (newProps.containsKey(key)) {
                // perfect
                continue;
            } else if (key.indexOf(":") != -1) {
                // ignore
                continue;
            } else {
                // remove
                myInstanceMap.remove(key);
            }
        }
        boolean anyChanges = false;
        for (final Entry<String, String> entry : newProps.entrySet()) {
            Object existingValue = myInstanceMap.get(entry.getKey());
            if (entry.getValue().equals(existingValue)) {
                // SLING-3389: dont rewrite the properties if nothing changed!
                if (logger.isDebugEnabled()) {
                    logger.debug("doUpdateProperties: unchanged: {}={}", entry.getKey(), entry.getValue());
                }
                continue;
            }
            if (logger.isDebugEnabled()) {
                logger.debug("doUpdateProperties: changed: {}={}", entry.getKey(), entry.getValue());
            }
            anyChanges = true;
            myInstanceMap.put(entry.getKey(), entry.getValue());
        }
        if (anyChanges) {
            resourceResolver.commit();
        }
    } catch (LoginException e) {
        logger.error("handleEvent: could not log in administratively: " + e, e);
        throw new RuntimeException("Could not log in to repository (" + e + ")", e);
    } catch (PersistenceException e) {
        logger.error("handleEvent: got a PersistenceException: " + e, e);
        throw new RuntimeException("Exception while talking to repository (" + e + ")", e);
    } finally {
        if (resourceResolver != null) {
            resourceResolver.close();
        }
    }
    logger.debug("doUpdateProperties: updating properties done.");
}
Also used : HashMap(java.util.HashMap) Resource(org.apache.sling.api.resource.Resource) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) LoginException(org.apache.sling.api.resource.LoginException) HashSet(java.util.HashSet)

Example 20 with PersistenceException

use of org.apache.sling.api.resource.PersistenceException 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)

Aggregations

PersistenceException (org.apache.sling.api.resource.PersistenceException)146 Resource (org.apache.sling.api.resource.Resource)102 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)63 ModifiableValueMap (org.apache.sling.api.resource.ModifiableValueMap)37 HashMap (java.util.HashMap)35 LoginException (org.apache.sling.api.resource.LoginException)32 RepositoryException (javax.jcr.RepositoryException)27 ValueMap (org.apache.sling.api.resource.ValueMap)23 Node (javax.jcr.Node)18 Map (java.util.Map)15 Calendar (java.util.Calendar)14 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 InputStream (java.io.InputStream)6 ConfigurationPersistenceException (org.apache.sling.caconfig.spi.ConfigurationPersistenceException)6 InstanceDescription (org.apache.sling.discovery.InstanceDescription)6 QueueInfo (org.apache.sling.event.impl.jobs.config.QueueConfigurationManager.QueueInfo)6 Test (org.junit.Test)5 Session (javax.jcr.Session)4