Compare commits
11 Commits
4af552b29e
...
4c80e247f5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c80e247f5 | ||
|
|
83017c6bee | ||
|
|
323231f907 | ||
|
|
b1c3d90b40 | ||
|
|
511721b798 | ||
|
|
9f42a733e7 | ||
|
|
50556ef605 | ||
|
|
9194d127d2 | ||
|
|
33b0576ccc | ||
|
|
33cdc29e80 | ||
|
|
d7d4713953 |
@@ -20,6 +20,7 @@ variables:
|
||||
PROD_TEMPLATE_UPDATER: "parr/parr-template-updater"
|
||||
PROD_WORKLOAD_BUILDER: "parr/parr-workload-builder"
|
||||
PROD_TASK_RECONCILIATION: "parr/parr-task-reconciliation"
|
||||
PROD_SNAPSHOTS: "parr/parr-snapshots"
|
||||
|
||||
|
||||
stages:
|
||||
@@ -1010,3 +1011,61 @@ prod_task_reconciliation_deploy:
|
||||
- RUNNER: shell-api-swarm-01
|
||||
tags:
|
||||
- ${RUNNER}
|
||||
|
||||
|
||||
### SNAPSHOTS PROD ###
|
||||
prod_snapshots_build:
|
||||
stage: build
|
||||
only:
|
||||
- /^sn[0-9]+\.[0-9]+\.[0-9]+$/
|
||||
except:
|
||||
- branches
|
||||
services:
|
||||
- name: docker:20.10.21-dind
|
||||
command: [
|
||||
"--insecure-registry=10.99.253.167:8090",
|
||||
"--registry-mirror=http://10.99.253.167:8090",
|
||||
"--insecure-registry=harbor.dvgd.rzd",
|
||||
"--tls=false"
|
||||
]
|
||||
variables:
|
||||
DOCKER_HOST: tcp://docker:2375
|
||||
DOCKER_DRIVER: overlay2
|
||||
DOCKER_TLS_CERTDIR: ""
|
||||
script:
|
||||
- APP_VERSION=$(echo $CI_COMMIT_TAG | tr -d sn)
|
||||
- IMAGE_VERSION=$(echo $CI_COMMIT_TAG | sed 's/sn/v/g')
|
||||
- AUTHOR=$CI_COMMIT_AUTHOR
|
||||
- |
|
||||
docker build \
|
||||
-t $REPO/$PROD_SNAPSHOTS:$IMAGE_VERSION \
|
||||
-t $REPO/$PROD_SNAPSHOTS:latest \
|
||||
-t $PROD_SNAPSHOTS:$IMAGE_VERSION \
|
||||
-t $PROD_SNAPSHOTS:latest \
|
||||
--build-arg app_version=$APP_VERSION \
|
||||
--build-arg commit_author="$AUTHOR" \
|
||||
-f PARR.SnapshotWorker/Dockerfile .
|
||||
- docker login -u $HARBOR_PUSH_USER -p $HARBOR_PUSH_PASS $REPO
|
||||
- docker push --all-tags $REPO/$PROD_SNAPSHOTS
|
||||
tags:
|
||||
- docker
|
||||
|
||||
|
||||
prod_snapshots_deploy:
|
||||
stage: deploy
|
||||
environment:
|
||||
name: parr-snapshots
|
||||
only:
|
||||
- /^sn[0-9]+\.[0-9]+\.[0-9]+$/
|
||||
except:
|
||||
- branches
|
||||
script:
|
||||
- IMAGE_VERSION=$(echo $CI_COMMIT_TAG | sed 's/sn/v/g')
|
||||
- docker login -u $HARBOR_PULL_USER -p $HARBOR_PULL_PASS $REPO
|
||||
#- tag=$CI_COMMIT_TAG docker compose up -d
|
||||
- tag=$IMAGE_VERSION docker stack deploy -c docker-compose.snapshots.yml parr-snapshots --with-registry-auth
|
||||
parallel:
|
||||
matrix:
|
||||
- RUNNER: shell-api-swarm-01
|
||||
tags:
|
||||
- ${RUNNER}
|
||||
|
||||
@@ -99,6 +99,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.WorkloadBuilderWorker"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.TaskReconciliationWorker", "PARR.TaskReconciliationWorker\PARR.TaskReconciliationWorker.csproj", "{DB701295-1696-4E1A-9088-D3AECF823BA6}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PARR.SnapshotWorker", "PARR.SnapshotWorker\PARR.SnapshotWorker.csproj", "{F5318808-942F-4EFB-9BC9-00B9F4704EB5}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -275,6 +277,10 @@ Global
|
||||
{DB701295-1696-4E1A-9088-D3AECF823BA6}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{DB701295-1696-4E1A-9088-D3AECF823BA6}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{DB701295-1696-4E1A-9088-D3AECF823BA6}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{F5318808-942F-4EFB-9BC9-00B9F4704EB5}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -2,22 +2,31 @@
|
||||
|
||||
namespace PARR.API.Contracts.V1.Requests.Queries
|
||||
{
|
||||
public class RobotHistoryQuery
|
||||
public record RobotHistoryQuery
|
||||
{
|
||||
/// <summary>
|
||||
/// Фильтр по ИД шаблона
|
||||
/// </summary>
|
||||
public Guid? TemplateId { get; set; }
|
||||
public Guid? TemplateId { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Фильтр по ИД робота
|
||||
/// </summary>
|
||||
public RobotsEnum? RobotCode { get; set; }
|
||||
public RobotsEnum? RobotCode { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Фильтр по уровню истории
|
||||
/// </summary>
|
||||
public RobotHistoryLevelEnum? HistoryLevel { get; set; }
|
||||
public RobotHistoryLevelEnum? HistoryLevel { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Дата начала
|
||||
/// </summary>
|
||||
public DateTimeOffset? DateFrom { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Дата окончания
|
||||
/// </summary>
|
||||
public DateTimeOffset? DateTo { get; init; }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ namespace PARR.API.Controllers.V1
|
||||
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
|
||||
|
||||
IQueryable<RobotHistory> query = robotHistoryService.Get()
|
||||
.AsNoTracking()
|
||||
.Include(t => t.RobotConfiguration)
|
||||
.ThenInclude(t => t!.Template)
|
||||
.Include(t => t.RobotConfiguration)
|
||||
@@ -79,19 +80,38 @@ namespace PARR.API.Controllers.V1
|
||||
if (request.HistoryLevel.HasValue)
|
||||
query = query.Where(t => t.HistoryLevel == (int)request.HistoryLevel);
|
||||
|
||||
if (request.DateFrom.HasValue)
|
||||
{
|
||||
var startDateUtc = request.DateFrom.Value.ToUniversalTime();
|
||||
query = query.Where(t => t.DateCreated >= startDateUtc);
|
||||
}
|
||||
|
||||
if (request.DateTo.HasValue)
|
||||
{
|
||||
var endDateUtc = request.DateTo.Value.ToUniversalTime();
|
||||
query = query.Where(t => t.DateCreated < endDateUtc);
|
||||
}
|
||||
|
||||
var history = await robotHistoryService.GetPage(query, paginationFilter).ToListAsync();
|
||||
|
||||
if (!history.Any())
|
||||
if (history.Count == 0)
|
||||
return NoContent();
|
||||
|
||||
var robotsIp = history.Where(t => !string.IsNullOrEmpty(t.RobotIp)).Select(t => t.RobotIp).Distinct().ToList();
|
||||
var users = await userService.Get().Where(t => robotsIp.Any(x => x == t.Ip)).Distinct().ToListAsync();
|
||||
var usersDictionary = await userService.Get()
|
||||
.AsNoTracking()
|
||||
.Where(t => robotsIp.Contains(t.Ip))
|
||||
.ToDictionaryAsync(t => t.Ip, t => t);
|
||||
|
||||
var response = mapper.Map<List<RobotHistoryResponse>>(history);
|
||||
response.ForEach(item =>
|
||||
foreach (var item in response)
|
||||
{
|
||||
item.User = mapper.Map<UserBaseResponse>(users.FirstOrDefault(t => t.Ip == item.RobotIp));
|
||||
});
|
||||
if (!string.IsNullOrWhiteSpace(item.RobotIp) && usersDictionary.TryGetValue(item.RobotIp, out var user))
|
||||
{
|
||||
item.User = mapper.Map<UserBaseResponse>(user);
|
||||
}
|
||||
}
|
||||
|
||||
var paginationResponse = new PagedResponse<RobotHistoryResponse>(response, true).GetPaginatedProps(paginationFilter, query);
|
||||
|
||||
return Ok(paginationResponse);
|
||||
|
||||
@@ -7,6 +7,7 @@ using PARR.API.Contracts.V1.Responses;
|
||||
using PARR.API.Contracts.V1.Responses.Base;
|
||||
using PARR.API.Controllers.V1.Base;
|
||||
using PARR.API.Services.Interfaces;
|
||||
using PARR.API.Settings;
|
||||
using PARR.Core.Services.RobotTask.Interfaces;
|
||||
using PARR.Domain.Common.Roles;
|
||||
using PARR.Domain.Entities.Base.History;
|
||||
@@ -18,38 +19,22 @@ namespace PARR.API.Controllers.V1
|
||||
[Authorize(Roles = ParrRoles.EsppRobot.RoleOrAdmin)]
|
||||
public class RobotTaskController : BaseApiController
|
||||
{
|
||||
private readonly IRobotTaskService robotTaskService;
|
||||
|
||||
private readonly IMapper mapper;
|
||||
//private readonly SettingsFromDb settingsFromDb;
|
||||
//private readonly IRobotConfigurationRepository robotConfigurationService;
|
||||
//private readonly ILogger<RobotTaskController> logger;
|
||||
private readonly IClientService clientService;
|
||||
//private readonly IRobotHistoryRepository robotHistoryService;
|
||||
//private readonly IShortcodesService shortcodesService;
|
||||
//private readonly INextRunService nextRunService;
|
||||
private readonly IRobotTaskService _robotTaskService;
|
||||
private readonly CommonSettings _commonSettings;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly IClientService _clientService;
|
||||
|
||||
public RobotTaskController(
|
||||
IMapper mapper,
|
||||
//SettingsFromDb settingsFromDb,
|
||||
//IRobotConfigurationRepository robotConfigurationService,
|
||||
//ILogger<RobotTaskController> logger,
|
||||
IClientService clientService,
|
||||
//IRobotHistoryRepository robotHistoryService,
|
||||
//IShortcodesService shortcodesService,
|
||||
//INextRunService nextRunService
|
||||
IRobotTaskService robotTaskService
|
||||
IRobotTaskService robotTaskService,
|
||||
CommonSettings commonSettings
|
||||
)
|
||||
{
|
||||
this.robotTaskService = robotTaskService;
|
||||
this.mapper = mapper;
|
||||
//this.settingsFromDb = settingsFromDb;
|
||||
//this.robotConfigurationService = robotConfigurationService;
|
||||
//this.logger = logger;
|
||||
this.clientService = clientService;
|
||||
//this.robotHistoryService = robotHistoryService;
|
||||
//this.shortcodesService = shortcodesService;
|
||||
//this.nextRunService = nextRunService;
|
||||
_robotTaskService = robotTaskService;
|
||||
_commonSettings = commonSettings;
|
||||
_mapper = mapper;
|
||||
_clientService = clientService;
|
||||
}
|
||||
|
||||
|
||||
@@ -66,314 +51,37 @@ namespace PARR.API.Controllers.V1
|
||||
switch (robotCode)
|
||||
{
|
||||
case RobotsEnum.TemplateOrder:
|
||||
var templateTask = await robotTaskService.GetTemplateTaskAsync(
|
||||
var templateTask = await _robotTaskService.GetTemplateTaskAsync(
|
||||
taskStatusCode,
|
||||
requestQuery.SetInProgressStatus ?? false,
|
||||
clientService.GetClientIp()?.ToString(),
|
||||
_clientService.GetClientIp()?.ToString(),
|
||||
requestQuery.RobotId
|
||||
);
|
||||
var templateResponse = mapper.Map<RobotTaskTemplateResponse>(templateTask);
|
||||
var templateResponse = _mapper.Map<RobotTaskTemplateResponse>(templateTask);
|
||||
|
||||
return Ok(new Response<RobotTaskTemplateResponse>(templateResponse, true));
|
||||
case RobotsEnum.ScheduleOrder:
|
||||
var historyIniciator = new HistoryInitiator
|
||||
{
|
||||
InitiatorComment="Задание роботу, расписание.",
|
||||
InitiatorIp=clientService.GetClientIp()?.ToString(),
|
||||
InitiatorParrComponentId= ParrComponentsEnum.Api
|
||||
InitiatorComment = "Задание роботу, расписание.",
|
||||
InitiatorIp = _clientService.GetClientIp()?.ToString(),
|
||||
InitiatorParrComponentId = ParrComponentsEnum.Api
|
||||
};
|
||||
var scheduleTask = await robotTaskService.GetScheduleTaskAsync(
|
||||
var scheduleTask = await _robotTaskService.GetScheduleTaskAsync(
|
||||
taskStatusCode,
|
||||
requestQuery.SetInProgressStatus ?? false,
|
||||
historyIniciator.InitiatorIp,
|
||||
requestQuery.RobotId,
|
||||
historyIniciator
|
||||
historyIniciator,
|
||||
_commonSettings.ScheduleCooldownDuration
|
||||
);
|
||||
|
||||
var scheduleResponse = mapper.Map<RobotTaskScheduleResponse>(scheduleTask);
|
||||
var scheduleResponse = _mapper.Map<RobotTaskScheduleResponse>(scheduleTask);
|
||||
|
||||
return Ok(new Response<RobotTaskScheduleResponse>(scheduleResponse, true));
|
||||
default:
|
||||
throw new AppValidationException("Некорректное значение robotCode");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#region Old
|
||||
|
||||
// /// <summary>
|
||||
// /// Получить задание для робота по коду робота и по статусу задания
|
||||
// /// </summary>
|
||||
// /// <param name="robotCode"></param>
|
||||
// /// <param name="taskStatusCode"></param>
|
||||
// /// <returns></returns>
|
||||
// [HttpGet(ApiRoutes.RobotTask.GetByRobotAndStatusTask)]
|
||||
// public async Task<IActionResult> GetByRobotAndStatusTask([FromRoute] RobotsEnum robotCode, [FromRoute] TaskStatusEnum taskStatusCode, [FromQuery] RobotTaskQuery requestQuery)
|
||||
// {
|
||||
// //Ищем все задания с превышенным кол-вом попыток и с просроченным временем и ставим им статус ошибки
|
||||
// await robotConfigurationService.MarkExpiredTasksAsFailedAsync(settingsFromDb.RobotAttemptsNumber, settingsFromDb.RobotWaitTime);
|
||||
|
||||
|
||||
// var query = robotConfigurationService.Get()
|
||||
// .AsSingleQuery()
|
||||
// .Where(t => t.RobotCode == (int)robotCode && t.TaskStatusCode == (int)taskStatusCode);
|
||||
|
||||
// switch (robotCode)
|
||||
// {
|
||||
// case RobotsEnum.TemplateOrder:
|
||||
// // шаблоны
|
||||
// query = query
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Field)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Value)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(a => a!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(g => g.GroupType)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(w => w!.Job)
|
||||
// .ThenInclude(t => t!.Tnk)
|
||||
// .ThenInclude(s => s!.Subprocess)
|
||||
// .ThenInclude(p => p!.Process);
|
||||
|
||||
// query = query
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.UnitsInTemplate);
|
||||
|
||||
// break;
|
||||
|
||||
// case RobotsEnum.ScheduleOrder:
|
||||
// //расписание
|
||||
// query = query
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Field)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Unit)
|
||||
// .ThenInclude(t => t!.UnitValues)
|
||||
// .ThenInclude(t => t.Value)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(a => a!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(g => g.GroupType)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(a => a!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(t => t!.EsppSchValues)
|
||||
// .ThenInclude(t => t!.EsppSchTypeConfig)
|
||||
// .ThenInclude(t => t!.EsppSchTypeSchedule)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(t => t!.ScheduleExcludeType)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Job)
|
||||
// .ThenInclude(t => t!.Group)
|
||||
// .ThenInclude(t => t.ScheduleExcludeTypeCalendar)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.Job)
|
||||
// .ThenInclude(t => t!.Tnk)
|
||||
// .Include(t => t.Template)
|
||||
// .ThenInclude(t => t!.UnitsInTemplate);
|
||||
|
||||
// //выбираем только записи с созданными шаблонами (у которых статус 20 или 30), а только потом у них ищем расписания
|
||||
// var createdTemplates = robotConfigurationService.Get()
|
||||
// .Where(t => t.RobotCode == (int)RobotsEnum.TemplateOrder && (t.TaskStatusCode == (int)TaskStatusEnum.Ok))
|
||||
// .Select(t => t.TemplateId);
|
||||
// query = query.Where(t => t.RobotCode == (int)RobotsEnum.ScheduleOrder && createdTemplates.Contains(t.TemplateId));
|
||||
// // query = query.Where(t => t.RobotCode == (int)RobotsEnum.ScheduleOrder && t.TemplateId==Guid.Parse("7cb7c3be-506d-40e0-a63f-4554edb52459"));
|
||||
// break;
|
||||
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
|
||||
|
||||
// // сортируем по NextRun, чтобы те у которых дата след срабатывания ближе к текущей, выполнились скорее
|
||||
// query = query.OrderBy(t => t.Template!.NextRun).ThenBy(t => t.Template!.IsActiveSchedule).ThenBy(t => t.Template.IsActiveTemplate);
|
||||
|
||||
// RobotConfiguration? task = null;
|
||||
|
||||
// //ищем задание в ожидании, если нашли, выбираем его
|
||||
// task = await query.FirstOrDefaultAsync(t => t.RobotStatusCode == (int)RobotStatusEnum.Wait);
|
||||
|
||||
// if (task == null)
|
||||
// {
|
||||
// //ищем задания в работе, которые можно перезапустить
|
||||
// //Поиск по `RobotStatusCode` = 22.
|
||||
// //Далее проверяется `LastStatusUpdated`, что время последнего смены статуса не превышает допустимого(берется из настроек, поле `RobotWaitTime`)
|
||||
// //и что текущая попытка не больше разрешенной(берется из настроек, поле `RobotAttemptsNumber`) - если это так, берется эта запись.
|
||||
|
||||
// var endDate = DateTimeOffset.UtcNow.Add(-settingsFromDb.RobotWaitTime);
|
||||
// task = await query
|
||||
// .FirstOrDefaultAsync(t =>
|
||||
// t.RobotStatusCode == (int)RobotStatusEnum.InProgress
|
||||
// && t.AttemptsNumber < settingsFromDb.RobotAttemptsNumber
|
||||
// && t.LastRobotStatusUpdated < endDate
|
||||
// );
|
||||
// }
|
||||
|
||||
// if (task == null)
|
||||
// return NotFound();
|
||||
|
||||
// if (requestQuery?.SetInProgressStatus == true)
|
||||
// {
|
||||
// var resultSetStatus = await SetInProgressStatusAsync(task.Id);
|
||||
// if (resultSetStatus == false)
|
||||
// {
|
||||
// logger.LogError($"Ошибка при установке статуса {RobotStatusEnum.InProgress.ToString()} для задания RobotConfigutationId {task.Id} (при выдаче задания роботу)");
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при выдаче задания." } }));
|
||||
// }
|
||||
// }
|
||||
|
||||
// switch (robotCode)
|
||||
// {
|
||||
// case RobotsEnum.TemplateOrder:
|
||||
// { //RobotTaskTemplateResponse
|
||||
// var robotTaskTemplateResponse = mapper.Map<RobotTaskTemplateResponse>(task);
|
||||
|
||||
// robotTaskTemplateResponse.FullDescription = NormalizeLineEndingsToCrlf(await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.FullDescription, task.Template!));
|
||||
// robotTaskTemplateResponse.ShortDescription = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.ShortDescription, task.Template!);
|
||||
// robotTaskTemplateResponse.Solution = NormalizeLineEndingsToCrlf(await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.Solution, task.Template!));
|
||||
// robotTaskTemplateResponse.TnkName = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.TnkName, task.Template!);
|
||||
// robotTaskTemplateResponse.WorkName = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.WorkName, task.Template!);
|
||||
// robotTaskTemplateResponse.WorkGroup = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.WorkGroup, task.Template!);
|
||||
// robotTaskTemplateResponse.ResponseArea = await shortcodesService.ApplyShortcodesAsync(robotTaskTemplateResponse.ResponseArea, task.Template!);
|
||||
|
||||
// return Ok(new Response<RobotTaskTemplateResponse>(robotTaskTemplateResponse, true));
|
||||
// }
|
||||
// case RobotsEnum.ScheduleOrder:
|
||||
// { // если был запрос на расписание, проверяем у него nextRun, lastRun, обновляем их
|
||||
// var resultUpdateNextRun = await UpdateNextRunAsync(task);
|
||||
// if (!resultUpdateNextRun)
|
||||
// {
|
||||
// logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}", task.TemplateId);
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при расчете NextRun" } }));
|
||||
// }
|
||||
|
||||
// //RobotTaskScheduleResponse
|
||||
// var robotTaskScheduleResponse = mapper.Map<RobotTaskScheduleResponse>(task);
|
||||
|
||||
// robotTaskScheduleResponse.Timezone = settingsFromDb.EsppScheduleTimezone;
|
||||
|
||||
// robotTaskScheduleResponse.WorkGroup = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.WorkGroup, task.Template!);
|
||||
// robotTaskScheduleResponse.ResponseArea = await shortcodesService.ApplyShortcodesAsync(robotTaskScheduleResponse.ResponseArea, task.Template!);
|
||||
|
||||
// //var nextRunWithRobotTz = nextRunService.GetNextRunWithTimezoneEsppAndResponseArea(task.Template!.NextRun, task.Template!.Job?.Group?.IsResponseAreaTimezone, robotTaskScheduleResponse.ResponseArea);
|
||||
// //nextRun в часовой зоне УЗ Робота ЕСПП
|
||||
// var nextRunWithRobotTz = task.Template!.NextRun.Add(nextRunService.GetEsppAccountOffset());
|
||||
|
||||
// //на всякий случай еще раз проверяем, что дата не устарела и отправляем задание
|
||||
// if (nextRunWithRobotTz < DateTimeOffset.UtcNow)
|
||||
// {
|
||||
// logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}, итоговое значение для робота, меньше чем сейчас {nextRunWithRobotTz}<{now}",
|
||||
// task.TemplateId, nextRunWithRobotTz, DateTimeOffset.UtcNow);
|
||||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при расчете NextRun" } }));
|
||||
// }
|
||||
|
||||
// robotTaskScheduleResponse.NextStart = EsppScheduleHelpers.GetNextRun(nextRunWithRobotTz);
|
||||
// robotTaskScheduleResponse.GenerationTime = EsppScheduleHelpers.GetGenerationTime(nextRunWithRobotTz);
|
||||
|
||||
// return Ok(new Response<RobotTaskScheduleResponse>(robotTaskScheduleResponse, true));
|
||||
// }
|
||||
// default:
|
||||
// break;
|
||||
// }
|
||||
|
||||
// return BadRequest();
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// Обоновить NextRun если он устарел
|
||||
// /// </summary>
|
||||
// /// <param name="task"></param>
|
||||
// /// <returns></returns>
|
||||
// private async Task<bool> UpdateNextRunAsync(RobotConfiguration task)
|
||||
// {
|
||||
// var template = task.Template!;
|
||||
|
||||
// //var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
||||
// var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
// if (!nextRun.HasValue)
|
||||
// {
|
||||
// logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun=null, ошибка в расчетах.", template.Id);
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (nextRun.Value < DateTimeOffset.UtcNow)
|
||||
// {
|
||||
// logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun<Now [{nextRun}<{now}], ошибка в расчетах.", template.Id, nextRun.Value, DateTimeOffset.UtcNow);
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (nextRun != template.NextRun)
|
||||
// {
|
||||
// logger.LogDebug($"Для шаблона id {template.Id} обновляю nextRun, новое значение {nextRun}, старое значение {template.NextRun}");
|
||||
|
||||
// template.LastRun = template.NextRun;
|
||||
// template.NextRun = nextRun.Value;
|
||||
|
||||
// await robotConfigurationService.CommitAsync(new HistoryInitiator { InitiatorComment = "При получении задания роботом, обновил NextRun", InitiatorIp = clientService.GetClientIp()?.ToString(), InitiatorParrComponentId = ParrComponentsEnum.Api });
|
||||
// }
|
||||
|
||||
// return true;
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// Устанавливаем статус "Робот взял в работу", пишем в историю работы роботов инф о начале работ
|
||||
// /// </summary>
|
||||
// /// <param name="taskId"></param>
|
||||
// /// <returns></returns>
|
||||
// private async Task<bool> SetInProgressStatusAsync(Guid taskId)
|
||||
// {
|
||||
// var config = await robotConfigurationService.GetAsync(taskId);
|
||||
|
||||
// //изменение статуса робота
|
||||
// robotConfigurationService.ChangeRobotStatus(RobotStatusEnum.InProgress, config!);
|
||||
|
||||
// if (!await robotConfigurationService.CommitAsync())
|
||||
// return false;
|
||||
|
||||
// //записываем в лог робота
|
||||
// var history = new RobotHistory
|
||||
// {
|
||||
// Id = Guid.NewGuid(),
|
||||
// HistoryLevel = (int)RobotHistoryLevelEnum.Start,
|
||||
// TaskStatusCode = config.TaskStatusCode,
|
||||
// RobotConfigurationId = config.Id,
|
||||
// RobotIp = clientService.GetClientIp()?.ToString()
|
||||
// };
|
||||
|
||||
// if (!await robotHistoryService.CreateAsync(history) || !await robotHistoryService.CommitAsync())
|
||||
// return false;
|
||||
|
||||
// return true;
|
||||
// }
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// Приводит переносы строк в тексте к формату CRLF (\r\n)
|
||||
// /// </summary>
|
||||
// /// <param name="text">Исходный текст</param>
|
||||
// /// <returns>Текст с унифицированными переносами строк</returns>
|
||||
// private string NormalizeLineEndingsToCrlf(string? text)
|
||||
// {
|
||||
// if (string.IsNullOrEmpty(text))
|
||||
// return string.Empty;
|
||||
|
||||
// // Заменяем любые варианты переносов (\r\n, \r, \n) на единый \r\n
|
||||
// return System.Text.RegularExpressions.Regex.Replace(text, @"\r\n|\r|\n", "\r\n");
|
||||
// }
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,6 +23,10 @@ namespace PARR.API.Installers
|
||||
configuration.GetSection(nameof(MonitoringSettings)).Bind(monitoringSettings);
|
||||
services.AddSingleton(monitoringSettings);
|
||||
|
||||
var commonSettings = new CommonSettings();
|
||||
configuration.GetSection(nameof(CommonSettings)).Bind(commonSettings);
|
||||
services.AddSingleton(commonSettings);
|
||||
|
||||
//TODO: add other
|
||||
}
|
||||
}
|
||||
|
||||
15
PARR.API/Settings/CommonSettings.cs
Normal file
15
PARR.API/Settings/CommonSettings.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
namespace PARR.API.Settings
|
||||
{
|
||||
/// <summary>
|
||||
/// Общие настройки API
|
||||
/// </summary>
|
||||
public record CommonSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Период охлаждения (кулдаун) для расписаний.
|
||||
/// Запрещает повторно брать активные шаблоны в работу, если с момента их последнего запуска прошло меньше этого времени.
|
||||
/// Применяется только для инициаторов EsppScheduleSync и NextRun.
|
||||
/// </summary>
|
||||
public TimeSpan ScheduleCooldownDuration { get; init; } = TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
@@ -113,5 +113,8 @@
|
||||
"RabbitMq": {
|
||||
"ThresholdConnections": 33
|
||||
}
|
||||
},
|
||||
"CommonSettings": {
|
||||
"ScheduleCooldownDuration": "03:00:00"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using FluentValidation;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
using PARR.Core.Common.Helpers;
|
||||
using PARR.Core.Common.Implementations;
|
||||
using PARR.Core.Common.Interfaces;
|
||||
@@ -12,6 +13,8 @@ using PARR.Core.Services.RobotTask.Implementations;
|
||||
using PARR.Core.Services.RobotTask.Interfaces;
|
||||
using PARR.Core.Services.Shortcodes;
|
||||
using PARR.Core.Services.Shortcodes.Handlers;
|
||||
using PARR.Core.Services.Snapshots.Implementations;
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
using PARR.Core.Services.TaskServices.Handlers;
|
||||
using PARR.Core.Services.TaskServices.Handlers.Factory;
|
||||
using PARR.Core.Services.TaskServices.Implementations;
|
||||
@@ -25,6 +28,7 @@ using PARR.Core.Services.UnitService.Implementations;
|
||||
using PARR.Core.Services.UnitService.Interfaces;
|
||||
using PARR.Core.Services.Workload.Implementations;
|
||||
using PARR.Core.Services.Workload.Interfaces;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
using PARR.Domain.Enums;
|
||||
using PARR.Domain.Settings;
|
||||
|
||||
@@ -115,6 +119,16 @@ namespace PARR.Core
|
||||
|
||||
#endregion
|
||||
|
||||
#region Сервисы сбора снапшотов
|
||||
|
||||
services.TryAddSingleton<ISnapshotSettings, DefaultSnapshotSettings>();
|
||||
|
||||
services.AddScoped<ISnapshotProvider, RobotConfigurationSnapshotService>();
|
||||
services.AddScoped<ISnapshotProvider, RobotSnapshotService>();
|
||||
// тут другие сервисы, реализующие ISnapshotProvider
|
||||
|
||||
#endregion
|
||||
|
||||
#region Workload
|
||||
|
||||
services.AddScoped<WorkloadCacheService>();
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
using PARR.Core.Repositories.Base;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.Core.Repositories.Interfaces.RobotRepositories
|
||||
{
|
||||
public interface IRobotConfigurationSnapshotRepository : IBaseRepository<RobotConfigurationSnapshot>
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -162,7 +162,7 @@ namespace PARR.Core.Services.NextRunServices.Subservices
|
||||
};
|
||||
|
||||
var key = values[0].Value.Value;
|
||||
if (!regDict.TryGetValue(key, out int regMinutes))
|
||||
if (!regDict.TryGetValue(key, out int regHours))
|
||||
{
|
||||
logger.LogError("Неизвестное значение: {Value}", key);
|
||||
throw new ArgumentException($"Неизвестное значение: {key}");
|
||||
@@ -175,7 +175,7 @@ namespace PARR.Core.Services.NextRunServices.Subservices
|
||||
////TODO: вот это повторяется от метода к методу
|
||||
////Если итоговая дата указывает на прошлое, то повторяем расчёт и уходим в рекурсию
|
||||
//if (calcDay < DateTimeOffset.UtcNow /* || calcDay <= referenceDate*/)
|
||||
// calcDay = GetNextDateRegularly(values, calcDay.AddHours(regMinutes));
|
||||
// calcDay = GetNextDateRegularly(values, calcDay.AddHours(regHours));
|
||||
|
||||
//return calcDay;
|
||||
|
||||
@@ -189,12 +189,12 @@ namespace PARR.Core.Services.NextRunServices.Subservices
|
||||
// Сразу вычисляем, сколько целых интервалов нужно прибавить, чтобы догнать текущее время.
|
||||
if (calcDay < nowInTargetZone)
|
||||
{
|
||||
double totalMinutesPast = (nowInTargetZone - calcDay).TotalMinutes;
|
||||
double totalHoursPast = (nowInTargetZone - calcDay).TotalHours;
|
||||
|
||||
// Считаем, сколько полных интервалов помещается в этот отрезок времени
|
||||
long intervalsToSkip = (long)Math.Ceiling(totalMinutesPast / regMinutes);
|
||||
long intervalsToSkip = (long)Math.Ceiling(totalHoursPast / regHours);
|
||||
|
||||
calcDay = calcDay.AddMinutes(intervalsToSkip * regMinutes);
|
||||
calcDay = calcDay.AddHours(intervalsToSkip * regHours);
|
||||
}
|
||||
|
||||
// Проверяем условия и делаем микро-шаги, если необходимо
|
||||
@@ -204,7 +204,7 @@ namespace PARR.Core.Services.NextRunServices.Subservices
|
||||
{
|
||||
return calcDay;
|
||||
}
|
||||
calcDay = calcDay.AddMinutes(regMinutes);
|
||||
calcDay = calcDay.AddHours(regHours);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Core.Repositories.Interfaces.RobotRepositories;
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
using PARR.Domain.DTOs.RobotSnapshotDTO;
|
||||
using PARR.Domain.DTOs.User;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
@@ -9,21 +11,32 @@ using PARR.Domain.Exceptions;
|
||||
|
||||
namespace PARR.Core.Services.RobotSnapshotServices
|
||||
{
|
||||
internal class RobotSnapshotService : IRobotSnapshotService
|
||||
internal class RobotSnapshotService : IRobotSnapshotService, ISnapshotProvider
|
||||
{
|
||||
private readonly IRobotSnapshotRepository _robotSnapshotRepository;
|
||||
private readonly IUserRepository _userRepository;
|
||||
private readonly IMapper _mapper;
|
||||
private readonly ILogger<RobotSnapshotService> _logger;
|
||||
private readonly ISnapshotSettings _snapshotSettings;
|
||||
|
||||
// Тут любое значение, не используем метод создания снапшота
|
||||
public TimeSpan Interval => TimeSpan.FromHours(1);
|
||||
|
||||
public TimeSpan RetentionPeriod => _snapshotSettings.RobotSnapshotRetentionPeriod;
|
||||
|
||||
public RobotSnapshotService(
|
||||
IRobotSnapshotRepository robotSnapshotRepository,
|
||||
IUserRepository userRepository,
|
||||
IMapper mapper
|
||||
IMapper mapper,
|
||||
ILogger<RobotSnapshotService> logger,
|
||||
ISnapshotSettings snapshotSettings
|
||||
)
|
||||
{
|
||||
_robotSnapshotRepository = robotSnapshotRepository;
|
||||
_userRepository = userRepository;
|
||||
_mapper = mapper;
|
||||
_logger = logger;
|
||||
_snapshotSettings = snapshotSettings;
|
||||
}
|
||||
|
||||
|
||||
@@ -348,5 +361,26 @@ namespace PARR.Core.Services.RobotSnapshotServices
|
||||
}
|
||||
|
||||
|
||||
public Task TakeSnapshotAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Метод пустой! Нам не нужно собирать данные по таймеру,
|
||||
// так как они и так пишутся сюда через контроллер API.
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
|
||||
public async Task CleanUpOldSnapshotsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var thresholdDate = DateTimeOffset.UtcNow - RetentionPeriod;
|
||||
|
||||
_logger.LogInformation("[{ServiceName}] Запуск очистки старых снапшотов. Удаление данных старше {ThresholdDate}", GetType().Name, thresholdDate);
|
||||
|
||||
// Удаляем старые записи напрямую в PostgreSQL
|
||||
var deletedCount = await _robotSnapshotRepository.Get()
|
||||
.Where(s => s.DateCreated < thresholdDate)
|
||||
.ExecuteDeleteAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("[{ServiceName}] Очистка завершена. Удалено устаревших строк снапшотов: {Count}", GetType().Name, deletedCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
|
||||
public async Task<RobotTaskTemplate> GetTemplateTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId)
|
||||
{
|
||||
var templateTask = await GetTaskAsync(RobotsEnum.TemplateOrder, taskStatusCode, acquireTask, robotIp, robotId);
|
||||
var templateTask = await GetTaskAsync(RobotsEnum.TemplateOrder, taskStatusCode, acquireTask, robotIp, robotId, TimeSpan.Zero);
|
||||
|
||||
var task = mapper.Map<RobotTaskTemplate>(templateTask);
|
||||
|
||||
@@ -72,9 +72,9 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
}
|
||||
|
||||
|
||||
public async Task<RobotTaskSchedule> GetScheduleTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, IHistoryInitiator historyInitiator)
|
||||
public async Task<RobotTaskSchedule> GetScheduleTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, IHistoryInitiator historyInitiator, TimeSpan scheduleCooldownDuration)
|
||||
{
|
||||
var scheduleTask = await GetTaskAsync(RobotsEnum.ScheduleOrder, taskStatusCode, acquireTask, robotIp, robotId);
|
||||
var scheduleTask = await GetTaskAsync(RobotsEnum.ScheduleOrder, taskStatusCode, acquireTask, robotIp, robotId, scheduleCooldownDuration);
|
||||
|
||||
// Проверяем nextRun, lastRun, обновляем их
|
||||
|
||||
@@ -121,14 +121,14 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
/// <param name="robotIp"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotFoundException"></exception>
|
||||
private async Task<RobotConfiguration> GetTaskAsync(RobotsEnum robotCode, TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId)
|
||||
private async Task<RobotConfiguration> GetTaskAsync(RobotsEnum robotCode, TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, TimeSpan scheduleCooldownDuration)
|
||||
{
|
||||
// 1. Ищем все задания с превышенным кол-вом попыток и просроченным временем, ставим им статус ошибки
|
||||
await robotConfigurationRepository.MarkExpiredTasksAsFailedAsync(settingsFromDb.RobotAttemptsNumber, settingsFromDb.RobotWaitTime);
|
||||
|
||||
|
||||
// 2. Ищем доступные задания
|
||||
var availableTasks = await GetAvailableTasksAsync(robotCode, taskStatusCode);
|
||||
var availableTasks = await GetAvailableTasksAsync(robotCode, taskStatusCode, scheduleCooldownDuration);
|
||||
|
||||
if (availableTasks.Count == 0)
|
||||
throw new NotFoundException("Нет доступных заданий для робота");
|
||||
@@ -137,7 +137,7 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
|
||||
if (acquireTask)
|
||||
{
|
||||
// Берем задание в работу, устанавливаем ей статус "В работе"
|
||||
// Берем задание в работу, устанавливаем ему статус "В работе"
|
||||
acquiredTaskId = await AcquireTaskAsync(availableTasks, robotIp, robotId);
|
||||
|
||||
if (acquiredTaskId == null)
|
||||
@@ -165,21 +165,35 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
/// <param name="robotCode"></param>
|
||||
/// <param name="taskStatusCode"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<List<Guid>> GetAvailableTasksAsync(RobotsEnum robotCode, TaskStatusEnum taskStatusCode)
|
||||
private async Task<List<Guid>> GetAvailableTasksAsync(RobotsEnum robotCode, TaskStatusEnum taskStatusCode, TimeSpan scheduleCooldownDuration)
|
||||
{
|
||||
var query = robotConfigurationRepository.Get()
|
||||
.AsNoTracking()
|
||||
.Where(t => t.RobotCode == (int)robotCode && t.TaskStatusCode == (int)taskStatusCode);
|
||||
.Where(t => t.RobotCode == (int)robotCode/* && t.TaskStatusCode == (int)taskStatusCode*/);
|
||||
|
||||
// Если это задание для робота расписаний
|
||||
if (robotCode == RobotsEnum.ScheduleOrder)
|
||||
{
|
||||
// Выбираем только записи с созданными шаблонами (у которых статус 30), а только потом ищем у них расписания
|
||||
var createdTemplates = robotConfigurationRepository.Get()
|
||||
.Where(t => t.RobotCode == (int)RobotsEnum.TemplateOrder && t.TaskStatusCode == (int)TaskStatusEnum.Ok)
|
||||
.Select(t => t.TemplateId);
|
||||
#region Старый не оптимизированный запрос
|
||||
//var createdTemplates = robotConfigurationRepository.Get()
|
||||
// .Where(t => t.RobotCode == (int)RobotsEnum.TemplateOrder && t.TaskStatusCode == (int)TaskStatusEnum.Ok)
|
||||
// .Select(t => t.TemplateId);
|
||||
//query = query.Where(t => createdTemplates.Contains(t.TemplateId));
|
||||
#endregion
|
||||
query = query.Where(t => t.Template!.RobotConfigurations.Any(x => x.RobotCode == (int)RobotsEnum.TemplateOrder && x.TaskStatusCode == (int)TaskStatusEnum.Ok));
|
||||
|
||||
query = query.Where(t => createdTemplates.Contains(t.TemplateId));
|
||||
|
||||
// Не берем шаблоны, у которых lastRun + 3 часа < сейчас, и у них последний инициатор был или nextRun (10) или esppSchedule (5), это условие применяется только к активированным расписаниям
|
||||
var cooldownThreshold = DateTimeOffset.UtcNow.Add(-scheduleCooldownDuration);
|
||||
query = query.Where(t =>
|
||||
// Условие кулдауна: проверяем, попадает ли шаблон под ЗАПРЕТ
|
||||
!(
|
||||
t.Template!.IsActiveSchedule
|
||||
&& (t.Template.InitiatorParrComponentId == ParrComponentsEnum.EsppScheduleSync || t.Template.InitiatorParrComponentId == ParrComponentsEnum.NextRun)
|
||||
&& t.Template.LastRun >= cooldownThreshold
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Сортируем по nextRun, чтобы те, у кого nextRun ближе к текущей, выполнились скорее
|
||||
@@ -189,7 +203,14 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
var tasks = new List<Guid>();
|
||||
|
||||
// Ещем первые 10 заданий в статусе ОЖИДАНИЕ
|
||||
tasks = await query.Where(t => t.RobotStatusCode == (int)RobotStatusEnum.Wait).Take(TakeTasks).Select(t => t.Id).ToListAsync();
|
||||
tasks = await query
|
||||
.Where(t =>
|
||||
t.RobotStatusCode == (int)RobotStatusEnum.Wait
|
||||
&& t.TaskStatusCode == (int)taskStatusCode
|
||||
).Take(TakeTasks)
|
||||
.Select(t => t.Id)
|
||||
.ToListAsync();
|
||||
|
||||
|
||||
logger.LogDebug("Найдено заданий в статусе 'Ожидание' {Count} шт. Робот '{Robot}'", tasks.Count, robotCode.ToString());
|
||||
|
||||
@@ -203,6 +224,7 @@ namespace PARR.Core.Services.RobotTask.Implementations
|
||||
var endDate = DateTimeOffset.UtcNow.Add(-settingsFromDb.RobotWaitTime);
|
||||
|
||||
tasks = await query.Where(t => t.RobotStatusCode == (int)RobotStatusEnum.InProgress
|
||||
&& t.TaskStatusCode==(int)taskStatusCode
|
||||
&& t.AttemptsNumber < settingsFromDb.RobotAttemptsNumber
|
||||
&& t.LastRobotStatusUpdated < endDate)
|
||||
.Take(TakeTasks)
|
||||
|
||||
@@ -29,7 +29,8 @@ namespace PARR.Core.Services.RobotTask.Interfaces
|
||||
/// <param name="robotIp"></param>
|
||||
/// <param name="robotId"></param>
|
||||
/// <param name="historyInitiator"></param>
|
||||
/// <param name="scheduleCooldownDuration"></param>
|
||||
/// <returns></returns>
|
||||
Task<RobotTaskSchedule> GetScheduleTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, IHistoryInitiator historyInitiator);
|
||||
Task<RobotTaskSchedule> GetScheduleTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, IHistoryInitiator historyInitiator, TimeSpan scheduleCooldownDuration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Core.Repositories.Interfaces.RobotRepositories;
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
using PARR.Domain.Exceptions;
|
||||
|
||||
namespace PARR.Core.Services.Snapshots.Implementations
|
||||
{
|
||||
/// <summary>
|
||||
/// Снапшоты для таблицы RobotConfiguration
|
||||
/// </summary>
|
||||
internal class RobotConfigurationSnapshotService : ISnapshotProvider
|
||||
{
|
||||
private readonly IRobotConfigurationRepository _robotConfigurationRepository;
|
||||
private readonly IRobotConfigurationSnapshotRepository _robotConfigurationSnapshotRepository;
|
||||
private readonly ILogger<RobotConfigurationSnapshotService> _logger;
|
||||
private readonly ISnapshotSettings _snapshotSettings;
|
||||
|
||||
public TimeSpan Interval => _snapshotSettings.RobotConfigurationSnapshotInterval;// TimeSpan.FromMinutes(2);
|
||||
|
||||
public TimeSpan RetentionPeriod => _snapshotSettings.RobotConfigurationSnapshotRetentionPeriod;//TimeSpan.FromDays(60);
|
||||
|
||||
public RobotConfigurationSnapshotService(
|
||||
IRobotConfigurationRepository robotConfigurationRepository,
|
||||
IRobotConfigurationSnapshotRepository robotConfigurationSnapshotRepository,
|
||||
ILogger<RobotConfigurationSnapshotService> logger,
|
||||
ISnapshotSettings snapshotSettings
|
||||
)
|
||||
{
|
||||
_robotConfigurationRepository = robotConfigurationRepository;
|
||||
_robotConfigurationSnapshotRepository = robotConfigurationSnapshotRepository;
|
||||
_logger = logger;
|
||||
_snapshotSettings = snapshotSettings;
|
||||
}
|
||||
|
||||
|
||||
public async Task TakeSnapshotAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
_logger.LogDebug("Сбор метрик для снапшота RobotConfigurations...");
|
||||
|
||||
var stats = await _robotConfigurationRepository.Get()
|
||||
.GroupBy(t => new { t.RobotCode, t.RobotStatusCode, t.TaskStatusCode })
|
||||
.Select(g => new
|
||||
{
|
||||
g.Key.RobotCode,
|
||||
g.Key.RobotStatusCode,
|
||||
g.Key.TaskStatusCode,
|
||||
Count = g.Count()
|
||||
})
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
if (!stats.Any())
|
||||
{
|
||||
_logger.LogDebug("Нет активных заданий роботов для создания снапшота.");
|
||||
return;
|
||||
}
|
||||
|
||||
var snapshots = stats.Select(s => new RobotConfigurationSnapshot
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
DateCreated = now,
|
||||
RobotCode = s.RobotCode,
|
||||
RobotStatusCode = s.RobotStatusCode,
|
||||
TaskStatusCode = s.TaskStatusCode,
|
||||
Count = s.Count
|
||||
}).ToList();
|
||||
|
||||
if (!await _robotConfigurationSnapshotRepository.AddRangeAsync(snapshots) || !await _robotConfigurationSnapshotRepository.CommitAsync())
|
||||
throw new DbErrorException("Ошибка при сохранении в БД");
|
||||
|
||||
_logger.LogInformation("Успешно сохранен снапшот RobotConfigurations. Записано строк: {Count}. Периодичность: {Interval}", snapshots.Count, Interval);
|
||||
}
|
||||
|
||||
|
||||
public async Task CleanUpOldSnapshotsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
// Вычисляем граничную дату (всё, что было ДО нее — удаляем)
|
||||
var thresholdDate = DateTimeOffset.UtcNow.Subtract(RetentionPeriod);
|
||||
|
||||
_logger.LogInformation("[{ServiceName}] Запуск очистки старых снапшотов. Удаление данных старше {ThresholdDate}", GetType().Name, thresholdDate);
|
||||
|
||||
// Фильтруем старые записи и вызываем ExecuteDeleteAsync для удаления прямо в базе данных
|
||||
var deletedCount = await _robotConfigurationSnapshotRepository.Get()
|
||||
.Where(s => s.DateCreated < thresholdDate)
|
||||
.ExecuteDeleteAsync(cancellationToken);
|
||||
|
||||
_logger.LogInformation("[{ServiceName}] Очистка завершена. Удалено устаревших строк снапшотов: {Count}", GetType().Name, deletedCount);
|
||||
}
|
||||
}
|
||||
}
|
||||
31
PARR.Core/Services/Snapshots/Interfaces/ISnapshotProvider.cs
Normal file
31
PARR.Core/Services/Snapshots/Interfaces/ISnapshotProvider.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
namespace PARR.Core.Services.Snapshots.Interfaces
|
||||
{
|
||||
/// <summary>
|
||||
/// Общий снапшот провайдер.
|
||||
/// Используется для реализации паттерна "Стратегия"
|
||||
/// </summary>
|
||||
public interface ISnapshotProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// Периодичность создания снапшота (не меньше 1 минуты).
|
||||
/// </summary>
|
||||
TimeSpan Interval { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Срок хранения снапшотов (например, 30 дней). Всё, что старше — удаляется.
|
||||
/// </summary>
|
||||
TimeSpan RetentionPeriod { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Метод сбора метрик и записи их в базу данных.
|
||||
/// </summary>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task TakeSnapshotAsync(CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Метод очистки устаревших снапшотов.
|
||||
/// </summary>
|
||||
Task CleanUpOldSnapshotsAsync(CancellationToken cancellationToken);
|
||||
}
|
||||
}
|
||||
35
PARR.Core/Services/Snapshots/Interfaces/ISnapshotSettings.cs
Normal file
35
PARR.Core/Services/Snapshots/Interfaces/ISnapshotSettings.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
namespace PARR.Core.Services.Snapshots.Interfaces
|
||||
{
|
||||
/// <summary>
|
||||
/// Настройки снапшотов
|
||||
/// </summary>
|
||||
public interface ISnapshotSettings
|
||||
{
|
||||
/// <summary>
|
||||
/// Интервал создания снапшотов для таблицы RobotConfiguration
|
||||
/// </summary>
|
||||
TimeSpan RobotConfigurationSnapshotInterval { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Длительность хранения снапшотов для RobotConfiguration в таблице ConfigurationShapshots
|
||||
/// </summary>
|
||||
TimeSpan RobotConfigurationSnapshotRetentionPeriod { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Длительность хранения снапшотов работы роботов в таблице Shapshots
|
||||
/// </summary>
|
||||
TimeSpan RobotSnapshotRetentionPeriod { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Настройки по умолчанию для ISnapshotSettings
|
||||
/// </summary>
|
||||
internal record DefaultSnapshotSettings : ISnapshotSettings
|
||||
{
|
||||
public TimeSpan RobotConfigurationSnapshotInterval => TimeSpan.FromMinutes(2);
|
||||
|
||||
public TimeSpan RobotConfigurationSnapshotRetentionPeriod => TimeSpan.FromDays(60);
|
||||
|
||||
public TimeSpan RobotSnapshotRetentionPeriod => TimeSpan.FromDays(60);
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,7 @@ namespace PARR.DAL.Context
|
||||
#region Robot
|
||||
|
||||
public DbSet<RobotSnapshot> RobotSnapshots { get; set; }
|
||||
public DbSet<RobotConfigurationSnapshot> RobotConfigurationSnapshots { get; set; }
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -242,7 +243,14 @@ namespace PARR.DAL.Context
|
||||
},
|
||||
new { Name = nameof(SettingsFromDb.EsppUnitTag), Description = "Префикс тега в поле ЭК \"Дополнительная информация\"", Value = "ПАРР_" },
|
||||
new { Name = nameof(SettingsFromDb.JobIdForUnusedTemplates), Description = "Job в который перемещаем ниспользованные шаблоны", Value = "8f85a91c-a223-4686-bb69-1f0ee73624f2" },
|
||||
new { Name = nameof(SettingsFromDb.DefaultResponseAreaToTimeOffset), Description = "Зона ответственности для получения тайм зоны по умолчанию для расписаний", Value = "17-МСК" }
|
||||
new { Name = nameof(SettingsFromDb.DefaultResponseAreaToTimeOffset), Description = "Зона ответственности для получения тайм зоны по умолчанию для расписаний", Value = "17-МСК" },
|
||||
new
|
||||
{
|
||||
Name = nameof(SettingsFromDb.MinRelationshipsThresholdPct),
|
||||
Description = "Минимально допустимый процент связей для продолжения синхронизации. Защищает от удаления данных, " +
|
||||
"если передающая система АИХ ИТ передала аномально малый объем связей. 0 — Защита ОТКЛЮЧЕНА, 100 — Строгий режим.",
|
||||
Value = "97"
|
||||
}
|
||||
);
|
||||
});
|
||||
#endregion
|
||||
|
||||
@@ -84,8 +84,12 @@ namespace PARR.DAL
|
||||
services.AddTransient<IParrComponentRepository, ParrComponentRepository>();
|
||||
services.AddTransient<ITemplateStatusTypeRepository, TemplateStatusTypeRepository>();
|
||||
|
||||
services.AddScoped<IRobotSnapshotRepository, RobotSnapshotRepository>();
|
||||
#region Robot
|
||||
|
||||
services.AddScoped<IRobotSnapshotRepository, RobotSnapshotRepository>();
|
||||
services.AddScoped<IRobotConfigurationSnapshotRepository, RobotConfigurationSnapshotRepository>();
|
||||
|
||||
#endregion
|
||||
|
||||
#region Schedule
|
||||
|
||||
|
||||
4090
PARR.DAL/Migrations/20260713002251_tblRobotConfigurationSnapshots.Designer.cs
generated
Normal file
4090
PARR.DAL/Migrations/20260713002251_tblRobotConfigurationSnapshots.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,77 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PARR.DAL.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class tblRobotConfigurationSnapshots : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "ConfigurationSnapshots",
|
||||
schema: "robot",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<Guid>(type: "uuid", nullable: false),
|
||||
DateCreated = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
|
||||
RobotCode = table.Column<int>(type: "integer", nullable: false),
|
||||
RobotStatusCode = table.Column<int>(type: "integer", nullable: false),
|
||||
TaskStatusCode = table.Column<int>(type: "integer", nullable: false),
|
||||
Count = table.Column<int>(type: "integer", nullable: false, comment: "Количество заданий в этой комбинации статусов")
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_ConfigurationSnapshots", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_ConfigurationSnapshots_RobotStatuses_RobotStatusCode",
|
||||
column: x => x.RobotStatusCode,
|
||||
principalTable: "RobotStatuses",
|
||||
principalColumn: "Code",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_ConfigurationSnapshots_Robots_RobotCode",
|
||||
column: x => x.RobotCode,
|
||||
principalTable: "Robots",
|
||||
principalColumn: "Code",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
table.ForeignKey(
|
||||
name: "FK_ConfigurationSnapshots_TaskStatuses_TaskStatusCode",
|
||||
column: x => x.TaskStatusCode,
|
||||
principalTable: "TaskStatuses",
|
||||
principalColumn: "Code",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
},
|
||||
comment: "Снимки заданий роботам");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ConfigurationSnapshots_RobotCode_DateCreated",
|
||||
schema: "robot",
|
||||
table: "ConfigurationSnapshots",
|
||||
columns: new[] { "RobotCode", "DateCreated" });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ConfigurationSnapshots_RobotStatusCode",
|
||||
schema: "robot",
|
||||
table: "ConfigurationSnapshots",
|
||||
column: "RobotStatusCode");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_ConfigurationSnapshots_TaskStatusCode",
|
||||
schema: "robot",
|
||||
table: "ConfigurationSnapshots",
|
||||
column: "TaskStatusCode");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "ConfigurationSnapshots",
|
||||
schema: "robot");
|
||||
}
|
||||
}
|
||||
}
|
||||
4096
PARR.DAL/Migrations/20260714002637_tblSettingsFromDbMinRelationshipsThresholdPct.Designer.cs
generated
Normal file
4096
PARR.DAL/Migrations/20260714002637_tblSettingsFromDbMinRelationshipsThresholdPct.Designer.cs
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace PARR.DAL.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class tblSettingsFromDbMinRelationshipsThresholdPct : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.InsertData(
|
||||
table: "Settings",
|
||||
columns: new[] { "Name", "Description", "Value" },
|
||||
values: new object[] { "MinRelationshipsThresholdPct", "Минимально допустимый процент связей для продолжения синхронизации. Защищает от удаления данных, если передающая система АИХ ИТ передала аномально малый объем связей. 0 — Защита ОТКЛЮЧЕНА, 100 — Строгий режим.", "97" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DeleteData(
|
||||
table: "Settings",
|
||||
keyColumn: "Name",
|
||||
keyValue: "MinRelationshipsThresholdPct");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,7 +175,7 @@ namespace PARR.DAL.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.Job", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.Job", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
@@ -234,7 +234,7 @@ namespace PARR.DAL.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobAutoControl", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobAutoControl", b =>
|
||||
{
|
||||
b.Property<Guid>("JobId")
|
||||
.HasColumnType("uuid");
|
||||
@@ -256,7 +256,7 @@ namespace PARR.DAL.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobFieldFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobFieldFilter", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
@@ -290,7 +290,7 @@ namespace PARR.DAL.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobRelationshipFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobRelationshipFilter", b =>
|
||||
{
|
||||
b.Property<Guid>("UnitFilterId")
|
||||
.HasColumnType("uuid");
|
||||
@@ -321,7 +321,7 @@ namespace PARR.DAL.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobUnitFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobUnitFilter", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
@@ -347,7 +347,7 @@ namespace PARR.DAL.Migrations
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.UnitsInTemplate", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.UnitsInTemplate", b =>
|
||||
{
|
||||
b.Property<Guid>("TemplateId")
|
||||
.HasColumnType("uuid");
|
||||
@@ -1004,6 +1004,42 @@ namespace PARR.DAL.Migrations
|
||||
b.ToTable("RobotConfigurations");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.RobotEntities.RobotConfigurationSnapshot", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("uuid");
|
||||
|
||||
b.Property<int>("Count")
|
||||
.HasColumnType("integer")
|
||||
.HasComment("Количество заданий в этой комбинации статусов");
|
||||
|
||||
b.Property<DateTimeOffset>("DateCreated")
|
||||
.HasColumnType("timestamp with time zone");
|
||||
|
||||
b.Property<int>("RobotCode")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("RobotStatusCode")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.Property<int>("TaskStatusCode")
|
||||
.HasColumnType("integer");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("RobotStatusCode");
|
||||
|
||||
b.HasIndex("TaskStatusCode");
|
||||
|
||||
b.HasIndex("RobotCode", "DateCreated");
|
||||
|
||||
b.ToTable("ConfigurationSnapshots", "robot", t =>
|
||||
{
|
||||
t.HasComment("Снимки заданий роботам");
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.RobotEntities.RobotSnapshot", b =>
|
||||
{
|
||||
b.Property<Guid>("Id")
|
||||
@@ -2490,6 +2526,12 @@ namespace PARR.DAL.Migrations
|
||||
Name = "DefaultResponseAreaToTimeOffset",
|
||||
Description = "Зона ответственности для получения тайм зоны по умолчанию для расписаний",
|
||||
Value = "17-МСК"
|
||||
},
|
||||
new
|
||||
{
|
||||
Name = "MinRelationshipsThresholdPct",
|
||||
Description = "Минимально допустимый процент связей для продолжения синхронизации. Защищает от удаления данных, если передающая система АИХ ИТ передала аномально малый объем связей. 0 — Защита ОТКЛЮЧЕНА, 100 — Строгий режим.",
|
||||
Value = "97"
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3232,7 +3274,7 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("DistributionPeriodType");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.Job", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.Job", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.JobGroupEntities.JobGroup", "Group")
|
||||
.WithMany("Jobs")
|
||||
@@ -3251,18 +3293,18 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("Tnk");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobAutoControl", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobAutoControl", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Job.Job", "Job")
|
||||
b.HasOne("PARR.Domain.Entities.JobEntities.Job", "Job")
|
||||
.WithOne("AutoControl")
|
||||
.HasForeignKey("PARR.Domain.Entities.Job.JobAutoControl", "JobId")
|
||||
.HasForeignKey("PARR.Domain.Entities.JobEntities.JobAutoControl", "JobId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Job");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobFieldFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobFieldFilter", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Unit.UnitField", "UnitField")
|
||||
.WithMany("JobFieldFilters")
|
||||
@@ -3270,7 +3312,7 @@ namespace PARR.DAL.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PARR.Domain.Entities.Job.JobUnitFilter", "UnitFilter")
|
||||
b.HasOne("PARR.Domain.Entities.JobEntities.JobUnitFilter", "UnitFilter")
|
||||
.WithMany("FieldFilters")
|
||||
.HasForeignKey("UnitFilterId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -3281,7 +3323,7 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("UnitFilter");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobRelationshipFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobRelationshipFilter", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Unit.UnitField", "UnitField")
|
||||
.WithMany("RelationshipFilters")
|
||||
@@ -3289,7 +3331,7 @@ namespace PARR.DAL.Migrations
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PARR.Domain.Entities.Job.JobUnitFilter", "UnitFilter")
|
||||
b.HasOne("PARR.Domain.Entities.JobEntities.JobUnitFilter", "UnitFilter")
|
||||
.WithMany("RelationshipFilters")
|
||||
.HasForeignKey("UnitFilterId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -3300,9 +3342,9 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("UnitFilter");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobUnitFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobUnitFilter", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Job.Job", "Job")
|
||||
b.HasOne("PARR.Domain.Entities.JobEntities.Job", "Job")
|
||||
.WithMany("UnitFilters")
|
||||
.HasForeignKey("JobId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -3311,7 +3353,7 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("Job");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.UnitsInTemplate", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.UnitsInTemplate", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Template", "Template")
|
||||
.WithMany("UnitsInTemplate")
|
||||
@@ -3507,6 +3549,33 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("Template");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.RobotEntities.RobotConfigurationSnapshot", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Robot", "Robot")
|
||||
.WithMany("ConfigurationSnapshots")
|
||||
.HasForeignKey("RobotCode")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PARR.Domain.Entities.RobotStatus", "RobotStatus")
|
||||
.WithMany("ConfigurationSnapshots")
|
||||
.HasForeignKey("RobotStatusCode")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.HasOne("PARR.Domain.Entities.TaskStatus", "TaskStatus")
|
||||
.WithMany("ConfigurationSnapshots")
|
||||
.HasForeignKey("TaskStatusCode")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Robot");
|
||||
|
||||
b.Navigation("RobotStatus");
|
||||
|
||||
b.Navigation("TaskStatus");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.RobotHistory", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.RobotHistoryLevel", "RobotHistoryLevel")
|
||||
@@ -3634,7 +3703,7 @@ namespace PARR.DAL.Migrations
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Template", b =>
|
||||
{
|
||||
b.HasOne("PARR.Domain.Entities.Job.Job", "Job")
|
||||
b.HasOne("PARR.Domain.Entities.JobEntities.Job", "Job")
|
||||
.WithMany("Templates")
|
||||
.HasForeignKey("JobId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
@@ -3802,7 +3871,7 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("Periods");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.Job", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.Job", b =>
|
||||
{
|
||||
b.Navigation("AutoControl");
|
||||
|
||||
@@ -3811,7 +3880,7 @@ namespace PARR.DAL.Migrations
|
||||
b.Navigation("UnitFilters");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Job.JobUnitFilter", b =>
|
||||
modelBuilder.Entity("PARR.Domain.Entities.JobEntities.JobUnitFilter", b =>
|
||||
{
|
||||
b.Navigation("FieldFilters");
|
||||
|
||||
@@ -3860,6 +3929,8 @@ namespace PARR.DAL.Migrations
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.Robot", b =>
|
||||
{
|
||||
b.Navigation("ConfigurationSnapshots");
|
||||
|
||||
b.Navigation("RobotConfigurations");
|
||||
});
|
||||
|
||||
@@ -3875,6 +3946,8 @@ namespace PARR.DAL.Migrations
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.RobotStatus", b =>
|
||||
{
|
||||
b.Navigation("ConfigurationSnapshots");
|
||||
|
||||
b.Navigation("RobotConfigurations");
|
||||
});
|
||||
|
||||
@@ -3937,6 +4010,8 @@ namespace PARR.DAL.Migrations
|
||||
|
||||
modelBuilder.Entity("PARR.Domain.Entities.TaskStatus", b =>
|
||||
{
|
||||
b.Navigation("ConfigurationSnapshots");
|
||||
|
||||
b.Navigation("RobotConfigurations");
|
||||
|
||||
b.Navigation("RobotHistories");
|
||||
|
||||
@@ -131,6 +131,7 @@ namespace PARR.DAL.Repositories
|
||||
.ExecuteUpdateAsync(s => s
|
||||
.SetProperty(t => t.RobotStatusCode, (int)RobotStatusEnum.InProgress)
|
||||
.SetProperty(t => t.LastRobotStatusUpdated, DateTimeOffset.UtcNow)
|
||||
.SetProperty(t => t.AttemptsNumber, t => t.AttemptsNumber + 1)
|
||||
);
|
||||
|
||||
return affectedRows > 0;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Core.Repositories.Interfaces.RobotRepositories;
|
||||
using PARR.DAL.Context;
|
||||
using PARR.DAL.Repositories.Base;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
|
||||
namespace PARR.DAL.Repositories.RobotRepositories
|
||||
{
|
||||
internal class RobotConfigurationSnapshotRepository : BaseRepository<RobotConfigurationSnapshot>, IRobotConfigurationSnapshotRepository
|
||||
{
|
||||
public RobotConfigurationSnapshotRepository(ILogger<RobotConfigurationSnapshotRepository> logger, DataContext dataContext) : base(logger, dataContext) { }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
@@ -17,5 +18,7 @@ namespace PARR.Domain.Entities
|
||||
|
||||
|
||||
public ICollection<RobotConfiguration> RobotConfigurations { get; set; } = new HashSet<RobotConfiguration>();
|
||||
|
||||
public ICollection<RobotConfigurationSnapshot> ConfigurationSnapshots { get; set; } = new HashSet<RobotConfigurationSnapshot>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PARR.Domain.Constants;
|
||||
using PARR.Domain.Entities.Base;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace PARR.Domain.Entities.RobotEntities
|
||||
{
|
||||
/// <summary>
|
||||
/// Снимки заданий роботам
|
||||
/// </summary>
|
||||
[Table("ConfigurationSnapshots", Schema = DatabaseSchemas.Robot)]
|
||||
[Index(nameof(RobotCode), nameof(DateCreated))]
|
||||
[Comment("Снимки заданий роботам")]
|
||||
public class RobotConfigurationSnapshot : IBaseEntity
|
||||
{
|
||||
[Key]
|
||||
public Guid Id { get; set; }
|
||||
|
||||
public DateTimeOffset DateCreated { get; set; }
|
||||
|
||||
[NotMapped]
|
||||
public DateTimeOffset? DateModified { get; set; }
|
||||
|
||||
public int RobotCode { get; set; }
|
||||
|
||||
public int RobotStatusCode { get; set; }
|
||||
|
||||
public int TaskStatusCode { get; set; }
|
||||
|
||||
[Comment("Количество заданий в этой комбинации статусов")]
|
||||
public int Count { get; set; }
|
||||
|
||||
|
||||
[ForeignKey(nameof(RobotCode))]
|
||||
public Robot? Robot { get; set; }
|
||||
|
||||
[ForeignKey(nameof(RobotStatusCode))]
|
||||
public RobotStatus? RobotStatus { get; set; }
|
||||
|
||||
[ForeignKey(nameof(TaskStatusCode))]
|
||||
public TaskStatus? TaskStatus { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace PARR.Domain.Entities
|
||||
@@ -19,5 +20,7 @@ namespace PARR.Domain.Entities
|
||||
public string Description { get; set; } = string.Empty;
|
||||
|
||||
public ICollection<RobotConfiguration> RobotConfigurations { get; set; } = new HashSet<RobotConfiguration>();
|
||||
|
||||
public ICollection<RobotConfigurationSnapshot> ConfigurationSnapshots { get; set; } = new HashSet<RobotConfigurationSnapshot>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using PARR.Domain.Entities.RobotEntities;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace PARR.Domain.Entities
|
||||
@@ -21,5 +22,7 @@ namespace PARR.Domain.Entities
|
||||
public ICollection<RobotConfiguration> RobotConfigurations { get; set; } = new HashSet<RobotConfiguration>();
|
||||
|
||||
public ICollection<RobotHistory> RobotHistories { get; set; } = new HashSet<RobotHistory>();
|
||||
|
||||
public ICollection<RobotConfigurationSnapshot> ConfigurationSnapshots { get; set; } = new HashSet<RobotConfigurationSnapshot>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -138,5 +138,19 @@ namespace PARR.Domain.Settings
|
||||
/// Зона ответственности для получения тайм зоны по умолчанию для расписаний
|
||||
/// </summary>
|
||||
public string DefaultResponseAreaToTimeOffset { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Минимально допустимый процент связей для продолжения синхронизации.
|
||||
/// Защищает от удаления данных, если передающая система АИХ ИТ передала аномально малый объем связей.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Диапазон: от 0 до 100
|
||||
/// <list type="bullet">
|
||||
/// <item><description>0 — Защита ОТКЛЮЧЕНА. Синхронизация запишет даже 0 связей (риск затереть данные).</description></item>
|
||||
/// <item><description>100 — Строгий режим. Синхронизация упадет, если пропадет хотя бы одна связь.</description></item>
|
||||
/// <item><description>97 — (Рекомендуется) Стоп, если объем новых связей ниже 97% от предыдущего.</description></item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public int MinRelationshipsThresholdPct { get; set; } = 0;
|
||||
}
|
||||
}
|
||||
@@ -61,69 +61,5 @@ namespace PARR.NextRun
|
||||
}, workerSettings.RepeatEvery);
|
||||
}
|
||||
|
||||
|
||||
///// <summary>
|
||||
///// Рассчет следующей даты срабатываения
|
||||
///// </summary>
|
||||
///// <returns></returns>
|
||||
//private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
|
||||
//{
|
||||
// logger.LogInformation("Начинаю обновлять NextRun по расписанию");
|
||||
|
||||
// await UpdateNextRunAsync(templateService, nextRunService, robotConfigurationService);
|
||||
|
||||
// logger.LogInformation($"Завершено обновление полей NextRun.");
|
||||
//}
|
||||
|
||||
|
||||
//private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
|
||||
//{
|
||||
// // выбираем все шаблоны с просроченным nextRun в статусе Used
|
||||
|
||||
// var templatesForUpdate = await templateService.Get()
|
||||
// .Include(t => t.RobotConfigurations)
|
||||
// .Where(t =>
|
||||
// t.StatusTypeId == TemplateStatusTypeEnum.Used
|
||||
// && t.NextRun < DateTimeOffset.UtcNow
|
||||
// ).ToListAsync();
|
||||
|
||||
// logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count);
|
||||
|
||||
// if (!templatesForUpdate.Any())
|
||||
// return;
|
||||
|
||||
|
||||
// foreach (var template in templatesForUpdate)
|
||||
// {
|
||||
// var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
// if (newNextRun.HasValue)
|
||||
// {
|
||||
// template.LastRun = template.NextRun;
|
||||
// template.NextRun = newNextRun.Value;
|
||||
|
||||
// //так как nextRun обновился, пробуем поставить задание на обновление
|
||||
// var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
|
||||
// robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name);
|
||||
// }
|
||||
// }
|
||||
|
||||
// if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun }))
|
||||
// {
|
||||
// logger.LogInformation("Обновлены значения полей NextRun для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.LogError("Ошибка при обновлении значений полей NextRun, для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count);
|
||||
// }
|
||||
|
||||
//}
|
||||
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -99,81 +99,5 @@ namespace PARR.NextRun
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
///// <summary>
|
||||
///// Обновить все NextRun в JobGroup
|
||||
///// </summary>
|
||||
///// <param name="jobGroupId"></param>
|
||||
///// <returns></returns>
|
||||
//private async Task UpdateNextRunAsync(NextRunUpdateMq queryMq)
|
||||
//{
|
||||
// using var scope = serviceProvider.CreateScope();
|
||||
|
||||
// var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>();
|
||||
// var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunService>();
|
||||
// var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();
|
||||
|
||||
// // Берем шаблоны только в статусе Used
|
||||
// var templates = await templateService.Get()
|
||||
// .Include(t => t.RobotConfigurations)
|
||||
// .Where(t =>
|
||||
// t.Job!.GroupId == queryMq.JobGroupId
|
||||
// && t.StatusTypeId == TemplateStatusTypeEnum.Used
|
||||
// ).ToListAsync();
|
||||
|
||||
// logger.LogInformation("Найдено шаблонов {count} шт. в статусе Used в группе работ {jobGroupId}", templates.Count, queryMq.JobGroupId);
|
||||
|
||||
// if (!templates.Any())
|
||||
// return;
|
||||
|
||||
// var updatedTemplates = 0;
|
||||
|
||||
// foreach (var template in templates)
|
||||
// {
|
||||
// var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
// if (newNextRun == null)
|
||||
// {
|
||||
// logger.LogError("При расчете nextRun для шаблона {templateId}, {templateName} вернулся null", template.Id, template.Name);
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// if (template.NextRun != newNextRun)
|
||||
// {
|
||||
// logger.LogInformation("Обновлен nextRun для шаблона {templateId}, {templateName}, newNextRun: {newNextRun}, oldNextRun: {oldNextRun}",
|
||||
// template.Id, template.Name, newNextRun, template.NextRun);
|
||||
|
||||
// template.LastRun = template.NextRun;
|
||||
// template.NextRun = newNextRun.Value;
|
||||
|
||||
// //так как nextRun обновился, пробуем поставить задание на обновление
|
||||
// var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
|
||||
// robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
|
||||
|
||||
// updatedTemplates++;
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.LogDebug("Не требуется обновлять nextRun для шаблона {templateId}, {templateName}. Рассчитанный и исходный равны. NextRun: {NextRun}",
|
||||
// template.Id, template.Name, template.NextRun);
|
||||
// }
|
||||
// }
|
||||
|
||||
// if (updatedTemplates > 0)
|
||||
// {
|
||||
// if (await templateService.CommitAsync(queryMq.Initiator))
|
||||
// {
|
||||
// logger.LogInformation("Успешно обновлены nextRun у {count} шаблонов, группа работ: {jobGroupId}", updatedTemplates, queryMq.JobGroupId);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.LogError("При сохранении nextRun для шаблонов {count} шт, произошла ошибка при сохранении в БД. JobGroupId: {jobGroupId}", updatedTemplates, queryMq.JobGroupId);
|
||||
// }
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// logger.LogInformation("Для группы работ {jobGroupId}, все nextRun актуальны. Нечего обновлять.", queryMq.JobGroupId);
|
||||
// }
|
||||
//}
|
||||
}
|
||||
}
|
||||
|
||||
39
PARR.SnapshotWorker/Dockerfile
Normal file
39
PARR.SnapshotWorker/Dockerfile
Normal file
@@ -0,0 +1,39 @@
|
||||
# See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
# This stage is used when running from VS in fast mode (Default for Debug configuration)
|
||||
FROM 10.99.253.167:8090/dotnet/runtime:9.0 AS base
|
||||
WORKDIR /app
|
||||
|
||||
|
||||
# This stage is used to build the service project
|
||||
FROM 10.99.253.167:8090/dotnet/sdk:9.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
USER root
|
||||
WORKDIR /src
|
||||
COPY ["NuGet.config", "."]
|
||||
COPY ["PARR.SnapshotWorker/PARR.SnapshotWorker.csproj", "PARR.SnapshotWorker/"]
|
||||
COPY ["PARR.Core/PARR.Core.csproj", "PARR.Core/"]
|
||||
COPY ["PARR.Domain/PARR.Domain.csproj", "PARR.Domain/"]
|
||||
COPY ["PARR.DAL/PARR.DAL.csproj", "PARR.DAL/"]
|
||||
COPY ["PARR.Infrastructure/PARR.Infrastructure.csproj", "PARR.Infrastructure/"]
|
||||
RUN dotnet restore "./PARR.SnapshotWorker/PARR.SnapshotWorker.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/PARR.SnapshotWorker"
|
||||
RUN dotnet build "./PARR.SnapshotWorker.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
# This stage is used to publish the service project to be copied to the final stage
|
||||
FROM build AS publish
|
||||
ARG app_version=0.0.0-default
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./PARR.SnapshotWorker.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false /p:Version=$app_version
|
||||
|
||||
# This stage is used in production or when running from VS in regular mode (Default when not using the Debug configuration)
|
||||
FROM base AS final
|
||||
|
||||
#author
|
||||
ARG commit_author=unknown
|
||||
LABEL org.opencontainers.image.authors=$commit_author
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "PARR.SnapshotWorker.dll"]
|
||||
27
PARR.SnapshotWorker/PARR.SnapshotWorker.csproj
Normal file
27
PARR.SnapshotWorker/PARR.SnapshotWorker.csproj
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Worker">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>dotnet-PARR.SnapshotWorker-87e7d52e-d873-4487-b6f4-e27d412ec0c1</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Elastic.CommonSchema.Serilog" Version="8.19.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.16" />
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
|
||||
<PackageReference Include="Serilog.Extensions.Hosting" Version="9.0.0" />
|
||||
<PackageReference Include="Serilog.Settings.Configuration" Version="9.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\PARR.Core\PARR.Core.csproj" />
|
||||
<ProjectReference Include="..\PARR.DAL\PARR.DAL.csproj" />
|
||||
<ProjectReference Include="..\PARR.Domain\PARR.Domain.csproj" />
|
||||
<ProjectReference Include="..\PARR.Infrastructure\PARR.Infrastructure.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
43
PARR.SnapshotWorker/Program.cs
Normal file
43
PARR.SnapshotWorker/Program.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Elastic.CommonSchema.Serilog;
|
||||
using PARR.Core;
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
using PARR.DAL;
|
||||
using PARR.Infrastructure;
|
||||
using PARR.SnapshotWorker;
|
||||
using PARR.SnapshotWorker.Settings;
|
||||
using Serilog;
|
||||
|
||||
var builder = Host.CreateApplicationBuilder(args);
|
||||
|
||||
builder.Services.AddLogging(config =>
|
||||
{
|
||||
config.ClearProviders();
|
||||
|
||||
var logger = new LoggerConfiguration();
|
||||
|
||||
if (builder.Environment.IsProduction())
|
||||
logger.WriteTo.Console(new EcsTextFormatter());
|
||||
else
|
||||
logger.WriteTo.Console();
|
||||
|
||||
logger.ReadFrom.Configuration(builder.Configuration);
|
||||
|
||||
config.AddSerilog(logger.CreateLogger());
|
||||
});
|
||||
|
||||
var commonSettings = new CommonSettings();
|
||||
builder.Configuration.GetSection(nameof(CommonSettings)).Bind(commonSettings);
|
||||
builder.Services.AddSingleton(commonSettings);
|
||||
builder.Services.AddSingleton<ISnapshotSettings>(commonSettings);
|
||||
|
||||
builder.Services.AddDalServices(builder.Configuration);
|
||||
builder.Services.AddCoreServices(builder.Configuration);
|
||||
builder.Services.AddInfrastructureServices(builder.Configuration);
|
||||
|
||||
builder.Configuration.AddDalConfigurations(builder.Services);
|
||||
builder.Services.AddDallSettings(builder.Configuration);
|
||||
|
||||
builder.Services.AddHostedService<Worker>();
|
||||
|
||||
var host = builder.Build();
|
||||
host.Run();
|
||||
15
PARR.SnapshotWorker/Properties/launchSettings.json
Normal file
15
PARR.SnapshotWorker/Properties/launchSettings.json
Normal file
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"profiles": {
|
||||
"PARR.SnapshotWorker": {
|
||||
"commandName": "Project",
|
||||
"environmentVariables": {
|
||||
"DOTNET_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker"
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json"
|
||||
}
|
||||
13
PARR.SnapshotWorker/Settings/CommonSettings.cs
Normal file
13
PARR.SnapshotWorker/Settings/CommonSettings.cs
Normal file
@@ -0,0 +1,13 @@
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
|
||||
namespace PARR.SnapshotWorker.Settings
|
||||
{
|
||||
internal record CommonSettings : ISnapshotSettings
|
||||
{
|
||||
public TimeSpan RobotConfigurationSnapshotInterval { get; init; }
|
||||
|
||||
public TimeSpan RobotConfigurationSnapshotRetentionPeriod { get; init; }
|
||||
|
||||
public TimeSpan RobotSnapshotRetentionPeriod { get; init; }
|
||||
}
|
||||
}
|
||||
114
PARR.SnapshotWorker/Worker.cs
Normal file
114
PARR.SnapshotWorker/Worker.cs
Normal file
@@ -0,0 +1,114 @@
|
||||
using PARR.Core.Common.Interfaces;
|
||||
using PARR.Core.Services.Snapshots.Interfaces;
|
||||
|
||||
namespace PARR.SnapshotWorker
|
||||
{
|
||||
public class Worker : BackgroundService
|
||||
{
|
||||
private readonly ILogger<Worker> _logger;
|
||||
private readonly IIntervalService _intervalService;
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
|
||||
// Хранилище времени СЛЕДУЮЩЕГО запуска для каждого сервиса
|
||||
private readonly Dictionary<string, DateTimeOffset> _nextRunTimers = new();
|
||||
|
||||
// День последней успешной очистки базы данных
|
||||
private int _lastCleanupDay = -1;
|
||||
|
||||
// Интервал, должен быть меньше минуты, чтобы попадать во все возможные интервалы
|
||||
TimeSpan tickInterval = TimeSpan.FromSeconds(25);
|
||||
|
||||
public Worker(
|
||||
ILogger<Worker> logger,
|
||||
IIntervalService intervalService,
|
||||
IServiceProvider serviceProvider
|
||||
)
|
||||
{
|
||||
_logger = logger;
|
||||
_intervalService = intervalService;
|
||||
_serviceProvider = serviceProvider;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_logger.LogInformation("Запуск фонового сервиса создания системных снапшотов");
|
||||
|
||||
await _intervalService.IntervalInitAsync(async () =>
|
||||
{
|
||||
var now = DateTimeOffset.UtcNow;
|
||||
|
||||
using (var scope = _serviceProvider.CreateScope())
|
||||
{
|
||||
// Собираем абсолютно все зарегистрированные сервисы снапшотов
|
||||
var providers = scope.ServiceProvider.GetServices<ISnapshotProvider>();
|
||||
|
||||
#region Параллельный сбор снапшотов
|
||||
|
||||
var tasksToRun = new List<Task>();
|
||||
|
||||
foreach (var provider in providers)
|
||||
{
|
||||
var providerKey = provider.GetType().FullName!;
|
||||
|
||||
// Если сервис видим впервые, планируем его первый старт прямо сейчас
|
||||
if (!_nextRunTimers.ContainsKey(providerKey))
|
||||
{
|
||||
_nextRunTimers[providerKey] = now;
|
||||
}
|
||||
|
||||
// Если текущее время добежало до запланированного «будильника»
|
||||
if (now >= _nextRunTimers[providerKey])
|
||||
{
|
||||
// СРАЗУ планируем следующий старт, чтобы сетка времени не съезжала
|
||||
// из-за времени выполнения самого метода
|
||||
_nextRunTimers[providerKey] = now.Add(provider.Interval);
|
||||
|
||||
// Добавляем таску в список для параллельного выполнения (без await!)
|
||||
tasksToRun.Add(ExecuteSafelyAsync(provider, () => provider.TakeSnapshotAsync(stoppingToken), "Создание снапшота"));
|
||||
}
|
||||
}
|
||||
|
||||
// Запускаем все готовые снапшоты ОДНОВРЕМЕННО
|
||||
if (tasksToRun.Any())
|
||||
{
|
||||
await Task.WhenAll(tasksToRun);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Ежедневная очистка БД
|
||||
|
||||
// Если наступили новые сутки в формате UTC — запускаем ротацию старых данных
|
||||
if (now.Day != _lastCleanupDay)
|
||||
{
|
||||
_logger.LogInformation("Наступили новые сутки. Запуск процесса очистки устаревших снапшотов...");
|
||||
|
||||
foreach (var provider in providers)
|
||||
{
|
||||
await ExecuteSafelyAsync(provider, () => provider.CleanUpOldSnapshotsAsync(stoppingToken), "Очистка старых данных");
|
||||
}
|
||||
|
||||
// Запоминаем, что за сегодня очистку уже провели успешно
|
||||
_lastCleanupDay = now.Day;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
|
||||
}, tickInterval);
|
||||
}
|
||||
|
||||
private async Task ExecuteSafelyAsync(ISnapshotProvider provider, Func<Task> action, string operationName)
|
||||
{
|
||||
try
|
||||
{
|
||||
await action();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Критическая ошибка во время операции '{Operation}' в сервисе {ProviderName}", operationName, provider.GetType().Name);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
29
PARR.SnapshotWorker/appsettings.Development.json
Normal file
29
PARR.SnapshotWorker/appsettings.Development.json
Normal file
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"RedisConnection": "10.99.253.216:6379,password=ParrP@ssPtk202MMdevDvs"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Debug",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "File",
|
||||
"Args": {
|
||||
"path": "log/log-.txt",
|
||||
"rollingInterval": "Day"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
30
PARR.SnapshotWorker/appsettings.json
Normal file
30
PARR.SnapshotWorker/appsettings.json
Normal file
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=10.99.253.184;Database=parr;User Id=app_parr; Password=PosdfkhT&)%sdfligL&%5546;",
|
||||
"RedisConnection": "parr-redis:6379,password=ParrP@ssPtk202MMdevDvs"
|
||||
},
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.EntityFrameworkCore": "Error",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Error",
|
||||
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
|
||||
"Microsoft.Hosting.Lifetime": "Information"
|
||||
}
|
||||
}
|
||||
},
|
||||
"CommonSettings": {
|
||||
"RobotConfigurationSnapshotInterval": "00:02:00",
|
||||
"RobotConfigurationSnapshotRetentionPeriod": "60:00:00:00",
|
||||
"RobotSnapshotRetentionPeriod": "60:00:00:00"
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@
|
||||
<DockerServiceName>parr.api</DockerServiceName>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<None Include="docker-compose.snapshots.yml" />
|
||||
<None Include="docker-compose.task-reconciliation.yml" />
|
||||
<None Include="docker-compose.template-matcher.yml" />
|
||||
<None Include="docker-compose.template-generator.yml" />
|
||||
|
||||
26
docker-compose.snapshots.yml
Normal file
26
docker-compose.snapshots.yml
Normal file
@@ -0,0 +1,26 @@
|
||||
version: '3.9'
|
||||
|
||||
services:
|
||||
parr-snapshots:
|
||||
image: harbor.dvgd.rzd/parr/parr-snapshots:${tag:-latest}
|
||||
environment:
|
||||
- ASPNETCORE_ENVIRONMENT=Production
|
||||
- TZ=Europe/Moscow
|
||||
logging:
|
||||
driver: fluentd
|
||||
options:
|
||||
fluentd-address: dvgd-efk-01.dvgd.oao.rzd:24224
|
||||
fluentd-retry-wait: '10s'
|
||||
fluentd-max-retries: '30'
|
||||
fluentd-async: 'true'
|
||||
fluentd-buffer-limit: '52428800'
|
||||
tag: parr.snapshots.serilog
|
||||
networks:
|
||||
- parr-network
|
||||
deploy:
|
||||
replicas: 1
|
||||
|
||||
networks:
|
||||
parr-network:
|
||||
driver: overlay
|
||||
external: true
|
||||
Reference in New Issue
Block a user