From 73d6da757faf57e43df52e3332a7a3b9ee67cdba Mon Sep 17 00:00:00 2001 From: Harald Laabs Date: Fri, 24 Oct 2014 17:40:34 +0200 Subject: [PATCH 1/2] Make get_group run in O(n*log(n)) instead of O(n^2) by using a cache --- lib/ansible/inventory/__init__.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/ansible/inventory/__init__.py b/lib/ansible/inventory/__init__.py index 60c7eae67b..c0b93cc07c 100644 --- a/lib/ansible/inventory/__init__.py +++ b/lib/ansible/inventory/__init__.py @@ -67,6 +67,7 @@ class Inventory(object): self._groups_list = {} self._pattern_cache = {} self._vars_plugins = [] + self._groups_cache = {} # to be set by calling set_playbook_basedir by playbook code self._playbook_basedir = None @@ -394,6 +395,7 @@ class Inventory(object): if a.name not in groups: groups[a.name] = [h.name for h in a.get_hosts()] self._groups_list = groups + self._groups_cache = {} return self._groups_list def get_groups(self): @@ -422,10 +424,11 @@ class Inventory(object): return matching_host def get_group(self, groupname): - for group in self.groups: - if group.name == groupname: - return group - return None + if not self._groups_cache: + for group in self.groups: + self._groups_cache[group.name] = group + + return self._groups_cache.get(groupname) def get_group_variables(self, groupname, update_cached=False, vault_password=None): if groupname not in self._vars_per_group or update_cached: @@ -499,6 +502,7 @@ class Inventory(object): if group.name not in self.groups_list(): self.groups.append(group) self._groups_list = None # invalidate internal cache + self._groups_cache = {} else: raise AnsibleError("group already in inventory: %s" % group.name) From 2641f70e47774e935c64a3c707c51806203bacd7 Mon Sep 17 00:00:00 2001 From: Abhijit Menon-Sen Date: Wed, 19 Aug 2015 10:46:08 +0530 Subject: [PATCH 2/2] Reset self._groups_cache in refresh_inventory --- lib/ansible/inventory/__init__.py | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ansible/inventory/__init__.py b/lib/ansible/inventory/__init__.py index c0b93cc07c..5a06f5275f 100644 --- a/lib/ansible/inventory/__init__.py +++ b/lib/ansible/inventory/__init__.py @@ -672,6 +672,7 @@ class Inventory(object): self._vars_per_host = {} self._vars_per_group = {} self._groups_list = {} + self._groups_cache = {} self.groups = [] self.parse_inventory(self.host_list)