Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alert job 1009 #1053

Merged
merged 4 commits into from
Aug 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Controller/FluxController.php
Original file line number Diff line number Diff line change
Expand Up @@ -797,7 +797,7 @@ public function fluxInfo(Request $request, $id, $page, $logPage)

// Add log to indicate this action
$log = new Log();
$log->setDateCreated(new \DateTime());
$log->setCreated(new \DateTime());
$log->setType('I');

$log->setRule($rule);
Expand Down
2 changes: 1 addition & 1 deletion src/Controller/TaskController.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public function stopTask(Job $taskStop): RedirectResponse

// Add log to indicate this action
$log = new Log();
$log->setDateCreated(new \DateTime());
$log->setCreated(new \DateTime());
$log->setType('W');
$log->setMessage('The task has been manually stopped. ');
$log->setJob($taskStop);
Expand Down
1 change: 1 addition & 0 deletions src/DataFixtures/LoadConfigData.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ class LoadConfigData implements FixtureInterface
['name' => 'base_uri', 'value' => '', 'update' => false],
['name' => 'email_from', 'value' => 'no-reply@myddleware.com', 'update' => false],
['name' => 'cron_enabled', 'value' => true, 'update' => true],
['name' => 'alert_date_ref', 'value' => '1999-01-01 00:00:00', 'update' => true],
];

public function load(ObjectManager $manager)
Expand Down
10 changes: 5 additions & 5 deletions src/Entity/Log.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class Log
/**
* @ORM\Column(name="created", type="datetime", nullable=false)
*/
private DateTime $dateCreated;
private DateTime $created;

/**
* @ORM\Column(name="type", type="string", length=5, nullable=false)
Expand Down Expand Up @@ -88,16 +88,16 @@ public function getId(): int
return $this->id;
}

public function setDateCreated($dateCreated): self
public function setCreated($created): self
{
$this->dateCreated = $dateCreated;
$this->created = $created;

return $this;
}

public function getDateCreated(): DateTime
public function getCreated(): DateTime
{
return $this->dateCreated;
return $this->created;
}

public function setType($type): self
Expand Down
114 changes: 85 additions & 29 deletions src/Manager/NotificationManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,21 @@
use Exception;
use Swift_Mailer;
use Swift_Message;
use Swift_SmtpTransport;

use App\Entity\User;

use Twig\Environment;
use App\Entity\Config;
use Swift_SmtpTransport;
use Twig\Error\LoaderError;
use Twig\Error\SyntaxError;
use Psr\Log\LoggerInterface;
use Twig\Error\RuntimeError;
use Doctrine\DBAL\Connection;
use App\Repository\JobRepository;
use App\Repository\LogRepository;
use App\Repository\RuleRepository;
use App\Repository\UserRepository;
use App\Repository\ConfigRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
Expand All @@ -64,6 +66,8 @@ class NotificationManager
private RuleRepository $ruleRepository;
private $fromEmail;
private Environment $twig;
private ConfigRepository $configRepository;
private LogRepository $logRepository;

public function __construct(
LoggerInterface $logger,
Expand All @@ -76,7 +80,9 @@ public function __construct(
Swift_Mailer $mailer,
ToolsManager $tools,
ParameterBagInterface $params,
Environment $twig
Environment $twig,
ConfigRepository $configRepository,
LogRepository $logRepository
) {
$this->logger = $logger;
$this->connection = $connection;
Expand All @@ -89,49 +95,99 @@ public function __construct(
$this->tools = $tools;
$this->params = $params;
$this->twig = $twig;
$this->configRepository = $configRepository;
$this->logRepository = $logRepository;
}

/**
* Send alert if a job is running too long.
* Send alert
*
* @throws Exception
*/
public function sendAlert(): bool
{
try {

// Set all config parameters
$this->setConfigParam();
if (empty($this->configParams['alert_time_limit'])) {
throw new Exception('No alert time set in the parameters file. Please set the parameter alert_limit_minute in the file config/parameters.yml.');
}
// Calculate the date corresponding to the beginning still authorised
$timeLimit = new DateTime('now', new \DateTimeZone('GMT'));
$timeLimit->modify('-'.$this->configParams['alert_time_limit'].' minutes');

// Search if a job is lasting more time that the limit authorized
$job = $this->jobRepository->findJobStarted($timeLimit);
// If a job is found, we send the alert
if (!empty($job)) {
// Create text
$textMail = $this->translator->trans('email_alert.body', [
'%min%' => $this->configParams['alert_time_limit'],
'%begin%' => $job->getBegin()->format('Y-m-d H:i:s'),
'%id%' => $job->getId(),
'%base_uri%' => (!empty($this->configParams['base_uri']) ? $this->configParams['base_uri'].'rule/task/view/'.$job->getId().'/log' : ''),
]);

return $this->send($textMail, $this->translator->trans('email_alert.subject'));
}

$this->sendAlertTaskTooLong();
$this->sendAlertLimitReached();

return true;

} catch (Exception $e) {
$error = 'Error : '.$e->getMessage().' '.$e->getFile().' Line : ( '.$e->getLine().' )';
$this->logger->error($error);
throw new Exception($error);
}
}


