forked from coppit/docker-inotify-command
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.py
executable file
·303 lines (221 loc) · 11.7 KB
/
monitor.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
#!/usr/bin/python3
import datetime
import json
import logging
import os
import re
import subprocess
import sys
import tempfile
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
RUNAS = "/files/runas.sh"
#-----------------------------------------------------------------------------------------------------------------------
def remove_linefeeds(input_filename):
temp = tempfile.NamedTemporaryFile(delete=False)
with open(input_filename, "r") as input_file:
with open(temp.name, "w") as output_file:
for line in input_file:
output_file.write(line)
return temp.name
#-----------------------------------------------------------------------------------------------------------------------
def to_seconds(timestr):
hms = timestr.split(':')
seconds = 0
while hms:
seconds *= 60
seconds += int(hms.pop(0))
return seconds
#-----------------------------------------------------------------------------------------------------------------------
def read_config(config_file):
config_file = remove_linefeeds(config_file)
# Shenanigans to read docker env vars, and the bash format config file. I didn't want to ask them to change their
# config files.
dump_command = '/usr/bin/python3 -c "import os, json;print(json.dumps(dict(os.environ)))"'
pipe = subprocess.Popen(['/bin/bash', '-c', dump_command], stdout=subprocess.PIPE)
string = pipe.stdout.read().decode('ascii')
base_env = json.loads(string)
source_command = 'source {}'.format(config_file)
pipe = subprocess.Popen(['/bin/bash', '-c', 'set -a && {} && {}'.format(source_command,dump_command)],
stdout=subprocess.PIPE)
string = pipe.stdout.read().decode('ascii')
config_env = json.loads(string)
env = config_env.copy()
env.update(base_env)
class Args:
pass
args = Args()
if "WATCH_DIR" not in env:
logging.error("Configuration error. WATCH_DIR must be defined.")
sys.exit(1)
if not os.path.isdir(env["WATCH_DIR"]):
logging.error("Configuration error. WATCH_DIR must be a directory.")
sys.exit(1)
args.watch_dir = env["WATCH_DIR"]
if "SETTLE_DURATION" not in env or not re.match("([0-9]{1,2}:){0,2}[0-9]{1,2}", env["SETTLE_DURATION"]):
logging.error("Configuration error. SETTLE_DURATION must be defined as HH:MM:SS or MM:SS or SS.")
sys.exit(1)
args.settle_duration = to_seconds(env["SETTLE_DURATION"])
if "MAX_WAIT_TIME" not in env or not re.match("([0-9]{1,2}:){0,2}[0-9]{1,2}", env["MAX_WAIT_TIME"]):
logging.error("Configuration error. MAX_WAIT_TIME must be defined as HH:MM:SS or MM:SS or SS.")
sys.exit(1)
args.max_wait_time = to_seconds(env["MAX_WAIT_TIME"])
if args.settle_duration > args.max_wait_time:
logging.error("Configuration error. SETTLE_DURATION cannot be greater than MAX_WAIT_TIME.")
sys.exit(1)
if "MIN_PERIOD" not in env or not re.match("([0-9]{1,2}:){0,2}[0-9]{1,2}", env["MIN_PERIOD"]):
logging.error("Configuration error. MIN_PERIOD must be defined as HH:MM:SS or MM:SS or SS.")
sys.exit(1)
args.min_period = to_seconds(env["MIN_PERIOD"])
if "USER_ID" not in env or not re.match("[0-9]{1,}", env["USER_ID"]):
logging.error("Configuration error. USER_ID must be a whole number.")
sys.exit(1)
args.user_id = env["USER_ID"]
if "GROUP_ID" not in env or not re.match("[0-9]{1,}", env["GROUP_ID"]):
logging.error("Configuration error. GROUP_ID must be a whole number.")
sys.exit(1)
args.group_id = env["GROUP_ID"]
if "COMMAND" not in env:
logging.error("Configuration error. COMMAND must be defined.")
sys.exit(1)
args.command = env["COMMAND"]
if "UMASK" not in env or not re.match("0[0-7]{3}", env["UMASK"]):
logging.error("Configuration error. UMASK must be defined as an octal 0### number.")
sys.exit(1)
args.umask = env["UMASK"]
if "DEBUG" in env and not re.match("[01]", env["DEBUG"]):
logging.error("Configuration error. DEBUG must be defined as 0 or 1.")
sys.exit(1)
args.debug = "DEBUG" in env and env["DEBUG"] == "1"
if "IGNORE_EVENTS_WHILE_COMMAND_IS_RUNNING" not in env or not re.match("[01]", env["IGNORE_EVENTS_WHILE_COMMAND_IS_RUNNING"]):
logging.error("Configuration error. IGNORE_EVENTS_WHILE_COMMAND_IS_RUNNING must be defined as 0 or 1.")
sys.exit(1)
args.ignore_events_while_command_is_running = env["IGNORE_EVENTS_WHILE_COMMAND_IS_RUNNING"] == "1"
logging.info("CONFIGURATION:")
logging.info(" WATCH_DIR=%s", args.watch_dir)
logging.info("SETTLE_DURATION=%s", args.settle_duration)
logging.info(" MAX_WAIT_TIME=%s", args.max_wait_time)
logging.info(" MIN_PERIOD=%s", args.min_period)
logging.info(" COMMAND=%s", args.command)
logging.info(" USER_ID=%s", args.user_id)
logging.info(" GROUP_ID=%s", args.group_id)
logging.info(" UMASK=%s", args.umask)
logging.info(" DEBUG=%s", args.debug)
logging.info("IGNORE_EVENTS_WHILE_COMMAND_IS_RUNNING=%s", args.ignore_events_while_command_is_running)
return args
#-----------------------------------------------------------------------------------------------------------------------
# This is the main watchdog class. When a new event is detected, the class keeps track of the time since that event was
# detected, as well as the time since any event was detected. After being reset, it starts looking for a new event
# again.
#
# This class runs in parallel with the rest of the program, so we shouldn't be missing any events due to not listening
# at the time.
class ModifyHandler(FileSystemEventHandler):
_detected_event, _detected_time, _last_event_time, _enabled = None, None, None, True
def on_any_event(self, event):
if not self._enabled:
return
# Ignore changes to the watch dir itself. event.src_path doesn't exist for delete events
if os.path.exists(event.src_path) and os.path.samefile(args.watch_dir, event.src_path):
return
self._last_event_time = datetime.datetime.now()
if not self._detected_event:
self._detected_event = event
self._detected_time = self._last_event_time
def enable_monitoring(self, enabled):
self._enabled = enabled
def detected_event(self):
return self._detected_event
def reset(self):
self._detected_event = None
self._detected_time = None
def time_since_detected(self):
return (datetime.datetime.now() - self._detected_time).total_seconds()
def time_since_last_event(self):
return (datetime.datetime.now() - self._last_event_time).total_seconds()
#-----------------------------------------------------------------------------------------------------------------------
def run_command(args, event_handler):
# Reset before, in case IGNORE_EVENTS_WHILE_COMMAND_IS_RUNNING is set, and new events come in while the command is
# running
event_handler.reset()
logging.info("Running command with user ID %s, group ID %s, and umask %s", args.user_id, args.group_id, args.umask)
logging.info("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
event_handler.enable_monitoring(not args.ignore_events_while_command_is_running)
returncode = subprocess.call([RUNAS, args.user_id, args.group_id, args.umask, args.command])
event_handler.enable_monitoring(True)
logging.info("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^")
logging.info("Finished running command. Exit code was %i", returncode)
#-----------------------------------------------------------------------------------------------------------------------
def wait_for_change(event_handler):
logging.info("Waiting for new change")
while True:
event = event_handler.detected_event()
if event:
logging.info("Detected change to %s %s", "directory" if event.is_directory else "file", event.src_path)
return
time.sleep(.1)
#-----------------------------------------------------------------------------------------------------------------------
def wait_for_events_to_stabilize(settle_duration, max_wait_time, event_handler):
logging.info("Waiting for watch directory to stabilize for %i seconds before triggering command", settle_duration)
while True:
if event_handler.time_since_last_event() >= settle_duration:
logging.info("Watch directory stabilized for %s seconds. Triggering command.", settle_duration)
return
elif event_handler.time_since_detected() >= max_wait_time:
logging.warn("WARNING: Watch directory didn't stabilize for %s seconds. Triggering command anyway.",
max_wait_time)
return
time.sleep(.1)
#-----------------------------------------------------------------------------------------------------------------------
def block_until_min_period(min_period, last_command_run):
seconds_since_last_run = (datetime.datetime.now() - last_command_run).total_seconds()
if seconds_since_last_run >= min_period:
return
logging.info("Command triggered, but it's too soon to run the command again. Waiting another %i seconds",
args.min_period - seconds_since_last_run)
time.sleep(min_period - seconds_since_last_run)
#-----------------------------------------------------------------------------------------------------------------------
config_file = sys.argv[1]
name = os.path.splitext(os.path.basename(config_file))[0]
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] {}: %(message)s'.format(name), datefmt='%Y-%m-%d %H:%M:%S')
args = read_config(config_file)
#args["DEBUG"] = True
if args.debug:
logging.getLogger().setLevel(logging.DEBUG)
logging.info("Starting monitor for %s", name)
# Launch the watchdog
event_handler = ModifyHandler()
observer = Observer()
observer.schedule(event_handler, args.watch_dir, recursive=True)
observer.start()
try:
# Initialize this to some time in the past
last_command_run = datetime.datetime.now() - datetime.timedelta(seconds=args.min_period+10)
# To help keep myself sane. "waiting for change" -> "waiting to stabilize or time out" -> "command triggered" ->
# "command running" -> "waiting for change". We can also go from "command triggered" -> "waiting to stabilize or
# time out", if new changes are detected while we're waiting for the min_period to expire.
state = "waiting for change"
while True:
# Need to put an "if" on this state because the loop can restart if new changes are detected while waiting for
# min_period to expire.
if state == "waiting for change":
wait_for_change(event_handler)
state = "waiting to stabilize or time out"
wait_for_events_to_stabilize(args.settle_duration, args.max_wait_time, event_handler)
state = "command triggered"
block_until_min_period(args.min_period, last_command_run)
# In case new events came in while we were sleeping. (But skip this if we've already waited our max_wait_time)
if event_handler.time_since_last_event() < args.settle_duration and \
event_handler.time_since_detected() < args.max_wait_time:
logging.info("Detected new changes while waiting.")
state = "waiting to stabilize or time out"
continue
state = "command running"
run_command(args, event_handler)
last_command_run = datetime.datetime.now()
state = "waiting for change"
except KeyboardInterrupt:
observer.stop()
observer.join()
sys.exit(0)