DocSpace-buildtools/common/Tools/ASC.MigrationPersonalToDocspace/MigrationCreator.cs

293 lines
11 KiB
C#
Raw Normal View History

// (c) Copyright Ascensio System SIA 2010-2022
//
// This program is a free software product.
// You can redistribute it and/or modify it under the terms
// of the GNU Affero General Public License (AGPL) version 3 as published by the Free Software
// Foundation. In accordance with Section 7(a) of the GNU AGPL its Section 15 shall be amended
// to the effect that Ascensio System SIA expressly excludes the warranty of non-infringement of
// any third-party rights.
//
// This program is distributed WITHOUT ANY WARRANTY, without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For details, see
// the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
//
// You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, EU, LV-1021.
//
// The interactive user interfaces in modified source and object code versions of the Program must
// display Appropriate Legal Notices, as required under Section 5 of the GNU AGPL version 3.
//
// Pursuant to Section 7(b) of the License you must retain the original Product logo when
// distributing the program. Pursuant to Section 7(e) we decline to grant you any rights under
// trademark law for use of our trademarks.
//
// All the Product's GUI elements, including illustrations and icon sets, as well as technical writing
// content are licensed under the terms of the Creative Commons Attribution-ShareAlike 4.0
// International. See the License terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
namespace ASC.Migration.PersonalToDocspace.Creator;
2022-11-07 12:58:11 +00:00
[Scope]
public class MigrationCreator
{
2022-08-14 22:12:59 +00:00
private readonly IHostEnvironment _hostEnvironment;
private readonly IConfiguration _configuration;
2022-09-13 14:11:23 +00:00
private readonly TenantDomainValidator _tenantDomainValidator;
private readonly TempStream _tempStream;
private readonly DbFactory _dbFactory;
private readonly StorageFactory _storageFactory;
2022-11-01 09:27:29 +00:00
private readonly StorageFactoryConfig _storageFactoryConfig;
private readonly ModuleProvider _moduleProvider;
private List<IModuleSpecifics> _modules;
private string _pathToSave;
private string _userName;
2022-11-30 16:03:44 +00:00
private string _toRegion;
2022-11-01 09:27:29 +00:00
private int _tenant;
private readonly int _limit = 1000;
private readonly List<ModuleName> _namesModules = new List<ModuleName>()
{
ModuleName.Core,
ModuleName.Files,
ModuleName.Files2,
ModuleName.Tenants,
ModuleName.WebStudio
2022-11-01 09:27:29 +00:00
};
public MigrationCreator(
IHostEnvironment hostEnvironment,
IConfiguration configuration,
TenantDomainValidator tenantDomainValidator,
TempStream tempStream,
DbFactory dbFactory,
StorageFactory storageFactory,
StorageFactoryConfig storageFactoryConfig,
ModuleProvider moduleProvider)
{
_hostEnvironment = hostEnvironment;
_configuration = configuration;
_tenantDomainValidator = tenantDomainValidator;
_tempStream = tempStream;
_dbFactory = dbFactory;
_storageFactory = storageFactory;
_storageFactoryConfig = storageFactoryConfig;
_moduleProvider = moduleProvider;
}
2022-11-30 16:03:44 +00:00
public async Task<string> Create(int tenant, string userName, string toRegion)
2022-11-01 09:27:29 +00:00
{
2022-11-30 16:03:44 +00:00
Init(tenant, userName, toRegion);
2022-11-01 09:27:29 +00:00
var id = GetId();
2022-11-07 12:58:11 +00:00
var fileName = _userName + ".tar.gz";
var path = Path.Combine(_pathToSave, fileName);
2022-11-01 09:27:29 +00:00
using (var writer = new ZipWriteOperator(_tempStream, path))
{
DoMigrationDb(id, writer);
await DoMigrationStorage(id, writer);
2022-11-07 12:58:11 +00:00
}
return fileName;
2022-11-01 09:27:29 +00:00
}
2022-11-30 16:03:44 +00:00
private void Init(int tenant, string userName, string toRegion)
{
2022-11-01 09:27:29 +00:00
_modules = _moduleProvider.AllModules.Where(m => _namesModules.Contains(m.ModuleName)).ToList();
2022-08-14 22:12:59 +00:00
_pathToSave = "";
2022-11-30 16:03:44 +00:00
_toRegion = toRegion;
2022-08-14 22:12:59 +00:00
_userName = userName;
_tenant = tenant;
2022-11-01 09:27:29 +00:00
}
2022-08-14 22:12:59 +00:00
private Guid GetId()
{
try
2022-11-01 09:27:29 +00:00
{
2022-11-30 16:03:44 +00:00
var userDbContext = _dbFactory.CreateDbContext<UserDbContext>();
2022-11-29 13:38:44 +00:00
return userDbContext.Users.FirstOrDefault(q => q.Tenant == _tenant && q.Status == EmployeeStatus.Active && q.UserName == _userName).Id;
2022-08-14 22:12:59 +00:00
}
2022-11-01 09:27:29 +00:00
catch (Exception)
2022-08-14 22:12:59 +00:00
{
throw new Exception("username was not found");
}
}
2022-08-14 22:12:59 +00:00
private void DoMigrationDb(Guid id, IDataWriteOperator writer)
{
foreach (var module in _modules)
{
var tablesToProcess = module.Tables.Where(t => t.InsertMethod != InsertMethod.None).ToList();
2022-11-30 16:03:44 +00:00
using (var connection = _dbFactory.OpenConnection())
{
foreach (var table in tablesToProcess)
{
2022-12-23 10:54:23 +00:00
Console.WriteLine($"backup table {table.Name}");
using (var data = new DataTable(table.Name))
{
ActionInvoker.Try(
state =>
{
data.Clear();
int counts;
var offset = 0;
do
{
var t = (TableInfo)state;
var dataAdapter = _dbFactory.CreateDataAdapter();
2022-09-13 15:13:40 +00:00
dataAdapter.SelectCommand = module.CreateSelectCommand(connection.Fix(), _tenant, t, _limit, offset, id).WithTimeout(600);
counts = ((DbDataAdapter)dataAdapter).Fill(data);
offset += _limit;
} while (counts == _limit);
},
table,
maxAttempts: 5,
onFailure: error => { throw ThrowHelper.CantBackupTable(table.Name, error); });
foreach (var col in data.Columns.Cast<DataColumn>().Where(col => col.DataType == typeof(DateTime)))
{
col.DateTimeMode = DataSetDateTime.Unspecified;
}
module.PrepareData(data);
2022-11-01 09:27:29 +00:00
if (data.TableName == "tenants_tenants")
{
2022-11-07 12:58:11 +00:00
ChangeAlias(data);
ChangeName(data);
}
using (var file = _tempStream.Create())
{
data.WriteXml(file, XmlWriteMode.WriteSchema);
data.Clear();
writer.WriteEntry(KeyHelper.GetTableZipKey(module, data.TableName), file);
}
}
}
}
2022-11-01 09:27:29 +00:00
}
}
2022-08-14 22:12:59 +00:00
private void ChangeAlias(DataTable data)
{
2022-09-05 11:27:38 +00:00
var aliases = GetAliases();
2022-08-14 22:12:59 +00:00
var newAlias = _userName;
2022-09-13 14:11:23 +00:00
while (true)
2022-08-14 22:12:59 +00:00
{
2022-09-13 14:11:23 +00:00
try
2022-08-14 22:12:59 +00:00
{
2022-09-13 14:11:23 +00:00
_tenantDomainValidator.ValidateDomainLength(newAlias);
_tenantDomainValidator.ValidateDomainCharacters(newAlias);
if (aliases.Contains(newAlias))
2022-08-14 22:12:59 +00:00
{
2022-09-13 14:11:23 +00:00
throw new Exception($"Alias is busy");
2022-08-14 22:12:59 +00:00
}
2022-09-13 14:11:23 +00:00
break;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
newAlias = Console.ReadLine();
2022-08-14 22:12:59 +00:00
}
}
data.Rows[0]["alias"] = newAlias;
2022-11-12 21:44:57 +00:00
}
private List<string> GetAliases()
{
using var dbContext = _dbFactory.CreateDbContext<TenantDbContext>(_toRegion);
var tenants = dbContext.Tenants.Select(t => t.Alias).ToList();
var forbidens = dbContext.TenantForbiden.Select(tf => tf.Address).ToList();
return tenants.Union(forbidens).ToList();
2022-11-07 12:58:11 +00:00
}
private void ChangeName(DataTable data)
{
data.Rows[0]["name"] = "";
2022-08-14 22:12:59 +00:00
}
2022-11-01 09:27:29 +00:00
private async Task DoMigrationStorage(Guid id, IDataWriteOperator writer)
{
Console.WriteLine($"start backup storage");
2022-11-01 09:27:29 +00:00
var fileGroups = await GetFilesGroup(id);
foreach (var group in fileGroups)
{
Console.WriteLine($"start backup fileGroup: {group}");
foreach (var file in group)
{
2022-11-01 09:27:29 +00:00
var storage = _storageFactory.GetStorage(_tenant, group.Key);
var file1 = file;
ActionInvoker.Try(state =>
{
var f = (BackupFileInfo)state;
using var fileStream = storage.GetReadStreamAsync(f.Domain, f.Path).Result;
writer.WriteEntry(file1.GetZipKey(), fileStream);
}, file, 5);
}
Console.WriteLine($"end backup fileGroup: {group}");
}
var restoreInfoXml = new XElement(
"storage_restore",
fileGroups
.SelectMany(group => group.Select(file => (object)file.ToXElement()))
.ToArray());
using (var tmpFile = _tempStream.Create())
{
restoreInfoXml.WriteTo(tmpFile);
writer.WriteEntry(KeyHelper.GetStorageRestoreInfoZipKey(), tmpFile);
}
Console.WriteLine($"end backup storage");
}
2022-11-01 09:27:29 +00:00
private async Task<List<IGrouping<string, BackupFileInfo>>> GetFilesGroup(Guid id)
{
2022-11-01 09:27:29 +00:00
var files = (await GetFilesToProcess(id)).ToList();
2022-11-30 16:03:44 +00:00
var backupsContext = _dbFactory.CreateDbContext<BackupsContext>();
2022-11-29 13:38:44 +00:00
var exclude = backupsContext.Backups.AsQueryable().Where(b => b.TenantId == _tenant && b.StorageType == 0 && b.StoragePath != null).ToList();
2022-09-05 11:27:38 +00:00
files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains($"/file_{e.StoragePath}/"))).ToList();
return files.GroupBy(file => file.Module).ToList();
}
2022-11-01 09:27:29 +00:00
protected async Task<IEnumerable<BackupFileInfo>> GetFilesToProcess(Guid id)
{
2022-11-01 09:27:29 +00:00
var files = new List<BackupFileInfo>();
2022-11-30 16:03:44 +00:00
foreach (var module in _storageFactoryConfig.GetModuleList().Where(m => m == "files"))
{
2022-11-30 16:03:44 +00:00
var store = _storageFactory.GetStorage(_tenant, module);
var domains = _storageFactoryConfig.GetDomainList(module).ToArray();
foreach (var domain in domains)
{
2022-11-01 09:27:29 +00:00
files.AddRange(await store.ListFilesRelativeAsync(domain, "\\", "*.*", true).Select(path => new BackupFileInfo(domain, module, path, _tenant)).ToListAsync());
}
2022-11-01 09:27:29 +00:00
files.AddRange(await
store.ListFilesRelativeAsync(string.Empty, "\\", "*.*", true)
.Where(path => domains.All(domain => !path.Contains(domain + "/")))
.Select(path => new BackupFileInfo(string.Empty, module, path, _tenant))
.ToListAsync());
}
2022-11-29 13:38:44 +00:00
2022-11-30 16:03:44 +00:00
var filesDbContext = _dbFactory.CreateDbContext<FilesDbContext>();
2022-11-29 13:38:44 +00:00
files = files.Where(f => UserIsFileOwner(id, f, filesDbContext)).ToList();
return files.Distinct();
}
2022-08-14 22:12:59 +00:00
private bool UserIsFileOwner(Guid id, BackupFileInfo fileInfo, FilesDbContext filesDbContext)
{
var stringId = id.ToString();
return filesDbContext.Files.Any(
f => f.CreateBy == id &&
f.TenantId == _tenant &&
fileInfo.Path.Contains("\\file_" + f.Id + "\\"));
}
}