From 755680dd5794d3fe248b00aa40f7e8506ac2e925 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc?= <1536036+zoic21@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:13:07 +0200 Subject: [PATCH 1/9] Keep MQTT2 configuration and credentials in shared files for Jeego-managed Mosquitto --- core/class/mqtt2.class.php | 74 ++++++++++++++++++++++++++++++++--- plugin_info/configuration.php | 20 +++++++--- 2 files changed, 83 insertions(+), 11 deletions(-) diff --git a/core/class/mqtt2.class.php b/core/class/mqtt2.class.php index 32d428f..7c169c5 100644 --- a/core/class/mqtt2.class.php +++ b/core/class/mqtt2.class.php @@ -149,7 +149,7 @@ public static function dependancy_end() { if ($mode == 'none') { return; } - if ($mode != 'local' && $mode != 'docker') { + if ($mode != 'local' && $mode != 'docker' && $mode != 'jeego') { return; } if ($mode == 'docker' && is_object(eqLogic::byLogicalId('1::mqtt2_mosquitto', 'docker2'))) { @@ -211,6 +211,30 @@ public static function ensurePassword() { public static function setPassword($_mode = 'local') { $path = __DIR__ . '/../../data/passwords'; + if ($_mode == 'jeego') { + self::ensurePassword(); + $temporary = tempnam(dirname($path), '.passwords-'); + if ($temporary === false) { + throw new Exception(__('Impossible de préparer le fichier de mots de passe MQTT', __FILE__)); + } + try { + if (file_put_contents($temporary, config::byKey('mqtt::password', __CLASS__)) === false) { + throw new Exception(__('Impossible d’écrire les identifiants MQTT', __FILE__)); + } + exec('mosquitto_passwd -U ' . escapeshellarg($temporary) . ' 2>&1', $output, $status); + if ($status !== 0) { + throw new Exception(__('mosquitto_passwd indisponible ou en échec ; mettez à jour l’image Core', __FILE__)); + } + if (!chmod($temporary, 0640) || !rename($temporary, $path)) { + throw new Exception(__('Impossible de publier le fichier de mots de passe MQTT', __FILE__)); + } + } finally { + if (file_exists($temporary)) { + unlink($temporary); + } + } + return; + } self::ensurePassword(); unlink($path); file_put_contents($path, config::byKey('mqtt::password', __CLASS__)); @@ -288,7 +312,7 @@ public static function installMosquitto($_mode = 'local') { throw new Exception(__("Un broker Mosquitto est déjà installé en local sur la machine. Veuillez le désinstaller", __FILE__)); } self::installDocker2(); - } else { + } elseif ($_mode != 'jeego') { self::installLocalMosquitto(); } self::generateCertificates(); @@ -346,7 +370,7 @@ public static function installMosquitto($_mode = 'local') { unlink(__DIR__ . '/../../data/mosquitto.conf'); } - if ($_mode == 'local') { + if ($_mode == 'local' || $_mode == 'jeego') { $replace = array( ' /mosquitto/' => ' ' . __DIR__ . '/../../data/', '/data/config/ssl/' => '/data/ssl/', @@ -364,6 +388,36 @@ public static function installMosquitto($_mode = 'local') { '#cloud_username#' => mb_strtolower(config::byKey('market::username')), '#cloud_password#' => config::byKey('market::password'), ); + if ($_mode == 'jeego') { + $configuration = str_replace(array_keys($replace), $replace, config::byKey('mosquitto::parameters', __CLASS__)); + $configuration = str_replace( + array(__DIR__ . '/../../data/', __DIR__ . '/../config/'), + array(dirname(__DIR__, 2) . '/data/', dirname(__DIR__) . '/config/'), + $configuration + ); + $configuration = preg_replace('/^[\t ]*(?:log_dest|persistence_location)[\t ]+[^\n]*$/m', '', $configuration); + $configuration = "# MQTT2 broker managed by Jeego\nlog_dest stdout\npersistence_location /mosquitto/data/\n" . ltrim($configuration); + $path = __DIR__ . '/../../data/mosquitto.conf'; + $temporary = tempnam(dirname($path), '.mosquitto-'); + if ($temporary === false) { + throw new Exception(__('Impossible de préparer la configuration Mosquitto', __FILE__)); + } + try { + if (file_put_contents($temporary, $configuration) === false || !chmod($temporary, 0640) || !rename($temporary, $path)) { + throw new Exception(__('Impossible de publier la configuration Mosquitto', __FILE__)); + } + } finally { + if (file_exists($temporary)) { + unlink($temporary); + } + } + event::add('jeedom::alert', array( + 'level' => 'warning', + 'page' => 'plugin', + 'message' => __('Configuration préparée. Installez ou redémarrez Mosquitto dans Jeego, onglet Services, pour l’appliquer.', __FILE__), + )); + return; + } shell_exec(system::getCmdSudo() . ' chmod 777 ' . __DIR__ . '/../../data/mosquitto.conf'); file_put_contents(__DIR__ . '/../../data/mosquitto.conf', str_replace(array_keys($replace), $replace, config::byKey('mosquitto::parameters', __CLASS__))); if ($_mode == 'docker') { @@ -389,6 +443,9 @@ public static function installMosquitto($_mode = 'local') { } public static function uninstallMosquitto() { + if (config::byKey('mode', __CLASS__) == 'jeego') { + throw new Exception(__('Gérez le conteneur Mosquitto dans Jeego, onglet Services', __FILE__)); + } if (shell_exec(system::getCmdSudo() . ' which mosquitto | wc -l') != 0) { event::add('jeedom::alert', array( 'level' => 'warning', @@ -406,6 +463,8 @@ public static function uninstallMosquitto() { public static function restartMosquitto() { switch (config::byKey('mode', __CLASS__)) { + case 'jeego': + throw new Exception(__('Gérez le conteneur Mosquitto dans Jeego, onglet Services', __FILE__)); case 'remote': throw new Exception(__('Cette action est impossible avec un brocker distant', __FILE__), 1); break; @@ -433,6 +492,8 @@ public static function restartMosquitto() { public static function stopMosquitto() { switch (config::byKey('mode', __CLASS__)) { + case 'jeego': + throw new Exception(__('Gérez le conteneur Mosquitto dans Jeego, onglet Services', __FILE__)); case 'remote': throw new Exception(__('Cette action est impossible avec un brocker distant', __FILE__), 1); break; @@ -465,6 +526,7 @@ public static function deamon_info() { $return['launchable'] = 'ok'; switch (config::byKey('mode', __CLASS__)) { case 'local': + case 'jeego': break; case 'remote': if (empty(config::byKey('remote::protocol', __CLASS__)) || empty(config::byKey('remote::ip', __CLASS__)) || empty(config::byKey('remote::port', __CLASS__))) { @@ -518,7 +580,7 @@ public static function deamon_start() { } self::createListenner(); $path_ssl = realpath(__DIR__ . '/../../data/ssl'); - if (config::byKey('mode', __CLASS__) == 'local' || config::byKey('mode', __CLASS__) == 'docker') { + if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { if (!file_exists($path_ssl . '/client.crt') || !file_exists($path_ssl . '/client.key') || filesize($path_ssl . '/client.crt') == 0 || filesize($path_ssl . '/client.key') == 0) { self::generateClientCert(); shell_exec(system::getCmdSudo() . ' cp ' . jeedom::getTmpFolder(__CLASS__) . '/ssl/client.* ' . $path_ssl . '/'); @@ -533,7 +595,7 @@ public static function deamon_start() { $cmd = system::getCmdSudo() . ' /usr/bin/node ' . $mqtt2_path . '/mqtt2d.js'; $cmd .= ' --loglevel ' . log::convertLogLevel(log::getLogLevel(__CLASS__)); $cmd .= ' --socketport ' . config::byKey('socketport', __CLASS__); - if (config::byKey('mode', __CLASS__) == 'local' || config::byKey('mode', __CLASS__) == 'docker') { + if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { $cmd .= ' --mqtt_server mqtts://127.0.0.1:8883'; $cmd .= ' --client_key ' . $path_ssl . '/client.key'; $cmd .= ' --client_crt ' . $path_ssl . '/client.crt'; @@ -633,7 +695,7 @@ public static function getSubscribed() { public static function getFormatedInfos() { $infos = array(); $authentifications = explode(':', explode("\n", config::byKey('mqtt::password', __CLASS__))[0]); - if (config::byKey('mode', __CLASS__) == 'local' || config::byKey('mode', __CLASS__) == 'docker') { + if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { $infos['ip'] = '127.0.0.1'; $infos['port'] = '1883'; $infos['protocol'] = 'mqtt'; diff --git a/plugin_info/configuration.php b/plugin_info/configuration.php index 06eed0d..44d132d 100644 --- a/plugin_info/configuration.php +++ b/plugin_info/configuration.php @@ -34,6 +34,7 @@ + @@ -71,6 +72,15 @@ +
+ +
+ {{Préparer la configuration}} + {{Télécharger le certificat client}} +

{{MQTT Manager conserve la configuration, les identifiants, les certificats et les liaisons entre Jeedom. Après préparation ou modification d’une liaison, installez ou redémarrez Mosquitto dans Jeego, onglet Services. Les journaux et les commandes du conteneur sont disponibles dans Jeego.}}

+
+
+
-
+
-
+
@@ -209,7 +219,7 @@
-
+
@@ -449,7 +459,7 @@ }) }) - $('#bt_mqtt2InstallMosquitto').off('click').on('click', function() { + $('#bt_mqtt2InstallMosquitto, #bt_mqtt2PrepareJeego').off('click').on('click', function() { $.ajax({ type: "POST", url: "plugins/mqtt2/core/ajax/mqtt2.ajax.php", @@ -466,7 +476,7 @@ return } $('.pluginDisplayCard[data-plugin_id=' + $('#span_plugin_id').text() + ']').click() - $.fn.showAlert({message: '{{Installation réussie}}',level: 'success',emptyBefore: true}) + $.fn.showAlert({message: $('.configKey[data-l1key=mode]').value() === 'jeego' ? '{{Configuration préparée. Appliquez-la dans Jeego, onglet Services.}}' : '{{Installation réussie}}',level: 'success',emptyBefore: true}) } }) }) From 5d04250277611e8f6f5d2cd4eaaddca1d008856d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc?= <1536036+zoic21@users.noreply.github.com> Date: Thu, 22 Oct 2026 21:49:50 +0200 Subject: [PATCH 2/9] feat: restart Jeego-managed Mosquitto through the authenticated local API --- core/class/mqtt2.class.php | 80 ++++++++++++++++++++++++++++++++++- plugin_info/configuration.php | 7 +-- 2 files changed, 82 insertions(+), 5 deletions(-) diff --git a/core/class/mqtt2.class.php b/core/class/mqtt2.class.php index 7c169c5..15438f6 100644 --- a/core/class/mqtt2.class.php +++ b/core/class/mqtt2.class.php @@ -414,7 +414,7 @@ public static function installMosquitto($_mode = 'local') { event::add('jeedom::alert', array( 'level' => 'warning', 'page' => 'plugin', - 'message' => __('Configuration préparée. Installez ou redémarrez Mosquitto dans Jeego, onglet Services, pour l’appliquer.', __FILE__), + 'message' => __('Configuration préparée. Cliquez sur (Re)Démarrer pour l’appliquer ; installez d’abord le broker dans Jeego si nécessaire.', __FILE__), )); return; } @@ -461,10 +461,86 @@ public static function uninstallMosquitto() { } } + private static function jeegoMessage($_message) { + return substr(str_replace((string) getenv('JEEGO_API_KEY'), '[masquée]', $_message), 0, 512); + } + + private static function jeegoRequest($_method, $_path, $_timeout = 5) { + $url = rtrim((string) getenv('JEEGO_API_URL'), '/'); + $key = (string) getenv('JEEGO_API_KEY'); + $server = parse_url($url); + $host = isset($server['host']) ? trim($server['host'], '[]') : ''; + $loopback = $host == '::1' || (filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false && substr($host, 0, 4) == '127.'); + if (!is_array($server) || !isset($server['scheme'], $server['port'], $server['path']) + || $server['scheme'] != 'http' || !$loopback || $server['port'] < 1 || $server['port'] > 65535 + || $server['path'] != '/api/v1' || isset($server['user']) || isset($server['pass']) + || isset($server['query']) || isset($server['fragment']) || !preg_match('/^[a-f0-9]{64}$/D', $key)) { + throw new Exception(__('API Jeego non configurée. Mettez à jour Jeego et recréez le conteneur Jeedom pour recevoir ses accès.', __FILE__)); + } + if (!function_exists('curl_init')) { + throw new Exception(__('L’extension PHP cURL est nécessaire pour joindre Jeego', __FILE__)); + } + $request = curl_init($url . $_path); + curl_setopt_array($request, array( + CURLOPT_RETURNTRANSFER => true, + CURLOPT_CUSTOMREQUEST => $_method, + CURLOPT_HTTPHEADER => array('Authorization: Bearer ' . $key, 'Accept: application/json', 'Content-Type: application/json'), + CURLOPT_CONNECTTIMEOUT => 2, + CURLOPT_TIMEOUT => max(1, $_timeout), + CURLOPT_FOLLOWLOCATION => false, + CURLOPT_PROXY => '', + )); + if ($_method == 'POST') { + curl_setopt($request, CURLOPT_POSTFIELDS, '{}'); + } + $response = curl_exec($request); + $status = curl_getinfo($request, CURLINFO_HTTP_CODE); + curl_close($request); + if ($response === false) { + throw new Exception(__('API Jeego injoignable ; vérifiez le service Jeego. Une demande déjà acceptée peut continuer dans son historique.', __FILE__)); + } + $data = json_decode($response, true); + if ($status != ($_method == 'POST' ? 202 : 200)) { + $message = isset($data['error']['message']) && is_string($data['error']['message']) ? $data['error']['message'] : __('Réponse HTTP inattendue', __FILE__) . ' (' . $status . ')'; + throw new Exception('Jeego : ' . self::jeegoMessage($message)); + } + if (!is_array($data)) { + throw new Exception(__('Réponse JSON de Jeego invalide', __FILE__)); + } + return $data; + } + + private static function restartJeegoMosquitto() { + $deadline = microtime(true) + 60; + $task = self::jeegoRequest('POST', '/services/mosquitto/actions/restart'); + if (!isset($task['id']) || !is_string($task['id']) || !preg_match('/^[a-f0-9]{32}$/D', $task['id'])) { + throw new Exception(__('Identifiant de tâche Jeego invalide', __FILE__)); + } + $id = $task['id']; + while (true) { + if (!isset($task['id'], $task['status']) || $task['id'] !== $id || !in_array($task['status'], array('running', 'succeeded', 'failed', 'interrupted'), true)) { + throw new Exception(__('État de tâche Jeego invalide', __FILE__)); + } + if ($task['status'] == 'succeeded') { + return; + } + if ($task['status'] == 'failed' || $task['status'] == 'interrupted') { + $message = isset($task['error']) && is_string($task['error']) ? $task['error'] : __('Redémarrage de Mosquitto échoué ou interrompu', __FILE__); + throw new Exception('Jeego : ' . self::jeegoMessage($message)); + } + if (microtime(true) >= $deadline) { + throw new Exception(__('Redémarrage non confirmé dans le délai prévu ; consultez l’historique de Jeego avant de réessayer', __FILE__)); + } + usleep(500000); + $task = self::jeegoRequest('GET', '/tasks/' . $id, min(5, max(1, (int) ceil($deadline - microtime(true))))); + } + } + public static function restartMosquitto() { switch (config::byKey('mode', __CLASS__)) { case 'jeego': - throw new Exception(__('Gérez le conteneur Mosquitto dans Jeego, onglet Services', __FILE__)); + self::restartJeegoMosquitto(); + break; case 'remote': throw new Exception(__('Cette action est impossible avec un brocker distant', __FILE__), 1); break; diff --git a/plugin_info/configuration.php b/plugin_info/configuration.php index 44d132d..d20ce87 100644 --- a/plugin_info/configuration.php +++ b/plugin_info/configuration.php @@ -75,9 +75,10 @@
+ {{(Re)Démarrer}} {{Préparer la configuration}} {{Télécharger le certificat client}} -

{{MQTT Manager conserve la configuration, les identifiants, les certificats et les liaisons entre Jeedom. Après préparation ou modification d’une liaison, installez ou redémarrez Mosquitto dans Jeego, onglet Services. Les journaux et les commandes du conteneur sont disponibles dans Jeego.}}

+

{{MQTT Manager conserve la configuration, les identifiants, les certificats et les liaisons entre Jeedom. Après préparation ou modification d’une liaison, cliquez sur (Re)Démarrer pour appliquer la configuration. L’installation du broker et ses journaux restent disponibles dans Jeego, onglet Services.}}

@@ -415,7 +416,7 @@ }) }) - $('#bt_mqtt2RestartMosquitto').off('click').on('click', function() { + $('#bt_mqtt2RestartMosquitto, #bt_mqtt2RestartJeego').off('click').on('click', function() { $.ajax({ type: "POST", url: "plugins/mqtt2/core/ajax/mqtt2.ajax.php", @@ -476,7 +477,7 @@ return } $('.pluginDisplayCard[data-plugin_id=' + $('#span_plugin_id').text() + ']').click() - $.fn.showAlert({message: $('.configKey[data-l1key=mode]').value() === 'jeego' ? '{{Configuration préparée. Appliquez-la dans Jeego, onglet Services.}}' : '{{Installation réussie}}',level: 'success',emptyBefore: true}) + $.fn.showAlert({message: $('.configKey[data-l1key=mode]').value() === 'jeego' ? '{{Configuration préparée. Cliquez sur (Re)Démarrer pour l’appliquer.}}' : '{{Installation réussie}}',level: 'success',emptyBefore: true}) } }) }) From 0338243cbf3a8a246a9a92d49fb3401a00ca1f91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc?= <1536036+zoic21@users.noreply.github.com> Date: Fri, 23 Oct 2026 10:34:56 +0200 Subject: [PATCH 3/9] fix(mqtt2): resolve Node.js through PATH when starting the daemon --- core/class/mqtt2.class.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/class/mqtt2.class.php b/core/class/mqtt2.class.php index 15438f6..5d1c44d 100644 --- a/core/class/mqtt2.class.php +++ b/core/class/mqtt2.class.php @@ -668,7 +668,7 @@ public static function deamon_start() { chdir($mqtt2_path); self::setPassword(config::byKey('mode', __CLASS__)); $authentifications = explode(':', explode("\n", config::byKey('mqtt::password', __CLASS__))[0]); - $cmd = system::getCmdSudo() . ' /usr/bin/node ' . $mqtt2_path . '/mqtt2d.js'; + $cmd = system::getCmdSudo() . ' node ' . escapeshellarg($mqtt2_path . '/mqtt2d.js'); $cmd .= ' --loglevel ' . log::convertLogLevel(log::getLogLevel(__CLASS__)); $cmd .= ' --socketport ' . config::byKey('socketport', __CLASS__); if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { From 58b39494efcb26d1eb0b34dfaabfe324ad0c3d2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc?= <1536036+zoic21@users.noreply.github.com> Date: Fri, 23 Oct 2026 10:49:55 +0200 Subject: [PATCH 4/9] Use the standard broker controls for Jeego installations Default Jeego environments to the managed broker and hide native and Docker choices. Install and start Mosquitto through the existing install button, and route restart, stop, removal, status and logs through the Jeego API. --- core/class/mqtt2.class.php | 92 ++++++++++++++++++++++----------- desktop/modal/mosquitto.log.php | 2 +- plugin_info/configuration.php | 39 +++++++------- plugin_info/install.php | 7 ++- 4 files changed, 89 insertions(+), 51 deletions(-) diff --git a/core/class/mqtt2.class.php b/core/class/mqtt2.class.php index 5d1c44d..323fae3 100644 --- a/core/class/mqtt2.class.php +++ b/core/class/mqtt2.class.php @@ -21,6 +21,18 @@ class mqtt2 extends eqLogic { + public static function isJeego() { + return trim((string) getenv('JEEGO_API_URL')) != ''; + } + + public static function getMode($_mode = null) { + $mode = $_mode === null ? config::byKey('mode', __CLASS__, 'local') : $_mode; + if (self::isJeego() && in_array($mode, array('', 'none', 'local', 'docker'), true)) { + return 'jeego'; + } + return $mode; + } + public static function createListenner() { $listeners = listener::searchClassFunctionOption('mqtt2', 'handleEvent'); if (count($listeners) > 1) { @@ -65,7 +77,7 @@ public static function syncTopicToJeedomCloud($_local_topic = '', $_remote_topic $conf .= "# End autogenerate for " . $_local_topic . " <-> cloud-" . $_remote_topic . "\n"; $current_conf = preg_replace('/(# Begin autogenerate for ' . $_local_topic . ' <-> cloud-' . $_remote_topic . ')((.|\n)*)(# End autogenerate for ' . $_local_topic . ' <-> cloud-' . $_remote_topic . ')/m', "", config::byKey('mosquitto::parameters', __CLASS__)); config::save('mosquitto::parameters', trim($current_conf) . "\n\n" . trim($conf), __CLASS__); - mqtt2::installMosquitto(config::byKey('mode', 'mqtt2')); + mqtt2::installMosquitto(self::getMode()); } public static function syncTopicToLocalMqtt($_local_topic, $_remote_topic, $_username, $_password, $_ip, $_port = 1883) { @@ -100,7 +112,7 @@ public static function syncTopicToLocalMqtt($_local_topic, $_remote_topic, $_use $conf .= "# End autogenerate for " . $_local_topic . " <-> " . $_remote_topic . "\n"; $current_conf = preg_replace('/(# Begin autogenerate for ' . $_local_topic . ' <-> ' . $_remote_topic . ')((.|\n)*)(# End autogenerate for ' . $_local_topic . ' <-> ' . $_remote_topic . ')/m', "", config::byKey('mosquitto::parameters', __CLASS__)); config::save('mosquitto::parameters', trim($current_conf) . "\n\n" . trim($conf), __CLASS__); - mqtt2::installMosquitto(config::byKey('mode', 'mqtt2')); + mqtt2::installMosquitto(self::getMode()); } public static function cronDaily() { @@ -145,7 +157,7 @@ public static function devicesParameters($_device = '') { } public static function dependancy_end() { - $mode = config::byKey('mode', __CLASS__, 'local'); + $mode = self::getMode(); if ($mode == 'none') { return; } @@ -210,6 +222,7 @@ public static function ensurePassword() { } public static function setPassword($_mode = 'local') { + $_mode = self::getMode($_mode); $path = __DIR__ . '/../../data/passwords'; if ($_mode == 'jeego') { self::ensurePassword(); @@ -304,6 +317,7 @@ public static function installDocker2() { } public static function installMosquitto($_mode = 'local') { + $_mode = self::getMode($_mode); if ($_mode == 'remote') { return; } @@ -411,11 +425,7 @@ public static function installMosquitto($_mode = 'local') { unlink($temporary); } } - event::add('jeedom::alert', array( - 'level' => 'warning', - 'page' => 'plugin', - 'message' => __('Configuration préparée. Cliquez sur (Re)Démarrer pour l’appliquer ; installez d’abord le broker dans Jeego si nécessaire.', __FILE__), - )); + self::jeegoMosquittoAction('install'); return; } shell_exec(system::getCmdSudo() . ' chmod 777 ' . __DIR__ . '/../../data/mosquitto.conf'); @@ -443,8 +453,9 @@ public static function installMosquitto($_mode = 'local') { } public static function uninstallMosquitto() { - if (config::byKey('mode', __CLASS__) == 'jeego') { - throw new Exception(__('Gérez le conteneur Mosquitto dans Jeego, onglet Services', __FILE__)); + if (self::getMode() == 'jeego') { + self::jeegoMosquittoAction('remove'); + return; } if (shell_exec(system::getCmdSudo() . ' which mosquitto | wc -l') != 0) { event::add('jeedom::alert', array( @@ -461,11 +472,30 @@ public static function uninstallMosquitto() { } } + public static function isMosquittoRunning() { + if (self::getMode() == 'jeego') { + $service = self::jeegoRequest('GET', '/services/mosquitto'); + return isset($service['status']) && $service['status'] == 'running'; + } + return shell_exec(system::getCmdSudo() . ' ps ax | grep mosquitto | grep mqtt2 | grep -v grep | wc -l') != 0; + } + + public static function getMosquittoLog() { + if (self::getMode() == 'jeego') { + $data = self::jeegoRequest('GET', '/services/mosquitto/logs'); + if (!isset($data['logs']) || !is_string($data['logs'])) { + throw new Exception(__('Journaux Mosquitto invalides', __FILE__)); + } + return str_replace((string) getenv('JEEGO_API_KEY'), '[masquée]', $data['logs']); + } + return (string) shell_exec(system::getCmdSudo() . ' cat /var/log/mosquitto/mosquitto.log'); + } + private static function jeegoMessage($_message) { return substr(str_replace((string) getenv('JEEGO_API_KEY'), '[masquée]', $_message), 0, 512); } - private static function jeegoRequest($_method, $_path, $_timeout = 5) { + private static function jeegoRequest($_method, $_path, $_timeout = 5, $_body = array()) { $url = rtrim((string) getenv('JEEGO_API_URL'), '/'); $key = (string) getenv('JEEGO_API_KEY'); $server = parse_url($url); @@ -491,7 +521,7 @@ private static function jeegoRequest($_method, $_path, $_timeout = 5) { CURLOPT_PROXY => '', )); if ($_method == 'POST') { - curl_setopt($request, CURLOPT_POSTFIELDS, '{}'); + curl_setopt($request, CURLOPT_POSTFIELDS, json_encode((object) $_body)); } $response = curl_exec($request); $status = curl_getinfo($request, CURLINFO_HTTP_CODE); @@ -510,9 +540,10 @@ private static function jeegoRequest($_method, $_path, $_timeout = 5) { return $data; } - private static function restartJeegoMosquitto() { - $deadline = microtime(true) + 60; - $task = self::jeegoRequest('POST', '/services/mosquitto/actions/restart'); + private static function jeegoMosquittoAction($_action) { + $deadline = microtime(true) + ($_action == 'install' ? 300 : 60); + $body = $_action == 'remove' ? array('confirm' => true) : array(); + $task = self::jeegoRequest('POST', '/services/mosquitto/actions/' . $_action, 5, $body); if (!isset($task['id']) || !is_string($task['id']) || !preg_match('/^[a-f0-9]{32}$/D', $task['id'])) { throw new Exception(__('Identifiant de tâche Jeego invalide', __FILE__)); } @@ -525,11 +556,11 @@ private static function restartJeegoMosquitto() { return; } if ($task['status'] == 'failed' || $task['status'] == 'interrupted') { - $message = isset($task['error']) && is_string($task['error']) ? $task['error'] : __('Redémarrage de Mosquitto échoué ou interrompu', __FILE__); + $message = isset($task['error']) && is_string($task['error']) ? $task['error'] : __('Opération Mosquitto échouée ou interrompue', __FILE__); throw new Exception('Jeego : ' . self::jeegoMessage($message)); } if (microtime(true) >= $deadline) { - throw new Exception(__('Redémarrage non confirmé dans le délai prévu ; consultez l’historique de Jeego avant de réessayer', __FILE__)); + throw new Exception(__('Opération non confirmée dans le délai prévu ; consultez l’historique de Jeego avant de réessayer', __FILE__)); } usleep(500000); $task = self::jeegoRequest('GET', '/tasks/' . $id, min(5, max(1, (int) ceil($deadline - microtime(true))))); @@ -537,9 +568,9 @@ private static function restartJeegoMosquitto() { } public static function restartMosquitto() { - switch (config::byKey('mode', __CLASS__)) { + switch (self::getMode()) { case 'jeego': - self::restartJeegoMosquitto(); + self::jeegoMosquittoAction('restart'); break; case 'remote': throw new Exception(__('Cette action est impossible avec un brocker distant', __FILE__), 1); @@ -567,9 +598,10 @@ public static function restartMosquitto() { } public static function stopMosquitto() { - switch (config::byKey('mode', __CLASS__)) { + switch (self::getMode()) { case 'jeego': - throw new Exception(__('Gérez le conteneur Mosquitto dans Jeego, onglet Services', __FILE__)); + self::jeegoMosquittoAction('stop'); + break; case 'remote': throw new Exception(__('Cette action est impossible avec un brocker distant', __FILE__), 1); break; @@ -600,7 +632,7 @@ public static function deamon_info() { $return['log'] = __CLASS__; $return['state'] = 'nok'; $return['launchable'] = 'ok'; - switch (config::byKey('mode', __CLASS__)) { + switch (self::getMode()) { case 'local': case 'jeego': break; @@ -643,10 +675,10 @@ public static function deamon_start() { throw new Exception(__('Le topic racine n\'est pas valide. Le topic racine ne peut etre identique à un topic ou un plugin est abonné.', __FILE__)); } log::remove(__CLASS__ . '_update'); - if (config::byKey('mode', __CLASS__, 'local') == 'local') { + if (self::getMode() == 'local') { if (shell_exec(system::getCmdSudo() . ' ps ax | grep mosquitto | grep mqtt2 | grep -v grep | wc -l') == 0) { log::add(__CLASS__, 'warning', __('Service mosquitto non lancé, je lance une installation', __FILE__)); - self::installMosquitto(config::byKey('mode', __CLASS__, 'local')); + self::installMosquitto(self::getMode()); } } self::deamon_stop(); @@ -656,7 +688,7 @@ public static function deamon_start() { } self::createListenner(); $path_ssl = realpath(__DIR__ . '/../../data/ssl'); - if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { + if (in_array(self::getMode(), array('local', 'docker', 'jeego'))) { if (!file_exists($path_ssl . '/client.crt') || !file_exists($path_ssl . '/client.key') || filesize($path_ssl . '/client.crt') == 0 || filesize($path_ssl . '/client.key') == 0) { self::generateClientCert(); shell_exec(system::getCmdSudo() . ' cp ' . jeedom::getTmpFolder(__CLASS__) . '/ssl/client.* ' . $path_ssl . '/'); @@ -666,18 +698,18 @@ public static function deamon_start() { } $mqtt2_path = realpath(dirname(__FILE__) . '/../../resources/mqtt2d'); chdir($mqtt2_path); - self::setPassword(config::byKey('mode', __CLASS__)); + self::setPassword(self::getMode()); $authentifications = explode(':', explode("\n", config::byKey('mqtt::password', __CLASS__))[0]); $cmd = system::getCmdSudo() . ' node ' . escapeshellarg($mqtt2_path . '/mqtt2d.js'); $cmd .= ' --loglevel ' . log::convertLogLevel(log::getLogLevel(__CLASS__)); $cmd .= ' --socketport ' . config::byKey('socketport', __CLASS__); - if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { + if (in_array(self::getMode(), array('local', 'docker', 'jeego'))) { $cmd .= ' --mqtt_server mqtts://127.0.0.1:8883'; $cmd .= ' --client_key ' . $path_ssl . '/client.key'; $cmd .= ' --client_crt ' . $path_ssl . '/client.crt'; } else { $cmd .= ' --mqtt_server ' . config::byKey('remote::protocol', __CLASS__) . '://' . config::byKey('remote::ip', __CLASS__) . ':' . config::byKey('remote::port', __CLASS__); - if (config::byKey('mode', __CLASS__) == 'remote' && config::byKey('remote::protocol', __CLASS__) == 'mqtts' && config::byKey('mqtt::client_key', __CLASS__) != '' && config::byKey('mqtt::client_crt', __CLASS__)!= '') { + if (self::getMode() == 'remote' && config::byKey('remote::protocol', __CLASS__) == 'mqtts' && config::byKey('mqtt::client_key', __CLASS__) != '' && config::byKey('mqtt::client_crt', __CLASS__)!= '') { file_put_contents($path_ssl . '/client.key', config::byKey('mqtt::client_key', __CLASS__)); file_put_contents($path_ssl . '/client.crt', config::byKey('mqtt::client_crt', __CLASS__)); $cmd .= ' --client_key ' . $path_ssl . '/client.key'; @@ -717,7 +749,7 @@ public static function deamon_start() { } public static function postConfig_mqtt_password($_value) { - self::setPassword(config::byKey('mode', __CLASS__)); + self::setPassword(self::getMode()); } public static function deamon_stop() { @@ -771,7 +803,7 @@ public static function getSubscribed() { public static function getFormatedInfos() { $infos = array(); $authentifications = explode(':', explode("\n", config::byKey('mqtt::password', __CLASS__))[0]); - if (in_array(config::byKey('mode', __CLASS__), array('local', 'docker', 'jeego'))) { + if (in_array(self::getMode(), array('local', 'docker', 'jeego'))) { $infos['ip'] = '127.0.0.1'; $infos['port'] = '1883'; $infos['protocol'] = 'mqtt'; diff --git a/desktop/modal/mosquitto.log.php b/desktop/modal/mosquitto.log.php index e8e57a4..0c9cc73 100644 --- a/desktop/modal/mosquitto.log.php +++ b/desktop/modal/mosquitto.log.php @@ -19,7 +19,7 @@ } ?> -
+