diff --git a/cron/centAcl-Func.php b/cron/centAcl-Func.php index 941b4d38ea5..164075b2f27 100644 --- a/cron/centAcl-Func.php +++ b/cron/centAcl-Func.php @@ -160,7 +160,7 @@ function getFilteredPollers($host, $resId) } } } else { - # If result of query is empty and user have poller restriction, clean host table. + // If result of query is empty and user have poller restrictions, clean host table. if ($isPollerFilter) { $host = array(); } diff --git a/cron/centAcl.php b/cron/centAcl.php index 9caa13ce6c3..1b211d01d73 100644 --- a/cron/centAcl.php +++ b/cron/centAcl.php @@ -45,6 +45,10 @@ $centreonDbName = $conf_centreon['db']; $centreonLog = new CentreonLog(); +/* + * Define the period between two update in second for LDAP user/contactgroup + */ +define('LDAP_UPDATE_PERIOD', 3600); /** * CentAcl script @@ -78,10 +82,7 @@ if (empty($data)) { try { // at first run (eg: after the install), data may be missing. - $pearDB->query( - "INSERT INTO cron_operation (name, system, activate) - VALUES ('centAcl.php', '1', '1')" - ); + $pearDB->query("INSERT INTO cron_operation (name, system, activate) VALUES ('centAcl.php', '1', '1')"); } catch (\PDOException $e) { programExit("Error can't insert centAcl values in the `cron_operation` table."); } @@ -110,9 +111,31 @@ programExit($errorMessage); } - $resourceCache = array(); + /** + * Sync ACL with LDAP's contactgroup + * If the LDAP is enabled and the last check is greater than the update period + * + * @TODO : Synchronize LDAP with contacts data in background to avoid it at login + */ + $ldapEnable = '0'; + $ldapLastUpdate = 0; + $queryOptions = "SELECT `key`, `value` FROM `options` WHERE `key` IN ('ldap_auth_enable', 'ldap_last_acl_update')"; + $res = $pearDB->query($queryOptions); + while ($row = $res->fetch()) { + switch ($row['key']) { + case 'ldap_auth_enable': + $ldapEnable = $row['value']; + break; + case 'ldap_last_acl_update': + $ldapLastUpdate = $row['value']; + break; + } + } + if ($ldapEnable === '1' && $ldapLastUpdate < (time() - LDAP_UPDATE_PERIOD)) { + $cgObj->syncWithLdap(); + } - /** ********************************************** + /** * Check expected contact data sync on login with the LDAP, depending on last sync time and own sync interval */ $pearDB->beginTransaction(); @@ -143,14 +166,11 @@ programExit("Error when updating LDAP's reference date for next synchronization"); } - // @TODO : Synchronize LDAP with contacts data in background to avoid it at login - $cgObj->syncWithLdap(); - - /** ********************************************** + /** * Remove data from old groups (deleted groups) */ - $aclGroupToDelete = "SELECT DISTINCT acl_group_id " . - "FROM " . $centreonDbName . ".acl_groups WHERE acl_group_activate = '1'"; + $aclGroupToDelete = "SELECT DISTINCT acl_group_id + FROM " . $centreonDbName . ".acl_groups WHERE acl_group_activate = '1'"; $aclGroupToDelete2 = "SELECT DISTINCT acl_group_id FROM " . $centreonDbName . ".acl_res_group_relations"; $pearDB->beginTransaction(); try { @@ -165,7 +185,7 @@ ); } - /** *********************************************** + /** * Check if some ACL have global options selected for * all the resources */ @@ -181,7 +201,6 @@ /** * Add Hosts */ - if ($row['all_hosts']) { $pearDB->beginTransaction(); try { @@ -219,7 +238,6 @@ } } - /** * Add Hostgroups */ @@ -316,7 +334,6 @@ * if no : go away. * if yes : let's go to build cache and update database */ - $tabGroups = array(); $dbResult1 = $pearDB->query( "SELECT DISTINCT acl_groups.acl_group_id @@ -333,9 +350,8 @@ if (count($tabGroups)) { - /** *********************************************** + /** * Cache for hosts and host Templates - * */ $hostTemplateCache = []; $res = $pearDB->query( @@ -357,7 +373,7 @@ } unset($h); - /** *********************************************** + /** * Cache for host poller relation */ $hostPollerCache = array(); @@ -371,7 +387,7 @@ $hostPollerCache[$row['nagios_server_id']][$row['host_host_id']] = $row['host_host_id']; } - /** *********************************************** + /** * Get all included Hosts */ $hostIncCache = []; @@ -386,7 +402,7 @@ $hostIncCache[$h["acl_res_id"]][$h["host_host_id"]] = 1; } - /** *********************************************** + /** * Get all excluded Hosts */ $hostExclCache = []; @@ -401,7 +417,7 @@ $hostExclCache[$h["acl_res_id"]][$h["host_host_id"]] = 1; } - /** *********************************************** + /** * Service Cache */ $svcCache = []; @@ -413,7 +429,7 @@ $svcCache[$s["service_id"]] = 1; } - /** *********************************************** + /** * Host Host relation */ $hostHGRelation = []; @@ -426,7 +442,7 @@ } unset($hg); - /** *********************************************** + /** * Host Service relation */ $hsRelation = []; @@ -453,7 +469,7 @@ } $dbResult->closeCursor(); - /** *********************************************** + /** * Create Service template model Cache */ $svcTplCache = []; @@ -522,17 +538,18 @@ // Prepare statement $deleteHandler = $pearDBO->prepare("DELETE FROM centreon_acl WHERE group_id = ?"); - /** *********************************************** + /** * Begin to build ACL */ $cpt = 0; + $resourceCache = array(); foreach ($tabGroups as $aclGroupId) { /* * Delete old data for this group */ $deleteHandler->execute(array($aclGroupId)); - /** *********************************************** + /** * Select */ $dbResult2 = $pearDB->prepare( @@ -733,17 +750,17 @@ $stmt->bindValue(':aclGroupId', $aclGroupId, \PDO::PARAM_INT); $stmt->execute(); } - } - /** - * Include module specific ACL evaluation - */ - $extensionsPaths = getModulesExtensionsPaths($pearDB); - foreach ($extensionsPaths as $extensionPath) { - require_once $extensionPath . 'centAcl.php'; + /** + * Include module specific ACL evaluation + */ + $extensionsPaths = getModulesExtensionsPaths($pearDB); + foreach ($extensionsPaths as $extensionPath) { + require_once $extensionPath . 'centAcl.php'; + } } - /* + /** * Remove lock */ $dbResult = $pearDB->prepare( diff --git a/doc/en/api/clapi/objects/service_templates.rst b/doc/en/api/clapi/objects/service_templates.rst index 8d02f6eb5b9..cb7e9c92d91 100644 --- a/doc/en/api/clapi/objects/service_templates.rst +++ b/doc/en/api/clapi/objects/service_templates.rst @@ -225,10 +225,9 @@ Getmacro In order to view the custom macro list of a service template, use the **GETMACRO** action:: [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a getmacro -v "MyTemplate" - macro name;macro value;description - $_SERVICETIME$;80;description of macro1 - $_SERVICEPL$;400;description of macro2 - + macro name;macro value;description;is_password + $_SERVICETIME$;80;description of macro1;0 + $_SERVICEPL$;400;description of macro2;0 Setmacro -------- @@ -236,7 +235,8 @@ Setmacro In order to set a macro for a specific service template use the **SETMACRO** action:: [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;time;80" - [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;pl;400" + [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;pl;400;description" + [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;password;mypassword;;1" .. note:: You need to generate your configuration file and restart monitoring engine in order to apply changes. diff --git a/doc/en/faq/performance.rst b/doc/en/faq/performance.rst index f4bce6d33b2..3f5dc2b59e1 100644 --- a/doc/en/faq/performance.rst +++ b/doc/en/faq/performance.rst @@ -79,14 +79,16 @@ Centreon storage database schema can be view here : RRDCacheD ********* -RRDCacheD is a process to reduce disk I/O during the update of performance's graphs and status' graphs. -The RRDCacheD process is loaded by the Centreon Broker module and mutualise I/O disques instead of recording -one by one the data from the collect. +RRDCacheD is a process to reduce disk I/O during the update of performance's graphs and status' graphs. The RRDCacheD +process is loaded by the Centreon Broker module and mutualise I/O disques instead of recording one by one the data from +the collect. Installation ============ -The RRDCacheD process is available in **rrdtool** package and already installed on your server. +Execute the following command: :: + + # yum install rrdtool-cached Configuration ============= @@ -98,14 +100,13 @@ Edit the **/etc/sysconfig/rrdcached** file and complete information:: # Settings for rrdcached OPTIONS="-m 664 -l unix:/var/rrdtool/rrdcached/rrdcached.sock -s rrdcached -b /var/rrdtool/rrdcached -w 3600 -z 3600 -f 7200" - RRDC_USER=rrdcach + RRDC_USER=rrdcached .. note:: The order of setting is pretty important. If **-m 664** is define before **-l unix:/var/rrdtool/rrdcached/rrdcached.sock** option then rights will be incorrect on socket. Options are following one: - +--------+-----------------------------------------------------------------------------------+ | Option | Description | +========+===================================================================================+ @@ -118,36 +119,70 @@ Options are following one: +--------+-----------------------------------------------------------------------------------+ .. note:: - Please modify values with you needs. + Please modify values with your needs. + +Creating the service startup file +********************************* + +Replace the default **/usr/lib/systemd/system/rrdcached.service** init script: :: + + # cp /usr/share/centreon/examples/rrdcached.systemd /usr/lib/systemd/system/rrdcached.service + +Execute following commands: :: + + mkdir -p /var/rrdtool + useradd rrdcached -d '/var/rrdtool/rrdcached' -G centreon-broker,centreon -m + chmod 775 -R /var/rrdtool Groups configuration ******************** -Create groups using commands:: +Create groups using commands: :: - # usermod -a -g rrdcached centreon-broker - # usermod -a -g rrdcached apache - # usermod -a -g centreon rrdcached - # usermod -a -g centreon-broker rrdcached + # usermod -a -G rrdcached centreon-broker + # usermod -a -G rrdcached apache + # usermod -a -G centreon rrdcached + # usermod -a -G centreon-broker rrdcached -Restart Apache process:: +Restart process: :: - # systemctl restart httpd24-httpd + # systemctl daemon-reload + # systemctl enable rrdcached + # systemctl start rrdcached -Start RRDCacheD process:: +Check the status of the process: :: - # /etc/init.d/rrdcached start + # systemctl status rrdcached + ● rrdcached.service - Data caching daemon for rrdtool + Loaded: loaded (/etc/systemd/system/rrdcached.service; disabled; vendor preset: disabled) + Active: active (running) since ven. 2018-10-26 10:14:08 UTC; 39min ago + Docs: man:rrdcached(1) + Main PID: 28811 (rrdcached) + CGroup: /system.slice/rrdcached.service + └─28811 /usr/bin/rrdcached -m 664 -l unix:/var/rrdtool/rrdcached/rrdcached.sock -s rrdcached -b /var/rrdtool/rrdcached -w 7200 -f 14400 -z 3600 -p /var/rrdtool/rrdcached/rrdcached.pid + + oct. 26 10:14:08 demo-front rrdcached[28811]: starting up + oct. 26 10:14:08 demo-front systemd[1]: Started Data caching daemon for rrdtool. + oct. 26 10:14:08 demo-front rrdcached[28811]: listening for connections + oct. 26 10:14:08 demo-front systemd[1]: Starting Data caching daemon for rrdtool... Centreon web configuration ************************** -Go to **Administration > Options > RRDTool** menu, enable process and set unix socket path: +Go to **Configuration > Pollers > Broker configuration** menu, select the broker inserting data into RRD files then in +the **Output** tab enable process and set unix socket path: + +* Enable RRDCached: unix +* RRDCacheD listening socket/port: /var/rrdtool/rrdcached/rrdcached.sock + +Enable process and set unix socket path: .. image:: /images/faq/rrdcached_config.png :align: center .. warning:: - Instead of configuration was made into **Administration** you need to generate and export configuration of central server and restart cbd process to apply changes. + Instead of configuration was made into **Administration** you need to generate and export configuration of central + server and restart cbd process to apply changes. .. image:: /images/faq/rrd_file_generator.png :align: center @@ -155,7 +190,9 @@ Go to **Administration > Options > RRDTool** menu, enable process and set unix s Centreon web interface ********************** -RRDCacheD don't update performances graphs in real time. If a blank range appears on right of performances graphs it means that cache are not yet written to disk. +RRDCacheD don't update performances graphs in real time. If a blank range appears on right of performances graphs it +means that cache are not yet written to disk. .. warning:: - If the **RRDCacheD process crash** (in theory because it's a stable process) data will be lost! It is not possible to get data unless rebuild all graphs from Centreon web. + If the **RRDCacheD process crash** (in theory because it's a stable process) data will be lost! It is not possible + to get data unless rebuild all graphs from Centreon web. diff --git a/doc/en/images/faq/rrdcached_config.png b/doc/en/images/faq/rrdcached_config.png index a681679b10a..28338f8c898 100644 Binary files a/doc/en/images/faq/rrdcached_config.png and b/doc/en/images/faq/rrdcached_config.png differ diff --git a/doc/fr/api/clapi/objects/service_templates.rst b/doc/fr/api/clapi/objects/service_templates.rst index bfc10ad3d42..3e6f7b24ad9 100644 --- a/doc/fr/api/clapi/objects/service_templates.rst +++ b/doc/fr/api/clapi/objects/service_templates.rst @@ -224,9 +224,9 @@ Getmacro In order to view the custom macro list of a service template, use the **GETMACRO** action:: [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a getmacro -v "MyTemplate" - macro name;macro value;description - $_SERVICETIME$;80;description of macro1 - $_SERVICEPL$;400;description of macro2 + macro name;macro value;description;is_password + $_SERVICETIME$;80;description of macro1;0 + $_SERVICEPL$;400;description of macro2;0 Setmacro @@ -235,7 +235,8 @@ Setmacro In order to set a macro for a specific service template use the **SETMACRO** action:: [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;time;80" - [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;pl;400" + [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;pl;400;description" + [root@centreon ~]# ./centreon -u admin -p centreon -o STPL -a setmacro -v "MyTemplate;password;mypassword;;1" .. note:: You need to generate your configuration file and restart monitoring engine in order to apply changes. diff --git a/doc/fr/faq/performance.rst b/doc/fr/faq/performance.rst index f37856d0bc7..e2caae5f002 100644 --- a/doc/fr/faq/performance.rst +++ b/doc/fr/faq/performance.rst @@ -28,7 +28,7 @@ cas où des index sont manquants les requêtes sont plus longues à être exécu Synchronisation des index ************************* -Des fichiers d'index sont générées pour chaque version de Centreon depuis la version `2.4.0``. +Des fichiers d'index sont générées pour chaque version de Centreon depuis la version ``2.4.0``. Ils sont situés dans le répertoire ``data`` normalement situé dans les répertoires ``bin`` ou ``www``. Il y a un fichier JSON pour chaque base de données: @@ -79,15 +79,16 @@ Le schéma de la base de données Centreon_storage ici : RRDCacheD ********* -RRDCacheD est un processus qui permet de limiter les E/S disque lors de la mise à jour des graphiques -de performance et/ou des graphiques de statut (fichiers RRDs). -Pour cela, le processus RRDCacheD est appelé par le module Centreon Broker et mutualise les écritures -sur disque plutôt que d'enregistrer une à une les données issues de la collecte. +RRDCacheD est un processus qui permet de limiter les E/S disque lors de la mise à jour des graphiques de performance +et/ou des graphiques de statut (fichiers RRDs). Pour cela, le processus RRDCacheD est appelé par le module Centreon +Broker et mutualise les écritures sur disque plutôt que d'enregistrer une à une les données issues de la collecte. Installation ============ -Le processus RRDCacheD est disponible dnas le paquet **rrdtool** déjà installé sur votre serveur Centreon. +Exécuter la commande suivante : :: + + # yum install rrdtool-cached Configuration ============= @@ -98,11 +99,12 @@ Options générales Éditer le fichier **/etc/sysconfig/rrdcached** et modifier les informations suivantes :: # Settings for rrdcached - OPTIONS="-m 664 -l unix:/var/rrdtool/rrdcached/rrdcached.sock -s rrdcached -b /var/rrdtool/rrdcached -w 3600 -z 3600 -f 7200" + OPTIONS="-m 664 -l unix:/var/rrdtool/rrdcached/rrdcached.sock -s rrdcached -b /var/rrdtool/rrdcached -w 3600 -z 3600 -f 7200" RRDC_USER=rrdcached .. note:: - L'ordre des options est très important, si l'option ** -m 664** est placée après l'option **-l unix:/var/rrdtool/rrdcached/rrdcached.sock** alors la socket sera créée avec les mauvais droits. + L'ordre des options est très important, si l'option ** -m 664** est placée après l'option + **-l unix:/var/rrdtool/rrdcached/rrdcached.sock** alors la socket sera créée avec les mauvais droits. Concernant les autres options importantes : @@ -123,34 +125,66 @@ Concernant les autres options importantes : .. note:: Ces valeurs doivent être adaptées en fonction du besoin/des contraintes de la plate-forme concernée ! +Création du fichier de démarrage du service +******************************************* + +Remplacer le fichier par defaut **/usr/lib/systemd/system/rrdcached.service** : :: + + # cp /usr/share/centreon/examples/rrdcached.systemd /usr/lib/systemd/system/rrdcached.service + +Exécuter les actions suivantes : :: + + mkdir -p /var/rrdtool + useradd rrdcached -d '/var/rrdtool/rrdcached' -G centreon-broker,centreon -m + chmod 775 -R /var/rrdtool + Configuration des groupes ************************* Créer les groupes en exécutant les commandes suivantes :: - # usermod -a -g rrdcached centreon-broker - # usermod -a -g rrdcached apache - # usermod -a -g centreon rrdcached - # usermod -a -g centreon-broker rrdcached + # usermod -a -G rrdcached centreon-broker + # usermod -a -G rrdcached apache + # usermod -a -G centreon rrdcached + # usermod -a -G centreon-broker rrdcached -Redémarrer le processus Apache pour prendre en compte les modifications :: +Redémarrer les processus : :: - # systemctl restart httpd24-httpd + # systemctl daemon-reload + # systemctl enable rrdcached + # systemctl start rrdcached -Démarrer le processus RRDCacheD :: +Contrôler le statut du processus : :: - # /etc/init.d/rrdcached start + # systemctl status rrdcached + ● rrdcached.service - Data caching daemon for rrdtool + Loaded: loaded (/etc/systemd/system/rrdcached.service; disabled; vendor preset: disabled) + Active: active (running) since ven. 2018-10-26 10:14:08 UTC; 39min ago + Docs: man:rrdcached(1) + Main PID: 28811 (rrdcached) + CGroup: /system.slice/rrdcached.service + └─28811 /usr/bin/rrdcached -m 664 -l unix:/var/rrdtool/rrdcached/rrdcached.sock -s rrdcached -b /var/rrdtool/rrdcached -w 7200 -f 14400 -z 3600 -p /var/rrdtool/rrdcached/rrdcached.pid + + oct. 26 10:14:08 demo-front rrdcached[28811]: starting up + oct. 26 10:14:08 demo-front systemd[1]: Started Data caching daemon for rrdtool. + oct. 26 10:14:08 demo-front rrdcached[28811]: listening for connections + oct. 26 10:14:08 demo-front systemd[1]: Starting Data caching daemon for rrdtool... Configurer le processus dans l'interface web Centreon ***************************************************** -Se rendre dans le menu **Administration > Options > RRDTool**, activer l'utilisation du processus et renseigner l'accès au socket **/var/rrdtool/rrdcached/rrdcached.sock** : +Se rendre dans le menu **Configuration > Pollers > Broker configuration**, éditer le broker insérant les données dans +les fichiers RRD, sans l'onglet "Output" renseigner les données suivantes : + +* Enable RRDCached: unix +* RRDCacheD listening socket/port: /var/rrdtool/rrdcached/rrdcached.sock .. image:: /images/faq/rrdcached_config.png :align: center .. warning:: - Attention, même si la modification a été réalisé dans le menu **Administration**, il est nécessaire d'exporter la configuration et de redémarrer le processus centreon-broker via un export de la configuration du serveur central et un redémarrage du processus cbd. + Attention, même si la modification a été réalisé, il est nécessaire d'exporter la configuration et de redémarrer le + processus centreon-broker via un export de la configuration du serveur central et un redémarrage du processus cbd. .. image:: /images/faq/rrd_file_generator.png :align: center @@ -163,4 +197,5 @@ Il est donc possible de voir un petit blanc sur la droite de certains graphiques Cela veut dire que les données sont encore dans le cache du processus, cela est normal ! .. warning:: - Attention, si le **processus crash** pour une raison quelconque (aucune en théorie c'est plutôt stable), les **données** sont **perdues**, donc aucun moyen de les rejouer sauf en reconstruisant les graphiques via centreon-broker. + Attention, si le **processus crash** pour une raison quelconque (aucune en théorie c'est plutôt stable), les + **données** sont **perdues**, donc aucun moyen de les rejouer sauf en reconstruisant les graphiques via centreon-broker. diff --git a/doc/fr/images/faq/rrdcached_config.png b/doc/fr/images/faq/rrdcached_config.png index b27296e14b5..28338f8c898 100644 Binary files a/doc/fr/images/faq/rrdcached_config.png and b/doc/fr/images/faq/rrdcached_config.png differ diff --git a/src/Centreon/Domain/Repository/NagiosServerRepository.php b/src/Centreon/Domain/Repository/NagiosServerRepository.php index d313437d2ff..fa946dc1a01 100644 --- a/src/Centreon/Domain/Repository/NagiosServerRepository.php +++ b/src/Centreon/Domain/Repository/NagiosServerRepository.php @@ -93,4 +93,33 @@ public function truncate() $stmt = $this->db->prepare($sql); $stmt->execute(); } + + /** + * Sets poller as updated (shows that poller needs restarting) + * @param int $id id of poller + */ + public function setUpdated(int $id): void + { + $sql = "UPDATE `nagios_server` SET `updated` = '1' WHERE `id` = :id"; + $stmt = $this->db->prepare($sql); + $stmt->bindParam(':id', $id, \PDO::PARAM_INT); + $stmt->execute(); + } + + /** + * Get Central Poller + * @return int|null + */ + public function getCentral(): ?int + { + $query = "SELECT id FROM nagios_server WHERE localhost = '1' LIMIT 1"; + $stmt = $this->db->prepare($query); + $stmt->execute(); + + if (!$stmt->rowCount()) { + return null; + } + + return (int)$stmt->fetch()['id']; + } } diff --git a/tmpl/install/redhat/rrdcached.systemd b/tmpl/install/redhat/rrdcached.systemd new file mode 100644 index 00000000000..3e7b4ddf0dd --- /dev/null +++ b/tmpl/install/redhat/rrdcached.systemd @@ -0,0 +1,14 @@ +[Unit] +Description=Data caching daemon for rrdtool +Documentation=man:rrdcached(1) + +[Service] +# If you enable socket-activable rrdcached.socket, +# command line socket declarations will be ignored +PIDFile=/var/rrdtool/rrdcached/rrdcached.pid +EnvironmentFile=/etc/sysconfig/rrdcached +ExecStart=/usr/bin/rrdcached $OPTIONS -p /var/rrdtool/rrdcached/rrdcached.pid +User=rrdcached + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/www/class/centreon-clapi/centreonServiceTemplate.class.php b/www/class/centreon-clapi/centreonServiceTemplate.class.php index f44792c17d5..764891202ed 100644 --- a/www/class/centreon-clapi/centreonServiceTemplate.class.php +++ b/www/class/centreon-clapi/centreonServiceTemplate.class.php @@ -480,18 +480,20 @@ public function getmacro($parameters) } $macroObj = new \Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( - array("svc_macro_name", "svc_macro_value", "description"), + array("svc_macro_name", "svc_macro_value", "description", "is_password"), -1, 0, null, null, array("svc_svc_id" => $elements[0]['service_id']) ); - echo "macro name;macro value;description\n"; + echo "macro name;macro value;description;is_password\n"; foreach ($macroList as $macro) { + $password = !empty($macro['is_password']) ? (int)$macro['is_password'] : 0; echo $macro['svc_macro_name'] . $this->delim - . $macro['svc_macro_value'] . $this->delim - . $macro['description'] . "\n"; + . $macro['svc_macro_value'] . $this->delim + . $macro['description'] . $this->delim + . $password . "\n"; } } @@ -509,7 +511,11 @@ public function setmacro($parameters) throw new CentreonClapiException(self::MISSINGPARAMETER); } - $params[3] = isset($params[3]) ? $params[3] : null; + $serviceDescription = $params[0]; + $macroName = $params[1]; + $macroValue = $params[2]; + $macroDescription = isset($params[3]) ? $params[3] : ''; + $macroPassword = !empty($params[4]) ? (int)$params[4] : 0; $elements = $this->object->getList( "service_id", @@ -518,13 +524,13 @@ public function setmacro($parameters) null, null, array( - 'service_description' => $params[0], + 'service_description' => $serviceDescription, 'service_register' => 0 ), "AND" ); if (!count($elements)) { - throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ":" . $params[0]); + throw new CentreonClapiException(self::OBJECT_NOT_FOUND . ":" . $serviceDescription); } $macroObj = new \Centreon_Object_Service_Macro_Custom($this->dependencyInjector); $macroList = $macroObj->getList( @@ -535,7 +541,7 @@ public function setmacro($parameters) null, array( "svc_svc_id" => $elements[0]['service_id'], - "svc_macro_name" => $this->wrapMacro($params[1]) + "svc_macro_name" => $this->wrapMacro($macroName) ), "AND" ); @@ -543,17 +549,19 @@ public function setmacro($parameters) $macroObj->update( $macroList[0][$macroObj->getPrimaryKey()], array( - 'svc_macro_value' => $params[2], - 'description' => isset($params[3]) ? $params[3] : '' + 'svc_macro_value' => $macroValue, + 'is_password' => $macroPassword, + 'description' => $macroDescription ) ); } else { $macroObj->insert( array( 'svc_svc_id' => $elements[0]['service_id'], - 'svc_macro_name' => $this->wrapMacro($params[1]), - 'svc_macro_value' => $params[2], - 'description' => isset($params[3]) ? $params[3] : '' + 'svc_macro_name' => $this->wrapMacro($macroName), + 'is_password' => $macroPassword, + 'svc_macro_value' => $macroValue, + 'description' => $macroDescription ) ); } diff --git a/www/class/centreonGraph.class.php b/www/class/centreonGraph.class.php index 4c4d59f13f4..888b87f546f 100644 --- a/www/class/centreonGraph.class.php +++ b/www/class/centreonGraph.class.php @@ -113,6 +113,7 @@ class CentreonGraph protected $vname; protected $metrics; protected $longer; + protected $rrdCachedOptions; public $onecurve; public $checkcurve; @@ -206,6 +207,19 @@ public function __construct($user_id, $index = null, $debug = 0, $compress = nul $DBRESULT->closeCursor(); unset($opt); + /* Get RRDCacheD options */ + $result = $this->DB->query( + "SELECT config_key, config_value + FROM cfg_centreonbroker_info AS cbi + INNER JOIN cfg_centreonbroker AS cb ON (cb.config_id = cbi.config_id) + INNER JOIN nagios_server AS ns ON (ns.id = cb.ns_nagios_server) + WHERE ns.localhost = '1' + AND cbi.config_key IN ('rrd_cached_option', 'rrd_cached')" + ); + while ($row = $result->fetch()) { + $this->rrdCachedOptions[$row['config_key']] = $row['config_value']; + } + if (isset($index)) { $DBRESULT = $this->DB->query("SELECT `metric_id` FROM `ods_view_details` @@ -1504,9 +1518,11 @@ public function getOVDColor($metricId) if (is_null($this->colorCache)) { $this->colorCache = array(); - $DBRESULT = $this->DB->query("SELECT metric_id, rnd_color FROM `ods_view_details` WHERE `index_id` = '" . $this->index . "'"); + $DBRESULT = $this->DB->query( + "SELECT metric_id, rnd_color FROM `ods_view_details` WHERE `index_id` = '" . $this->index . "'" + ); while (($row = $DBRESULT->fetchRow())) { - $this->colorCache[$row['metric_id']] = $row['rnd_color']; + $this->colorCache[$row['metric_id']] = $row['rnd_color']; } } @@ -1519,7 +1535,7 @@ public function getOVDColor($metricId) 'INSERT INTO `ods_view_details` (rnd_color, index_id, metric_id) ' . 'VALUES ("' . $lRndcolor . '", ' . $this->index . ', ' . $metricId . ')' ); - } + } return $lRndcolor; } @@ -1565,7 +1581,7 @@ public function getRandomWebColor() '#ff66ff', '#ff9900', '#ff9933', '#ff9966', '#ff9999', '#ff99cc', '#ff99ff', '#ffcc00', '#ffcc33', '#ffcc66', '#ffcc99', '#ffcccc', '#ffccff'); - return $webSafeColors[rand(0,sizeof($webSafeColors)-1)]; + return $webSafeColors[rand(0, sizeof($webSafeColors)-1)]; } /** @@ -1780,8 +1796,8 @@ private function checkDBAvailability($metric_id) */ protected function flushRrdcached($metricsId) { - if (!isset($this->generalOpt['rrdcached_enable']) - || $this->generalOpt['rrdcached_enable'] == 0 + if (!isset($this->rrdCachedOptions['rrd_cached_option']) + || !in_array($this->rrdCachedOptions['rrd_cached_option'], ['unix', 'tcp']) ) { return true; } @@ -1791,20 +1807,14 @@ protected function flushRrdcached($metricsId) */ $errno = 0; $errstr = ''; - if (isset($this->generalOpt['rrdcached_port']) - && trim($this->generalOpt['rrdcached_port']) != '' - ) { - $sock = @fsockopen('127.0.0.1', trim($this->generalOpt['rrdcached_port']), $errno, $errstr); - if ($sock === false) { - return false; - } - } elseif (isset($this->generalOpt['rrdcached_unix_path']) - && trim($this->generalOpt['rrdcached_unix_path']) != '' - ) { - $sock = @fsockopen('unix://' . trim($this->generalOpt['rrdcached_unix_path']), $errno, $errstr); + if ($this->rrdCachedOptions['rrd_cached_option'] === 'tcp') { + $sock = fsockopen('127.0.0.1', trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr); + } elseif ($this->rrdCachedOptions['rrd_cached_option'] === 'unix') { + $sock = fsockopen('unix://' . trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr); } else { return false; } + if (false === $sock) { // @todo log the error return false; diff --git a/www/class/centreonGraphNg.class.php b/www/class/centreonGraphNg.class.php index a788d9a5bb1..44d4d8aaccd 100644 --- a/www/class/centreonGraphNg.class.php +++ b/www/class/centreonGraphNg.class.php @@ -156,6 +156,7 @@ class CentreonGraphNg protected $vnodesDependencies; protected $vmetricsOrder; protected $graphData; + protected $rrdCachedOptions; /** * Connect to databases @@ -228,6 +229,20 @@ public function __construct($userId) $stmt = $this->db->prepare("SELECT `key`, `value` FROM options"); $stmt->execute(); $this->generalOpt = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC); + + /* Get RRDCacheD options */ + $stmt = $this->db->query( + "SELECT config_key, config_value + FROM cfg_centreonbroker_info AS cbi + INNER JOIN cfg_centreonbroker AS cb ON (cb.config_id = cbi.config_id) + INNER JOIN nagios_server AS ns ON (ns.id = cb.ns_nagios_server) + WHERE ns.localhost = '1' + AND cbi.config_key IN ('rrd_cached_option', 'rrd_cached')" + ); + + while ($row = $stmt->fetch()) { + $this->rrdCachedOptions[$row['config_key']] = $row['config_value']; + } } /** @@ -332,8 +347,8 @@ protected function getCurveDsConfig($metric) break; } - if (is_null($dsDataRegular) && - preg_match('/^' . preg_quote($dsVal['ds_name'], '/') . '$/i', $metric['metric_name']) + if (is_null($dsDataRegular) + && preg_match('/^' . preg_quote($dsVal['ds_name'], '/') . '$/i', $metric['metric_name']) ) { $dsDataRegular = $dsVal; } @@ -594,11 +609,12 @@ public function addMetric($metricId, $isVirtual = 0) { if ($isVirtual == 0) { $stmt = $this->dbCs->prepare( - "SELECT m.index_id, host_id, service_id, metric_id, metric_name, unit_name, min, max, warn, warn_low, crit, crit_low - FROM metrics AS m, index_data AS i - WHERE m.metric_id = :metric_id - AND m.hidden = '0' - AND m.index_id = i.id" + "SELECT m.index_id, host_id, service_id, metric_id, metric_name, + unit_name, min, max, warn, warn_low, crit, crit_low + FROM metrics AS m, index_data AS i + WHERE m.metric_id = :metric_id + AND m.hidden = '0' + AND m.index_id = i.id" ); $stmt->bindParam(':metric_id', $metricId, PDO::PARAM_INT); $stmt->execute(); @@ -655,7 +671,8 @@ private function initCurveList() foreach ($this->metrics as $metricId => &$tm) { if (isset($tm['ds_data']['ds_invert']) && $tm['ds_data']['ds_invert']) { - $this->addArgument("DEF:vi" . $metricId . "=" . $this->dbPath . $metricId . ".rrd:value:AVERAGE CDEF:v" . $metricId . "=vi" . $metricId . ",-1,*"); + $this->addArgument("DEF:vi" . $metricId . "=" . $this->dbPath . $metricId . ".rrd:value:AVERAGE CDEF:v" + . $metricId . "=vi" . $metricId . ",-1,*"); } else { $this->addArgument("DEF:v" . $metricId . "=" . $this->dbPath . $metricId . ".rrd:value:AVERAGE"); } @@ -664,7 +681,8 @@ private function initCurveList() $this->manageMetrics(); foreach ($this->vmetricsOrder as $vmetricId) { - $this->addArgument($this->vmetrics[$vmetricId]['def_type'] . ":vv" . $vmetricId . "=" . $this->vmetrics[$vmetricId]['rpn_function']); + $this->addArgument($this->vmetrics[$vmetricId]['def_type'] . ":vv" . $vmetricId . "=" + . $this->vmetrics[$vmetricId]['rpn_function']); } } @@ -876,7 +894,8 @@ private function getIndexData() } if ($this->indexData["host_name"] != "_Module_Meta") { - $this->extraDatas['title'] = $this->indexData['service_description'] . " " . _("graph on") . " " . $this->indexData['host_name']; + $this->extraDatas['title'] = $this->indexData['service_description'] . " " . _("graph on") . " " + . $this->indexData['host_name']; } else { $this->extraDatas['title'] = _("Graph") . " " . $this->indexData["service_description"]; } @@ -1034,7 +1053,13 @@ public function getJsonStream() 2 => $stderr ); - $process = proc_open($this->generalOpt['rrdtool_path_bin']['value'] . " - ", $descriptorspec, $pipes, null, null); + $process = proc_open( + $this->generalOpt['rrdtool_path_bin']['value'] . " - ", + $descriptorspec, + $pipes, + null, + null + ); $this->graphData = array( 'global' => $this->extraDatas, 'metrics' => array(), @@ -1101,17 +1126,23 @@ public function getOVDColor($indexId, $metricId) if (is_null($this->colorCache)) { $this->colorCache = array(); - $stmt = $this->db->prepare("SELECT metric_id, rnd_color FROM `ods_view_details` WHERE `index_id` = :index_id"); + $stmt = $this->db->prepare( + "SELECT metric_id, rnd_color FROM `ods_view_details` WHERE `index_id` = :index_id" + ); $stmt->bindParam(':index_id', $indexId, PDO::PARAM_INT); $stmt->execute(); $this->colorCache = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC); } - if (isset($this->colorCache[$metricId]) && preg_match("/^\#[a-f0-9]{6,6}/i", $this->colorCache[$metricId]['rnd_color'])) { + if (isset($this->colorCache[$metricId]) + && preg_match("/^\#[a-f0-9]{6,6}/i", $this->colorCache[$metricId]['rnd_color']) + ) { return $this->colorCache[$metricId]['rnd_color']; } $lRndcolor = $this->getRandomWebColor(); - $stmt = $this->db->prepare("INSERT INTO `ods_view_details` (rnd_color, index_id, metric_id) VALUES (:rnd_color, :index_id, :metric_id)"); + $stmt = $this->db->prepare( + "INSERT INTO `ods_view_details` (rnd_color, index_id, metric_id) VALUES (:rnd_color, :index_id, :metric_id)" + ); $stmt->bindParam(':rnd_color', $lRndcolor, PDO::PARAM_STR); $stmt->bindParam(':index_id', $indexId, PDO::PARAM_INT); $stmt->bindParam(':metric_id', $metricId, PDO::PARAM_INT); @@ -1231,23 +1262,22 @@ private function checkDBAvailability($metricId) */ protected function flushRrdcached($metricsId) { - if (!isset($this->generalOpt['rrdcached_enable']['value']) - || $this->generalOpt['rrdcached_enable']['value'] == 0) { + if (!isset($this->rrdCachedOptions['rrd_cached_option']) + || !in_array($this->rrdCachedOptions['rrd_cached_option'], ['unix', 'tcp']) + ) { return true; } $errno = 0; $errstr = ''; - if (isset($this->generalOpt['rrdcached_port']['value']) - && trim($this->generalOpt['rrdcached_port']['value']) != '') { - $sock = fsockopen('127.0.0.1', trim($this->generalOpt['rrdcached_port']['value']), $errno, $errstr); - } elseif (isset($this->generalOpt['rrdcached_unix_path']['value']) - && trim($this->generalOpt['rrdcached_unix_path']['value']) != '') { - $sock = fsockopen('unix://' . trim($this->generalOpt['rrdcached_unix_path']['value']), $errno, $errstr); + if ($this->rrdCachedOptions['rrd_cached_option'] === 'tcp') { + $sock = fsockopen('127.0.0.1', trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr); + } elseif ($this->rrdCachedOptions['rrd_cached_option'] === 'unix') { + $sock = fsockopen('unix://' . trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr); } else { return false; } - + if (false === $sock) { $this->log("socket connection: " . $errstr); return false; diff --git a/www/class/centreonGraphService.class.php b/www/class/centreonGraphService.class.php index bea982aa089..581c0ae4ddd 100644 --- a/www/class/centreonGraphService.class.php +++ b/www/class/centreonGraphService.class.php @@ -122,6 +122,7 @@ public function getData($rows = 200) "warn" => null ); $info['legend'] = str_replace('\\\\', '\\', $metric['metric_legend']); + $info['metric_name'] = !empty($metric['ds_name']) ? $metric['ds_name'] : $info['legend']; /* Add legend getting data */ foreach ($legendDataInfo as $name => $key) { diff --git a/www/class/centreonGraphStatus.class.php b/www/class/centreonGraphStatus.class.php index d270a0bec4a..18611ea3bd5 100644 --- a/www/class/centreonGraphStatus.class.php +++ b/www/class/centreonGraphStatus.class.php @@ -54,6 +54,7 @@ public function __construct($index, $start, $end) $this->endTime = $end; $this->statusPath = $this->getStatusPath(); $this->generalOpt = $this->getOptions(); + $this->rrdCachedOptions = $this->getRrdCachedOptions(); } /** @@ -133,28 +134,22 @@ public function getData() */ public function flushRrdCached($indexData) { - if (false === isset($this->generalOpt['rrdcached_enabled']) || - $this->generalOpt['rrdcached_enabled'] == 0 + if (!isset($this->rrdCachedOptions['rrd_cached_option']) + || !in_array($this->rrdCachedOptions['rrd_cached_option'], ['unix', 'tcp']) ) { return true; } $errno = 0; $errstr = ''; - if (isset($this->general_opt['rrdcached_port']) - && trim($this->general_opt['rrdcached_port']) != '' - ) { - $sock = @fsockopen('127.0.0.1', trim($this->general_opt['rrdcached_port']), $errno, $errstr); - if ($sock === false) { - return false; - } - } elseif (isset($this->general_opt['rrdcached_unix_path']) - && trim($this->general_opt['rrdcached_unix_path']) != '' - ) { - $sock = @fsockopen('unix://' . trim($this->general_opt['rrdcached_unix_path']), $errno, $errstr); + if ($this->rrdCachedOptions['rrd_cached_option'] === 'tcp') { + $sock = fsockopen('127.0.0.1', trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr); + } elseif ($this->rrdCachedOptions['rrd_cached_option'] === 'unix') { + $sock = fsockopen('unix://' . trim($this->rrdCachedOptions['rrd_cached']), $errno, $errstr); } else { return false; } + if (false === $sock) { return false; } @@ -209,6 +204,30 @@ protected function getOptions() } return $result; } + + /** + * Get the RRDCacheD options of local RRD Broker + * + * @return array of RRDCacheD options + */ + protected function getRrdCachedOptions() + { + $result = $this->pearDB->query( + "SELECT config_key, config_value + FROM cfg_centreonbroker_info AS cbi + INNER JOIN cfg_centreonbroker AS cb ON (cb.config_id = cbi.config_id) + INNER JOIN nagios_server AS ns ON (ns.id = cb.ns_nagios_server) + WHERE ns.localhost = '1' + AND cbi.config_key IN ('rrd_cached_option', 'rrd_cached')" + ); + + $rrdCachedOptions = []; + while ($row = $result->fetch()) { + $this->rrdCachedOptions[$row['config_key']] = $row['config_value']; + } + + return $rrdCachedOptions; + } /** * Get the status RRD path diff --git a/www/class/config-generate-remote/Host.php b/www/class/config-generate-remote/Host.php index eda729197c8..a1cdec444b6 100644 --- a/www/class/config-generate-remote/Host.php +++ b/www/class/config-generate-remote/Host.php @@ -49,6 +49,8 @@ private function getHostGroups(array &$host) $this->stmtHg = $this->backendInstance->db->prepare("SELECT hostgroup_hg_id FROM hostgroup_relation + INNER JOIN hostgroup ON hg_id = hostgroup_hg_id + AND hg_activate = '1' WHERE host_host_id = :host_id "); } diff --git a/www/class/config-generate-remote/Relations/TrapsMatching.php b/www/class/config-generate-remote/Relations/TrapsMatching.php index 932b9a0c70c..837e98715ca 100644 --- a/www/class/config-generate-remote/Relations/TrapsMatching.php +++ b/www/class/config-generate-remote/Relations/TrapsMatching.php @@ -22,6 +22,7 @@ use \PDO; use ConfigGenerateRemote\Abstracts\AbstractObject; +use ConfigGenerateRemote\ServiceCategory; class TrapsMatching extends AbstractObject { @@ -106,7 +107,7 @@ public function generateObject($trapId, $trapMatchCache) continue; } $this->generateObjectInFile($value, $value['tmo_id']); - serviceCategory::getInstance($this->dependencyInjector)->generateObject($value['severity_id']); + ServiceCategory::getInstance($this->dependencyInjector)->generateObject($value['severity_id']); } } diff --git a/www/class/config-generate/contact.class.php b/www/class/config-generate/contact.class.php index 3c56290b100..3507270f050 100644 --- a/www/class/config-generate/contact.class.php +++ b/www/class/config-generate/contact.class.php @@ -226,20 +226,21 @@ public function generateFromContactId($contact_id) if (is_null($this->contacts[$contact_id])) { return null; } - if ($this->checkGenerate($contact_id)) { - return $this->contacts[$contact_id]['register'] == 1 - ? $this->contacts[$contact_id]['contact_name'] - : $this->contacts[$contact_id]['name']; - } if ($this->contacts[$contact_id]['register'] == 0 && !isset($this->contacts[$contact_id]['name'])) { $this->contacts[$contact_id]['name'] = $this->contacts[$contact_id]['contact_name']; unset($this->contacts[$contact_id]['contact_name']); } - $this->contacts[$contact_id]['use'] = array(); - $this->contacts[$contact_id]['use'][] = - $this->generateFromContactId($this->contacts[$contact_id]['contact_template_id']); + if ($this->checkGenerate($contact_id)) { + return $this->contacts[$contact_id]['register'] == 1 + ? $this->contacts[$contact_id]['contact_name'] + : $this->contacts[$contact_id]['name']; + } + + $this->contacts[$contact_id]['use'] = [ + $this->generateFromContactId($this->contacts[$contact_id]['contact_template_id']) + ]; $this->getContactNotificationCommands($contact_id, 'host'); $this->getContactNotificationCommands($contact_id, 'service'); $period = Timeperiod::getInstance($this->dependencyInjector); diff --git a/www/include/Administration/myAccount/DB-Func.php b/www/include/Administration/myAccount/DB-Func.php index c99deeb4e4f..bce49bde2b2 100644 --- a/www/include/Administration/myAccount/DB-Func.php +++ b/www/include/Administration/myAccount/DB-Func.php @@ -169,7 +169,9 @@ function updateContact($contact_id = null) $rq .= "contact_js_effects = "; isset($ret["contact_js_effects"]) ? $rq .= "'1', " : $rq .= "'0', "; $rq .= "contact_autologin_key = "; - $rq .= isset($ret["contact_autologin_key"]) ? "'" . $pearDB->escape($ret['contact_autologin_key']) . "'" : "''"; + $rq .= !empty($ret["contact_autologin_key"]) + ? "'" . $pearDB->escape($ret['contact_autologin_key']) . "'" + : "NULL "; $rq .= "WHERE contact_id = :contactId"; $stmt = $pearDB->prepare($rq); diff --git a/www/include/Administration/parameters/rrdtool/form.ihtml b/www/include/Administration/parameters/rrdtool/form.ihtml index 76c0807c700..be9eb74abcd 100644 --- a/www/include/Administration/parameters/rrdtool/form.ihtml +++ b/www/include/Administration/parameters/rrdtool/form.ihtml @@ -34,26 +34,4 @@ {/if} {$form.hidden} - {$helptext} diff --git a/www/include/configuration/configGenerate/xml/restartPollers.php b/www/include/configuration/configGenerate/xml/restartPollers.php index 6aeddb43adb..c6b3990607d 100644 --- a/www/include/configuration/configGenerate/xml/restartPollers.php +++ b/www/include/configuration/configGenerate/xml/restartPollers.php @@ -196,7 +196,7 @@ function log_error($errno, $errstr, $errfile, $errline) } } $DBRESULT = $pearDB->query("UPDATE `nagios_server` SET `last_restart` = '" - . time() . "' WHERE `id` = '" . $host["id"] . "'"); + . time() . "', `updated` = '0' WHERE `id` = '" . $host["id"] . "'"); } foreach ($msg_restart as $key => $str) { diff --git a/www/include/configuration/configObject/host/formHost.ihtml b/www/include/configuration/configObject/host/formHost.ihtml index ecfe277c7ae..1a8ee76bef1 100644 --- a/www/include/configuration/configObject/host/formHost.ihtml +++ b/www/include/configuration/configObject/host/formHost.ihtml @@ -550,7 +550,7 @@ jQuery(function() { } {/literal}{else}{literal} if ($passwordCheckbox.is(':checked')) { - $passwordCheckbox.parent('span').hide(); + $passwordCheckbox.closest('span').hide(); } {/literal}{/if}{literal} }); @@ -682,7 +682,7 @@ function clonerefreshListener(el){ if (jQuery(elem).find("input[id^='macroPassword_']").is(':checked')) { jQuery(elem).find("input[name^='macroValue']").prop('type', 'password'); - jQuery(elem).find("input[id^='macroPassword_']").parent('span').hide(); + jQuery(elem).find("input[id^='macroPassword_']").closest('span').hide(); } }); } diff --git a/www/include/configuration/configObject/service/formService.ihtml b/www/include/configuration/configObject/service/formService.ihtml index e48760af01a..f7bdb69e29c 100644 --- a/www/include/configuration/configObject/service/formService.ihtml +++ b/www/include/configuration/configObject/service/formService.ihtml @@ -472,7 +472,7 @@ jQuery(function() { } {/literal}{else}{literal} if ($passwordCheckbox.is(':checked')) { - $passwordCheckbox.parent('span').hide(); + $passwordCheckbox.closest('span').hide(); } {/literal}{/if}{literal} @@ -590,7 +590,7 @@ jQuery(function() { if (jQuery(elem).find("input[id^='macroPassword_']").is(':checked')) { jQuery(elem).find("input[name^='macroValue']").prop('type', 'password'); - jQuery(elem).find("input[id^='macroPassword_']").parent('span').hide(); + jQuery(elem).find("input[id^='macroPassword_']").closest('span').hide(); } }); } diff --git a/www/include/configuration/configObject/traps-mibs/formMibs.php b/www/include/configuration/configObject/traps-mibs/formMibs.php index a7baa46e8d0..969809a4033 100755 --- a/www/include/configuration/configObject/traps-mibs/formMibs.php +++ b/www/include/configuration/configObject/traps-mibs/formMibs.php @@ -70,15 +70,6 @@ function myDecodeMib($arg) 'linkedObject' => 'centreonManufacturer' ); -/** - * commented out as deprecated, but kept for reference -$route = './include/common/webServices/rest/internal.php?object=centreon_configuration_manufacturer' . - '&action=defaultValues&target=traps&field=manufacturer_id&id='; -$attrManufacturer1 = array_merge( - $attrManufacturer, - array('defaultDatasetRoute' => $route) -); -*/ $form->addElement('select2', 'mnftr', _("Vendor Name"), array(), $attrManufacturer); $form->addElement('file', 'filename', _("File (.mib)")); @@ -117,43 +108,46 @@ function myDecodeMib($arg) */ $subA = $form->addElement('submit', 'submit', _("Import"), array("class" => "btc bt_success")); $form->addElement('header', 'status', _("Status")); -$valid = false; $msg = null; $stdout = null; if ($form->validate()) { $ret = $form->getSubmitValues(); - $fileObj = $form->getElement('filename'); + $manufacturerId = filter_var($ret['mnftr'], FILTER_VALIDATE_INT); - if ($fileObj->isUploadedFile()) { + if ($manufacturerId === false) { + $tpl->assign('msg', 'Wrong manufacturer given.'); + } elseif ($fileObj->isUploadedFile()) { /* * Upload File */ $values = $fileObj->getValue(); $msg .= str_replace("\n", "
", $stdout); - $msg .= "
Moving traps in DataBase..."; + $msg .= "
Moving traps in database..."; + + $command = "@CENTREONTRAPD_BINDIR@/centFillTrapDB -f '" . $values["tmp_name"] + . "' -m " . $manufacturerId . " --severity=info 2>&1"; if ($debug) { - print("@CENTREONTRAPD_BINDIR@/centFillTrapDB -f '" . $values["tmp_name"] . "' -m " . - htmlentities($ret["mnftr"], ENT_QUOTES, "UTF-8") . " --severity=info 2>&1"); + print($command); } - $stdout = shell_exec( - "@CENTREONTRAPD_BINDIR@/centFillTrapDB -f '" . $values["tmp_name"] . - "' -m " . htmlentities($ret["mnftr"], ENT_QUOTES, "UTF-8") . " --severity=info 2>&1" - ); + $stdout = shell_exec($command); unlink($values['tmp_name']); - $msg .= "
" . str_replace("\n", "
", $stdout); - $msg .= "
Generate Traps configuration files from Monitoring Engine configuration form!"; - if ($msg) { - if (strlen($msg) > $max_characters) { - $msg = substr($msg, 0, $max_characters) . "..." . - sprintf(_("Message truncated (exceeded %s characters)"), $max_characters); - } - $tpl->assign('msg', $msg); + + if ($stdout === null) { + $msg .= '
An error occured during generation.'; + } else { + $msg .= '
' . str_replace('\n', '
', $stdout) + . '
Generate Traps configuration files from Monitoring Engine configuration form!'; + } + + if (strlen($msg) > $max_characters) { + $msg = substr($msg, 0, $max_characters) . "..." . + sprintf(_("Message truncated (exceeded %s characters)"), $max_characters); } + $tpl->assign('msg', $msg); } - $valid = true; } /* diff --git a/www/include/configuration/configServers/DB-Func.php b/www/include/configuration/configServers/DB-Func.php index 4155adc1a6a..f7f7f0e06ff 100644 --- a/www/include/configuration/configServers/DB-Func.php +++ b/www/include/configuration/configServers/DB-Func.php @@ -774,9 +774,9 @@ function updateServer(int $id, $data): void */ function checkChangeState(int $poller_id, int $last_restart): bool { - global $pearDBO, $conf_centreon; + global $pearDBO, $conf_centreon, $pearDB; - if (!isset($last_restart) || $last_restart == "") { + if (!isset($last_restart) || $last_restart === "") { return false; } @@ -860,5 +860,19 @@ function checkChangeState(int $poller_id, int $last_restart): bool REQUEST; $dbResult = $pearDBO->query($query); - return $dbResult->rowCount() ? true : false; + if ($dbResult->rowCount()) { + // requires restart if storage db has log information about changes + return true; + } else { + // also requires restart if flag updated is set to true + $configStmt = $pearDB->prepare("SELECT updated FROM nagios_server WHERE id = :pollerID LIMIT 1"); + $configStmt->bindValue(':pollerID', $poller_id, \PDO::PARAM_INT); + $configStmt->execute(); + $row = $configStmt->fetch(\PDO::FETCH_ASSOC); + if ($row['updated']) { + return true; + } + } + + return false; } diff --git a/www/include/monitoring/recurrentDowntime/listDowntime.php b/www/include/monitoring/recurrentDowntime/listDowntime.php index 9a3d8cd91a7..134948b594a 100644 --- a/www/include/monitoring/recurrentDowntime/listDowntime.php +++ b/www/include/monitoring/recurrentDowntime/listDowntime.php @@ -47,7 +47,7 @@ FILTER_SANITIZE_STRING ); -if ($search) { +if ($_POST["Search"]) { //saving chosen filters values $centreon->historySearch[$url] = array(); $centreon->historySearch[$url]["search"] = $search; diff --git a/www/install/createTables.sql b/www/install/createTables.sql index e5fc6eb661a..03bdaeb77d2 100644 --- a/www/install/createTables.sql +++ b/www/install/createTables.sql @@ -1636,6 +1636,7 @@ CREATE TABLE `nagios_server` ( `centreonbroker_logs_path` VARCHAR(255), `remote_id` int(11) NULL, `remote_server_centcore_ssh_proxy` enum('0','1') NOT NULL DEFAULT '1', + `updated` enum('1','0') NOT NULL DEFAULT '0', PRIMARY KEY (`id`), CONSTRAINT `nagios_server_remote_id_id` FOREIGN KEY (`remote_id`) REFERENCES `nagios_server` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8; diff --git a/www/install/php/Update-19.10.2.php b/www/install/php/Update-19.10.2.php index 18ee41d1a2c..e8cc8aebee2 100644 --- a/www/install/php/Update-19.10.2.php +++ b/www/install/php/Update-19.10.2.php @@ -17,3 +17,16 @@ * For more information : contact@centreon.com * */ +include_once __DIR__ . "/../../class/centreonLog.class.php"; +$centreonLog = new CentreonLog(); + +try { + $pearDB->query( + "UPDATE `contact` SET `contact_autologin_key` = NULL WHERE `contact_autologin_key` =''" + ); +} catch (\PDOException $e) { + $centreonLog->insertLog( + 2, + "UPGRADE : 19.10.2 Unable to set default contact_autologin_key" + ); +} \ No newline at end of file diff --git a/www/install/sql/centreon/Update-DB-20.04.0-beta.1.sql b/www/install/sql/centreon/Update-DB-20.04.0-beta.1.sql new file mode 100644 index 00000000000..b2cd796756b --- /dev/null +++ b/www/install/sql/centreon/Update-DB-20.04.0-beta.1.sql @@ -0,0 +1,2 @@ +--new updated field of pollers- +ALTER TABLE `nagios_server` ADD COLUMN `updated` enum('0','1') NOT NULL DEFAULT '0'; \ No newline at end of file diff --git a/www/install/steps/process/createDbUser.php b/www/install/steps/process/createDbUser.php index a95847764cd..3e30eceb508 100644 --- a/www/install/steps/process/createDbUser.php +++ b/www/install/steps/process/createDbUser.php @@ -1,7 +1,7 @@ fetchAll(PDO::FETCH_COLUMN)[0])[0]; } -// Compatibility adaptation for mysql 8 with php7.1 before 7.1.16, or php7.2 before 7.2.4. -$createUser = "CREATE USER :dbUser@:host IDENTIFIED BY :dbPass"; -$alterQuery = "ALTER USER :dbUser@:host IDENTIFIED WITH mysql_native_password BY :dbPass"; - $queryValues = []; $queryValues[':dbUser'] = $parameters['db_user']; $queryValues[':host'] = $host; $queryValues[':dbPass'] = $parameters['db_password']; +// Compatibility adaptation for mysql 8 with php7.1 before 7.1.16, or php7.2 before 7.2.4. +$createUser = "CREATE USER :dbUser@:host IDENTIFIED BY :dbPass"; + +// As ALTER USER won't work on a mariaDB < 10.2, we need to check it before trying this request +$checkMysqlVersion = "SHOW VARIABLES WHERE Variable_name LIKE 'version%'"; + +// creating the user - mandatory for MySQL DB +$alterQuery = "ALTER USER :dbUser@:host IDENTIFIED WITH mysql_native_password BY :dbPass"; $query = "GRANT ALL PRIVILEGES ON `%s`.* TO " . $parameters['db_user'] . "@" . $host . " WITH GRANT OPTION"; $flushQuery = "FLUSH PRIVILEGES"; @@ -90,11 +94,28 @@ } // creating the user $prepareCreate->execute(); + + // checking mysql version before trying to alter the password plugin + $prepareCheckVersion = $link->query($checkMysqlVersion); + while ($row = $prepareCheckVersion->fetch()) { + if (!isset($versionNumber) && $row['Variable_name'] === "version") { + $versionNumber = $row['version']; + } elseif (!isset($versionName) && $row['Variable_name'] === "version_comment") { + $versionName = $row['version_comment']; + } + } + if ((strpos($versionName, "MariaDB") !== false && version_compare($versionNumber, '10.2.0') >= 0) + || (strpos($versionName, "MySQL") !== false && version_compare($versionNumber, '8.0.0') >= 0) + ) { + // altering the mysql's password plugin using the ALTER USER request + $prepareAlter->execute(); + } + // granting privileges $link->exec(sprintf($query, $parameters['db_configuration'])); $link->exec(sprintf($query, $parameters['db_storage'])); - // altering the mysql's password plugin - $prepareAlter->execute(); + + // enabling the new parameters $link->exec($flushQuery); } catch (\PDOException $e) { $return['msg'] = $e->getMessage();