-
Notifications
You must be signed in to change notification settings - Fork 5.6k
Expand file tree
/
Copy pathdaemons.py
More file actions
643 lines (539 loc) · 21 KB
/
daemons.py
File metadata and controls
643 lines (539 loc) · 21 KB
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
"""
Make me some salt!
"""
import logging
import os
import warnings
import salt.utils.kinds as kinds
from salt.exceptions import SaltClientError, SaltSystemExit, get_error_message
from salt.utils import migrations
from salt.utils.platform import is_junos
from salt.utils.process import HAS_PSUTIL
# All salt related deprecation warnings should be shown once each!
warnings.filterwarnings(
"once", # Show once
"", # No deprecation message match
DeprecationWarning, # This filter is for DeprecationWarnings
r"^(salt|salt\.(.*))$", # Match module(s) 'salt' and 'salt.<whatever>'
append=True,
)
# While we are supporting Python2.6, hide nested with-statements warnings
warnings.filterwarnings(
"ignore",
"With-statements now directly support multiple context managers",
DeprecationWarning,
append=True,
)
# Filter the backports package UserWarning about being re-imported
warnings.filterwarnings(
"ignore",
"^Module backports was already imported from (.*), but (.*) is being added to"
" sys.path$",
UserWarning,
append=True,
)
# the try block below bypasses an issue at build time so that modules don't
# cause the build to fail
try:
import salt.utils.parsers
from salt.utils.network import ip_bracket
from salt.utils.verify import check_user, verify_env, verify_socket
except ImportError as exc:
if exc.args[0] != "No module named _msgpack":
raise
log = logging.getLogger(__name__)
class DaemonsMixin: # pylint: disable=no-init
"""
Uses the same functions for all daemons
"""
def verify_hash_type(self):
"""
Verify and display a nag-messsage to the log if vulnerable hash-type is used.
:return:
"""
if self.config["hash_type"].lower() in ["md5", "sha1"]:
log.warning(
"IMPORTANT: Do not use %s hashing algorithm! Please set "
'"hash_type" to sha256 in Salt %s config!',
self.config["hash_type"],
self.__class__.__name__,
)
def action_log_info(self, action):
"""
Say daemon starting.
:param action
:return:
"""
log.info("%s the Salt %s", action, self.__class__.__name__)
def start_log_info(self):
"""
Say daemon starting.
:return:
"""
log.info("The Salt %s is starting up", self.__class__.__name__)
def shutdown_log_info(self):
"""
Say daemon shutting down.
:return:
"""
log.info("The Salt %s is shut down", self.__class__.__name__)
def environment_failure(self, error):
"""
Log environment failure for the daemon and exit with the error code.
:param error:
:return:
"""
log.exception(
"Failed to create environment for %s: %s",
self.__class__.__name__,
get_error_message(error),
)
self.shutdown(error)
class Master(
salt.utils.parsers.MasterOptionParser, DaemonsMixin
): # pylint: disable=no-init
"""
Creates a master server
"""
def _handle_signals(self, signum, sigframe):
if hasattr(self.master, "process_manager"):
# escalate signal to the process manager processes
self.master.process_manager._handle_signals(signum, sigframe)
super()._handle_signals(signum, sigframe)
def verify_environment(self):
if not self.config["verify_env"]:
return
v_dirs = [
self.config["pki_dir"],
os.path.join(self.config["pki_dir"], "minions"),
os.path.join(self.config["pki_dir"], "minions_pre"),
os.path.join(self.config["pki_dir"], "minions_denied"),
os.path.join(self.config["pki_dir"], "minions_autosign"),
os.path.join(self.config["pki_dir"], "minions_rejected"),
self.config["cachedir"],
os.path.join(self.config["cachedir"], "jobs"),
os.path.join(self.config["cachedir"], "proc"),
self.config["sock_dir"],
self.config["token_dir"],
self.config["syndic_dir"],
self.config["sqlite_queue_dir"],
]
pki_dir = self.config["pki_dir"]
if (
self.config["cluster_id"]
and self.config["cluster_pki_dir"]
# and self.config["cluster_pki_dir"] != self.config["pki_dir"]
):
v_dirs.extend(
[
self.config["cluster_pki_dir"],
os.path.join(self.config["cluster_pki_dir"], "peers"),
os.path.join(self.config["cluster_pki_dir"], "minions"),
os.path.join(self.config["cluster_pki_dir"], "minions_pre"),
os.path.join(self.config["cluster_pki_dir"], "minions_denied"),
os.path.join(self.config["cluster_pki_dir"], "minions_autosign"),
os.path.join(self.config["cluster_pki_dir"], "minions_rejected"),
]
)
pki_dir = [self.config["pki_dir"], self.config["cluster_pki_dir"]]
verify_env(
v_dirs,
self.config["user"],
permissive=self.config["permissive_pki_access"],
root_dir=self.config["root_dir"],
pki_dir=pki_dir,
)
def prepare(self):
"""
Run the preparation sequence required to start a salt master server.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
"""
super().prepare()
try:
self.verify_environment()
except OSError as error:
self.environment_failure(error)
self.action_log_info("Setting up")
# TODO: AIO core is separate from transport
if not verify_socket(
self.config["interface"],
self.config["publish_port"],
self.config["ret_port"],
):
self.shutdown(4, "The ports are not available to bind")
self.config["interface"] = ip_bracket(self.config["interface"])
migrations.migrate_paths(self.config)
# Late import so logging works correctly
import salt.master
self.master = salt.master.Master(self.config)
self.daemonize_if_required()
self.set_pidfile()
salt.utils.process.notify_systemd()
def start(self):
"""
Start the actual master.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
"""
super().start()
if check_user(self.config["user"]):
self.action_log_info("Starting up")
self.verify_hash_type()
self.master.start()
def shutdown(self, exitcode=0, exitmsg=None):
"""
If sub-classed, run any shutdown operations on this method.
"""
self.shutdown_log_info()
msg = "The salt master is shutdown. "
if exitmsg is not None:
exitmsg = msg + exitmsg
else:
exitmsg = msg.strip()
super().shutdown(exitcode, exitmsg)
class Minion(
salt.utils.parsers.MinionOptionParser, DaemonsMixin
): # pylint: disable=no-init
"""
Create a minion server
"""
def _handle_signals(self, signum, sigframe): # pylint: disable=unused-argument
# escalate signal to the process manager processes
if hasattr(self.minion, "stop"):
# If the minion has a stop method, call it - this is the case for
# MinionManager
self.minion.stop(signum, super()._handle_signals)
else:
super()._handle_signals(signum, sigframe)
# pylint: disable=no-member
def prepare(self):
"""
Run the preparation sequence required to start a salt minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
"""
super().prepare()
try:
if self.config["verify_env"]:
confd = self.config.get("default_include")
if confd:
# If 'default_include' is specified in config, then use it
if "*" in confd:
# Value is of the form "minion.d/*.conf"
confd = os.path.dirname(confd)
if not os.path.isabs(confd):
# If configured 'default_include' is not an absolute
# path, consider it relative to folder of 'conf_file'
# (/etc/salt by default)
confd = os.path.join(
os.path.dirname(self.config["conf_file"]), confd
)
else:
confd = os.path.join(
os.path.dirname(self.config["conf_file"]), "minion.d"
)
v_dirs = [
self.config["pki_dir"],
self.config["cachedir"],
self.config["sock_dir"],
self.config["extension_modules"],
confd,
]
verify_env(
v_dirs,
self.config["user"],
permissive=self.config["permissive_pki_access"],
root_dir=self.config["root_dir"],
pki_dir=self.config["pki_dir"],
)
except OSError as error:
self.environment_failure(error)
log.info('Setting up the Salt Minion "%s"', self.config["id"])
migrations.migrate_paths(self.config)
# Bail out if we find a process running and it matches out pidfile
if (HAS_PSUTIL and not self.claim_process_responsibility()) or (
not HAS_PSUTIL and self.check_running()
):
self.action_log_info("An instance is already running. Exiting")
self.shutdown(1)
transport = self.config.get("transport").lower()
try:
# Late import so logging works correctly
import salt.minion
# If the minion key has not been accepted, then Salt enters a loop
# waiting for it, if we daemonize later then the minion could halt
# the boot process waiting for a key to be accepted on the master.
# This is the latest safe place to daemonize
self.daemonize_if_required()
self.set_pidfile()
if self.config.get("master_type") == "func":
salt.minion.eval_master_func(self.config)
self.minion = salt.minion.MinionManager(self.config)
except Exception: # pylint: disable=broad-except
log.error(
"An error occured while setting up the minion manager", exc_info=True
)
self.shutdown(1)
def start(self):
"""
Start the actual minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
"""
super().start()
while True:
try:
self._real_start()
except SaltClientError as exc:
# Restart for multi_master failover when daemonized
if self.options.daemon:
continue
break
def _real_start(self):
try:
if check_user(self.config["user"]):
self.action_log_info("Starting up")
self.verify_hash_type()
self.minion.tune_in()
if self.minion.restart:
raise SaltClientError("Minion could not connect to Master")
except (KeyboardInterrupt, SaltSystemExit) as error:
self.action_log_info("Stopping")
if isinstance(error, KeyboardInterrupt):
log.warning("Exiting on Ctrl-c")
self.shutdown()
else:
log.error(error)
self.shutdown(error.code)
def call(self, cleanup_protecteds):
"""
Start the actual minion as a caller minion.
cleanup_protecteds is list of yard host addresses that should not be
cleaned up this is to fix race condition when salt-caller minion starts up
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
"""
try:
self.prepare()
if check_user(self.config["user"]):
self.minion.opts["__role"] = kinds.APPL_KIND_NAMES[
kinds.applKinds.caller
]
self.minion.call_in()
except (KeyboardInterrupt, SaltSystemExit) as exc:
self.action_log_info("Stopping")
if isinstance(exc, KeyboardInterrupt):
log.warning("Exiting on Ctrl-c")
self.shutdown()
else:
log.error(exc)
self.shutdown(exc.code)
def shutdown(self, exitcode=0, exitmsg=None):
"""
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
"""
self.action_log_info("Shutting down")
if hasattr(self, "minion") and hasattr(self.minion, "destroy"):
self.minion.destroy()
super().shutdown(
exitcode,
(
"The Salt {} is shutdown. {}".format(
self.__class__.__name__, (exitmsg or "")
).strip()
),
)
# pylint: enable=no-member
class ProxyMinion(
salt.utils.parsers.ProxyMinionOptionParser, DaemonsMixin
): # pylint: disable=no-init
"""
Create a proxy minion server
"""
def _handle_signals(self, signum, sigframe): # pylint: disable=unused-argument
# escalate signal to the process manager processes
self.minion.stop(signum, super()._handle_signals)
super()._handle_signals(signum, sigframe)
# pylint: disable=no-member
def prepare(self):
"""
Run the preparation sequence required to start a salt proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
"""
super().prepare()
## allow for native minion
if not is_junos():
if not self.values.proxyid:
self.error("salt-proxy requires --proxyid")
# Proxies get their ID from the command line. This may need to change in
# the future.
# We used to set this here. Now it is set in ProxyMinionOptionParser
# by passing it via setup_config to config.minion_config
# self.config['id'] = self.values.proxyid
try:
if self.config["verify_env"]:
confd = self.config.get("default_include")
if confd:
# If 'default_include' is specified in config, then use it
if "*" in confd:
# Value is of the form "minion.d/*.conf"
confd = os.path.dirname(confd)
if not os.path.isabs(confd):
# If configured 'default_include' is not an absolute
# path, consider it relative to folder of 'conf_file'
# (/etc/salt by default)
confd = os.path.join(
os.path.dirname(self.config["conf_file"]), confd
)
else:
confd = os.path.join(
os.path.dirname(self.config["conf_file"]), "proxy.d"
)
v_dirs = [
self.config["pki_dir"],
self.config["cachedir"],
self.config["sock_dir"],
self.config["extension_modules"],
confd,
]
verify_env(
v_dirs,
self.config["user"],
permissive=self.config["permissive_pki_access"],
root_dir=self.config["root_dir"],
pki_dir=self.config["pki_dir"],
)
except OSError as error:
self.environment_failure(error)
self.action_log_info('Setting up "{}"'.format(self.config["id"]))
migrations.migrate_paths(self.config)
# Bail out if we find a process running and it matches out pidfile
if self.check_running():
self.action_log_info("An instance is already running. Exiting")
self.shutdown(1)
# TODO: AIO core is separate from transport
# Late import so logging works correctly
import salt.minion
# If the minion key has not been accepted, then Salt enters a loop
# waiting for it, if we daemonize later then the minion could halt
# the boot process waiting for a key to be accepted on the master.
# This is the latest safe place to daemonize
self.daemonize_if_required()
self.set_pidfile()
if self.config.get("master_type") == "func":
salt.minion.eval_master_func(self.config)
self.minion = salt.minion.ProxyMinionManager(self.config)
def start(self):
"""
Start the actual proxy minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
"""
super().start()
try:
if check_user(self.config["user"]):
self.action_log_info("The Proxy Minion is starting up")
self.verify_hash_type()
self.minion.tune_in()
if self.minion.restart:
raise SaltClientError("Proxy Minion could not connect to Master")
except (KeyboardInterrupt, SaltSystemExit) as exc:
self.action_log_info("Proxy Minion Stopping")
if isinstance(exc, KeyboardInterrupt):
log.warning("Exiting on Ctrl-c")
self.shutdown()
else:
log.error(exc)
self.shutdown(exc.code)
def shutdown(self, exitcode=0, exitmsg=None):
"""
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
"""
if hasattr(self, "minion") and "proxymodule" in self.minion.opts:
proxy_fn = self.minion.opts["proxymodule"].loaded_base_name + ".shutdown"
self.minion.opts["proxymodule"][proxy_fn](self.minion.opts)
self.action_log_info("Shutting down")
super().shutdown(
exitcode,
(
"The Salt {} is shutdown. {}".format(
self.__class__.__name__, (exitmsg or "")
).strip()
),
)
# pylint: enable=no-member
class Syndic(
salt.utils.parsers.SyndicOptionParser, DaemonsMixin
): # pylint: disable=no-init
"""
Create a syndic server
"""
def prepare(self):
"""
Run the preparation sequence required to start a salt syndic minion.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).prepare()
"""
super().prepare()
try:
if self.config["verify_env"]:
verify_env(
[
self.config["pki_dir"],
self.config["sock_dir"],
self.config["extension_modules"],
],
self.config["user"],
permissive=self.config["permissive_pki_access"],
root_dir=self.config["root_dir"],
pki_dir=self.config["pki_dir"],
)
except OSError as error:
self.environment_failure(error)
self.action_log_info('Setting up "{}"'.format(self.config["id"]))
# Late import so logging works correctly
import salt.minion
self.daemonize_if_required()
self.syndic = salt.minion.SyndicManager(self.config)
self.set_pidfile()
def start(self):
"""
Start the actual syndic.
If sub-classed, don't **ever** forget to run:
super(YourSubClass, self).start()
NOTE: Run any required code before calling `super()`.
"""
super().start()
if check_user(self.config["user"]):
self.action_log_info("Starting up")
self.verify_hash_type()
try:
self.syndic.tune_in()
except KeyboardInterrupt:
self.action_log_info("Stopping")
self.shutdown()
def shutdown(self, exitcode=0, exitmsg=None):
"""
If sub-classed, run any shutdown operations on this method.
:param exitcode
:param exitmsg
"""
self.action_log_info("Shutting down")
super().shutdown(
exitcode,
(
"The Salt {} is shutdown. {}".format(
self.__class__.__name__, (exitmsg or "")
).strip()
),
)