2022-06-30 01:46:41 +02:00
|
|
|
|
using System.Data.SqlClient;
|
2019-03-25 18:21:05 +01:00
|
|
|
|
using Bit.Core.Jobs;
|
2021-02-22 22:35:16 +01:00
|
|
|
|
using Bit.Core.Settings;
|
2019-03-25 18:21:05 +01:00
|
|
|
|
using Bit.Migrator;
|
|
|
|
|
|
|
|
|
|
namespace Bit.Admin.HostedServices;
|
2022-08-29 20:53:16 +02:00
|
|
|
|
|
2019-03-25 18:21:05 +01:00
|
|
|
|
public class DatabaseMigrationHostedService : IHostedService, IDisposable
|
|
|
|
|
{
|
|
|
|
|
private readonly GlobalSettings _globalSettings;
|
|
|
|
|
private readonly ILogger<DatabaseMigrationHostedService> _logger;
|
|
|
|
|
private readonly DbMigrator _dbMigrator;
|
2022-08-29 20:53:16 +02:00
|
|
|
|
|
2019-03-25 18:21:05 +01:00
|
|
|
|
public DatabaseMigrationHostedService(
|
|
|
|
|
GlobalSettings globalSettings,
|
|
|
|
|
ILogger<DatabaseMigrationHostedService> logger,
|
|
|
|
|
ILogger<DbMigrator> migratorLogger,
|
|
|
|
|
ILogger<JobListener> listenerLogger)
|
|
|
|
|
{
|
|
|
|
|
_globalSettings = globalSettings;
|
|
|
|
|
_logger = logger;
|
|
|
|
|
_dbMigrator = new DbMigrator(globalSettings.SqlServer.ConnectionString, migratorLogger);
|
2022-08-29 20:53:16 +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++)
|
|
|
|
|
{
|
2019-03-25 19:50:03 +01:00
|
|
|
|
try
|
2019-03-25 18:21:05 +01:00
|
|
|
|
{
|
|
|
|
|
_dbMigrator.MigrateMsSqlDatabase(true, cancellationToken);
|
|
|
|
|
// TODO: Maybe flip a flag somewhere to indicate migration is complete??
|
2022-08-29 20:53:16 +02:00
|
|
|
|
break;
|
|
|
|
|
}
|
2020-03-27 19:36:37 +01:00
|
|
|
|
catch (SqlException e)
|
2022-08-29 20:53:16 +02:00
|
|
|
|
{
|
2020-03-27 19:36:37 +01:00
|
|
|
|
if (i >= maxMigrationAttempts)
|
2019-03-25 18:21:05 +01:00
|
|
|
|
{
|
|
|
|
|
_logger.LogError(e, "Database failed to migrate.");
|
|
|
|
|
throw;
|
|
|
|
|
}
|
2020-03-27 19:36:37 +01:00
|
|
|
|
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 20:53:16 +02:00
|
|
|
|
}
|
2019-03-25 18:21:05 +01:00
|
|
|
|
|
|
|
|
|
public virtual Task StopAsync(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
return Task.FromResult(0);
|
|
|
|
|
}
|
2022-08-29 20:53:16 +02:00
|
|
|
|
|
2019-03-25 18:21:05 +01:00
|
|
|
|
public virtual void Dispose()
|
2022-08-29 20:53:16 +02:00
|
|
|
|
{ }
|
2019-03-25 18:21:05 +01:00
|
|
|
|
}
|