-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
watchdog.py
216 lines (151 loc) · 5.02 KB
/
watchdog.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""
Watch files and translate the changes into salt events.
.. versionadded:: 2019.2.0
:depends: - watchdog Python module >= 0.8.3
"""
import collections
import logging
import salt.utils.beacons
try:
# pylint: disable=no-name-in-module
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer
# pylint: enable=no-name-in-module
HAS_WATCHDOG = True
except ImportError:
HAS_WATCHDOG = False
class FileSystemEventHandler:
"""A dummy class to make the import work"""
def __init__(self):
pass
__virtualname__ = "watchdog"
log = logging.getLogger(__name__)
DEFAULT_MASK = [
"create",
"delete",
"modify",
"move",
]
class Handler(FileSystemEventHandler):
def __init__(self, queue, masks=None):
super().__init__()
self.masks = masks or DEFAULT_MASK
self.queue = queue
def on_created(self, event):
self._append_if_mask(event, "create")
def on_modified(self, event):
self._append_if_mask(event, "modify")
def on_deleted(self, event):
self._append_if_mask(event, "delete")
def on_moved(self, event):
self._append_if_mask(event, "move")
def _append_if_mask(self, event, mask):
logging.debug(event)
self._append_path_if_mask(event, mask)
def _append_path_if_mask(self, event, mask):
if mask in self.masks:
self.queue.append(event)
def __virtual__():
if HAS_WATCHDOG:
return __virtualname__
err_msg = "watchdog library is missing."
log.error("Unable to load %s beacon: %s", __virtualname__, err_msg)
return False, err_msg
def _get_queue(config):
"""
Check the context for the notifier and construct it if not present
"""
if "watchdog.observer" not in __context__:
queue = collections.deque()
observer = Observer()
for path in config.get("directories", {}):
path_params = config.get("directories").get(path)
masks = path_params.get("mask", DEFAULT_MASK)
event_handler = Handler(queue, masks)
observer.schedule(event_handler, path)
observer.start()
__context__["watchdog.observer"] = observer
__context__["watchdog.queue"] = queue
return __context__["watchdog.queue"]
class ValidationError(Exception):
pass
def validate(config):
"""
Validate the beacon configuration
"""
try:
_validate(config)
return True, "Valid beacon configuration"
except ValidationError as error:
return False, str(error)
def _validate(config):
if not isinstance(config, list):
raise ValidationError("Configuration for watchdog beacon must be a list.")
_config = {}
for part in config:
_config.update(part)
if "directories" not in _config:
raise ValidationError(
"Configuration for watchdog beacon must include directories."
)
if not isinstance(_config["directories"], dict):
raise ValidationError(
"Configuration for watchdog beacon directories must be a dictionary."
)
for path in _config["directories"]:
_validate_path(_config["directories"][path])
def _validate_path(path_config):
if not isinstance(path_config, dict):
raise ValidationError(
"Configuration for watchdog beacon directory path must be a dictionary."
)
if "mask" in path_config:
_validate_mask(path_config["mask"])
def _validate_mask(mask_config):
valid_mask = [
"create",
"modify",
"delete",
"move",
]
if not isinstance(mask_config, list):
raise ValidationError("Configuration for watchdog beacon mask must be list.")
if any(mask not in valid_mask for mask in mask_config):
raise ValidationError("Configuration for watchdog beacon contains invalid mask")
def to_salt_event(event):
return {
"tag": __virtualname__,
"path": event.src_path,
"change": event.event_type,
}
def beacon(config):
"""
Watch the configured directories
Example Config
.. code-block:: yaml
beacons:
watchdog:
- directories:
/path/to/dir:
mask:
- create
- modify
- delete
- move
The mask list can contain the following events (the default mask is create,
modify delete, and move):
* create - File or directory is created in watched directory
* modify - The watched directory is modified
* delete - File or directory is deleted from watched directory
* move - File or directory is moved or renamed in the watched directory
"""
config = salt.utils.beacons.list_to_dict(config)
queue = _get_queue(config)
ret = []
while queue:
ret.append(to_salt_event(queue.popleft()))
return ret
def close(config):
observer = __context__.pop("watchdog.observer", None)
if observer:
observer.stop()