DeactivateTemplates
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
namespace PARR.BLL.Domain.Mq
|
||||
{
|
||||
/// <summary>
|
||||
/// Модель в MQ, запрос на генерацию шаблона
|
||||
/// </summary>
|
||||
public class GeneratorTemplateMq
|
||||
{
|
||||
/// <summary>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.BLL.Contracts;
|
||||
using PARR.BLL.Domain.Mq;
|
||||
using PARR.BLL.Services.Interfaces;
|
||||
using PARR.DAL.Models;
|
||||
using PARR.GeneratorTemplates.Services;
|
||||
using PARR.GeneratorTemplates.Settings;
|
||||
|
||||
namespace PARR.GeneratorTemplates
|
||||
@@ -9,41 +14,50 @@ namespace PARR.GeneratorTemplates
|
||||
private readonly MqSettings mqSettings;
|
||||
private readonly IMqService mqService;
|
||||
private readonly ILogger<GeneratorTemplate> logger;
|
||||
private readonly ITransformService transformService;
|
||||
private readonly IValidatorService validatorService;
|
||||
private readonly IServiceProvider serviceProvider;
|
||||
|
||||
public GeneratorTemplate(
|
||||
MqSettings mqSettings,
|
||||
IMqService mqService,
|
||||
ILogger<GeneratorTemplate> logger
|
||||
ILogger<GeneratorTemplate> logger,
|
||||
ITransformService transformService,
|
||||
IValidatorService validatorService,
|
||||
IServiceProvider serviceProvider
|
||||
)
|
||||
{
|
||||
this.mqSettings = mqSettings;
|
||||
this.mqService = mqService;
|
||||
this.logger = logger;
|
||||
this.transformService = transformService;
|
||||
this.validatorService = validatorService;
|
||||
this.serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
public void Start()
|
||||
//TODO: метод не async, удалить позже асинк в worker
|
||||
public async Task Start()
|
||||
{
|
||||
mqService.Received += (msg) =>
|
||||
{
|
||||
logger.LogInformation($"Привет откуда надо!!! ${msg}");
|
||||
//todo: идем дальеш!
|
||||
//mqService.Received += async (msg) =>
|
||||
|
||||
// создать отдельный метод
|
||||
// преобразовать json в модель
|
||||
// попробовать поиск по регулярке
|
||||
//{
|
||||
// logger.LogInformation($"Привет откуда надо!!! ${msg}");
|
||||
// //todo: идем дальеш!
|
||||
|
||||
// проверить как ту дела с асинком
|
||||
// логгер работает в разных потоках все таки или нет?
|
||||
string msg = "{\"WorkId\":\"91219bec-e5f7-4a1a-b4c9-c135035d2498\",\"ApplicationId\":\"13044a1f-fa0c-476f-b501-2b8d06bac9f8\",\"Action\":\"deactivate\",\"Ek\":\"вРТ-*RZD\"}";
|
||||
await GenerateTemplates(msg);
|
||||
|
||||
// поиск в существующих шаблонах, есть ли такие и есть ли у них эти работы
|
||||
// поиск в хостах эк которых еще нет в шаблонах и у них такие работы
|
||||
// генерим список и вставляем в шаблоны
|
||||
};
|
||||
// // проверить как ту дела с асинком
|
||||
// // логгер работает в разных потоках все таки или нет?
|
||||
|
||||
var isConnected = mqService.InitConsumer(mqSettings);
|
||||
//};
|
||||
|
||||
if (!isConnected)
|
||||
throw new Exception("Ошибка при подключении к RabbitMq");
|
||||
|
||||
|
||||
//var isConnected = mqService.InitConsumer(mqSettings);
|
||||
|
||||
//if (!isConnected)
|
||||
// throw new Exception("Ошибка при подключении к RabbitMq");
|
||||
|
||||
|
||||
}
|
||||
@@ -52,5 +66,48 @@ namespace PARR.GeneratorTemplates
|
||||
{
|
||||
mqService.Dispose();
|
||||
}
|
||||
|
||||
|
||||
private async Task GenerateTemplates(string msg)
|
||||
{
|
||||
logger.LogDebug($"Получили запрос: {msg}");
|
||||
|
||||
var query = transformService.GetModelFromJson<GeneratorTemplateMq>(msg);
|
||||
if (query == null)
|
||||
return;
|
||||
|
||||
if (!await validatorService.IsValidApplicationAndWorksAsync(query.ApplicationId, query.WorkId))
|
||||
{
|
||||
logger.LogError($"Невалидны параметры {nameof(query.ApplicationId)}: {query.ApplicationId}, " +
|
||||
$"{nameof(query.WorkId)}: {query.WorkId}," +
|
||||
$" нет таких значений или они не связаны в таблице ${nameof(ApplicationsInWork)}");
|
||||
return;
|
||||
}
|
||||
|
||||
Enum.TryParse(typeof(GenerateTemplateActionsEnum), query.Action, true, out var action);
|
||||
|
||||
using (var scope = serviceProvider.CreateScope())
|
||||
{
|
||||
var templateManager = scope.ServiceProvider.GetService<ITemplateManager>();
|
||||
if (templateManager == null)
|
||||
throw new Exception($"Не найден сервис: {nameof(ITemplateManager)}");
|
||||
|
||||
switch (action)
|
||||
{
|
||||
case GenerateTemplateActionsEnum.create:
|
||||
await templateManager.CreateTemplates(query);
|
||||
break;
|
||||
|
||||
case GenerateTemplateActionsEnum.deactivate:
|
||||
await templateManager.DeactivateTemplates(query);
|
||||
break;
|
||||
|
||||
default:
|
||||
logger.LogError($"Во входящем запросе, поле {nameof(query.Action)} не содержит допустимых значений");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using PARR.BLL;
|
||||
using PARR.DAL;
|
||||
using PARR.GeneratorTemplates.Services;
|
||||
using PARR.GeneratorTemplates.Settings;
|
||||
|
||||
namespace PARR.GeneratorTemplates
|
||||
@@ -20,6 +21,9 @@ namespace PARR.GeneratorTemplates
|
||||
|
||||
//add other services
|
||||
services.AddTransient<IGeneratorTemplate, GeneratorTemplate>();
|
||||
services.AddTransient<ITransformService, TransformService>();
|
||||
services.AddTransient<IValidatorService, ValidatorService>();
|
||||
services.AddTransient<ITemplateManager, TemplateManager>();
|
||||
}
|
||||
|
||||
//2
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
{
|
||||
public interface IGeneratorTemplate
|
||||
{
|
||||
void Start();
|
||||
Task Start();
|
||||
void Stop();
|
||||
}
|
||||
}
|
||||
|
||||
10
PARR.GeneratorTemplates/Services/ITemplateManager.cs
Normal file
10
PARR.GeneratorTemplates/Services/ITemplateManager.cs
Normal file
@@ -0,0 +1,10 @@
|
||||
using PARR.BLL.Domain.Mq;
|
||||
|
||||
namespace PARR.GeneratorTemplates.Services
|
||||
{
|
||||
internal interface ITemplateManager
|
||||
{
|
||||
Task CreateTemplates(GeneratorTemplateMq query);
|
||||
Task DeactivateTemplates(GeneratorTemplateMq query);
|
||||
}
|
||||
}
|
||||
13
PARR.GeneratorTemplates/Services/ITransformService.cs
Normal file
13
PARR.GeneratorTemplates/Services/ITransformService.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace PARR.GeneratorTemplates.Services
|
||||
{
|
||||
internal interface ITransformService
|
||||
{
|
||||
T? GetModelFromJson<T>(string str);
|
||||
}
|
||||
}
|
||||
7
PARR.GeneratorTemplates/Services/IValidatorService.cs
Normal file
7
PARR.GeneratorTemplates/Services/IValidatorService.cs
Normal file
@@ -0,0 +1,7 @@
|
||||
namespace PARR.GeneratorTemplates.Services
|
||||
{
|
||||
internal interface IValidatorService
|
||||
{
|
||||
Task<bool> IsValidApplicationAndWorksAsync(Guid applicationId, Guid workId);
|
||||
}
|
||||
}
|
||||
71
PARR.GeneratorTemplates/Services/TemplateManager.cs
Normal file
71
PARR.GeneratorTemplates/Services/TemplateManager.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.BLL.Domain.Mq;
|
||||
using PARR.DAL.Contracts;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
|
||||
namespace PARR.GeneratorTemplates.Services
|
||||
{
|
||||
internal class TemplateManager : ITemplateManager
|
||||
{
|
||||
private readonly ITemplateService templateService;
|
||||
private readonly ILogger<TemplateManager> logger;
|
||||
|
||||
public TemplateManager(
|
||||
ITemplateService templateService,
|
||||
ILogger<TemplateManager> logger
|
||||
)
|
||||
{
|
||||
this.templateService = templateService;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public async Task CreateTemplates(GeneratorTemplateMq query)
|
||||
{
|
||||
//Согласно параметрам, находит все ЭК в таблице Hosts.
|
||||
//Далее проверяет есть ли такие шаблоны в таблице Templates, если нет, то создает.
|
||||
//Если такие шаблоны уже есть, ничего с ними не делает.
|
||||
|
||||
//TODO:
|
||||
}
|
||||
|
||||
public async Task DeactivateTemplates(GeneratorTemplateMq query)
|
||||
{
|
||||
//Ищет все активные шаблоны согласно параметрам в таблице Templates, и деактивирует их. Меняем на статус Updating
|
||||
|
||||
// делаем sql форматдля like из запроса.
|
||||
string pattern = query.Ek.Replace("*", "%").ToLower();
|
||||
|
||||
var existTemplates = await templateService.Get()
|
||||
.Include(t => t.Host)
|
||||
.Include(t => t.ApplicationsInWork)
|
||||
.Where(t =>
|
||||
t.IsActive == true
|
||||
&& t.ApplicationsInWork!.ApplicationId == query.ApplicationId
|
||||
&& t.ApplicationsInWork!.WorkId == query.WorkId
|
||||
&& EF.Functions.Like(t.Host!.Ek.ToLower(), pattern)
|
||||
)
|
||||
.ToListAsync();
|
||||
|
||||
if (!existTemplates.Any())
|
||||
{
|
||||
logger.LogInformation("Нет шаблонов для деактивации");
|
||||
return;
|
||||
}
|
||||
|
||||
existTemplates.ForEach(item =>
|
||||
{
|
||||
item.IsActive = false;
|
||||
item.StatusCode = (int)StatusTemplateEnum.Updating;
|
||||
item.DateModified = DateTimeOffset.UtcNow;
|
||||
});
|
||||
|
||||
if (await templateService.CommitAsync())
|
||||
existTemplates.ForEach(item => logger.LogInformation($"Деактивирован шаблон: {item.Name}"));
|
||||
else
|
||||
existTemplates.ForEach(item => logger.LogError($"Ошибка при дактивации шаблона: {item.Name}"));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
29
PARR.GeneratorTemplates/Services/TransformService.cs
Normal file
29
PARR.GeneratorTemplates/Services/TransformService.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace PARR.GeneratorTemplates.Services
|
||||
{
|
||||
internal class TransformService : ITransformService
|
||||
{
|
||||
private readonly ILogger<TransformService> logger;
|
||||
|
||||
public TransformService(ILogger<TransformService> logger)
|
||||
{
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public T? GetModelFromJson<T>(string str)
|
||||
{
|
||||
try
|
||||
{
|
||||
return JsonSerializer.Deserialize<T>(str);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, $"Ошибка при конвертации строки в модель. {str}");
|
||||
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
34
PARR.GeneratorTemplates/Services/ValidatorService.cs
Normal file
34
PARR.GeneratorTemplates/Services/ValidatorService.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using PARR.DAL.Services.Interfaces;
|
||||
|
||||
namespace PARR.GeneratorTemplates.Services
|
||||
{
|
||||
internal class ValidatorService : IValidatorService
|
||||
{
|
||||
private readonly IServiceProvider serviceProvider;
|
||||
|
||||
public ValidatorService(IServiceProvider serviceProvider)
|
||||
{
|
||||
this.serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Проверка, валидны ли поля и связана ли Работа с Приложением
|
||||
/// </summary>
|
||||
/// <param name="applicationId"></param>
|
||||
/// <param name="workId"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<bool> IsValidApplicationAndWorksAsync(Guid applicationId, Guid workId)
|
||||
{
|
||||
using (var scope = serviceProvider.CreateScope())
|
||||
{
|
||||
var service = scope.ServiceProvider.GetService<IApplicationsInWorkService>();
|
||||
|
||||
if (service == null)
|
||||
throw new Exception($"Не найден сервис: {nameof(IApplicationsInWorkService)}");
|
||||
|
||||
return await service.Get(applicationId, workId) != null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,7 @@ namespace PARR.GeneratorTemplatesWorker
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
// todo: обернуть в таск?
|
||||
generatorTemplate.Start();
|
||||
await generatorTemplate.Start();
|
||||
//while (!stoppingToken.IsCancellationRequested)
|
||||
//{
|
||||
// _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
|
||||
Reference in New Issue
Block a user