First almost working version of daemons

This commit is contained in:
osaajani 2019-12-12 00:56:30 +01:00
parent e709ed91b7
commit 6614c2cfeb
9 changed files with 491 additions and 20 deletions

View File

@ -5,7 +5,8 @@
"giggsey/libphonenumber-for-php": "^8.10",
"twig/twig": "^3.0",
"symfony/expression-language": "^5.0",
"robmorgan/phinx": "^0.11.1"
"robmorgan/phinx": "^0.11.1",
"monolog/monolog": "^2.0"
},
"require-dev": {
}

83
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"content-hash": "33914b1a0dd7fc84bdff76a4d2cc51a7",
"content-hash": "2c1bb9c8a11ff3457ba8db4d5d1d33ae",
"packages": [
{
"name": "ajani/flash-message",
@ -548,6 +548,87 @@
],
"time": "2018-02-26T14:16:22+00:00"
},
{
"name": "monolog/monolog",
"version": "2.0.1",
"source": {
"type": "git",
"url": "https://github.com/Seldaek/monolog.git",
"reference": "f9d56fd2f5533322caccdfcddbb56aedd622ef1c"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/Seldaek/monolog/zipball/f9d56fd2f5533322caccdfcddbb56aedd622ef1c",
"reference": "f9d56fd2f5533322caccdfcddbb56aedd622ef1c",
"shasum": ""
},
"require": {
"php": "^7.2",
"psr/log": "^1.0.1"
},
"provide": {
"psr/log-implementation": "1.0.0"
},
"require-dev": {
"aws/aws-sdk-php": "^2.4.9 || ^3.0",
"doctrine/couchdb": "~1.0@dev",
"elasticsearch/elasticsearch": "^6.0",
"graylog2/gelf-php": "^1.4.2",
"jakub-onderka/php-parallel-lint": "^0.9",
"php-amqplib/php-amqplib": "~2.4",
"php-console/php-console": "^3.1.3",
"phpspec/prophecy": "^1.6.1",
"phpunit/phpunit": "^8.3",
"predis/predis": "^1.1",
"rollbar/rollbar": "^1.3",
"ruflin/elastica": ">=0.90 <3.0",
"swiftmailer/swiftmailer": "^5.3|^6.0"
},
"suggest": {
"aws/aws-sdk-php": "Allow sending log messages to AWS services like DynamoDB",
"doctrine/couchdb": "Allow sending log messages to a CouchDB server",
"elasticsearch/elasticsearch": "Allow sending log messages to an Elasticsearch server via official client",
"ext-amqp": "Allow sending log messages to an AMQP server (1.0+ required)",
"ext-mbstring": "Allow to work properly with unicode symbols",
"ext-mongodb": "Allow sending log messages to a MongoDB server (via driver)",
"graylog2/gelf-php": "Allow sending log messages to a GrayLog2 server",
"mongodb/mongodb": "Allow sending log messages to a MongoDB server (via library)",
"php-amqplib/php-amqplib": "Allow sending log messages to an AMQP server using php-amqplib",
"php-console/php-console": "Allow sending log messages to Google Chrome",
"rollbar/rollbar": "Allow sending log messages to Rollbar",
"ruflin/elastica": "Allow sending log messages to an Elastic Search server"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.x-dev"
}
},
"autoload": {
"psr-4": {
"Monolog\\": "src/Monolog"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jordi Boggiano",
"email": "j.boggiano@seld.be",
"homepage": "http://seld.be"
}
],
"description": "Sends your logs to files, sockets, inboxes, databases and various web services",
"homepage": "http://github.com/Seldaek/monolog",
"keywords": [
"log",
"logging",
"psr-3"
],
"time": "2019-11-13T10:27:43+00:00"
},
{
"name": "psr/cache",
"version": "1.0.1",

View File

@ -214,6 +214,166 @@ namespace controllers\internals;
return $this->get_model()->gets_before_date_for_number_and_user($id_user, $date, $number);
}
/**
* Get all messages to send and the number to use to send theme
* @return array : [['text', 'origin', 'destination', 'flash'], ...]
*/
public function get_smss_to_send ()
{
$smss_to_send = [];
$internal_templating = new \controllers\internals\Templating();
$internal_setting = new \controllers\internals\Setting($this->bdd);
$internal_group = new \controllers\internals\Group($this->bdd);
$internal_conditional_group = new \controllers\internals\ConditionalGroup($this->bdd);
$internal_phone = new \controllers\internals\Phone($this->bdd);
$users_settings = [];
$users_phones = [];
$now = new \DateTime();
$now = $now->format('Y-m-d H:i:s');
$scheduleds = $this->get_model()->gets_before_date($now);
foreach ($scheduleds as $scheduled)
{
if (!isset($users_settings[$scheduled['id_user']]))
{
$users_settings[$scheduled['id_user']] = [];
$settings = $internal_setting->gets_for_user($scheduled['id_user']);
foreach ($settings as $name => $value)
{
$users_settings[$scheduled['id_user']][$name] = $value;
}
}
if (!isset($users_phones[$scheduled['id_user']]))
{
$users_phones[$scheduled['id_user']] = [];
$phones = $internal_phone->gets_for_user($scheduled['id_user']);
foreach ($phones as $phone)
{
$users_phones[$scheduled['id_user']][] = $phone;
}
}
$messages = [];
//Add messages for numbers
$numbers = $this->get_numbers($scheduled['id']);
foreach ($numbers as $number)
{
$message = [
'origin' => $scheduled['origin'],
'destination' => $number['number'],
'flash' => $scheduled['flash'],
];
if ($message['origin'] == null)
{
$k = array_rand($users_phones[$scheduled['id_user']]);
$rnd_phone = $users_phones[$scheduled['id_user']][$k];
$message['origin'] = $rnd_phone['number'];
}
if ((int) ($users_settings[$scheduled['id_user']]['templating'] ?? false))
{
$render = $internal_templating->render($scheduled['text']);
if (!$render['success'])
{
continue;
}
$message['text'] = $render['result'];
}
else
{
$message['text'] = $scheduled['text'];
}
$messages[] = $message;
}
//Add messages for contacts
$contacts = $this->get_contacts($scheduled['id']);
$groups = $this->get_groups($scheduled['id']);
foreach ($groups as $group)
{
$contacts_to_add = $internal_group->get_contacts($group['id']);
$contacts = array_merge($contacts, $contacts_to_add);
}
$conditional_groups = $this->get_conditional_groups($scheduled['id']);
foreach ($conditional_groups as $conditional_group)
{
$contacts_to_add = $internal_conditional_group->get_contacts_for_condition_and_user($scheduled['id_user'], $conditional_group['condition']);
$contacts = array_merge($contacts, $contacts_to_add);
}
$added_contacts = [];
foreach ($contacts as $contact)
{
if ($added_contacts[$contact['id']] ?? false)
{
continue;
}
$added_contacts[$contact['id']] = true;
$message = [
'origin' => $scheduled['origin'],
'destination' => $number['number'],
'flash' => $scheduled['flash'],
];
if ($message['origin'] == null)
{
$k = array_rand($users_phones[$scheduled['id_user']]);
$rnd_phone = $users_phones[$scheduled['id_user']][$k];
$message['origin'] = $rnd_phone['number'];
}
if ((int) ($users_settings[$scheduled['id_user']]['templating'] ?? false))
{
$contact['datas'] = json_decode($contact['datas'], true);
$render = $internal_templating->render($scheduled['text'], $contact);
if (!$render['success'])
{
continue;
}
$message['text'] = $render['result'];
}
else
{
$message['text'] = $scheduled['text'];
}
$messages[] = $message;
}
foreach ($messages as $message)
{
//Remove empty messages
if (trim($message['text']) == '')
{
continue;
}
$smss_to_send[] = $message;
}
}
return $smss_to_send;
}
/**
* Return numbers for a scheduled message

View File

@ -24,6 +24,16 @@ namespace controllers\internals;
*/
abstract protected function get_model () : \descartes\Model;
/**
* Return all the entries
* @return array
*/
public function get_all ()
{
return $this->get_model()->get_all();
}
/**
* Return a entry by his id

View File

@ -8,6 +8,8 @@ namespace daemons;
abstract class AbstractDaemon
{
protected $name;
protected $uniq;
protected $logger;
private $is_running = true;
private $signals = array (
SIGTERM,
@ -19,13 +21,19 @@ abstract class AbstractDaemon
/**
* Class used to handle POSIX signals and fork from the current process
*
* @param string $name : The name of the class
* @param array $signals :An array containing additional POSIX signals to handle [optionel]
* @param string $name : The name of the class
* @param object $logger : A PSR3 logger instance
* @param string $pid_dir : Directory for the pid files
* @param array $signals :An array containing additional POSIX signals to handle [optionel]
* @param bool $uniq : Must the process be uniq ?
*/
protected function __construct (string $name, array $signals = [])
protected function __construct (string $name, object $logger, string $pid_dir = '/var/run', array $signals = [], bool $uniq = false)
{
$this->name = $name;
$this->name = $name;
$this->logger = $logger;
$this->signals = array_merge($this->signals, $signals);
$this->uniq = $uniq;
$this->pid_dir = $pid_dir;
//Allow script to run indefinitly
set_time_limit(0);
@ -86,13 +94,73 @@ abstract class AbstractDaemon
*/
protected function start ()
{
$this->on_start();
while ($this->is_running)
//If process must be uniq and a process with the same pid file is already running
if (file_exists($this->pid_dir . '/' . $this->name . '.pid') && $this->uniq)
{
pcntl_signal_dispatch(); //Call dispatcher for signals
$this->run();
}
$this->on_stop();
echo "Another process named " . $this->name . " is already running.\n";
return false;
}
$pid = pcntl_fork(); //Fork current process into a child, so we will be able to later make the child indepedant, kill current process and keep only the child
if ($pid == -1) //Impossible to run script
{
echo "Impossible to create a subprocess.\n";
return false;
}
elseif ($pid) //Current script
{
echo "Child process started with pid " . $pid . ".\n";
return true;
}
//Child script
$sid = posix_setsid(); //Try to make the child process a main process
if ($sid == -1) //Error
{
$this->logger->critical('Cannot make the child process independent.');
exit(1);
}
//Create pid dir if not exists
if (!file_exists($this->pid_dir))
{
$success = mkdir($this->pid_dir, 0777, true);
if (!$success)
{
$this->logger->critical('Cannot create PID directory : ' . $this->pid_dir);
exit(2);
}
}
//Set process name
cli_set_process_title($this->name);
//Write the pid of the process into a file
file_put_contents($this->pid_dir . '/' . $this->name . '.pid', getmypid());
$this->on_start();
try
{
while ($this->is_running)
{
pcntl_signal_dispatch(); //Call dispatcher for signals
$this->run();
}
}
catch (\Exception $e)
{
$this->logger->critical('Exception : ' . $e->getMessage() . " in " . $e->getFile() . " line " . $e->getLine());
}
$this->on_stop();
//Delete pid file
if (file_exists($this->pid_dir . '/' . $this->name . '.pid'))
{
unlink($this->pid_dir . '/' . $this->name . '.pid');
}
}

