joerghoh commented on code in PR #41:
URL: 
https://github.com/apache/sling-org-apache-sling-event/pull/41#discussion_r2037401014


##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -777,4 +805,39 @@ public Job retryJobById(final String jobId) {
     public JobSchedulerImpl getJobScheduler() {
         return this.jobScheduler;
     }
+
+    /**
+     * Check the health status of the system by executing health checks with 
the configured tag
+     */
+    private void checkHealthStatus() {
+        try {
+            // Execute health checks with the configured tag
+            List<HealthCheckExecutionResult> results = healthCheckExecutor != 
null
+                    ? 
healthCheckExecutor.execute(HealthCheckSelector.tags("sling"))
+                    : null;
+
+            if (results == null || results.isEmpty()) {
+                isHealthy = false;
+                logger.warn("No health check results available. Marking system 
as unhealthy.");
+                return;
+            }
+
+            // Consider the system healthy only if all health checks pass
+            isHealthy = results.stream()
+                    .filter(result -> result != null && 
result.getHealthCheckResult() != null)
+                    .allMatch(result -> 
result.getHealthCheckResult().getStatus() == Result.Status.OK);
+
+            if (!isHealthy) {
+                logger.warn("System health check failed. Results: {}",

Review Comment:
   I don't think that it makes sense to consistently log this if the system is 
either on startup/shutdown on WARN; I think that logging it on DEBUG is more 
appropriate.



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -777,4 +805,39 @@ public Job retryJobById(final String jobId) {
     public JobSchedulerImpl getJobScheduler() {
         return this.jobScheduler;
     }
+
+    /**
+     * Check the health status of the system by executing health checks with 
the configured tag
+     */
+    private void checkHealthStatus() {
+        try {
+            // Execute health checks with the configured tag
+            List<HealthCheckExecutionResult> results = healthCheckExecutor != 
null
+                    ? 
healthCheckExecutor.execute(HealthCheckSelector.tags("sling"))
+                    : null;
+
+            if (results == null || results.isEmpty()) {

Review Comment:
   The API doc of ``HealthcheckExecutor.execute()`` does not mention that 
``null`` can be returned (but only an empty list). So I would remove this check.
   
   ```suggestion
               if (results.isEmpty()) {
   ```



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -777,4 +805,39 @@ public Job retryJobById(final String jobId) {
     public JobSchedulerImpl getJobScheduler() {
         return this.jobScheduler;
     }
+
+    /**
+     * Check the health status of the system by executing health checks with 
the configured tag
+     */
+    private void checkHealthStatus() {
+        try {
+            // Execute health checks with the configured tag
+            List<HealthCheckExecutionResult> results = healthCheckExecutor != 
null
+                    ? 
healthCheckExecutor.execute(HealthCheckSelector.tags("sling"))

Review Comment:
   the tag which is used for querying the HealthCheckExecutor should not be 
hardcoded; it should be configurable via OSGI config.



##########
src/test/java/org/apache/sling/event/impl/jobs/HealthCheckFailureTest.java:
##########
@@ -0,0 +1,208 @@
+/*
+ * 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.event.impl.jobs;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.*;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.felix.hc.api.Result;
+import org.apache.felix.hc.api.execution.HealthCheckExecutionResult;
+import org.apache.felix.hc.api.execution.HealthCheckExecutor;
+import org.apache.felix.hc.api.execution.HealthCheckMetadata;
+import org.apache.felix.hc.api.execution.HealthCheckSelector;
+import org.apache.sling.api.resource.PersistenceException;
+import org.apache.sling.api.resource.Resource;
+import org.apache.sling.api.resource.ResourceResolver;
+import org.apache.sling.event.impl.jobs.config.InternalQueueConfiguration;
+import org.apache.sling.event.impl.jobs.config.JobManagerConfiguration;
+import org.apache.sling.event.impl.jobs.config.QueueConfigurationManager;
+import 
org.apache.sling.event.impl.jobs.config.QueueConfigurationManager.QueueInfo;
+import org.apache.sling.event.impl.jobs.config.TopologyCapabilities;
+import org.apache.sling.event.impl.support.ResourceHelper;
+import org.apache.sling.event.jobs.Job;
+import org.apache.sling.testing.mock.sling.junit.SlingContext;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.MockedStatic;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+import org.apache.sling.event.impl.EnvironmentComponent;
+import com.codahale.metrics.MetricRegistry;
+import org.slf4j.Logger;
+
+public class HealthCheckFailureTest {
+
+    @Rule
+    public final SlingContext context = new SlingContext();
+
+    private JobManagerImpl jobManager;
+    private JobManagerConfiguration configuration;
+    private HealthCheckExecutor healthCheckExecutor;
+    private MetricRegistry metricRegistry;
+    private QueueConfigurationManager queueConfigManager;
+    private TopologyCapabilities topologyCapabilities;
+    private ResourceResolver resourceResolver;
+
+    @Before
+    public void setUp() {
+        // Mock QueueConfigurationManager and QueueInfo
+        queueConfigManager = mock(QueueConfigurationManager.class);
+        QueueInfo queueInfo = new QueueInfo();
+        queueInfo.queueName = "test-queue";
+        
when(queueConfigManager.getQueueInfo(any(String.class))).thenReturn(queueInfo);
+        queueInfo.queueConfiguration = new InternalQueueConfiguration();
+
+        // Mock TopologyCapabilities
+        topologyCapabilities = mock(TopologyCapabilities.class);
+        when(topologyCapabilities.detectTarget(any(String.class), 
any(Map.class), any(QueueInfo.class))).thenReturn(null);
+
+        resourceResolver = mock(ResourceResolver.class);

Review Comment:
   If you already use a SlingContext, you can avoid mocking all these 
resource-level objects, and create resources using the SlingContext; see 
https://sling.apache.org/documentation/development/sling-mock.html



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -190,6 +200,12 @@ protected void deactivate() {
      */
     @Override
     public void run() {
+        // Check health status before running maintenance
+        checkHealthStatus();
+        if (!isHealthy) {
+            logger.warn("System is not healthy. Aborting operation.");

Review Comment:
   In my opinion this can be a totally normal situation (because the HCs do not 
return OK yet), and for that I don't think that a WARN message is warranted. 
Also I would rephrase the log message:
   
   ```suggestion
               logger.info("System is not healthy (yet). Skipping cleanup 
operation.");
   ```
   
   WDYT?



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -202,6 +218,12 @@ public void run() {
      */
     @Override
     public void handleEvent(final Event event) {
+        // Check health status before handling events
+        checkHealthStatus();
+        if (!isHealthy) {
+            logger.warn("System is not healthy. Aborting operation.");

Review Comment:
   see above



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -777,4 +805,39 @@ public Job retryJobById(final String jobId) {
     public JobSchedulerImpl getJobScheduler() {
         return this.jobScheduler;
     }
+
+    /**
+     * Check the health status of the system by executing health checks with 
the configured tag
+     */
+    private void checkHealthStatus() {

Review Comment:
   Instead of using the global variable ``isHealthy`` I would make this method 
return the status directly, as I see it consistently used in this pattern:
   
   ```
   checkHealthState();
   if (!isHealthy) {
   ...
   }
   ```
   
   This would also prevent race conditions (as the JobManager service can be 
used by many threads concurrently, and the ``isHealthy``variable is neither an 
atomic type nor marked as volatile).
   



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -130,13 +135,18 @@ public class JobManagerImpl
     @Reference
     private QueueManager qManager;
 
+    @Reference
+    private HealthCheckExecutor healthCheckExecutor;

Review Comment:
   This adds a hard dependency to the Felix HealthChecks; can we turn this into 
an optional dependency?



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -300,6 +322,12 @@ private boolean internalRemoveJobById(final String jobId, 
final boolean forceRem
      */
     @Override
     public Job addJob(String topic, Map<String, Object> properties) {
+        // Check health status before adding a job
+        checkHealthStatus();
+        if (!isHealthy) {
+            logger.warn("System is not healthy. Aborting operation.");

Review Comment:
   see above



##########
src/main/java/org/apache/sling/event/impl/jobs/JobManagerImpl.java:
##########
@@ -777,4 +805,39 @@ public Job retryJobById(final String jobId) {
     public JobSchedulerImpl getJobScheduler() {
         return this.jobScheduler;
     }
+
+    /**
+     * Check the health status of the system by executing health checks with 
the configured tag
+     */
+    private void checkHealthStatus() {
+        try {
+            // Execute health checks with the configured tag
+            List<HealthCheckExecutionResult> results = healthCheckExecutor != 
null
+                    ? 
healthCheckExecutor.execute(HealthCheckSelector.tags("sling"))
+                    : null;
+
+            if (results == null || results.isEmpty()) {
+                isHealthy = false;

Review Comment:
   Not sure if that's appropriate. That means you **have to** have at least one 
HC configured to have the JobManager working, and that would be a breaking 
change.
   
   I would rather mark the system as healthy, and log on DEBUG that no HC is 
configured.
   



-- 
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.

To unsubscribe, e-mail: dev-unsubscr...@sling.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to