1
0
mirror of https://github.com/bitwarden/server.git synced 2024-12-11 15:17:44 +01:00
bitwarden-server/src/Admin/HostedServices/DatabaseMigrationHostedService.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

58 lines
1.6 KiB
C#
Raw Normal View History

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