2026-01-14 16:27:39 -05:00
|
|
|
|
using System.Data.Common;
|
|
|
|
|
|
using Bit.Core.Utilities;
|
2019-03-25 13:21:05 -04:00
|
|
|
|
|
|
|
|
|
|
namespace Bit.Admin.HostedServices;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2019-03-25 13:21:05 -04:00
|
|
|
|
public class DatabaseMigrationHostedService : IHostedService, IDisposable
|
|
|
|
|
|
{
|
|
|
|
|
|
private readonly ILogger<DatabaseMigrationHostedService> _logger;
|
2022-11-18 14:39:01 -05:00
|
|
|
|
private readonly IDbMigrator _dbMigrator;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2019-03-25 13:21:05 -04:00
|
|
|
|
public DatabaseMigrationHostedService(
|
2022-11-18 14:39:01 -05:00
|
|
|
|
IDbMigrator dbMigrator,
|
|
|
|
|
|
ILogger<DatabaseMigrationHostedService> logger)
|
2019-03-25 13:21:05 -04:00
|
|
|
|
{
|
|
|
|
|
|
_logger = logger;
|
2022-11-18 14:39:01 -05:00
|
|
|
|
_dbMigrator = dbMigrator;
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-03-25 13:21:05 -04:00
|
|
|
|
|
|
|
|
|
|
public virtual async Task StartAsync(CancellationToken cancellationToken)
|
|
|
|
|
|
{
|
|
|
|
|
|
// Wait 20 seconds to allow database to come online
|
2025-11-28 20:15:06 +05:00
|
|
|
|
await Task.Delay(20000, cancellationToken);
|
2019-03-25 13:21:05 -04:00
|
|
|
|
|
|
|
|
|
|
var maxMigrationAttempts = 10;
|
|
|
|
|
|
for (var i = 1; i <= maxMigrationAttempts; i++)
|
|
|
|
|
|
{
|
|
|
|
|
|
try
|
2022-08-29 14:53:16 -04:00
|
|
|
|
{
|
2022-11-18 14:39:01 -05:00
|
|
|
|
_dbMigrator.MigrateDatabase(true, cancellationToken);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
// TODO: Maybe flip a flag somewhere to indicate migration is complete??
|
2022-08-29 16:06:55 -04:00
|
|
|
|
break;
|
|
|
|
|
|
}
|
2026-01-14 16:27:39 -05:00
|
|
|
|
catch (DbException e)
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{
|
2020-03-27 14:36:37 -04:00
|
|
|
|
if (i >= maxMigrationAttempts)
|
2019-03-25 13:21:05 -04:00
|
|
|
|
{
|
|
|
|
|
|
_logger.LogError(e, "Database failed to migrate.");
|
|
|
|
|
|
throw;
|
|
|
|
|
|
}
|
2020-03-27 14:36:37 -04:00
|
|
|
|
else
|
2019-03-25 13:21:05 -04:00
|
|
|
|
{
|
|
|
|
|
|
_logger.LogError(e,
|
2026-01-14 16:27:39 -05:00
|
|
|
|
"Database unavailable for migration. Trying again (attempt #{AttemptNumber})...", i + 1);
|
2025-11-28 20:15:06 +05:00
|
|
|
|
await Task.Delay(20000, cancellationToken);
|
2019-03-25 13:21:05 -04:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
}
|
2019-03-25 13:21:05 -04:00
|
|
|
|
|
|
|
|
|
|
public virtual Task StopAsync(CancellationToken cancellationToken)
|
|
|
|
|
|
{
|
|
|
|
|
|
return Task.FromResult(0);
|
2022-08-29 15:53:48 -04:00
|
|
|
|
}
|
2022-08-29 16:06:55 -04:00
|
|
|
|
|
2019-03-25 13:21:05 -04:00
|
|
|
|
public virtual void Dispose()
|
2022-08-29 16:06:55 -04:00
|
|
|
|
{ }
|
2019-03-25 13:21:05 -04:00
|
|
|
|
}
|