Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package io.terrakube.api.plugin.scheduler.webhook;

import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
* Quartz job executed at API startup when webhook v1 is disabled, migrating any remaining
* workspaces from legacy v1 webhooks to shared v2 repository webhooks.
*
* <p>{@code @DisallowConcurrentExecution} ensures Quartz never runs overlapping instances of
* this migration job across cluster replicas or misfires.
*/
@Slf4j
@Component
@DisallowConcurrentExecution
@RequiredArgsConstructor
public class WebhookV1ToV2MigrationJob implements Job {

private final WebhookV1ToV2MigrationService migrationService;

@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
log.info("Starting Quartz webhook v1->v2 startup migration job");
WebhookV1ToV2MigrationService.MigrationSummary summary = migrationService.migrateAllUnmigrated();
if (summary.failed() > 0) {
log.warn("Finished Quartz webhook v1->v2 startup migration job with errors (migrated={}, skipped={}, failed={})",
summary.migrated(), summary.skipped(), summary.failed());
} else {
log.info("Finished Quartz webhook v1->v2 startup migration job (migrated={}, skipped={}, failed={})",
summary.migrated(), summary.skipped(), summary.failed());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package io.terrakube.api.plugin.scheduler.webhook;

import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.JobPersistenceException;
import org.quartz.ObjectAlreadyExistsException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import io.terrakube.api.plugin.vcs.WebhookProperties;
import lombok.extern.slf4j.Slf4j;

/**
* Schedules {@link WebhookV1ToV2MigrationJob} once on API startup when webhook v1 is disabled,
* using a deterministic {@link JobKey} so multi-replica deployments coalesce onto one execution
* in the clustered Quartz JDBC job store.
*/
@Slf4j
@Service
public class WebhookV1ToV2MigrationScheduler {

static final JobKey JOB_KEY = new JobKey("TerrakubeV2_WebhookV1ToV2Migration", "webhook-v1-migration");

private final Scheduler scheduler;
private final WebhookProperties webhookProperties;
private final WebhookV1ToV2MigrationTransactions transactions;

@Autowired
public WebhookV1ToV2MigrationScheduler(@Autowired(required = false) Scheduler scheduler,
WebhookProperties webhookProperties,
WebhookV1ToV2MigrationTransactions transactions) {
this.scheduler = scheduler;
this.webhookProperties = webhookProperties;
this.transactions = transactions;
}

@EventListener(ApplicationReadyEvent.class)
public void scheduleMigrationOnStartup() {
if (!webhookProperties.getV1().isDisabled()) {
log.info("Webhook v1 is enabled; skipping startup v1->v2 migration job");
return;
}
if (!webhookProperties.getV1().isMigrationOnStartup()) {
long remaining = transactions != null
? transactions.countUnmigratedV1Webhooks(WebhookV1ToV2MigrationService.SUPPORTED_VCS_TYPES)
: 0;
if (remaining > 0) {
log.warn("Webhook v1 is disabled (404) and startup migration is disabled, but {} unmigrated v1 webhook(s) remain; enable io.terrakube.webhook.v1.migration-on-startup or set WebhookV1Disabled=false to avoid dropped deliveries",
remaining);
} else {
log.info("Webhook v1->v2 startup migration job is disabled by configuration");
}
return;
}
if (scheduler == null) {
log.warn("Quartz scheduler is not available; skipping webhook v1->v2 startup migration");
return;
}

JobDetail jobDetail = JobBuilder.newJob(WebhookV1ToV2MigrationJob.class)
.withIdentity(JOB_KEY)
.withDescription("Migrate remaining webhook v1 workspaces to webhook v2 on startup")
.storeDurably(false)
.build();

Trigger trigger = TriggerBuilder.newTrigger()
.forJob(jobDetail)
.withIdentity(JOB_KEY.getName(), JOB_KEY.getGroup())
.startNow()
.build();

try {
scheduler.scheduleJob(jobDetail, trigger);
log.info("Scheduled webhook v1->v2 startup migration job {}", JOB_KEY);
} catch (ObjectAlreadyExistsException _) {
log.info("Webhook v1->v2 startup migration job {} is already scheduled by another replica", JOB_KEY);
} catch (JobPersistenceException e) {
log.info("Webhook v1->v2 startup migration job {} lost race to schedule on another replica", JOB_KEY, e);
} catch (SchedulerException e) {
log.error("Failed to schedule webhook v1->v2 startup migration job: {}", e.getMessage(), e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
package io.terrakube.api.plugin.scheduler.webhook;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import io.terrakube.api.plugin.vcs.RepoUrlNormalizer;
import io.terrakube.api.plugin.vcs.provider.azdevops.AzDevOpsWebhookService;
import io.terrakube.api.plugin.vcs.provider.bitbucket.BitBucketWebhookService;
import io.terrakube.api.plugin.vcs.provider.github.GitHubWebhookService;
import io.terrakube.api.plugin.vcs.provider.gitlab.GitLabWebhookService;
import io.terrakube.api.rs.vcs.Vcs;
import io.terrakube.api.rs.vcs.VcsType;
import io.terrakube.api.rs.webhook.Webhook;
import io.terrakube.api.rs.workspace.Workspace;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
* Migrates remaining v1 workspace webhooks to shared v2 repository webhooks and retries any
* previously migrated webhooks that still have a pending {@code syncError} or unconfirmed legacy
* {@code remoteHookId}.
*
* <p>Unmigrated webhooks are grouped by normalized repository URL so every workspace sharing a
* repository is marked {@code migratedV2 = true} before scheduling a single
* {@link RepoWebhookSyncJob} per repository, preventing coalescing races and ensuring shared hooks
* include all workspaces' event types. Legacy v1 remote hook deletion runs best-effort after v2
* sync scheduling, and {@code remoteHookId} is cleared only when deletion is confirmed.
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class WebhookV1ToV2MigrationService {

public static final Set<VcsType> SUPPORTED_VCS_TYPES = Set.of(
VcsType.GITHUB,
VcsType.GITLAB,
VcsType.AZURE_DEVOPS,
VcsType.AZURE_SP_MI,
VcsType.BITBUCKET);

public record MigrationSummary(int migrated, int skipped, int failed) {
}

private final WebhookV1ToV2MigrationTransactions transactions;
private final GitHubWebhookService gitHubWebhookService;
private final GitLabWebhookService gitLabWebhookService;
private final AzDevOpsWebhookService azDevOpsWebhookService;
private final BitBucketWebhookService bitBucketWebhookService;
private final RepoWebhookSyncScheduler repoWebhookSyncScheduler;

public MigrationSummary migrateAllUnmigrated() {

Check failure on line 56 in api/src/main/java/io/terrakube/api/plugin/scheduler/webhook/WebhookV1ToV2MigrationService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 79 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=AzBuilder_azb-server&issues=AaIoAE-cVNjnvCNino1O&open=AaIoAE-cVNjnvCNino1O&pullRequest=4066
List<Webhook> unmigrated = transactions.findUnmigratedV1Webhooks(SUPPORTED_VCS_TYPES);
List<Webhook> needsRetry = transactions.findMigratedWebhooksNeedingRetry(SUPPORTED_VCS_TYPES);

if (unmigrated.isEmpty() && needsRetry.isEmpty()) {
log.info("No unmigrated v1 webhooks or pending migration retries found; startup migration complete");
return new MigrationSummary(0, 0, 0);
}

int migrated = 0;
int skipped = 0;
int failed = 0;

if (!unmigrated.isEmpty()) {
log.info("Found {} unmigrated v1 webhook(s); grouping by repository for migration to v2",
unmigrated.size());
Map<String, List<Webhook>> groupedByRepo = new LinkedHashMap<>();
for (Webhook webhook : unmigrated) {
Workspace workspace = webhook.getWorkspace();
Vcs vcs = workspace != null ? workspace.getVcs() : null;
String normalizedUrl = workspace != null ? RepoUrlNormalizer.normalize(workspace.getSource()) : null;
if (workspace == null || vcs == null || normalizedUrl == null) {
log.warn("Skipping v1 webhook {} migration: missing workspace, VCS connection, or source URL",
webhook.getId());
skipped++;
continue;
}
groupedByRepo.computeIfAbsent(normalizedUrl, _ -> new ArrayList<>()).add(webhook);
}

for (Map.Entry<String, List<Webhook>> entry : groupedByRepo.entrySet()) {
String normalizedUrl = entry.getKey();
List<Webhook> repoWebhooks = entry.getValue();
List<Webhook> markedInGroup = new ArrayList<>();
String seedWorkspaceId = null;

for (Webhook webhook : repoWebhooks) {
try {
if (transactions.markMigrated(webhook.getId())) {
markedInGroup.add(webhook);
if (seedWorkspaceId == null && webhook.getWorkspace().getId() != null) {
seedWorkspaceId = webhook.getWorkspace().getId().toString();
}
migrated++;
} else {
skipped++;
}
} catch (Exception e) {
log.error("Failed to mark webhook {} on workspace {} as migrated: {}",
webhook.getId(), webhook.getWorkspace().getId(), e.getMessage(), e);
transactions.recordMigrationError(webhook.getId(), RepoWebhookSyncStatus.describe(e));
failed++;
}
}

if (!markedInGroup.isEmpty()) {
try {
repoWebhookSyncScheduler.scheduleSync(normalizedUrl, seedWorkspaceId);
log.info("Marked {} webhook(s) migrated for {} and scheduled shared v2 sync",
markedInGroup.size(), normalizedUrl);
} catch (Exception e) {
log.error("Failed to schedule shared webhook sync for {}: {}", normalizedUrl, e.getMessage(), e);
String error = RepoWebhookSyncStatus.describe(e);
for (Webhook webhook : markedInGroup) {
transactions.recordMigrationError(webhook.getId(), error);
}
failed += markedInGroup.size();
}

// Best-effort cleanup of legacy v1 remote hooks after v2 sync has been queued;
// failures keep remoteHookId intact so a later startup can retry cleanup without blocking v2.
for (Webhook webhook : markedInGroup) {
cleanupLegacyHookIfConfirmed(webhook);
}
}
}
}

if (!needsRetry.isEmpty()) {
log.info("Found {} migrated webhook(s) needing retry for syncError or legacy v1 hook cleanup",
needsRetry.size());
Map<String, String> reposToResync = new LinkedHashMap<>();
for (Webhook webhook : needsRetry) {
Workspace workspace = webhook.getWorkspace();
Vcs vcs = workspace != null ? workspace.getVcs() : null;
String normalizedUrl = workspace != null ? RepoUrlNormalizer.normalize(workspace.getSource()) : null;
if (workspace == null || vcs == null || normalizedUrl == null) {
continue;
}
if (webhook.getSyncError() != null && !webhook.getSyncError().isBlank()) {
reposToResync.putIfAbsent(normalizedUrl,
workspace.getId() != null ? workspace.getId().toString() : null);
}
cleanupLegacyHookIfConfirmed(webhook);
}
for (Map.Entry<String, String> entry : reposToResync.entrySet()) {
try {
repoWebhookSyncScheduler.scheduleSync(entry.getKey(), entry.getValue());
log.info("Re-scheduled shared v2 sync for {} after previous syncError", entry.getKey());
} catch (Exception e) {
log.error("Failed to re-schedule shared webhook sync for {}: {}",
entry.getKey(), e.getMessage(), e);
failed++;
}
}
}

MigrationSummary summary = new MigrationSummary(migrated, skipped, failed);
if (failed > 0) {
log.warn("Completed webhook v1->v2 startup migration with errors: migrated={}, skipped={}, failed={}",
summary.migrated(), summary.skipped(), summary.failed());
} else {
log.info("Completed webhook v1->v2 startup migration: migrated={}, skipped={}, failed={}",
summary.migrated(), summary.skipped(), summary.failed());
}
return summary;
}

private void cleanupLegacyHookIfConfirmed(Webhook webhook) {
String remoteHookId = webhook.getRemoteHookId();
if (remoteHookId == null || remoteHookId.isBlank()) {
return;
}
Workspace workspace = webhook.getWorkspace();
VcsType vcsType = workspace != null && workspace.getVcs() != null
? workspace.getVcs().getVcsType()
: null;
if (workspace == null || vcsType == null) {
return;
}
try {
if (deleteLegacyV1Hook(workspace, vcsType, remoteHookId)) {
transactions.clearRemoteHookId(webhook.getId());
} else {
log.warn("Legacy v1 hook {} on workspace {} was not confirmed deleted; keeping remoteHookId for retry",
remoteHookId, workspace.getId());
}
} catch (Exception e) {
log.warn("Failed to delete legacy v1 hook {} on workspace {}; keeping remoteHookId for retry: {}",
remoteHookId, workspace.getId(), e.getMessage());
}
}

private boolean deleteLegacyV1Hook(Workspace workspace, VcsType vcsType, String remoteHookId) {
return switch (vcsType) {
case GITHUB -> gitHubWebhookService.deleteWebhook(workspace, remoteHookId);
case GITLAB -> gitLabWebhookService.deleteWebhook(workspace, remoteHookId);
case AZURE_DEVOPS, AZURE_SP_MI -> azDevOpsWebhookService.deleteWebhook(workspace, remoteHookId);
case BITBUCKET -> bitBucketWebhookService.deleteWebhook(workspace, remoteHookId);
default -> throw new IllegalArgumentException("Unsupported VCS type for webhook migration: " + vcsType);
};
}
}
Loading
Loading