68
daemons/Phone.php Normal file
View File

@ -0,0 +1,68 @@
<?php
namespace daemons;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
/**
* Phone daemon class
*/
class Phone extends AbstractDaemon
{
private $msg_queue;
public function __construct($phone)
{
$name = 'Phone ' . $phone['number'];
$pid_dir = PWD_PID;
$additional_signals = [SIGUSR1, SIGUSR2];
$uniq = true; //Main server should be uniq
$queue_id = (int) mb_substr($phone['number'], 1);
$this->msg_queue = msg_get_queue($queue_id);
$logger = new Logger($name);
$logger->pushHandler(new StreamHandler(PWD_LOGS . '/raspisms.log', Logger::DEBUG));
//Construct the server and add SIGUSR1 and SIGUSR2
parent::__construct($name, $logger, $pid_dir, $additional_signals, $uniq);
//Start the daemon
parent::start();
}
public function run()
{
$msgtype = null;
$maxsize = 409600;
$message = null;
msg_receive($this->msg_queue, SEND_MSG, $msgtype, $maxsize, $message);
if (!$message)
{
return true;
}
$this->logger->debug(json_encode($message));
}
public function on_start()
{
$this->logger->info("Starting " . $this->name . " with pid " . getmypid());
}
public function on_stop()
{
$this->logger->info("Stopping " . $this->name . " with pid " . getmypid ());
}
public function handle_other_signals($signal)
{
$this->logger->info("Signal not handled by " . $this->name . " Daemon : " . $signal);
}
}

