|
| 1 | +package org.jenkinsci.plugins.github.admin; |
| 2 | + |
| 3 | +import java.time.Duration; |
| 4 | +import java.time.Instant; |
| 5 | +import java.util.Set; |
| 6 | +import java.util.logging.Logger; |
| 7 | +import java.util.stream.Collectors; |
| 8 | + |
| 9 | +import com.github.benmanes.caffeine.cache.Cache; |
| 10 | +import com.github.benmanes.caffeine.cache.Caffeine; |
| 11 | +import com.github.benmanes.caffeine.cache.Ticker; |
| 12 | +import com.google.common.annotations.VisibleForTesting; |
| 13 | + |
| 14 | +import hudson.Extension; |
| 15 | +import hudson.model.AdministrativeMonitor; |
| 16 | +import hudson.model.Item; |
| 17 | +import jenkins.model.Jenkins; |
| 18 | +import org.jenkinsci.plugins.github.Messages; |
| 19 | +import org.jenkinsci.plugins.github.extension.GHEventsSubscriber; |
| 20 | +import org.jenkinsci.plugins.github.extension.GHSubscriberEvent; |
| 21 | +import org.kohsuke.accmod.Restricted; |
| 22 | +import org.kohsuke.accmod.restrictions.NoExternalUse; |
| 23 | +import org.kohsuke.github.GHEvent; |
| 24 | +import org.kohsuke.stapler.HttpResponse; |
| 25 | +import org.kohsuke.stapler.WebMethod; |
| 26 | +import org.kohsuke.stapler.json.JsonHttpResponse; |
| 27 | +import org.kohsuke.stapler.verb.GET; |
| 28 | +import edu.umd.cs.findbugs.annotations.Nullable; |
| 29 | +import net.sf.json.JSONObject; |
| 30 | + |
| 31 | +@SuppressWarnings("unused") |
| 32 | +@Extension |
| 33 | +public class GitHubDuplicateEventsMonitor extends AdministrativeMonitor { |
| 34 | + |
| 35 | + @VisibleForTesting |
| 36 | + static final String LAST_DUPLICATE_CLICK_HERE_ANCHOR_ID = GitHubDuplicateEventsMonitor.class.getName() |
| 37 | + + ".last-duplicate"; |
| 38 | + |
| 39 | + @Override |
| 40 | + public String getDisplayName() { |
| 41 | + return Messages.duplicate_events_administrative_monitor_displayname(); |
| 42 | + } |
| 43 | + |
| 44 | + public String getDescription() { |
| 45 | + return Messages.duplicate_events_administrative_monitor_description(); |
| 46 | + } |
| 47 | + |
| 48 | + public String getBlurb() { |
| 49 | + return Messages.duplicate_events_administrative_monitor_blurb( |
| 50 | + LAST_DUPLICATE_CLICK_HERE_ANCHOR_ID, this.getLastDuplicateUrl()); |
| 51 | + } |
| 52 | + |
| 53 | + @VisibleForTesting |
| 54 | + String getLastDuplicateUrl() { |
| 55 | + return this.getUrl() + "/" + "last-duplicate.json"; |
| 56 | + } |
| 57 | + |
| 58 | + @Override |
| 59 | + public boolean isActivated() { |
| 60 | + return DuplicateEventsSubscriber.isDuplicateEventSeen(); |
| 61 | + } |
| 62 | + |
| 63 | + @Override |
| 64 | + public boolean hasRequiredPermission() { |
| 65 | + return Jenkins.get().hasPermission(Jenkins.SYSTEM_READ); |
| 66 | + } |
| 67 | + |
| 68 | + @Override |
| 69 | + public void checkRequiredPermission() { |
| 70 | + Jenkins.get().checkPermission(Jenkins.SYSTEM_READ); |
| 71 | + } |
| 72 | + |
| 73 | + @GET |
| 74 | + @WebMethod(name = "last-duplicate.json") |
| 75 | + public HttpResponse doGetLastDuplicatePayload() { |
| 76 | + Jenkins.get().checkPermission(Jenkins.SYSTEM_READ); |
| 77 | + JSONObject data; |
| 78 | + var lastDuplicate = DuplicateEventsSubscriber.getLastDuplicate(); |
| 79 | + if (lastDuplicate != null) { |
| 80 | + data = JSONObject.fromObject(lastDuplicate.ghSubscriberEvent().getPayload()); |
| 81 | + } else { |
| 82 | + data = getLastDuplicateNoEventPayload(); |
| 83 | + } |
| 84 | + return new JsonHttpResponse(data, 200); |
| 85 | + } |
| 86 | + |
| 87 | + @VisibleForTesting |
| 88 | + static JSONObject getLastDuplicateNoEventPayload() { |
| 89 | + return new JSONObject().accumulate("payload", "No duplicate events seen yet"); |
| 90 | + } |
| 91 | + |
| 92 | + /** |
| 93 | + * Tracks duplicate {@link GHEvent} triggering actions in Jenkins. |
| 94 | + * Events are tracked for 10 minutes, with the last detected duplicate reference retained for up to 24 hours |
| 95 | + * (see {@link #isDuplicateEventSeen}). |
| 96 | + * <p> |
| 97 | + * Duplicates are stored in-memory only, so a controller restart clears all entries as if none existed. |
| 98 | + * Persistent storage is omitted for simplicity, since webhook misconfigurations would likely cause new duplicates. |
| 99 | + */ |
| 100 | + @Extension |
| 101 | + public static final class DuplicateEventsSubscriber extends GHEventsSubscriber { |
| 102 | + |
| 103 | + private static final Logger LOGGER = Logger.getLogger(DuplicateEventsSubscriber.class.getName()); |
| 104 | + |
| 105 | + private static Ticker ticker = Ticker.systemTicker(); |
| 106 | + /** |
| 107 | + * Caches GitHub event GUIDs for 10 minutes to track recent events to detect duplicates. |
| 108 | + * <p> |
| 109 | + * Only the keys (event GUIDs) are relevant, as Caffeine automatically handles expiration based |
| 110 | + * on insertion time; the value is irrelevant, we put {@link #DUMMY}, as Caffeine doesn't provide any |
| 111 | + * Set structures. |
| 112 | + * <p> |
| 113 | + * Maximum cache size is set to 24k so it doesn't grow unbound (approx. 1MB). Each key takes 36 bytes, and |
| 114 | + * timestamp (assuming caffeine internally keeps long) takes 8 bytes; total of 44 bytes |
| 115 | + * per entry. So the maximum memory consumed by this cache is 24k * 44 = 1056k = 1.056 MB. |
| 116 | + */ |
| 117 | + private static final Cache<String, Object> EVENT_TRACKER = Caffeine.newBuilder() |
| 118 | + .maximumSize(24_000L) |
| 119 | + .expireAfterWrite(Duration.ofMinutes(10)) |
| 120 | + .ticker(() -> ticker.read()) |
| 121 | + .build(); |
| 122 | + private static final Object DUMMY = new Object(); |
| 123 | + |
| 124 | + private static volatile TrackedDuplicateEvent lastDuplicate; |
| 125 | + public record TrackedDuplicateEvent( |
| 126 | + String eventGuid, Instant lastUpdated, GHSubscriberEvent ghSubscriberEvent) { } |
| 127 | + private static final Duration TWENTY_FOUR_HOURS = Duration.ofHours(24); |
| 128 | + |
| 129 | + @VisibleForTesting |
| 130 | + @Restricted(NoExternalUse.class) |
| 131 | + static void setTicker(Ticker testTicker) { |
| 132 | + ticker = testTicker; |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * This subscriber is not applicable to any item |
| 137 | + * |
| 138 | + * @param item ignored |
| 139 | + * @return always false |
| 140 | + */ |
| 141 | + @Override |
| 142 | + protected boolean isApplicable(@Nullable Item item) { |
| 143 | + return false; |
| 144 | + } |
| 145 | + |
| 146 | + /** |
| 147 | + * {@inheritDoc} |
| 148 | + * <p> |
| 149 | + * Subscribes to events that trigger actions in Jenkins, such as repository scans or builds. |
| 150 | + * <p> |
| 151 | + * The {@link GHEvent} enum defines about 63 events, but not all are relevant to Jenkins. |
| 152 | + * Tracking unnecessary events increases memory usage, and they occur more frequently than those triggering any |
| 153 | + * work. |
| 154 | + * <p> |
| 155 | + * <a href="https://docs.github.com/en/webhooks/webhook-events-and-payloads"> |
| 156 | + * Documentation reference (also referenced in {@link GHEvent})</a> |
| 157 | + */ |
| 158 | + @Override |
| 159 | + protected Set<GHEvent> events() { |
| 160 | + return Set.of( |
| 161 | + GHEvent.CHECK_RUN, // associated with GitHub action Re-run button to trigger build |
| 162 | + GHEvent.CHECK_SUITE, // associated with GitHub action Re-run button to trigger build |
| 163 | + GHEvent.CREATE, // branch or tag creation |
| 164 | + GHEvent.DELETE, // branch or tag deletion |
| 165 | + GHEvent.PULL_REQUEST, // PR creation (also PR close or merge) |
| 166 | + GHEvent.PUSH // commit push |
| 167 | + ); |
| 168 | + } |
| 169 | + |
| 170 | + @Override |
| 171 | + protected void onEvent(final GHSubscriberEvent event) { |
| 172 | + String eventGuid = event.getEventGuid(); |
| 173 | + LOGGER.fine(() -> "Received event with GUID: " + eventGuid); |
| 174 | + if (eventGuid == null) { |
| 175 | + return; |
| 176 | + } |
| 177 | + if (EVENT_TRACKER.getIfPresent(eventGuid) != null) { |
| 178 | + lastDuplicate = new TrackedDuplicateEvent(eventGuid, getNow(), event); |
| 179 | + } |
| 180 | + EVENT_TRACKER.put(eventGuid, DUMMY); |
| 181 | + } |
| 182 | + |
| 183 | + /** |
| 184 | + * Checks if a duplicate event was recorded in the past 24 hours. |
| 185 | + * <p> |
| 186 | + * Events are not stored for 24 hours—only the most recent duplicate is checked within this timeframe. |
| 187 | + * |
| 188 | + * @return {@code true} if a duplicate was seen in the last 24 hours, {@code false} otherwise. |
| 189 | + */ |
| 190 | + public static boolean isDuplicateEventSeen() { |
| 191 | + return lastDuplicate != null |
| 192 | + && Duration.between(lastDuplicate.lastUpdated(), getNow()).compareTo(TWENTY_FOUR_HOURS) < 0; |
| 193 | + } |
| 194 | + |
| 195 | + private static Instant getNow() { |
| 196 | + return Instant.ofEpochSecond(0L, ticker.read()); |
| 197 | + } |
| 198 | + |
| 199 | + public static TrackedDuplicateEvent getLastDuplicate() { |
| 200 | + return lastDuplicate; |
| 201 | + } |
| 202 | + |
| 203 | + /** |
| 204 | + * Caffeine expired keys are not removed immediately. Method returns the non-expired keys; |
| 205 | + * required for the tests. |
| 206 | + */ |
| 207 | + @VisibleForTesting |
| 208 | + @Restricted(NoExternalUse.class) |
| 209 | + static Set<String> getEventCountsTracker() { |
| 210 | + return EVENT_TRACKER.asMap().keySet().stream() |
| 211 | + .filter(key -> EVENT_TRACKER.getIfPresent(key) != null) |
| 212 | + .collect(Collectors.toSet()); |
| 213 | + } |
| 214 | + } |
| 215 | +} |
0 commit comments