You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by GitBox <gi...@apache.org> on 2019/12/18 12:49:20 UTC

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider opened a new pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

cschneider opened a new pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17
 
 
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360641068
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/CommandPoller.java
 ##########
 @@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static org.apache.sling.distribution.journal.HandlerAdapter.create;
+
+import java.io.Closeable;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.distribution.journal.MessageInfo;
+import org.apache.sling.distribution.journal.MessagingProvider;
+import org.apache.sling.distribution.journal.Reset;
+import org.apache.sling.distribution.journal.impl.shared.Topics;
+import org.apache.sling.distribution.journal.messages.Messages.CommandMessage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CommandPoller implements Closeable {
+    private static final Logger LOG = LoggerFactory.getLogger(DistributionSubscriber.class);
+
+    private final String subSlingId;
+    private final String subAgentName;
+    private final boolean editable;
+    private final Closeable commandPoller;
+    private final AtomicLong clearOffset = new AtomicLong(-1);
+
+    public CommandPoller(MessagingProvider messagingProvider, Topics topics, String subSlingId, String subAgentName, boolean editable) {
+        this.subSlingId = subSlingId;
+        // TODO Auto-generated constructor stub
 
 Review comment:
   Ok

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360592668
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
+        distributionMetricsService.getPackageDistributedDuration().update((currentTimeMillis() - createdTime), TimeUnit.MILLISECONDS);
+        packageRetries.clear(pkgMsg.getPubAgentName());
+
+        Event event = DistributionEvent.eventImporterImported(pkgMsg, subAgentName);
+        eventAdmin.postEvent(event);
+    }
+    
+    /**
+     * Should be called on a exception while importing a package.
+     * 
+     * When we use an error queue and the max retries is reached the package is removed.
+     * In all other cases a DistributionException is thrown that signals that we should retry the
+     * package.
+     * 
+     * @param pkgMsg
+     * @param offset
+     * @param e
+     * @throws DistributionException if the package should be retried
+     */
+    public void failure(PackageMessage pkgMsg, long offset, Exception e) throws DistributionException {
+        distributionMetricsService.getFailedPackageImports().mark();
+
+        String pubAgentName = pkgMsg.getPubAgentName();
+        int retries = packageRetries.get(pubAgentName);
+        if (errorQueueEnabled && retries >= maxRetries) {
+            log.warn(format("Failed to import distribution package %s at offset %s after %s retries, removing the package.", pkgMsg.getPkgId(), offset, retries));
+            removeFailedPackage(pkgMsg, offset);
+        } else {
+            packageRetries.increase(pubAgentName);
+            String msg = format("Error processing distribution package %s. Retry attempts %s/%s.", pkgMsg.getPkgId(), retries, errorQueueEnabled ? Integer.toString(maxRetries) : "infinite");
+            throw new DistributionException(msg, e);
+        }
+    }
+
+    public void removePackage(PackageMessage pkgMsg, long offset) throws Exception {
+        log.info(format("Removing distribution package %s of type %s at offset %s", pkgMsg.getPkgId(), pkgMsg.getReqType(), offset));
+        Timer.Context context = distributionMetricsService.getRemovedPackageDuration().time();
+        try (ResourceResolver resolver = getServiceResolver()) {
+            if (editable) {
+                store(resolver, new PackageStatus(REMOVED, offset, pkgMsg.getPubAgentName()));
+            }
+            storeOffset(resolver, offset);
+            resolver.commit();
+        }
+        context.stop();
+    }
+
+    public void sendStoredStatus() throws InterruptedException, IOException {
 
 Review comment:
   I think that the previous `sendStoredStatus` implementation and flow was cleaner and clearer. Would you be ok getting that part back ?

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360594954
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/CommandPoller.java
 ##########
 @@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static org.apache.sling.distribution.journal.HandlerAdapter.create;
+
+import java.io.Closeable;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.distribution.journal.MessageInfo;
+import org.apache.sling.distribution.journal.MessagingProvider;
+import org.apache.sling.distribution.journal.Reset;
+import org.apache.sling.distribution.journal.impl.shared.Topics;
+import org.apache.sling.distribution.journal.messages.Messages.CommandMessage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class CommandPoller implements Closeable {
+    private static final Logger LOG = LoggerFactory.getLogger(DistributionSubscriber.class);
+
+    private final String subSlingId;
+    private final String subAgentName;
+    private final boolean editable;
+    private final Closeable commandPoller;
+    private final AtomicLong clearOffset = new AtomicLong(-1);
+
+    public CommandPoller(MessagingProvider messagingProvider, Topics topics, String subSlingId, String subAgentName, boolean editable) {
+        this.subSlingId = subSlingId;
+        // TODO Auto-generated constructor stub
 
 Review comment:
   The TODO seems resolved

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360588686
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
+        distributionMetricsService.getPackageDistributedDuration().update((currentTimeMillis() - createdTime), TimeUnit.MILLISECONDS);
+        packageRetries.clear(pkgMsg.getPubAgentName());
+
+        Event event = DistributionEvent.eventImporterImported(pkgMsg, subAgentName);
 
 Review comment:
   This is a change of logic which introduces a bug. The event must be sent when the commit succeeded but with this PR the imported event is sent even if the commit is rejected.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider merged pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider merged pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17
 
 
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360641578
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
+        distributionMetricsService.getPackageDistributedDuration().update((currentTimeMillis() - createdTime), TimeUnit.MILLISECONDS);
+        packageRetries.clear(pkgMsg.getPubAgentName());
+
+        Event event = DistributionEvent.eventImporterImported(pkgMsg, subAgentName);
+        eventAdmin.postEvent(event);
+    }
+    
+    /**
+     * Should be called on a exception while importing a package.
+     * 
+     * When we use an error queue and the max retries is reached the package is removed.
+     * In all other cases a DistributionException is thrown that signals that we should retry the
+     * package.
+     * 
+     * @param pkgMsg
+     * @param offset
+     * @param e
+     * @throws DistributionException if the package should be retried
+     */
+    public void failure(PackageMessage pkgMsg, long offset, Exception e) throws DistributionException {
+        distributionMetricsService.getFailedPackageImports().mark();
+
+        String pubAgentName = pkgMsg.getPubAgentName();
+        int retries = packageRetries.get(pubAgentName);
+        if (errorQueueEnabled && retries >= maxRetries) {
+            log.warn(format("Failed to import distribution package %s at offset %s after %s retries, removing the package.", pkgMsg.getPkgId(), offset, retries));
+            removeFailedPackage(pkgMsg, offset);
+        } else {
+            packageRetries.increase(pubAgentName);
+            String msg = format("Error processing distribution package %s. Retry attempts %s/%s.", pkgMsg.getPkgId(), retries, errorQueueEnabled ? Integer.toString(maxRetries) : "infinite");
+            throw new DistributionException(msg, e);
+        }
+    }
+
+    public void removePackage(PackageMessage pkgMsg, long offset) throws Exception {
+        log.info(format("Removing distribution package %s of type %s at offset %s", pkgMsg.getPkgId(), pkgMsg.getReqType(), offset));
+        Timer.Context context = distributionMetricsService.getRemovedPackageDuration().time();
+        try (ResourceResolver resolver = getServiceResolver()) {
+            if (editable) {
+                store(resolver, new PackageStatus(REMOVED, offset, pkgMsg.getPubAgentName()));
+            }
+            storeOffset(resolver, offset);
+            resolver.commit();
+        }
+        context.stop();
+    }
+
+    public void sendStoredStatus() throws InterruptedException, IOException {
 
 Review comment:
   I agree.. I will use the old logic.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360641113
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/DistributionSubscriber.java
 ##########
 @@ -405,61 +302,61 @@ private DistributionResponse executeUnsupported(DistributionRequest request) {
     }
 
     private void handlePackageMessage(MessageInfo info, PackageMessage message) {
-        if (! queueNames.contains(message.getPubAgentName())) {
+        if (!queueNames.contains(message.getPubAgentName())) {
             LOG.info(String.format("Skipping package for Publisher agent %s (not subscribed)", message.getPubAgentName()));
             return;
         }
-        if (! pkgType.equals(message.getPkgType())) {
+        if (!pkgType.equals(message.getPkgType())) {
             LOG.warn(String.format("Skipping package with type %s", message.getPkgType()));
             return;
         }
         DistributionQueueItem queueItem = QueueItemFactory.fromPackage(info, message, true);
-        try {
-            enqueue(queueItem);
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new RuntimeException();
-        }
+        enqueue(queueItem);
     }
 
     /**
-     * We block here if the buffer is full in order to limit the number of
-	 * binary packages fetched in memory. Note that each queued item contains
-	 * the binary package to be imported.
+     * We block here if the buffer is full in order to limit the number of binary
+     * packages fetched in memory. Note that each queued item contains the binary
+     * package to be imported.
      */
-	private void enqueue(DistributionQueueItem queueItem) throws InterruptedException {
-        while (running) {
-            if (queueItemsBuffer.offer(queueItem, 1000, TimeUnit.MILLISECONDS)) {
-                distributionMetricsService.getItemsBufferSize().increment();
-                return;
+    private void enqueue(DistributionQueueItem queueItem) {
+        try {
+            while (running) {
+                if (queueItemsBuffer.offer(queueItem, 1000, TimeUnit.MILLISECONDS)) {
+                    distributionMetricsService.getItemsBufferSize().increment();
+                    return;
+                }
             }
+            throw new InterruptedException();
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new RuntimeException();
         }
-        throw new InterruptedException();
-	}
+    }
 
     private void processQueue() {
         LOG.info("Started Queue processor");
-        while (! Thread.interrupted()) {
+        while (!Thread.interrupted()) {
             try {
-                processQueueItems();
+                fetchAndProcessQueueItem();
             } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
             }
         }
         LOG.info("Stopped Queue processor");
     }
 
-    private void processQueueItems() throws InterruptedException {
+    private void fetchAndProcessQueueItem() throws InterruptedException {
         try {
             // send status stored in a previous run if exists
-            try (Timer.Context context = distributionMetricsService.getSendStoredStatusDuration().time()) {
-                sendStoredStatus();
-            }
+            bookKeeper.sendStoredStatus();
             // block until an item is available
             DistributionQueueItem item = blockingPeekQueueItem();
             // and then process it
             try (Timer.Context context = distributionMetricsService.getProcessQueueItemDuration().time()) {
                 processQueueItem(item);
+                queueItemsBuffer.remove();
 
 Review comment:
   Done in next commit.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360639491
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
+        distributionMetricsService.getPackageDistributedDuration().update((currentTimeMillis() - createdTime), TimeUnit.MILLISECONDS);
+        packageRetries.clear(pkgMsg.getPubAgentName());
+
+        Event event = DistributionEvent.eventImporterImported(pkgMsg, subAgentName);
 
 Review comment:
   Makes sense. I did not take into account that a commit might fail.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360640222
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/DistributionSubscriber.java
 ##########
 @@ -405,61 +302,61 @@ private DistributionResponse executeUnsupported(DistributionRequest request) {
     }
 
     private void handlePackageMessage(MessageInfo info, PackageMessage message) {
-        if (! queueNames.contains(message.getPubAgentName())) {
+        if (!queueNames.contains(message.getPubAgentName())) {
             LOG.info(String.format("Skipping package for Publisher agent %s (not subscribed)", message.getPubAgentName()));
             return;
         }
-        if (! pkgType.equals(message.getPkgType())) {
+        if (!pkgType.equals(message.getPkgType())) {
             LOG.warn(String.format("Skipping package with type %s", message.getPkgType()));
             return;
         }
         DistributionQueueItem queueItem = QueueItemFactory.fromPackage(info, message, true);
-        try {
-            enqueue(queueItem);
-        } catch (InterruptedException e) {
-            Thread.currentThread().interrupt();
-            throw new RuntimeException();
-        }
+        enqueue(queueItem);
     }
 
     /**
-     * We block here if the buffer is full in order to limit the number of
-	 * binary packages fetched in memory. Note that each queued item contains
-	 * the binary package to be imported.
+     * We block here if the buffer is full in order to limit the number of binary
+     * packages fetched in memory. Note that each queued item contains the binary
+     * package to be imported.
      */
-	private void enqueue(DistributionQueueItem queueItem) throws InterruptedException {
-        while (running) {
-            if (queueItemsBuffer.offer(queueItem, 1000, TimeUnit.MILLISECONDS)) {
-                distributionMetricsService.getItemsBufferSize().increment();
-                return;
+    private void enqueue(DistributionQueueItem queueItem) {
+        try {
+            while (running) {
+                if (queueItemsBuffer.offer(queueItem, 1000, TimeUnit.MILLISECONDS)) {
+                    distributionMetricsService.getItemsBufferSize().increment();
+                    return;
+                }
             }
+            throw new InterruptedException();
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+            throw new RuntimeException();
         }
-        throw new InterruptedException();
-	}
+    }
 
     private void processQueue() {
         LOG.info("Started Queue processor");
-        while (! Thread.interrupted()) {
+        while (!Thread.interrupted()) {
             try {
-                processQueueItems();
+                fetchAndProcessQueueItem();
             } catch (InterruptedException e) {
                 Thread.currentThread().interrupt();
             }
         }
         LOG.info("Stopped Queue processor");
     }
 
-    private void processQueueItems() throws InterruptedException {
+    private void fetchAndProcessQueueItem() throws InterruptedException {
         try {
             // send status stored in a previous run if exists
-            try (Timer.Context context = distributionMetricsService.getSendStoredStatusDuration().time()) {
-                sendStoredStatus();
-            }
+            bookKeeper.sendStoredStatus();
             // block until an item is available
             DistributionQueueItem item = blockingPeekQueueItem();
             // and then process it
             try (Timer.Context context = distributionMetricsService.getProcessQueueItemDuration().time()) {
                 processQueueItem(item);
+                queueItemsBuffer.remove();
 
 Review comment:
   I introduced an error here. We should only remove the item and change the metrics in case of no IllegalStateException. I will fix this

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on issue #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on issue #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#issuecomment-568407623
 
 
   I fixed the issues @tmaret found in the review. To minimize the interactions with BookKeeper I moved the whole retry and metrics logic there. I also found and fixed an additional issue introduced during the initial commit.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] tmaret commented on issue #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
tmaret commented on issue #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#issuecomment-568467480
 
 
   I don't have time to do a throughout review again, but the changes LGTM. 
   
   It makes much more sense to keep the three repository write ops and single commit at the same place rather than spreading this logic all over the place.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360640065
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
+        distributionMetricsService.getPackageDistributedDuration().update((currentTimeMillis() - createdTime), TimeUnit.MILLISECONDS);
+        packageRetries.clear(pkgMsg.getPubAgentName());
+
+        Event event = DistributionEvent.eventImporterImported(pkgMsg, subAgentName);
+        eventAdmin.postEvent(event);
+    }
+    
+    /**
+     * Should be called on a exception while importing a package.
+     * 
+     * When we use an error queue and the max retries is reached the package is removed.
+     * In all other cases a DistributionException is thrown that signals that we should retry the
+     * package.
+     * 
+     * @param pkgMsg
+     * @param offset
+     * @param e
+     * @throws DistributionException if the package should be retried
+     */
+    public void failure(PackageMessage pkgMsg, long offset, Exception e) throws DistributionException {
+        distributionMetricsService.getFailedPackageImports().mark();
+
+        String pubAgentName = pkgMsg.getPubAgentName();
+        int retries = packageRetries.get(pubAgentName);
+        if (errorQueueEnabled && retries >= maxRetries) {
+            log.warn(format("Failed to import distribution package %s at offset %s after %s retries, removing the package.", pkgMsg.getPkgId(), offset, retries));
+            removeFailedPackage(pkgMsg, offset);
+        } else {
+            packageRetries.increase(pubAgentName);
+            String msg = format("Error processing distribution package %s. Retry attempts %s/%s.", pkgMsg.getPkgId(), retries, errorQueueEnabled ? Integer.toString(maxRetries) : "infinite");
+            throw new DistributionException(msg, e);
+        }
+    }
+
+    public void removePackage(PackageMessage pkgMsg, long offset) throws Exception {
+        log.info(format("Removing distribution package %s of type %s at offset %s", pkgMsg.getPkgId(), pkgMsg.getReqType(), offset));
+        Timer.Context context = distributionMetricsService.getRemovedPackageDuration().time();
+        try (ResourceResolver resolver = getServiceResolver()) {
+            if (editable) {
+                store(resolver, new PackageStatus(REMOVED, offset, pkgMsg.getPubAgentName()));
+            }
+            storeOffset(resolver, offset);
+            resolver.commit();
+        }
+        context.stop();
+    }
+
+    public void sendStoredStatus() throws InterruptedException, IOException {
+        try (Timer.Context context = distributionMetricsService.getSendStoredStatusDuration().time()) {
+            PackageStatus status = new PackageStatus(statusStore.load());
+            boolean sent = status.sent;
+            for (int retry = 0; !sent; retry++) {
+                sent = trySendStoredStatus(status, retry);
+            }
+        }
+    }
+
+    private boolean trySendStoredStatus(PackageStatus status, int retry) throws InterruptedException {
+        try {
+            PackageStatusMessage pkgStatMsg = PackageStatusMessage.newBuilder().setSubSlingId(subSlingId)
+                    .setSubAgentName(subAgentName).setPubAgentName(status.pubAgentName).setOffset(status.offset)
+                    .setStatus(status.status).build();
+            sender.accept(pkgStatMsg);
+            markStatusSent();
+            log.info("Sent status message {}", status);
+            return true;
+        } catch (Exception e) {
+            log.warn("Cannot send status (retry {})", retry, e);
+            Thread.sleep(RETRY_SEND_DELAY);
+            return false;
+        }
+    }
+
+    public void markStatusSent() {
+        try (ResourceResolver resolver = getServiceResolver()) {
+            statusStore.store(resolver, "sent", true);
+            resolver.commit();
+        } catch (Exception e) {
+            log.warn("Failed to mark status as sent", e);
+        }
+    }
+    
+    public long loadOffset() {
+        return  processedOffsets.load("offset", -1L);
+    }
+
+    public int getRetries(String pubAgentName) {
+        return packageRetries.get(pubAgentName);
+    }
+
+    public PackageRetries getPackageRetries() {
+        return packageRetries;
+    }
+
+    @Override
+    public void close() throws IOException {
+        IOUtils.closeQuietly(retriesGauge);
+    }
+    
+    private void removeFailedPackage(PackageMessage pkgMsg, long offset) throws DistributionException {
+        log.info(format("Removing failed distribution package %s of type %s at offset %s", pkgMsg.getPkgId(), pkgMsg.getReqType(), offset));
+        Timer.Context context = distributionMetricsService.getRemovedFailedPackageDuration().time();
+        try (ResourceResolver resolver = getServiceResolver()) {
+            store(resolver, new PackageStatus(REMOVED_FAILED, offset, pkgMsg.getPubAgentName()));
+            storeOffset(resolver, offset);
+            resolver.commit();
+        } catch (Exception e) {
+            throw new DistributionException("Error removing failed package", e);
+        }
+        context.stop();
+    }
+
+    private void store(ResourceResolver resolver, PackageStatus packageStatus) throws PersistenceException {
 
 Review comment:
   Make sense

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360589594
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
+        distributionMetricsService.getPackageDistributedDuration().update((currentTimeMillis() - createdTime), TimeUnit.MILLISECONDS);
+        packageRetries.clear(pkgMsg.getPubAgentName());
+
+        Event event = DistributionEvent.eventImporterImported(pkgMsg, subAgentName);
+        eventAdmin.postEvent(event);
+    }
+    
+    /**
+     * Should be called on a exception while importing a package.
+     * 
+     * When we use an error queue and the max retries is reached the package is removed.
+     * In all other cases a DistributionException is thrown that signals that we should retry the
+     * package.
+     * 
+     * @param pkgMsg
+     * @param offset
+     * @param e
+     * @throws DistributionException if the package should be retried
+     */
+    public void failure(PackageMessage pkgMsg, long offset, Exception e) throws DistributionException {
+        distributionMetricsService.getFailedPackageImports().mark();
+
+        String pubAgentName = pkgMsg.getPubAgentName();
+        int retries = packageRetries.get(pubAgentName);
+        if (errorQueueEnabled && retries >= maxRetries) {
+            log.warn(format("Failed to import distribution package %s at offset %s after %s retries, removing the package.", pkgMsg.getPkgId(), offset, retries));
+            removeFailedPackage(pkgMsg, offset);
+        } else {
+            packageRetries.increase(pubAgentName);
+            String msg = format("Error processing distribution package %s. Retry attempts %s/%s.", pkgMsg.getPkgId(), retries, errorQueueEnabled ? Integer.toString(maxRetries) : "infinite");
+            throw new DistributionException(msg, e);
+        }
+    }
+
+    public void removePackage(PackageMessage pkgMsg, long offset) throws Exception {
+        log.info(format("Removing distribution package %s of type %s at offset %s", pkgMsg.getPkgId(), pkgMsg.getReqType(), offset));
+        Timer.Context context = distributionMetricsService.getRemovedPackageDuration().time();
+        try (ResourceResolver resolver = getServiceResolver()) {
+            if (editable) {
+                store(resolver, new PackageStatus(REMOVED, offset, pkgMsg.getPubAgentName()));
+            }
+            storeOffset(resolver, offset);
+            resolver.commit();
+        }
+        context.stop();
+    }
+
+    public void sendStoredStatus() throws InterruptedException, IOException {
+        try (Timer.Context context = distributionMetricsService.getSendStoredStatusDuration().time()) {
+            PackageStatus status = new PackageStatus(statusStore.load());
+            boolean sent = status.sent;
+            for (int retry = 0; !sent; retry++) {
+                sent = trySendStoredStatus(status, retry);
+            }
+        }
+    }
+
+    private boolean trySendStoredStatus(PackageStatus status, int retry) throws InterruptedException {
+        try {
+            PackageStatusMessage pkgStatMsg = PackageStatusMessage.newBuilder().setSubSlingId(subSlingId)
+                    .setSubAgentName(subAgentName).setPubAgentName(status.pubAgentName).setOffset(status.offset)
+                    .setStatus(status.status).build();
+            sender.accept(pkgStatMsg);
+            markStatusSent();
+            log.info("Sent status message {}", status);
+            return true;
+        } catch (Exception e) {
+            log.warn("Cannot send status (retry {})", retry, e);
+            Thread.sleep(RETRY_SEND_DELAY);
+            return false;
+        }
+    }
+
+    public void markStatusSent() {
+        try (ResourceResolver resolver = getServiceResolver()) {
+            statusStore.store(resolver, "sent", true);
+            resolver.commit();
+        } catch (Exception e) {
+            log.warn("Failed to mark status as sent", e);
+        }
+    }
+    
+    public long loadOffset() {
+        return  processedOffsets.load("offset", -1L);
+    }
+
+    public int getRetries(String pubAgentName) {
+        return packageRetries.get(pubAgentName);
+    }
+
+    public PackageRetries getPackageRetries() {
+        return packageRetries;
+    }
+
+    @Override
+    public void close() throws IOException {
+        IOUtils.closeQuietly(retriesGauge);
+    }
+    
+    private void removeFailedPackage(PackageMessage pkgMsg, long offset) throws DistributionException {
+        log.info(format("Removing failed distribution package %s of type %s at offset %s", pkgMsg.getPkgId(), pkgMsg.getReqType(), offset));
+        Timer.Context context = distributionMetricsService.getRemovedFailedPackageDuration().time();
+        try (ResourceResolver resolver = getServiceResolver()) {
+            store(resolver, new PackageStatus(REMOVED_FAILED, offset, pkgMsg.getPubAgentName()));
+            storeOffset(resolver, offset);
+            resolver.commit();
+        } catch (Exception e) {
+            throw new DistributionException("Error removing failed package", e);
+        }
+        context.stop();
+    }
+
+    private void store(ResourceResolver resolver, PackageStatus packageStatus) throws PersistenceException {
 
 Review comment:
   I think we should keep `storeStatus` because it effectively stores the status. Suggest to s/store/storeStatus back.
   

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
tmaret commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360589124
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
 
 Review comment:
   same issue here, the metrics must be updated after the commit.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services

[GitHub] [sling-org-apache-sling-distribution-journal] cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities

Posted by GitBox <gi...@apache.org>.
cschneider commented on a change in pull request #17: SLING-8932 - Redesign DistributionSubscriber to offload responsibilities
URL: https://github.com/apache/sling-org-apache-sling-distribution-journal/pull/17#discussion_r360640067
 
 

 ##########
 File path: src/main/java/org/apache/sling/distribution/journal/impl/subscriber/BookKeeper.java
 ##########
 @@ -0,0 +1,300 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sling.distribution.journal.impl.subscriber;
+
+import static java.lang.String.format;
+import static java.lang.System.currentTimeMillis;
+import static java.util.Collections.singletonMap;
+import static org.apache.sling.api.resource.ResourceResolverFactory.SUBSERVICE;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.IMPORTED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED;
+import static org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status.REMOVED_FAILED;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import java.util.stream.Collectors;
+
+import org.apache.commons.io.IOUtils;
+import org.apache.sling.api.resource.LoginException;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.api.resource.ResourceResolverFactory;
+import org.apache.sling.api.resource.ValueMap;
+import org.apache.sling.commons.metrics.Timer;
+import org.apache.sling.distribution.common.DistributionException;
+import org.apache.sling.distribution.journal.impl.event.DistributionEvent;
+import org.apache.sling.distribution.journal.impl.queue.impl.PackageRetries;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService;
+import org.apache.sling.distribution.journal.impl.shared.DistributionMetricsService.GaugeService;
+import org.apache.sling.distribution.journal.messages.Messages.PackageMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage;
+import org.apache.sling.distribution.journal.messages.Messages.PackageStatusMessage.Status;
+import org.osgi.service.event.Event;
+import org.osgi.service.event.EventAdmin;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Keeps track of offset and processed status
+ * 
+ * The offset store is identified by the agentName only.
+ *
+ * With non clustered publish instances deployment, each
+ * instance stores the offset in its own node store, thus
+ * avoiding mix ups. Moreover, when cloning an instance
+ * from a node store, the cloned instance will implicitly
+ * recover the offsets and start from the last processed
+ * offset.
+ *
+ * With clustered publish instances deployment, only one
+ * Subscriber agent must run on the cluster in order to
+ * avoid mix ups.
+ *
+ * The clustered and non clustered publish instances use
+ * cases can be supported by only running the Subscriber
+ * agent on the leader instance.
+ */
+public class BookKeeper implements Closeable {
+    private static final String SUBSERVICE_BOOKKEEPER = "bookkeeper";
+    private static final int RETRY_SEND_DELAY = 1000;
+
+    private final Logger log = LoggerFactory.getLogger(this.getClass());
+    private final ResourceResolverFactory resolverFactory;
+    private final DistributionMetricsService distributionMetricsService;
+    private final EventAdmin eventAdmin;
+    private final Consumer<PackageStatusMessage> sender;
+    private final boolean editable;
+    private final int maxRetries;
+    private final boolean errorQueueEnabled;
+
+    private final PackageRetries packageRetries = new PackageRetries();
+    private final LocalStore statusStore;
+    private final LocalStore processedOffsets;
+    private final String subAgentName;
+    private final String subSlingId;
+    private GaugeService<Integer> retriesGauge;
+
+    public BookKeeper(ResourceResolverFactory resolverFactory, 
+            DistributionMetricsService distributionMetricsService,
+            EventAdmin eventAdmin,
+            Consumer<PackageStatusMessage> sender,
+            String subAgentName,
+            String subSlingId,
+            boolean editable, 
+            int maxRetries) { 
+        this.eventAdmin = eventAdmin;
+        String nameRetries = DistributionMetricsService.SUB_COMPONENT + ".current_retries;sub_name=" + subAgentName;
+        this.retriesGauge = distributionMetricsService.createGauge(nameRetries, "Retries of current package", packageRetries::getSum);
+        this.resolverFactory = resolverFactory;
+        this.distributionMetricsService = distributionMetricsService;
+        this.sender = sender;
+        this.subAgentName = subAgentName;
+        this.subSlingId = subSlingId;
+        this.editable = editable;
+        this.maxRetries = maxRetries;
+        // Error queues are enabled when the number
+        // of retry attempts is limited ; disabled otherwise
+        this.errorQueueEnabled = (maxRetries >= 0);
+        this.statusStore = new LocalStore(resolverFactory, "statuses", subAgentName);
+        this.processedOffsets = new LocalStore(resolverFactory, "packages", subAgentName);
+    }
+    
+    public void addPackageMDC(PackageMessage pkgMsg) {
+        MDC.put("module", "distribution");
+        MDC.put("package-id", pkgMsg.getPkgId());
+        String paths = pkgMsg.getPathsList().stream().collect(Collectors.joining(","));
+        MDC.put("paths", paths);
+        MDC.put("pub-sling-id", pkgMsg.getPubSlingId());
+        String pubAgentName = pkgMsg.getPubAgentName();
+        MDC.put("pub-agent-name", pubAgentName);
+        MDC.put("distribution-message-type", pkgMsg.getReqType().name());
+        MDC.put("retries", Integer.toString(packageRetries.get(pubAgentName)));
+        MDC.put("sub-sling-id", subSlingId);
+        MDC.put("sub-agent-name", subAgentName);
+    }
+    
+    public void imported(ResourceResolver importerResolver, PackageMessage pkgMsg, long offset, long createdTime)
+            throws PersistenceException {
+        if (editable) {
+            store(importerResolver, new PackageStatus(IMPORTED, offset, pkgMsg.getPubAgentName()));
+        }
+        storeOffset(importerResolver, offset);
+        distributionMetricsService.getImportedPackageSize().update(pkgMsg.getPkgLength());
 
 Review comment:
   Ok .. will change it.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
users@infra.apache.org


With regards,
Apache Git Services