View File

@ -1,43 +1,107 @@
<?php
namespace daemons;
use \Monolog\Logger;
use \Monolog\Handler\StreamHandler;
/**
* Main daemon class
*/
class Server extends AbstractDaemon
{
private $internal_user;
private $internal_phone;
private $internal_scheduled;
private $bdd;
public function __construct()
{
$logger = new Logger('server');
$logger->pushHandler(new StreamHandler(PWD_LOGS . '/raspisms.log', Logger::DEBUG));
$name = "RaspiSMS Server";
$pid_dir = PWD_PID;
$additional_signals = [SIGUSR1, SIGUSR2];
$uniq = true; //Main server should be uniq
//Construct the server and add SIGUSR1 and SIGUSR2
parent::__construct("server", [SIGUSR1, SIGUSR2]);
parent::__construct($name, $logger, $pid_dir, $additional_signals, $uniq);
//Start the daemon
parent::start ();
parent::start();
}
public function run()
{
// Le code qui s'exécute infiniment
echo "On tourne !\n";
sleep ( 5 );
//Create the internal controllers
$this->bdd = \descartes\Model::_connect(DATABASE_HOST, DATABASE_NAME, DATABASE_USER, DATABASE_PASSWORD, 'UTF8');
$this->internal_user = new \controllers\internals\User($this->bdd);
$this->internal_phone = new \controllers\internals\Phone($this->bdd);
$this->internal_scheduled = new \controllers\internals\Scheduled($this->bdd);
//Start all phones daemons
$phones = $this->internal_phone->get_all();
foreach ($phones as $phone)
{
$phone_name = 'Phone ' . $phone['number'];
$pid_file = PWD_PID . '/' . $phone_name . '.pid';
if (file_exists($pid_file))
{
continue;
}
//Create a new daemon for the phone and a new queue
$phone = new \daemons\Phone($phone);
}
$queues = [];
//Get all sms to send
$smss = $this->internal_scheduled->get_smss_to_send();
foreach ($smss as $sms)
{
if (!isset($queues[$sms['origin']]))
{
$queue_id = (int) mb_substr($sms['origin'], 1);
$queues[$sms['origin']] = msg_get_queue($queue_id);
}
$queue = $queues[$sms['origin']];
$msg = [
'text' => (string) $sms['text'],
'origin' => (string) $sms['origin'],
'destination' => (string) $sms['destination'],
'flash' => (bool) $sms['flash'],
];
msg_send($queue, SEND_MSG, $msg);
}
sleep(0.5);
}
public function on_start()
{
echo "Démarrage du processus avec le pid " . getmypid () . "\n";
$this->logger->info("Starting " . $this->name . " with pid " . getmypid());
}
public function on_stop()
{
echo "Arrêt du processus avec le pid " . getmypid () . "\n";
$this->logger->info("Stopping " . $this->name . " with pid " . getmypid ());
}
public function handle_other_signals($signal)
{
echo "Signal non géré par la classe Daemon : " . $signal . "\n";
$this->logger->info("Signal not handled by " . $this->name . " Daemon : " . $signal);
}
}

View File

@ -220,4 +220,14 @@ namespace models;
return $this->_run_query($query, $params);
}
/**
* Get scheduleds before a date
* @param string $date : Date to get scheduleds before
* @return array
*/
public function gets_before_date (string $date)
{
return $this->_select($this->get_table_name(), ['<=at' => $date]);
}
}

View File

@ -23,6 +23,15 @@ namespace models;
*/
abstract protected function get_table_name() : string;
/**
* Return all the entries
* @return array
*/
public function get_all ()
{
return $this->_select($this->get_table_name());
}
/**
* Return an entry by his id