-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Migrations: Add auto upgrade coordination for load-balanced setups #22815
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
nikolajlauridsen
merged 9 commits into
v17/dev
from
v17/feature/auto-migration-coordination-for-load-balanced-setups
May 18, 2026
Merged
Changes from 7 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
40b2464
Add auto upgrade coordination for load balanced setups
nikolajlauridsen 5b447c2
Add tests
nikolajlauridsen a763d71
Apply suggestions from code review
nikolajlauridsen 149be88
Potential fix for pull request finding
nikolajlauridsen bf2ec47
fix(infrastructure): move TryBecomeLeaderAsync inside try/catch in Un…
nikolajlauridsen 76cf1ab
Fix feedback
nikolajlauridsen cce0e2a
Update src/Umbraco.Infrastructure/Install/MigrationCoordinator.cs
nikolajlauridsen 17c9376
Recheck state
nikolajlauridsen 557b2e8
fix(tests): update concurrent race test for post-claim DetermineRunti…
nikolajlauridsen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
24 changes: 24 additions & 0 deletions
24
src/Umbraco.Infrastructure/Install/IMigrationCoordinator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| namespace Umbraco.Cms.Infrastructure.Install; | ||
|
|
||
| /// <summary> | ||
| /// Coordinates migration leadership across servers in a load-balanced environment. | ||
| /// </summary> | ||
| internal interface IMigrationCoordinator | ||
| { | ||
| /// <summary> | ||
| /// Attempts to become the migration leader, blocking until either this server wins the claim | ||
| /// or another server completes all migrations. | ||
| /// </summary> | ||
| /// <param name="cancellationToken">A token that cancels the leadership wait loop.</param> | ||
| /// <returns> | ||
| /// <c>true</c> if this server is the migration leader and must call <see cref="ReleaseLeadership"/> after | ||
| /// running migrations; <c>false</c> if another server completed migrations and this server should skip them. | ||
| /// </returns> | ||
| Task<bool> TryBecomeLeaderAsync(CancellationToken cancellationToken); | ||
|
|
||
| /// <summary> | ||
| /// Releases the migration leadership claim if it is still held by this instance. | ||
| /// Must be called in a <c>finally</c> block to ensure release even on failure. | ||
| /// </summary> | ||
| void ReleaseLeadership(); | ||
| } |
155 changes: 155 additions & 0 deletions
155
src/Umbraco.Infrastructure/Install/MigrationCoordinator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,155 @@ | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.Extensions.Options; | ||
| using Umbraco.Cms.Core; | ||
| using Umbraco.Cms.Core.Configuration.Models; | ||
| using Umbraco.Cms.Core.Factories; | ||
| using Umbraco.Cms.Core.Scoping; | ||
| using Umbraco.Cms.Core.Services; | ||
|
|
||
| namespace Umbraco.Cms.Infrastructure.Install; | ||
|
|
||
| /// <summary> | ||
| /// Coordinates migration leadership across servers in a load-balanced environment. | ||
| /// Exactly one server claims leadership, runs all migrations, then releases the claim. | ||
| /// All other servers wait until the leader finishes, then proceed with per-server initialization. | ||
| /// </summary> | ||
| internal sealed class MigrationCoordinator : IMigrationCoordinator | ||
| { | ||
| private readonly ICoreScopeProvider _scopeProvider; | ||
| private readonly IKeyValueService _keyValueService; | ||
| private readonly IRuntimeState _runtimeState; | ||
| private readonly IMachineInfoFactory _machineInfoFactory; | ||
| private readonly IOptions<UnattendedSettings> _unattendedSettings; | ||
| private readonly ILogger<MigrationCoordinator> _logger; | ||
| private string? _leaderClaim; | ||
|
|
||
| public MigrationCoordinator( | ||
| ICoreScopeProvider scopeProvider, | ||
| IKeyValueService keyValueService, | ||
| IRuntimeState runtimeState, | ||
| IMachineInfoFactory machineInfoFactory, | ||
| IOptions<UnattendedSettings> unattendedSettings, | ||
| ILogger<MigrationCoordinator> logger) | ||
| { | ||
| _scopeProvider = scopeProvider; | ||
| _keyValueService = keyValueService; | ||
| _runtimeState = runtimeState; | ||
| _machineInfoFactory = machineInfoFactory; | ||
| _unattendedSettings = unattendedSettings; | ||
| _logger = logger; | ||
| } | ||
|
Check warning on line 40 in src/Umbraco.Infrastructure/Install/MigrationCoordinator.cs
|
||
|
|
||
| /// <inheritdoc/> | ||
| public async Task<bool> TryBecomeLeaderAsync(CancellationToken cancellationToken) | ||
| { | ||
| var machineIdentifier = _machineInfoFactory.GetMachineIdentifier(); | ||
|
|
||
| while (cancellationToken.IsCancellationRequested is false) | ||
| { | ||
| if (TryClaimLeadership(machineIdentifier)) | ||
| { | ||
| _logger.LogInformation("This server claimed migration leadership."); | ||
| return true; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| _runtimeState.DetermineRuntimeLevel(); | ||
| } | ||
| catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) | ||
| { | ||
| return false; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogWarning(ex, "Could not determine runtime level during migration wait; will retry."); | ||
| } | ||
|
nikolajlauridsen marked this conversation as resolved.
|
||
|
|
||
| switch (_runtimeState.Level) | ||
| { | ||
| case RuntimeLevel.Run: | ||
| _logger.LogInformation("Migrations completed by another server; proceeding as follower."); | ||
| return false; | ||
| case RuntimeLevel.BootFailed: | ||
| _logger.LogError("Runtime entered BootFailed state while waiting for migrations."); | ||
| return false; | ||
| default: | ||
| _logger.LogDebug("Waiting for migration leader to finish..."); | ||
| try | ||
| { | ||
| await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken); | ||
| } | ||
| catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| break; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
Check warning on line 92 in src/Umbraco.Infrastructure/Install/MigrationCoordinator.cs
|
||
|
|
||
| /// <inheritdoc/> | ||
| public void ReleaseLeadership() | ||
| { | ||
| if (_leaderClaim is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| try | ||
| { | ||
| using ICoreScope scope = _scopeProvider.CreateCoreScope(); | ||
| scope.WriteLock(Constants.Locks.KeyValues); | ||
|
|
||
| string? current = _keyValueService.GetValue(Constants.Conventions.Migrations.UpgradeLockKey); | ||
| if (current == _leaderClaim) | ||
| { | ||
| _keyValueService.SetValue(Constants.Conventions.Migrations.UpgradeLockKey, string.Empty); | ||
| } | ||
|
|
||
| scope.Complete(); | ||
| _leaderClaim = null; | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| _logger.LogWarning(ex, "Failed to release migration leadership; continuing shutdown because leadership release is best-effort."); | ||
| } | ||
| } | ||
|
|
||
| private static bool IsStale(string claim, TimeSpan timeout) | ||
| { | ||
| var separatorIndex = claim.IndexOf('|'); | ||
| return separatorIndex < 0 | ||
| || !DateTimeOffset.TryParse(claim.AsSpan(separatorIndex + 1), out DateTimeOffset timestamp) | ||
| || DateTimeOffset.UtcNow - timestamp > timeout; | ||
| } | ||
|
|
||
| // Acquires WriteLock(KeyValues) so the read-then-write is serialized across all servers. | ||
| // Inner GetValue and SetValue calls create nested scopes that join the outer transaction; | ||
| // their internal WriteLock requests are no-ops because the lock is already held. | ||
| private bool TryClaimLeadership(string machineIdentifier) | ||
| { | ||
| TimeSpan timeout = _unattendedSettings.Value.MigrationClaimTimeout; | ||
|
|
||
| using ICoreScope scope = _scopeProvider.CreateCoreScope(); | ||
| scope.WriteLock(Constants.Locks.KeyValues); | ||
|
|
||
| string? current = _keyValueService.GetValue(Constants.Conventions.Migrations.UpgradeLockKey); | ||
|
|
||
| bool canClaim = string.IsNullOrEmpty(current) | ||
| || IsStale(current, timeout) | ||
| || current.StartsWith(machineIdentifier + "|", StringComparison.Ordinal); | ||
|
nikolajlauridsen marked this conversation as resolved.
|
||
|
|
||
| if (canClaim) | ||
| { | ||
| _leaderClaim = $"{machineIdentifier}|{DateTimeOffset.UtcNow:O}"; | ||
| _keyValueService.SetValue(Constants.Conventions.Migrations.UpgradeLockKey, _leaderClaim); | ||
| } | ||
|
|
||
| scope.Complete(); | ||
| return canClaim; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.