mirror of
https://github.com/bitwarden/server
synced 2026-01-29 07:43:22 +00:00
* Switch `SqlException` to `DbException` Co-authored-by: rkac-bw <148072202+rkac-bw@users.noreply.github.com> * Fix CA2253 --------- Co-authored-by: rkac-bw <148072202+rkac-bw@users.noreply.github.com>
58 lines
1.7 KiB
C#
58 lines
1.7 KiB
C#
using System.Data.Common;
|
|
using Bit.Core.Utilities;
|
|
|
|
namespace Bit.Admin.HostedServices;
|
|
|
|
public class DatabaseMigrationHostedService : IHostedService, IDisposable
|
|
{
|
|
private readonly ILogger<DatabaseMigrationHostedService> _logger;
|
|
private readonly IDbMigrator _dbMigrator;
|
|
|
|
public DatabaseMigrationHostedService(
|
|
IDbMigrator dbMigrator,
|
|
ILogger<DatabaseMigrationHostedService> logger)
|
|
{
|
|
_logger = logger;
|
|
_dbMigrator = dbMigrator;
|
|
}
|
|
|
|
public virtual async Task StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
// Wait 20 seconds to allow database to come online
|
|
await Task.Delay(20000, cancellationToken);
|
|
|
|
var maxMigrationAttempts = 10;
|
|
for (var i = 1; i <= maxMigrationAttempts; i++)
|
|
{
|
|
try
|
|
{
|
|
_dbMigrator.MigrateDatabase(true, cancellationToken);
|
|
// TODO: Maybe flip a flag somewhere to indicate migration is complete??
|
|
break;
|
|
}
|
|
catch (DbException e)
|
|
{
|
|
if (i >= maxMigrationAttempts)
|
|
{
|
|
_logger.LogError(e, "Database failed to migrate.");
|
|
throw;
|
|
}
|
|
else
|
|
{
|
|
_logger.LogError(e,
|
|
"Database unavailable for migration. Trying again (attempt #{AttemptNumber})...", i + 1);
|
|
await Task.Delay(20000, cancellationToken);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
public virtual Task StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
return Task.FromResult(0);
|
|
}
|
|
|
|
public virtual void Dispose()
|
|
{ }
|
|
}
|