Debian Codegraph @

lib/ansible/playbook/handler.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 ansible.errors import AnsibleAssertionError
21 from ansible.playbook.attribute import NonInheritableFieldAttribute
22 from ansible.playbook.task import Task
23
24
25 class Handler(Task):
26
27 listen = NonInheritableFieldAttribute(isa='list', default=list, listof=(str,), static=True)
28
29 def __init__(self, block=None, role=None, task_include=None):
30 self.notified_hosts = []
31
32 self.cached_name = False
33
34 super(Handler, self).__init__(block=block, role=role, task_include=task_include)
35
36 def __repr__(self):
37 """ returns a human-readable representation of the handler """
38 return "HANDLER: %s" % self.get_name()
39
40 def _validate_listen(self, attr, name, value):
41 new_value = self.get_validated_value(name, attr, value, None)
42 if self._role is not None:
43 for listener in new_value.copy():
44 new_value.extend([
45 f"{self._role.get_name(include_role_fqcn=True)} : {listener}",
46 f"{self._role.get_name(include_role_fqcn=False)} : {listener}",
47 ])
48 setattr(self, name, new_value)
49
50 @staticmethod
51 def load(data, block=None, role=None, task_include=None, variable_manager=None, loader=None):
52 t = Handler(block=block, role=role, task_include=task_include)
53 return t.load_data(data, variable_manager=variable_manager, loader=loader)
54
55 def notify_host(self, host):
56 if not self.is_host_notified(host):
57 self.notified_hosts.append(host)
58 return True
59 return False
60
61 def remove_host(self, host):
62 try:
63 self.notified_hosts.remove(host)
64 except ValueError:
65 raise AnsibleAssertionError(
66 f"Attempting to remove a notification on handler '{self}' for host '{host}' but it has not been notified."
67 )
68
69 def clear_hosts(self):
70 self.notified_hosts = []
71
72 def is_host_notified(self, host):
73 return host in self.notified_hosts