/**
* Send alert if a job is running too long.
*
* @throws Exception
*/
public function sendAlertTaskTooLong()
{
// Set all config parameters
$this->setConfigParam();
if (empty($this->configParams['alert_time_limit'])) {
throw new Exception('No alert time set in the parameters file. Please set the parameter alert_limit_minute in the file config/parameters.yml.');
}
// Calculate the date corresponding to the beginning still authorised
$timeLimit = new DateTime('now', new \DateTimeZone('GMT'));
$timeLimit->modify('-'.$this->configParams['alert_time_limit'].' minutes');

// Search if a job is lasting more time that the limit authorized
$job = $this->jobRepository->findJobStarted($timeLimit);
// If a job is found, we send the alert
if (!empty($job)) {
// Create text
$textMail = $this->translator->trans('email_alert.body', [
'%min%' => $this->configParams['alert_time_limit'],
'%begin%' => $job->getBegin()->format('Y-m-d H:i:s'),
'%id%' => $job->getId(),
'%base_uri%' => (!empty($this->configParams['base_uri']) ? $this->configParams['base_uri'].'rule/task/view/'.$job->getId().'/log' : ''),
]);

return $this->send($textMail, $this->translator->trans('email_alert.subject'));
}
}


/**
* Send alert if limit reached.
*
* @throws Exception
*/
public function sendAlertLimitReached()
{
// Get alert_date_ref
$alertDateRef = $this->configRepository->findAlertDateRef();

$alertDateRef = $alertDateRef['value'];

// Get error message
$newErrorLogs = $this->logRepository->findNewErrorLogs(new \DateTime($alertDateRef));

//Send Alerte
if (!empty($newErrorLogs)) {

$textMail = "Des nouveaux logs d'erreur ont été trouvés :\n\n";

// TODO: à translate
foreach ($newErrorLogs as $log) {
$textMail .= "Date de création: " . $log['created']->format('Y-m-d H:i:s') . "\n";
$textMail .= "Type: " . $log['type'] . "\n";
$textMail .= "Message: " . $log['message'] . "\n\n";
}

// TODO: check : envoyez l'e-mail
$this->send($textMail, "Alerte: Nouveaux logs d'erreur trouvés");
}
// Update alert_date_ref
$currentDate = new \DateTime();
$this->configRepository->setAlertDateRef($currentDate->format('Y-m-d H:i:s'));

}

protected function send($textMail, $subject) {
// Get the email adresses of all ADMIN
Expand Down
25 changes: 25 additions & 0 deletions src/Repository/ConfigRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,31 @@ public function findOneByAllowInstall($value): ?Config
;
}

public function findAlertDateRef()
{
return $this->createQueryBuilder('c')
->select('c.value')
->where('c.name = :name')
->setParameter('name', 'alert_date_ref')
->getQuery()
->getOneOrNullResult();
}

public function setAlertDateRef($newDate)
{
$entityManager = $this->getEntityManager();

// Supposons que votre entité de configuration s'appelle Config
$config = $this->findOneBy(['name' => 'alert_date_ref']);

if ($config) {
$config->setValue($newDate);
$entityManager->persist($config);
$entityManager->flush();
}
}


// /**
// * @return Config[] Returns an array of Config objects
// */
Expand Down
12 changes: 12 additions & 0 deletions src/Repository/LogRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,16 @@ public function getLogsReportForDocumentsSent(Job $job)
->getResult()
;
}

public function findNewErrorLogs($alertDateRef)
{
return $this->createQueryBuilder('l')
->select('l.created, l.type, l.message')
->where('l.created > :alertDateRef')
->andWhere('l.type = :type')
->setParameter('alertDateRef', $alertDateRef)
->setParameter('type', 'E')
->getQuery()
->getResult();
}
}