diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f5214b..9f1460e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ### Fixed - CI: fix Psalm cache directory, drop the stray `glpi-project/tools` composer dependency, declare a unique composer autoloader suffix +- Improve performance of the Static groups, Contact logs and Computer groups tabs (paginated, loaded in a few queries) +- Evaluate each dynamic group only once when an agent requests its database inventory parameters +- Show an error when a database inventory request fails, and send each credential type only once +- Do not lock the user session while waiting for the agent answer ## [1.1.4] - 2026-08-03 diff --git a/ajax/agent.php b/ajax/agent.php index 9375ec4..1ed464f 100644 --- a/ajax/agent.php +++ b/ajax/agent.php @@ -47,6 +47,9 @@ throw new NotFoundHttpException(); } + // The agent call can take seconds: release the session lock, the code below only reads the session + Session::writeClose(); + $answer = []; if ($_POST['action'] === PluginDatabaseinventoryInventoryAction::MA_PARTIAL) { diff --git a/inc/computergroup.class.php b/inc/computergroup.class.php index f655a0d..e90b480 100644 --- a/inc/computergroup.class.php +++ b/inc/computergroup.class.php @@ -199,30 +199,31 @@ public function countDynamicItem() $iterator = $DB->request($params); foreach ($iterator as $computergroup_dynamic) { - $search_params = Search::manageParams('Computer', json_decode((string) $computergroup_dynamic['search'], true, 512, JSON_THROW_ON_ERROR)); - $data = Search::prepareDatasForSearch('Computer', $search_params); - Search::constructSQL($data); - Search::constructData($data); - $count += $data['data']['totalcount']; + $count += self::countComputersForSearch((string) $computergroup_dynamic['search']); } return $count; } - public function countStaticItem() + /** + * Number of computers matched by a dynamic group search (JSON criteria). + */ + public static function countComputersForSearch(string $search): int { - /** @var DBmysql $DB */ - global $DB; + $search_params = Search::manageParams('Computer', json_decode($search, true, 512, JSON_THROW_ON_ERROR)); + $data = Search::prepareDatasForSearch('Computer', $search_params); + Search::constructSQL($data); + Search::constructData($data); - $params = [ - 'SELECT' => '*', - 'FROM' => PluginDatabaseinventoryComputerGroupStatic::getTable(), - 'WHERE' => ['plugin_databaseinventory_computergroups_id' => $this->fields['id']], - ]; - - $iterator = $DB->request($params); + return (int) $data['data']['totalcount']; + } - return count($iterator); + public function countStaticItem() + { + return countElementsInTable( + PluginDatabaseinventoryComputerGroupStatic::getTable(), + ['plugin_databaseinventory_computergroups_id' => $this->fields['id']], + ); } public static function install(Migration $migration) diff --git a/inc/computergroupstatic.class.php b/inc/computergroupstatic.class.php index f3c953b..d49156d 100644 --- a/inc/computergroupstatic.class.php +++ b/inc/computergroupstatic.class.php @@ -127,31 +127,70 @@ private static function showForItem(PluginDatabaseinventoryComputerGroup $comput return false; } - $staticsgroups = new PluginDatabaseinventoryComputerGroupStatic(); - $staticgrouplist = $staticsgroups->find( - [ - 'plugin_databaseinventory_computergroups_id' => $ID, + $static_table = self::getTable(); + $computer_table = Computer::getTable(); + $entity_table = Entity::getTable(); + $where = [$static_table . '.plugin_databaseinventory_computergroups_id' => $ID]; + + // every member is excluded from the "add" dropdown, displayed or not + $used = []; + foreach ($DB->request(['SELECT' => 'computers_id', 'FROM' => $static_table, 'WHERE' => $where]) as $row) { + $used[] = $row['computers_id']; + } + + // one page of members, with their computer and entity, in one query + $criteria = [ + 'FROM' => $static_table, + 'INNER JOIN' => [ + $computer_table => [ + 'ON' => [ + $static_table => 'computers_id', + $computer_table => 'id', + ], + ], ], - ); + 'LEFT JOIN' => [ + $entity_table => [ + 'ON' => [ + $computer_table => 'entities_id', + $entity_table => 'id', + ], + ], + ], + 'WHERE' => $where, + ]; + $total = $DB->request($criteria + ['COUNT' => 'total'])->current()['total']; + + $start = max(0, (int) ($_GET['start'] ?? 0)); + if ($start >= $total) { + $start = 0; + } + + $iterator = $DB->request($criteria + [ + 'SELECT' => [ + $computer_table . '.id', + $computer_table . '.name', + $computer_table . '.is_dynamic', + $computer_table . '.serial', + $computer_table . '.otherserial', + $entity_table . '.completename AS entityname', + $static_table . '.id AS idcompgroupstatic', + ], + 'ORDER' => $static_table . '.id', + 'START' => $start, + 'LIMIT' => (int) $_SESSION['glpilist_limit'], + ]); - $computers = new Computer(); $listofcomputers = []; - $used = []; - foreach ($staticgrouplist as $staticgroup) { - $used[] = $staticgroup['computers_id']; - if ($computers->getFromDB($staticgroup['computers_id'])) { - $listofcomputers[] = $computers->fields + [ - 'entityname' => Entity::getById($computers->fields['entities_id'])->fields['completename'], - 'link' => $computers->getLinkURL(), - 'idcompgroupstatic' => $staticgroup['id'], - ]; - } + foreach ($iterator as $row) { + $listofcomputers[] = $row + ['link' => Computer::getFormURLWithID($row['id'])]; } TemplateRenderer::getInstance()->display( '@databaseinventory/computergroupstatic.html.twig', [ 'item' => PluginDatabaseinventoryComputerGroup::getById($ID), + 'pager' => $total > 0 ? Html::printAjaxPager('', $start, $total, '', false) : '', 'computerslist' => $listofcomputers, 'groupstaticclass' => PluginDatabaseinventoryComputerGroupStatic::class, 'canread' => $computergroup->can($ID, READ), diff --git a/inc/contactlog.class.php b/inc/contactlog.class.php index aafeca7..cb15344 100644 --- a/inc/contactlog.class.php +++ b/inc/contactlog.class.php @@ -121,41 +121,25 @@ private static function showForDatabaseParams(PluginDatabaseinventoryDatabasePar return false; } - $contactlog = new PluginDatabaseinventoryContactLog(); - $contactloglist = $contactlog->find( - [ - 'plugin_databaseinventory_databaseparams_id' => $ID, - ], + // lines whose credential and agent are both gone are not displayed + [$listofctlog, $pager] = self::getContactLogPage( + ['plugin_databaseinventory_databaseparams_id' => $ID], + Agent::class, + 'agents_id', + false, ); - - $credential = new PluginDatabaseinventoryCredential(); - $agent = new Agent(); - $listofctlog = []; - foreach ($contactloglist as $dbpctlog) { - if ($credential->getFromDB($dbpctlog['plugin_databaseinventory_credentials_id'])) { - $linkcred = $credential->getLinkURL(); - $credname = $credential->fields['name']; - } - - if ($agent->getFromDB($dbpctlog['agents_id'])) { - $linkagent = $agent->getLinkURL(); - $agentname = $agent->fields['name']; - } - - if (isset($linkcred) || isset($linkagent)) { - $listofctlog[] = $dbpctlog + [ - 'linkcred' => $linkcred ?? '', - 'linkagent' => $linkagent ?? '', - 'credname' => $credname ?? '', - 'agentname' => $agentname ?? '', - ]; - } + foreach ($listofctlog as &$ctlog) { + $ctlog['linkagent'] = $ctlog['linkother']; + $ctlog['agentname'] = $ctlog['othername']; } + unset($ctlog); + TemplateRenderer::getInstance()->display( '@databaseinventory/contactlog.html.twig', [ 'itemtype' => PluginDatabaseinventoryDatabaseParam::getType(), + 'pager' => $pager, 'contactlogs' => $listofctlog, 'canread' => $databaseparams->can($ID, READ), ], @@ -164,6 +148,92 @@ private static function showForDatabaseParams(PluginDatabaseinventoryDatabasePar return true; } + /** + * Load one page of contact logs with the names of their credential and of the other linked item + * (agent or database param), in one query. + * + * @param array $where criteria on the contact log table + * @param class-string $other_itemtype Agent or PluginDatabaseinventoryDatabaseParam + * @param string $other_fk foreign key of the other item in the contact log table + * @param bool $require_credential true to skip lines whose credential is gone, + * false to skip lines whose credential and other item are both gone + * + * @return array{0: array>, 1: string} the lines and the pager HTML + */ + private static function getContactLogPage(array $where, string $other_itemtype, string $other_fk, bool $require_credential): array + { + /** @var DBmysql $DB */ + global $DB; + + $log_table = self::getTable(); + $credential_table = PluginDatabaseinventoryCredential::getTable(); + $other_table = $other_itemtype::getTable(); + + $full_where = []; + foreach ($where as $field => $value) { + $full_where[$log_table . '.' . $field] = $value; + } + + if ($require_credential) { + $full_where[] = ['NOT' => [$credential_table . '.id' => null]]; + } else { + $full_where[] = ['OR' => [ + ['NOT' => [$credential_table . '.id' => null]], + ['NOT' => [$other_table . '.id' => null]], + ]]; + } + + $criteria = [ + 'FROM' => $log_table, + 'LEFT JOIN' => [ + $credential_table => [ + 'ON' => [ + $log_table => 'plugin_databaseinventory_credentials_id', + $credential_table => 'id', + ], + ], + $other_table => [ + 'ON' => [ + $log_table => $other_fk, + $other_table => 'id', + ], + ], + ], + 'WHERE' => $full_where, + ]; + $total = $DB->request($criteria + ['COUNT' => 'total'])->current()['total']; + + $start = max(0, (int) ($_GET['start'] ?? 0)); + if ($start >= $total) { + $start = 0; + } + + $iterator = $DB->request($criteria + [ + 'SELECT' => [ + $log_table . '.*', + $credential_table . '.id AS credential_id', + $credential_table . '.name AS credname', + $other_table . '.id AS other_id', + $other_table . '.name AS othername', + ], + // newest first: the log grows at every agent contact + 'ORDER' => [$log_table . '.date_creation DESC', $log_table . '.id DESC'], + 'START' => $start, + 'LIMIT' => (int) $_SESSION['glpilist_limit'], + ]); + + $lines = []; + foreach ($iterator as $row) { + $row['linkcred'] = $row['credential_id'] !== null ? PluginDatabaseinventoryCredential::getFormURLWithID($row['credential_id']) : ''; + $row['credname'] ??= ''; + $row['linkother'] = $row['other_id'] !== null ? $other_itemtype::getFormURLWithID($row['other_id']) : ''; + $row['othername'] ??= ''; + $lines[] = $row; + } + + return [$lines, $total > 0 ? Html::printAjaxPager('', $start, $total, '', false) : '']; + } + private static function showForAgent(Agent $agent) { $ID = $agent->getField('id'); @@ -171,41 +241,25 @@ private static function showForAgent(Agent $agent) return false; } - $contactlog = new PluginDatabaseinventoryContactLog(); - $contactloglist = $contactlog->find( - [ - 'agents_id' => $ID, - ], + // lines whose credential is gone are not displayed + [$listofctlog, $pager] = self::getContactLogPage( + ['agents_id' => $ID], + PluginDatabaseinventoryDatabaseParam::class, + 'plugin_databaseinventory_databaseparams_id', + true, ); - - $credential = new PluginDatabaseinventoryCredential(); - $dbparam = new PluginDatabaseinventoryDatabaseParam(); - $listofctlog = []; - foreach ($contactloglist as $dbpctlog) { - if ($credential->getFromDB($dbpctlog['plugin_databaseinventory_credentials_id'])) { - $linkcred = $credential->getLinkURL(); - $credname = $credential->fields['name']; - } - - if ($dbparam->getFromDB($dbpctlog['plugin_databaseinventory_databaseparams_id'])) { - $linkdbparam = $dbparam->getLinkURL(); - $dbparamname = $dbparam->fields['name']; - } - - if (isset($linkcred)) { - $listofctlog[] = $dbpctlog + [ - 'linkcred' => $linkcred, - 'linkdbparam' => $linkdbparam ?? '', - 'credname' => $credname ?? '', - 'dbparamname' => $dbparamname ?? '', - ]; - } + foreach ($listofctlog as &$ctlog) { + $ctlog['linkdbparam'] = $ctlog['linkother']; + $ctlog['dbparamname'] = $ctlog['othername']; } + unset($ctlog); + TemplateRenderer::getInstance()->display( '@databaseinventory/contactlog.html.twig', [ 'itemtype' => Agent::getType(), + 'pager' => $pager, 'contactlogs' => $listofctlog, 'canread' => $agent->can($ID, READ), ], diff --git a/inc/databaseparam.class.php b/inc/databaseparam.class.php index 5da76f2..8af5cfb 100644 --- a/inc/databaseparam.class.php +++ b/inc/databaseparam.class.php @@ -175,7 +175,9 @@ public function getCredentialTypeLinked() $credential_type_table . '.id', $credential_type_table . '.name', ], - 'FROM' => $credential_type_table, + // several credentials of the same type must not repeat the type sent to the agent + 'DISTINCT' => true, + 'FROM' => $credential_type_table, 'JOIN' => [ $credential_table => [ 'ON' => [ diff --git a/inc/databaseparam_computergroup.class.php b/inc/databaseparam_computergroup.class.php index 8e4b781..8f0b88f 100644 --- a/inc/databaseparam_computergroup.class.php +++ b/inc/databaseparam_computergroup.class.php @@ -124,26 +124,81 @@ private static function showForItem(PluginDatabaseinventoryDatabaseParam $databa return false; } - $databaseparamcgroup = new PluginDatabaseinventoryDatabaseParam_ComputerGroup(); - $dbpcgrouplist = $databaseparamcgroup->find( - [ - 'plugin_databaseinventory_databaseparams_id' => $ID, + /** @var DBmysql $DB */ + global $DB; + + $relation_table = self::getTable(); + $group_table = PluginDatabaseinventoryComputerGroup::getTable(); + $group_fk = 'plugin_databaseinventory_computergroups_id'; + + // linked groups, the ids of relations whose group no longer exists are still "used" + $used = []; + $groups = []; + $iterator = $DB->request([ + 'SELECT' => [ + $relation_table . '.id AS iddbparamcgroup', + $relation_table . '.' . $group_fk, + $group_table . '.*', ], - ); + 'FROM' => $relation_table, + 'LEFT JOIN' => [ + $group_table => [ + 'ON' => [ + $relation_table => $group_fk, + $group_table => 'id', + ], + ], + ], + 'WHERE' => [$relation_table . '.plugin_databaseinventory_databaseparams_id' => $ID], + 'ORDER' => $relation_table . '.id', + ]); + foreach ($iterator as $row) { + $used[] = $row[$group_fk]; + if ($row['id'] !== null) { + $groups[] = $row; + } + } + + // static and dynamic members of all the groups in two queries + $group_ids = array_column($groups, 'id'); + $static_counts = []; + $searches = []; + if ($group_ids !== []) { + $count_iterator = $DB->request([ + 'SELECT' => [$group_fk, 'COUNT' => '* AS cpt'], + 'FROM' => PluginDatabaseinventoryComputerGroupStatic::getTable(), + 'WHERE' => [$group_fk => $group_ids], + 'GROUPBY' => $group_fk, + ]); + foreach ($count_iterator as $row) { + $static_counts[$row[$group_fk]] = (int) $row['cpt']; + } + + $dynamic_iterator = $DB->request([ + 'SELECT' => [$group_fk, 'search'], + 'FROM' => PluginDatabaseinventoryComputerGroupDynamic::getTable(), + 'WHERE' => [$group_fk => $group_ids], + ]); + foreach ($dynamic_iterator as $row) { + $searches[$row[$group_fk]][] = (string) $row['search']; + } + } - $dbcgroups = new PluginDatabaseinventoryComputerGroup(); $listofcgroups = []; - $used = []; - foreach ($dbpcgrouplist as $dbpcgroup) { - $used[] = $dbpcgroup['plugin_databaseinventory_computergroups_id']; - if ($dbcgroups->getFromDB($dbpcgroup['plugin_databaseinventory_computergroups_id'])) { - $listofcgroups[] = $dbcgroups->fields + [ - 'link' => $dbcgroups->getLinkURL(), - 'nbdynamicitems' => $dbcgroups->countDynamicItem(), - 'nbstaticitems' => $dbcgroups->countStaticItem(), - 'iddbparamcgroup' => $dbpcgroup['id'], - ]; + foreach ($groups as $group) { + $nbdynamicitems = 0; + foreach ($searches[$group['id']] ?? [] as $search) { + $nbdynamicitems += PluginDatabaseinventoryComputerGroup::countComputersForSearch($search); } + + $iddbparamcgroup = $group['iddbparamcgroup']; + unset($group['iddbparamcgroup'], $group[$group_fk]); + $listofcgroups[] = $group + [ + 'link' => PluginDatabaseinventoryComputerGroup::getFormURLWithID($group['id']), + 'nbdynamicitems' => $nbdynamicitems, + 'nbstaticitems' => $static_counts[$group['id']] ?? 0, + 'iddbparamcgroup' => $iddbparamcgroup, + ]; } TemplateRenderer::getInstance()->display( diff --git a/inc/inventoryaction.class.php b/inc/inventoryaction.class.php index f75fb39..00b3c4c 100644 --- a/inc/inventoryaction.class.php +++ b/inc/inventoryaction.class.php @@ -30,6 +30,8 @@ use Glpi\Asset\Asset_PeripheralAsset; +use function Safe\json_encode; + class PluginDatabaseinventoryInventoryAction extends CommonDBTM { public const MA_PARTIAL = 'partial_database_inventory'; @@ -199,8 +201,10 @@ public static function postItemForm($item) $out .= ''; echo $out; $url = $CFG_GLPI['url_base'] . '/plugins/databaseinventory/ajax/agent.php'; - $key = PluginDatabaseinventoryInventoryAction::MA_PARTIAL; - $js = << + */ + private static array $accessible_database_params = []; + public static function inventoryGetParams(array $params) { /** @var DBmysql $DB */ @@ -203,6 +210,12 @@ private static function getAccessibleDatabaseParams(Computer $computer): array /** @var DBmysql $DB */ global $DB; + // the inventory calls this once per requested param during the same agent contact + $computer_id = (int) $computer->fields['id']; + if (isset(self::$accessible_database_params[$computer_id])) { + return self::$accessible_database_params[$computer_id]; + } + $database_param_found = []; $database_param_table = PluginDatabaseinventoryDatabaseParam::getTable(); @@ -262,6 +275,7 @@ private static function getAccessibleDatabaseParams(Computer $computer): array $criteria = [ 'SELECT' => [ $computer_group_dynamic_table . '.id', + $computer_group_dynamic_table . '.search', $database_param_table . '.id AS database_param_id', ], 'FROM' => $computer_group_dynamic_table, @@ -301,17 +315,29 @@ private static function getAccessibleDatabaseParams(Computer $computer): array ]; } + // A dynamic group linked to several params comes back once per param: + // group the rows so that each search runs only once + $dynamic_groups = []; + foreach ($DB->request($criteria) as $data) { + $dynamic_groups[$data['id']]['search'] = $data['search']; + $dynamic_groups[$data['id']]['params'][] = $data['database_param_id']; + } + // check if Dynamic group match computer // if true, store databaseparam - $iterator = $DB->request($criteria); - foreach ($iterator as $data) { + foreach ($dynamic_groups as $dynamic_group_id => $dynamic_group_data) { + $missing_params = array_diff($dynamic_group_data['params'], $database_param_found); + if ($missing_params === []) { + continue; + } + $dynamic_group = new PluginDatabaseinventoryComputerGroupDynamic(); - $dynamic_group->getFromDB($data['id']); - if ($dynamic_group->isDynamicSearchMatchComputer($computer) && !in_array($data['database_param_id'], $database_param_found)) { - $database_param_found[] = $data['database_param_id']; + $dynamic_group->getFromResultSet(['id' => $dynamic_group_id, 'search' => $dynamic_group_data['search']]); + if ($dynamic_group->isDynamicSearchMatchComputer($computer)) { + array_push($database_param_found, ...array_values($missing_params)); } } - return $database_param_found; + return self::$accessible_database_params[$computer_id] = $database_param_found; } } diff --git a/setup.php b/setup.php index 70b5122..b63641d 100644 --- a/setup.php +++ b/setup.php @@ -51,10 +51,6 @@ function plugin_init_databaseinventory() $PLUGIN_HOOKS['config_page']['databaseinventory'] = 'front/databaseparam.php'; - if (!Plugin::isPluginActive('databaseinventory')) { - return; - } - $PLUGIN_HOOKS['handle_inventory_task']['databaseinventory'] = ['PluginDatabaseinventoryTask', 'handleInventoryTask']; $PLUGIN_HOOKS['inventory_get_params']['databaseinventory'] = ['PluginDatabaseinventoryTask', 'inventoryGetParams']; $PLUGIN_HOOKS['handle_agent_response']['databaseinventory'] = ['PluginDatabaseinventoryInventoryAction', 'HandleAgentResponse']; diff --git a/templates/computergroupstatic.html.twig b/templates/computergroupstatic.html.twig index e41455d..ffc10c9 100644 --- a/templates/computergroupstatic.html.twig +++ b/templates/computergroupstatic.html.twig @@ -66,6 +66,7 @@ {% endif %} {% if canread %} {% if computerslist is not empty %} + {{ pager|raw }}
diff --git a/templates/contactlog.html.twig b/templates/contactlog.html.twig index 1157f00..02d3ec0 100644 --- a/templates/contactlog.html.twig +++ b/templates/contactlog.html.twig @@ -40,6 +40,7 @@ {{ __('Date') }} {% endset %} + {{ pager|raw }} {{ tableheader }} {% for contactlog in contactlogs %}