Add metric about failure/success count of forwarding request Change-Id: I17f74f385b4d2ad64a9d75f16e76bd6a2687ab31
diff --git a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderMetrics.java b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderMetrics.java new file mode 100644 index 0000000..7abfad8 --- /dev/null +++ b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderMetrics.java
@@ -0,0 +1,56 @@ +// Copyright (C) 2025 The Android Open Source Project +// +// Licensed 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 com.ericsson.gerrit.plugins.highavailability.forwarder; + +import com.google.gerrit.metrics.Counter0; +import com.google.gerrit.metrics.Description; +import com.google.gerrit.metrics.MetricMaker; +import com.google.inject.assistedinject.Assisted; +import com.google.inject.assistedinject.AssistedInject; +import java.util.Locale; + +public class ForwarderMetrics { + private final Counter0 failureCounterMetric; + private final Counter0 successCounterMetric; + + public interface Factory { + ForwarderMetrics create(EventType eventType); + } + + @AssistedInject + public ForwarderMetrics(MetricMaker metricMaker, @Assisted EventType eventType) { + String event = eventType.toString().toLowerCase(Locale.US); + this.failureCounterMetric = + metricMaker.newCounter( + String.format("forwarding_%s_event/failure", event), + new Description(String.format("%s events forwarding failures count", event)) + .setCumulative() + .setRate()); + this.successCounterMetric = + metricMaker.newCounter( + String.format("forwarding_%s_event/success", event), + new Description(String.format("%s events forwarding success count", event)) + .setCumulative() + .setRate()); + } + + public void recordResult(boolean isSuccessful) { + if (isSuccessful) { + successCounterMetric.increment(); + } else { + failureCounterMetric.increment(); + } + } +}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderMetricsRegistry.java b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderMetricsRegistry.java new file mode 100644 index 0000000..7a8da41 --- /dev/null +++ b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderMetricsRegistry.java
@@ -0,0 +1,48 @@ +// Copyright (C) 2025 The Android Open Source Project +// +// Licensed 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 com.ericsson.gerrit.plugins.highavailability.forwarder; + +import com.google.inject.Inject; +import com.google.inject.Singleton; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; + +@Singleton +public class ForwarderMetricsRegistry { + + private final ForwarderMetrics.Factory metricsFactory; + + private Map<EventType, ForwarderMetrics> metrics = new HashMap<>(); + + @Inject + public ForwarderMetricsRegistry(ForwarderMetrics.Factory metricsFactory) { + this.metricsFactory = metricsFactory; + } + + public ForwarderMetrics get(EventType eventType) { + return metrics.get(eventType); + } + + public void put(EventType task) { + metrics.put(task, metricsFactory.create(task)); + } + + public void putAll(Collection<EventType> eventTypes) { + for (EventType eventType : eventTypes) { + put(eventType); + } + } +}
diff --git a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderModule.java b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderModule.java index 7cb107c..acd5a1b 100644 --- a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderModule.java +++ b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/ForwarderModule.java
@@ -15,18 +15,18 @@ package com.ericsson.gerrit.plugins.highavailability.forwarder; import com.ericsson.gerrit.plugins.highavailability.ConfigurableAllowedEventListeners; +import com.google.gerrit.extensions.config.FactoryModule; import com.google.gerrit.extensions.registration.DynamicItem; import com.google.gerrit.server.events.EventDispatcher; -import com.google.inject.AbstractModule; import com.google.inject.Scopes; -public class ForwarderModule extends AbstractModule { - +public class ForwarderModule extends FactoryModule { @Override protected void configure() { bind(AllowedForwardedEventListener.class) .to(ConfigurableAllowedEventListeners.class) .in(Scopes.SINGLETON); DynamicItem.bind(binder(), EventDispatcher.class).to(ForwardedAwareEventBroker.class); + factory(ForwarderMetrics.Factory.class); } }
diff --git a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarder.java b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarder.java index 11b03c4..c1b169f 100644 --- a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarder.java +++ b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarder.java
@@ -16,7 +16,9 @@ import com.ericsson.gerrit.plugins.highavailability.Configuration; import com.ericsson.gerrit.plugins.highavailability.Configuration.JGroups; +import com.ericsson.gerrit.plugins.highavailability.forwarder.EventType; import com.ericsson.gerrit.plugins.highavailability.forwarder.Forwarder; +import com.ericsson.gerrit.plugins.highavailability.forwarder.ForwarderMetricsRegistry; import com.ericsson.gerrit.plugins.highavailability.forwarder.IndexEvent; import com.google.common.flogger.FluentLogger; import com.google.gerrit.entities.Project; @@ -25,6 +27,7 @@ import com.google.inject.Inject; import com.google.inject.Singleton; import dev.failsafe.FailsafeExecutor; +import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.CompletableFuture; @@ -44,17 +47,22 @@ private final JGroups jgroupsConfig; private final Gson gson; private final FailsafeExecutor<Boolean> executor; + private final ForwarderMetricsRegistry metricsRegistry; @Inject JGroupsForwarder( MessageDispatcher dispatcher, Configuration cfg, @JGroupsGson Gson gson, - @JGroupsForwarderExecutor FailsafeExecutor<Boolean> executor) { + @JGroupsForwarderExecutor FailsafeExecutor<Boolean> executor, + ForwarderMetricsRegistry metricsRegistry) { this.dispatcher = dispatcher; this.jgroupsConfig = cfg.jgroups(); this.gson = gson; this.executor = executor; + + this.metricsRegistry = metricsRegistry; + this.metricsRegistry.putAll(Arrays.asList(EventType.values())); } @Override @@ -115,7 +123,13 @@ } private CompletableFuture<Boolean> execute(Command cmd) { - return executor.getAsync(() -> executeOnce(cmd)); + return executor + .getAsync(() -> executeOnce(cmd)) + .thenApplyAsync( + result -> { + metricsRegistry.get(cmd.type).recordResult(result); + return result; + }); } private boolean executeOnce(Command cmd) {
diff --git a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarder.java b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarder.java index d53cd82..21fad14 100644 --- a/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarder.java +++ b/src/main/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarder.java
@@ -16,7 +16,9 @@ import com.ericsson.gerrit.plugins.highavailability.Configuration; import com.ericsson.gerrit.plugins.highavailability.cache.Constants; +import com.ericsson.gerrit.plugins.highavailability.forwarder.EventType; import com.ericsson.gerrit.plugins.highavailability.forwarder.Forwarder; +import com.ericsson.gerrit.plugins.highavailability.forwarder.ForwarderMetricsRegistry; import com.ericsson.gerrit.plugins.highavailability.forwarder.IndexEvent; import com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpResponseHandler.HttpResult; import com.ericsson.gerrit.plugins.highavailability.peers.PeerInfo; @@ -33,6 +35,7 @@ import com.google.inject.Provider; import dev.failsafe.FailsafeExecutor; import java.io.IOException; +import java.util.Arrays; import java.util.Set; import java.util.concurrent.CompletableFuture; import javax.net.ssl.SSLException; @@ -55,6 +58,7 @@ private final Provider<Set<PeerInfo>> peerInfoProvider; private final Gson gson; private FailsafeExecutor<Boolean> executor; + private final ForwarderMetricsRegistry metricsRegistry; @Inject RestForwarder( @@ -63,18 +67,27 @@ Configuration cfg, Provider<Set<PeerInfo>> peerInfoProvider, @EventGson Gson gson, - @RestForwarderExecutor FailsafeExecutor<Boolean> executor) { + @RestForwarderExecutor FailsafeExecutor<Boolean> executor, + ForwarderMetricsRegistry metricsRegistry) { this.httpSession = httpClient; this.pluginRelativePath = Joiner.on("/").join("plugins", pluginName); this.cfg = cfg; this.peerInfoProvider = peerInfoProvider; this.gson = gson; this.executor = executor; + this.metricsRegistry = metricsRegistry; + this.metricsRegistry.putAll(Arrays.asList(EventType.values())); } @Override public CompletableFuture<Boolean> indexAccount(final int accountId, IndexEvent event) { - return execute(RequestMethod.POST, "index account", "index/account", accountId, event); + return execute( + RequestMethod.POST, + EventType.INDEX_ACCOUNT_UPDATE, + "index account", + "index/account", + accountId, + event); } @Override @@ -82,6 +95,7 @@ String projectName, int changeId, IndexEvent event) { return execute( RequestMethod.POST, + EventType.INDEX_CHANGE_UPDATE, "index change", "index/change", buildIndexEndpoint(projectName, changeId), @@ -93,6 +107,7 @@ String projectName, int changeId, IndexEvent event) { return execute( RequestMethod.POST, + EventType.INDEX_CHANGE_UPDATE_BATCH, "index change", "index/change/batch", buildIndexEndpoint(projectName, changeId), @@ -102,12 +117,23 @@ @Override public CompletableFuture<Boolean> deleteChangeFromIndex(final int changeId, IndexEvent event) { return execute( - RequestMethod.DELETE, "delete change", "index/change", buildIndexEndpoint(changeId), event); + RequestMethod.DELETE, + EventType.INDEX_CHANGE_DELETION, + "delete change", + "index/change", + buildIndexEndpoint(changeId), + event); } @Override public CompletableFuture<Boolean> indexGroup(final String uuid, IndexEvent event) { - return execute(RequestMethod.POST, "index group", "index/group", uuid, event); + return execute( + RequestMethod.POST, + EventType.INDEX_GROUP_UPDATE, + "index group", + "index/group", + uuid, + event); } private String buildIndexEndpoint(int changeId) { @@ -128,24 +154,37 @@ @Override public CompletableFuture<Boolean> indexProject(String projectName, IndexEvent event) { return execute( - RequestMethod.POST, "index project", "index/project", Url.encode(projectName), event); + RequestMethod.POST, + EventType.INDEX_PROJECT_UPDATE, + "index project", + "index/project", + Url.encode(projectName), + event); } @Override public CompletableFuture<Boolean> send(final Event event) { - return execute(RequestMethod.POST, "send event", "event", event.type, event); + return execute( + RequestMethod.POST, EventType.EVENT_SENT, "send event", "event", event.type, event); } @Override public CompletableFuture<Boolean> evict(final String cacheName, final Object key) { String json = gson.toJson(key); - return execute(RequestMethod.POST, "invalidate cache " + cacheName, "cache", cacheName, json); + return execute( + RequestMethod.POST, + EventType.CACHE_EVICTION, + "invalidate cache " + cacheName, + "cache", + cacheName, + json); } @Override public CompletableFuture<Boolean> addToProjectList(String projectName) { return execute( RequestMethod.POST, + EventType.PROJECT_LIST_ADDITION, "Update project_list, add ", buildProjectListEndpoint(), Url.encode(projectName)); @@ -155,6 +194,7 @@ public CompletableFuture<Boolean> removeFromProjectList(String projectName) { return execute( RequestMethod.DELETE, + EventType.PROJECT_LIST_DELETION, "Update project_list, remove ", buildProjectListEndpoint(), Url.encode(projectName)); @@ -164,6 +204,7 @@ public CompletableFuture<Boolean> deleteAllChangesForProject(Project.NameKey projectName) { return execute( RequestMethod.DELETE, + EventType.INDEX_CHANGE_DELETION_ALL_OF_PROJECT, "Delete all project changes from index", "index/change", buildAllChangesForProjectEndpoint(projectName.get())); @@ -174,18 +215,28 @@ } private CompletableFuture<Boolean> execute( - RequestMethod method, String action, String endpoint, Object id) { - return execute(method, action, endpoint, id, null); + RequestMethod method, EventType eventType, String action, String endpoint, Object id) { + return execute(method, eventType, action, endpoint, id, null); } private CompletableFuture<Boolean> execute( - RequestMethod method, String action, String endpoint, Object id, Object payload) { + RequestMethod method, + EventType eventType, + String action, + String endpoint, + Object id, + Object payload) { return peerInfoProvider.get().stream() .map(peer -> createRequest(method, peer, action, endpoint, id, payload)) .map(r -> executor.getAsync(() -> r.execute())) .reduce( CompletableFuture.completedFuture(true), - (a, b) -> a.thenCombine(b, (left, right) -> left && right)); + (a, b) -> a.thenCombine(b, (left, right) -> left && right)) + .thenApplyAsync( + result -> { + metricsRegistry.get(eventType).recordResult(result); + return result; + }); } private Request createRequest(
diff --git a/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarderTest.java b/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarderTest.java index 082b5d1..8dc9f43 100644 --- a/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarderTest.java +++ b/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/jgroups/JGroupsForwarderTest.java
@@ -23,6 +23,9 @@ import static org.mockito.Mockito.when; import com.ericsson.gerrit.plugins.highavailability.Configuration; +import com.ericsson.gerrit.plugins.highavailability.forwarder.ForwarderMetrics; +import com.ericsson.gerrit.plugins.highavailability.forwarder.ForwarderMetricsRegistry; +import com.ericsson.gerrit.plugins.highavailability.forwarder.IndexEvent; import com.google.gerrit.server.events.EventGsonProvider; import com.google.gerrit.server.git.WorkQueue; import com.google.gson.Gson; @@ -30,7 +33,7 @@ import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; -import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledThreadPoolExecutor; import org.jgroups.Address; import org.jgroups.blocks.MessageDispatcher; import org.jgroups.util.Rsp; @@ -38,7 +41,10 @@ import org.jgroups.util.UUID; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +@RunWith(org.mockito.junit.MockitoJUnitRunner.class) public class JGroupsForwarderTest { private static final int MAX_TRIES = 3; @@ -52,6 +58,9 @@ private MessageDispatcher dispatcher; private JGroupsForwarder forwarder; + @Mock ForwarderMetricsRegistry metricsRegistry; + @Mock ForwarderMetrics metrics; + @Before public void setUp() throws Exception { Gson eventGson = new EventGsonProvider().get(); @@ -67,10 +76,17 @@ WorkQueue workQueue = mock(WorkQueue.class); when(workQueue.createQueue(THREAD_POOLS_SIZE, "JGroupsForwarder")) - .thenReturn(Executors.newScheduledThreadPool(THREAD_POOLS_SIZE)); + .thenReturn(new ScheduledThreadPoolExecutor(THREAD_POOLS_SIZE)); + + when(metricsRegistry.get(any())).thenReturn(metrics); + forwarder = new JGroupsForwarder( - dispatcher, cfg, gson, new FailsafeExecutorProvider(cfg, workQueue).get()); + dispatcher, + cfg, + gson, + new FailsafeExecutorProvider(cfg, workQueue).get(), + metricsRegistry); } @Test @@ -78,7 +94,7 @@ RspList<Object> OK = new RspList<>(Map.of(A1, RSP_OK, A2, RSP_OK)); when(dispatcher.castMessage(any(), any(), any())).thenReturn(OK); - CompletableFuture<Boolean> result = forwarder.indexAccount(100, null); + CompletableFuture<Boolean> result = forwarder.indexAccount(100, new IndexEvent()); assertThat(result.get()).isTrue(); verify(dispatcher, times(1)).castMessage(any(), any(), any()); } @@ -90,7 +106,7 @@ RspList<Object> FAIL = new RspList<>(Map.of(A1, RSP_OK, A2, RSP_FAIL)); when(dispatcher.castMessage(any(), any(), any())).thenReturn(FAIL, OK); - CompletableFuture<Boolean> result = forwarder.indexAccount(100, null); + CompletableFuture<Boolean> result = forwarder.indexAccount(100, new IndexEvent()); assertThat(result.get()).isTrue(); verify(dispatcher, times(2)).castMessage(any(), any(), any()); } @@ -102,7 +118,7 @@ // return FAIL x MAX_TRIES when(dispatcher.castMessage(any(), any(), any())).thenReturn(FAIL, FAIL, FAIL); - CompletableFuture<Boolean> result = forwarder.indexAccount(100, null); + CompletableFuture<Boolean> result = forwarder.indexAccount(100, new IndexEvent()); assertThat(result.get()).isFalse(); verify(dispatcher, times(MAX_TRIES)).castMessage(any(), any(), any()); }
diff --git a/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarderTest.java b/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarderTest.java index 4b98fe1..9980f26 100644 --- a/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarderTest.java +++ b/src/test/java/com/ericsson/gerrit/plugins/highavailability/forwarder/rest/RestForwarderTest.java
@@ -25,6 +25,8 @@ import com.ericsson.gerrit.plugins.highavailability.Configuration; import com.ericsson.gerrit.plugins.highavailability.cache.Constants; +import com.ericsson.gerrit.plugins.highavailability.forwarder.ForwarderMetrics; +import com.ericsson.gerrit.plugins.highavailability.forwarder.ForwarderMetricsRegistry; import com.ericsson.gerrit.plugins.highavailability.forwarder.IndexEvent; import com.ericsson.gerrit.plugins.highavailability.forwarder.TestEvent; import com.ericsson.gerrit.plugins.highavailability.forwarder.rest.HttpResponseHandler.HttpResult; @@ -35,19 +37,20 @@ import com.google.gerrit.entities.AccountGroup; import com.google.gerrit.entities.Project; import com.google.gerrit.server.events.Event; -import com.google.gerrit.server.git.WorkQueue; import com.google.gson.Gson; import com.google.inject.Provider; import java.io.IOException; import java.time.Duration; import java.util.Set; -import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Answers; +import org.mockito.Mock; +@RunWith(org.mockito.junit.MockitoJUnitRunner.class) public class RestForwarderTest { private static final String URL = "http://fake.com"; private static final String PLUGIN_NAME = "high-availability"; @@ -111,6 +114,9 @@ private Configuration configMock; Provider<Set<PeerInfo>> peersMock; + @Mock ForwarderMetricsRegistry metricsRegistry; + @Mock ForwarderMetrics metrics; + @SuppressWarnings("unchecked") @Before public void setUp() { @@ -121,9 +127,7 @@ when(configMock.http().threadPoolSize()).thenReturn(2); peersMock = mock(Provider.class); when(peersMock.get()).thenReturn(ImmutableSet.of(new PeerInfo(URL))); - WorkQueue workQueue = mock(WorkQueue.class); - when(workQueue.createQueue(configMock.http().threadPoolSize(), "RestForwarderScheduler")) - .thenReturn(Executors.newScheduledThreadPool(2)); + when(metricsRegistry.get(any())).thenReturn(metrics); forwarder = new RestForwarder( httpSessionMock, @@ -131,7 +135,8 @@ configMock, peersMock, gson, // TODO: Create provider - new FailsafeExecutorProvider(configMock).get()); + new FailsafeExecutorProvider(configMock).get(), + metricsRegistry); } @Test