Debian Codegraph @

lib/ansible/executor/stats.py

raw
1 # (c) 2012-2014, Michael DeHaan <[email protected]>
2 #
3 # This file is part of Ansible
4 #
5 # Ansible is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Ansible is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Ansible. If not, see <http://www.gnu.org/licenses/>.
17
18 from __future__ import annotations
19
20 from collections.abc import MutableMapping
21
22 from ansible.utils.vars import merge_hash
23
24
25 class AggregateStats:
26 """ holds stats about per-host activity during playbook runs """
27
28 def __init__(self):
29
30 self.processed = {}
31 self.failures = {}
32 self.ok = {}
33 self.dark = {}
34 self.changed = {}
35 self.skipped = {}
36 self.rescued = {}
37 self.ignored = {}
38
39 # user defined stats, which can be per host or global
40 self.custom = {}
41
42 def increment(self, what, host):
43 """ helper function to bump a statistic """
44
45 self.processed[host] = 1
46 prev = (getattr(self, what)).get(host, 0)
47 getattr(self, what)[host] = prev + 1
48
49 def decrement(self, what, host):
50 _what = getattr(self, what)
51 try:
52 if _what[host] - 1 < 0:
53 # This should never happen, but let's be safe
54 raise KeyError("Don't be so negative")
55 _what[host] -= 1
56 except KeyError:
57 _what[host] = 0
58
59 def summarize(self, host):
60 """ return information about a particular host """
61
62 return dict(
63 ok=self.ok.get(host, 0),
64 failures=self.failures.get(host, 0),
65 unreachable=self.dark.get(host, 0),
66 changed=self.changed.get(host, 0),
67 skipped=self.skipped.get(host, 0),
68 rescued=self.rescued.get(host, 0),
69 ignored=self.ignored.get(host, 0),
70 )
71
72 def set_custom_stats(self, which, what, host=None):
73 """ allow setting of a custom stat"""
74
75 if host is None:
76 host = '_run'
77 if host not in self.custom:
78 self.custom[host] = {which: what}
79 else:
80 self.custom[host][which] = what
81
82 def update_custom_stats(self, which, what, host=None):
83 """ allow aggregation of a custom stat"""
84
85 if host is None:
86 host = '_run'
87 if host not in self.custom or which not in self.custom[host]:
88 return self.set_custom_stats(which, what, host)
89
90 # mismatching types
91 if not isinstance(what, type(self.custom[host][which])):
92 return None
93
94 if isinstance(what, MutableMapping):
95 self.custom[host][which] = merge_hash(self.custom[host][which], what)
96 else:
97 # let overloaded + take care of other types
98 self.custom[host][which] += what