-
-
Notifications
You must be signed in to change notification settings - Fork 19
/
proxy.py
1584 lines (1413 loc) · 56.6 KB
/
proxy.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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2019-2020 Mircea Ulinic. All rights reserved.
#
# The contents of this file are licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with the
# License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
"""
Salt Runner to invoke arbitrary commands on network devices that are not
managed via a Proxy or regular Minion. Therefore, this Runner doesn't
necessarily require the targets to be up and running, as it will connect to
collect the Grains, compile the Pillar, then execute the commands.
"""
from __future__ import absolute_import, print_function, unicode_literals
# Import Python std lib
import sys
import copy
import json
import math
import time
import hashlib
import logging
import threading
import traceback
import multiprocessing
import six
# Import Salt modules
import salt.cache
import salt.loader
import salt.client
import salt.output
import salt.version
import salt.utils.jid
import salt.utils.master
from salt.minion import SMinion
from salt.cli.batch import Batch
import salt.utils.stringutils
import salt.defaults.exitcodes
from salt.exceptions import SaltSystemExit, SaltInvocationError
from salt.defaults import DEFAULT_TARGET_DELIM
import salt.utils.napalm
import salt.utils.dictupdate
try:
import salt.utils.platform
from salt.utils.args import clean_kwargs
OLD_SALT = False
except ImportError:
OLD_SALT = True
import salt.utils
from salt.utils import clean_kwargs
try:
import progressbar
HAS_PROGRESSBAR = True
except ImportError:
HAS_PROGRESSBAR = False
# ------------------------------------------------------------------------------
# module properties
# ------------------------------------------------------------------------------
_SENTINEL = "FIN."
log = logging.getLogger(__name__)
# ------------------------------------------------------------------------------
# property functions
# ------------------------------------------------------------------------------
# ------------------------------------------------------------------------------
# helper functions -- will not be exported
# ------------------------------------------------------------------------------
def _napalm_is_proxy(opts):
return opts.get("proxy", {}).get("proxytype") == "napalm"
# Point the native is_proxy function to the above, so it doesn't check whether
# we're actually running under a Proxy Minion
salt.utils.napalm.is_proxy = _napalm_is_proxy
def _is_proxy():
return True
# Same rationale as above, for any other Proxy type.
if not OLD_SALT:
salt.utils.platform.is_proxy = _is_proxy
else:
salt.utils.is_proxy = _is_proxy
def _salt_call_and_return(
minion_id,
salt_function,
ret_queue,
unreachable_devices,
failed_devices,
arg=None,
jid=None,
events=True,
**opts
):
""" """
opts["jid"] = jid
ret, retcode = salt_call(
minion_id,
salt_function,
unreachable_devices=unreachable_devices,
failed_devices=failed_devices,
**opts
)
if events:
__salt__["event.send"](
"proxy/runner/{jid}/ret/{minion_id}".format(minion_id=minion_id, jid=jid),
{
"fun": salt_function,
"fun_args": arg,
"id": minion_id,
"jid": jid,
"return": ret,
"retcode": retcode,
"success": retcode == 0,
},
)
try:
ret = json.loads(json.dumps(ret))
except (ValueError, TypeError):
log.error("Function return is not JSON-serializable data", exc_info=True)
log.error(ret)
ret_queue.put(({minion_id: ret}, retcode))
sys.exit(retcode)
def _existing_proxy_cli_batch(
cli_batch, ret_queue, batch_stop_queue, sproxy_stop_queue
):
""" """
run = cli_batch.run()
cumulative_retcode = 0
for ret in run:
if not sproxy_stop_queue.empty():
break
retcode = 0
if ret and isinstance(ret, dict):
minion_id = list(ret.keys())[0]
if isinstance(ret[minion_id], dict) and "retcode" in ret[minion_id]:
retcode = ret[minion_id].pop("retcode")
ret_queue.put((ret, retcode))
cumulative_retcode = max(cumulative_retcode, retcode)
batch_stop_queue.put(cumulative_retcode)
def _receive_replies_async(ret_queue, done_queue, progress_bar):
""" """
count = 0
while True:
ret, retcode = ret_queue.get()
count += 1
if ret == _SENTINEL:
break
# When async, print out the replies as soon as they arrive
# after passing them through the outputter of choice
out_fmt = salt.output.out_format(
ret,
__opts__.get("output", "nested"),
opts=__opts__,
_retcode=retcode,
)
if out_fmt:
# out_fmt can be empty string, for example, when using the ``quiet``
# outputter, or potentially other use cases.
salt.utils.stringutils.print_cli(out_fmt)
if progress_bar:
progress_bar.update(count)
done_queue.put(_SENTINEL)
def _receive_replies_sync(ret_queue, static_queue, done_queue, progress_bar):
""" """
count = 0
cumulative_retcode = 0
while True:
ret, retcode = ret_queue.get()
static_queue.put((ret, retcode))
count += 1
if ret == _SENTINEL:
break
if progress_bar:
progress_bar.update(count)
done_queue.put(_SENTINEL)
class PingBatch(Batch):
def __init__(
self, opts, eauth=None, quiet=False, parser=None
): # pylint: disable=super-init-not-called
self.opts = opts
self.eauth = eauth if eauth else {}
self.pub_kwargs = eauth if eauth else {}
self.quiet = quiet
self.local = salt.client.get_local_client(opts["conf_file"])
self.minions, self.ping_gen, self.down_minions = self.gather_minions()
self.options = parser
def _gather_minions(self):
return self.minions, self.ping_gen, self.down_minions
class NoPingBatch(Batch):
"""
Similar to the native Salt Batch. but without issuing test.ping to ensure
that the Minions are up and running.
"""
def __init__(
self, opts, eauth=None, quiet=False, parser=None
): # pylint: disable=super-init-not-called
self.opts = opts
self.eauth = eauth if eauth else {}
self.pub_kwargs = eauth if eauth else {}
self.quiet = quiet
self.local = salt.client.get_local_client(opts["conf_file"])
self.minions, self.ping_gen, self.down_minions = self.opts["tgt"], [], []
self.options = parser
def gather_minions(self):
return self.minions, self.ping_gen, self.down_minions
# The SProxyMinion class is back-ported from Salt 2019.2.0 (to be released soon)
# and extended to allow more flexible options for the (pre-)loading of the
# Pillars and the Grains.
class SProxyMinion(SMinion):
"""
Create an object that has loaded all of the minion module functions,
grains, modules, returners etc. The SProxyMinion allows developers to
generate all of the salt minion functions and present them with these
functions for general use.
"""
def _matches_target(self):
match_func = self.matchers.get(
"{0}_match.match".format(self.opts["__tgt_type"]), None
)
if match_func is None:
return False
if self.opts["__tgt_type"] in ("grain", "grain_pcre", "pillar"):
delimiter = self.opts.get("delimiter", DEFAULT_TARGET_DELIM)
if not match_func(self.opts["__tgt"], delimiter=delimiter):
return False
elif not match_func(self.opts["__tgt"]):
return False
else:
if not self.matchers["glob_match.match"](self.opts["__tgt"]):
return False
return True
def gen_modules(self, initial_load=False): # pylint: disable=arguments-differ
"""
Tell the minion to reload the execution modules.
CLI Example:
.. code-block:: bash
salt '*' sys.reload_modules
"""
if self.opts.get("proxy_preload_grains", True):
loaded_grains = salt.loader.grains(self.opts)
self.opts["grains"].update(loaded_grains)
if (
self.opts["roster_opts"]
and self.opts.get("proxy_merge_roster_grains", True)
and "grains" in self.opts["roster_opts"]
and isinstance(self.opts["roster_opts"]["grains"], dict)
):
# Merge the Grains from the Roster opts
log.debug("Merging Grains with the Roster provided ones")
self.opts["grains"] = salt.utils.dictupdate.merge(
self.opts["roster_opts"]["grains"], self.opts["grains"]
)
cached_grains = None
if self.opts.get("proxy_use_cached_grains", True):
cached_grains = self.opts.pop("proxy_cached_grains", None)
initial_grains = copy.deepcopy(self.opts["grains"])
if cached_grains:
# Merging the collected Grains into the cached Grains, but only for
# the initial Pillar compilation, to ensure we only do so to avoid
# any processing errors.
initial_grains = salt.utils.dictupdate.merge(cached_grains, initial_grains)
if self.opts.get("proxy_load_pillar", True):
self.opts["pillar"] = salt.pillar.get_pillar(
self.opts,
initial_grains,
self.opts["id"],
saltenv=self.opts["saltenv"],
pillarenv=self.opts.get("pillarenv"),
).compile_pillar()
if self.opts["roster_opts"] and self.opts.get("proxy_merge_roster_opts", True):
if "proxy" not in self.opts["pillar"]:
self.opts["pillar"]["proxy"] = {}
self.opts["pillar"]["proxy"] = salt.utils.dictupdate.merge(
self.opts["pillar"]["proxy"], self.opts["roster_opts"]
)
self.opts["pillar"]["proxy"].pop("grains", None)
self.opts["pillar"]["proxy"].pop("pillar", None)
if self.opts.get("preload_targeting", False) or self.opts.get(
"invasive_targeting", False
):
log.debug("Loading the Matchers modules")
self.matchers = salt.loader.matchers(self.opts)
if self.opts.get("preload_targeting", False):
log.debug(
"Preload targeting requested, trying to see if %s matches the target %s (%s)",
self.opts["id"],
str(self.opts["__tgt"]),
self.opts["__tgt_type"],
)
matched = self._matches_target()
if not matched:
return
if "proxy" not in self.opts["pillar"] and "proxy" not in self.opts:
errmsg = (
'No "proxy" configuration key found in pillar or opts '
"dictionaries for id {id}. Check your pillar/options "
"configuration and contents. Salt-proxy aborted."
).format(id=self.opts["id"])
log.error(errmsg)
self._running = False
raise SaltSystemExit(code=salt.defaults.exitcodes.EX_GENERIC, msg=errmsg)
if "proxy" not in self.opts:
self.opts["proxy"] = {}
if "proxy" not in self.opts["pillar"]:
self.opts["pillar"]["proxy"] = {}
self.opts["proxy"] = salt.utils.dictupdate.merge(
self.opts["proxy"], self.opts["pillar"]["proxy"]
)
# Then load the proxy module
fq_proxyname = self.opts["proxy"]["proxytype"]
self.utils = salt.loader.utils(self.opts)
self.proxy = salt.loader.proxy(
self.opts, utils=self.utils, whitelist=[fq_proxyname]
)
self.functions = salt.loader.minion_mods(
self.opts, utils=self.utils, notify=False, proxy=self.proxy
)
self.functions.pack["__grains__"] = copy.deepcopy(self.opts["grains"])
self.functions.pack["__proxy__"] = self.proxy
self.proxy.pack["__salt__"] = self.functions
self.proxy.pack["__pillar__"] = self.opts["pillar"]
# No need to inject the proxy into utils, as we don't need scheduler for
# this sort of short living Minion.
# self.utils = salt.loader.utils(self.opts, proxy=self.proxy)
self.proxy.pack["__utils__"] = self.utils
# Reload all modules so all dunder variables are injected
self.proxy.reload_modules()
if self.opts.get("proxy_no_connect", False):
log.info("Requested not to initialize the connection with the device")
else:
log.debug("Trying to initialize the connection with the device")
# When requested --no-connect, don't init the connection, but simply
# go ahead and execute the function requested.
if (
"{0}.init".format(fq_proxyname) not in self.proxy
or "{0}.shutdown".format(fq_proxyname) not in self.proxy
):
errmsg = (
"[{0}] Proxymodule {1} is missing an init() or a shutdown() or both. ".format(
self.opts["id"], fq_proxyname
)
+ "Check your proxymodule. Salt-proxy aborted."
)
log.error(errmsg)
self._running = False
if self.unreachable_devices is not None:
self.unreachable_devices.append(self.opts["id"])
raise SaltSystemExit(
code=salt.defaults.exitcodes.EX_GENERIC, msg=errmsg
)
proxy_init_fn = self.proxy[fq_proxyname + ".init"]
try:
proxy_init_fn(self.opts)
self.connected = True
except Exception as exc:
log.error(
"Encountered error when starting up the connection with %s:",
self.opts["id"],
exc_info=True,
)
if self.unreachable_devices is not None:
self.unreachable_devices.append(self.opts["id"])
raise
if self.opts.get("proxy_load_grains", True):
# When the Grains are loaded from the cache, no need to re-load them
# again.
grains = copy.deepcopy(self.opts["grains"])
# Copy the existing Grains loaded so far, otherwise
# salt.loader.grains is going to wipe what's under the grains
# key in the opts.
# After loading, merge with the previous loaded grains, which
# may contain other grains from different sources, e.g., roster.
loaded_grains = salt.loader.grains(self.opts, proxy=self.proxy)
self.opts["grains"] = salt.utils.dictupdate.merge(grains, loaded_grains)
if self.opts.get("proxy_load_pillar", True):
self.opts["pillar"] = salt.pillar.get_pillar(
self.opts,
self.opts["grains"],
self.opts["id"],
saltenv=self.opts["saltenv"],
pillarenv=self.opts.get("pillarenv"),
).compile_pillar()
self.functions.pack["__opts__"] = self.opts
self.functions.pack["__grains__"] = copy.deepcopy(self.opts["grains"])
self.functions.pack["__pillar__"] = copy.deepcopy(self.opts["pillar"])
self.grains_cache = copy.deepcopy(self.opts["grains"])
if self.opts.get("invasive_targeting", False):
log.info(
"Invasive targeting requested, trying to see if %s matches the target %s (%s)",
self.opts["id"],
str(self.opts["__tgt"]),
self.opts["__tgt_type"],
)
matched = self._matches_target()
if not matched:
# Didn't match, shutting down this Proxy Minion, and exiting.
log.debug(
"%s does not match the target expression, aborting", self.opts["id"]
)
proxy_shut_fn = self.proxy[fq_proxyname + ".shutdown"]
proxy_shut_fn(self.opts)
return
self.module_executors = self.proxy.get(
"{0}.module_executors".format(fq_proxyname), lambda: []
)() or self.opts.get("module_executors", [])
if self.module_executors:
self.executors = salt.loader.executors(
self.opts, self.functions, proxy=self.proxy
)
# Late load the Returners, as they might need Grains, which may not be
# properly or completely loaded before this.
self.returners = None
if self.opts["returner"]:
self.returners = salt.loader.returners(
self.opts, self.functions, proxy=self.proxy
)
self.proxy.pack["__ret__"] = self.returners
self.ready = True
class StandaloneProxy(SProxyMinion):
def __init__(
self, opts, unreachable_devices=None
): # pylint: disable=super-init-not-called
self.opts = opts
self.connected = False
self.ready = False
self.unreachable_devices = unreachable_devices
self.gen_modules()
# ------------------------------------------------------------------------------
# callable functions
# ------------------------------------------------------------------------------
def salt_call(
minion_id,
salt_function=None,
unreachable_devices=None,
failed_devices=None,
with_grains=True,
with_pillar=True,
preload_grains=True,
preload_pillar=True,
default_grains=None,
default_pillar=None,
cache_grains=True,
cache_pillar=True,
use_cached_grains=True,
use_cached_pillar=True,
use_existing_proxy=False,
no_connect=False,
jid=None,
roster_opts=None,
test_ping=False,
tgt=None,
tgt_type=None,
preload_targeting=False,
invasive_targeting=False,
failhard=False,
timeout=60,
returner="",
returner_config="",
returner_kwargs=None,
args=(),
**kwargs
):
"""
Invoke a Salt Execution Function that requires or invokes an NAPALM
functionality (directly or indirectly).
minion_id:
The ID of the Minion to compile Pillar data for.
salt_function
The name of the Salt function to invoke.
preload_grains: ``True``
Whether to preload the Grains before establishing the connection with
the remote network device.
default_grains:
Dictionary of the default Grains to make available within the functions
loaded.
with_grains: ``True``
Whether to load the Grains modules and collect Grains data and make it
available inside the Execution Functions.
The Grains will be loaded after opening the connection with the remote
network device.
preload_pillar: ``True``
Whether to preload Pillar data before opening the connection with the
remote network device.
default_pillar:
Dictionary of the default Pillar data to make it available within the
functions loaded.
with_pillar: ``True``
Whether to load the Pillar modules and compile Pillar data and make it
available inside the Execution Functions.
use_cached_pillar: ``True``
Use cached Pillars whenever possible. If unable to gather cached data,
it falls back to compiling the Pillar.
use_cached_grains: ``True``
Use cached Grains whenever possible. If unable to gather cached data,
it falls back to collecting Grains.
cache_pillar: ``True``
Cache the compiled Pillar data before returning.
cache_grains: ``True``
Cache the collected Grains before returning.
use_existing_proxy: ``False``
Use the existing Proxy Minions when they are available (say on an
already running Master).
no_connect: ``False``
Don't attempt to initiate the connection with the remote device.
Default: ``False`` (it will initiate the connection).
jid: ``None``
The JID to pass on, when executing.
test_ping: ``False``
When using the existing Proxy Minion with the ``use_existing_proxy``
option, can use this argument to verify also if the Minion is
responsive.
arg
The list of arguments to send to the Salt function.
kwargs
Key-value arguments to send to the Salt function.
CLI Example:
.. code-block:: bash
salt-run proxy.salt_call bgp.neighbors junos 1.2.3.4 test test123
salt-run proxy.salt_call net.load_config junos 1.2.3.4 test test123 text='set system ntp peer 1.2.3.4'
"""
opts = copy.deepcopy(__opts__)
opts["id"] = minion_id
opts["pillarenv"] = __opts__.get("pillarenv", "base")
opts["__cli"] = __opts__.get("__cli", "salt-call")
opts["__tgt"] = tgt
opts["__tgt_type"] = tgt_type
if "saltenv" not in opts:
opts["saltenv"] = "base"
if not default_grains:
default_grains = {}
opts["grains"] = default_grains
if not default_pillar:
default_pillar = {}
opts["pillar"] = default_pillar
opts["proxy_load_pillar"] = with_pillar
opts["proxy_load_grains"] = with_grains
opts["proxy_preload_pillar"] = preload_pillar
opts["proxy_preload_grains"] = preload_grains
opts["proxy_cache_grains"] = cache_grains
opts["proxy_cache_pillar"] = cache_pillar
opts["preload_targeting"] = preload_targeting
opts["invasive_targeting"] = invasive_targeting
opts["proxy_no_connect"] = no_connect
opts["proxy_test_ping"] = test_ping
opts["proxy_use_cached_grains"] = use_cached_grains
if use_cached_grains:
cache_data = __salt__["cache.fetch"]("minions/{}".format(minion_id), "data")
if cache_data and "grains" in cache_data:
opts["proxy_cached_grains"] = cache_data["grains"]
opts["roster_opts"] = roster_opts
opts["returner"] = returner
if not returner_kwargs:
returner_kwargs = {}
minion_defaults = salt.config.DEFAULT_MINION_OPTS.copy()
minion_defaults.update(salt.config.DEFAULT_PROXY_MINION_OPTS)
for opt, val in six.iteritems(minion_defaults):
if opt not in opts:
opts[opt] = val
sa_proxy = StandaloneProxy(opts, unreachable_devices)
if not sa_proxy.ready:
log.debug(
"The SProxy Minion for %s is not able to start up, aborting", opts["id"]
)
return
kwargs = clean_kwargs(**kwargs)
ret = None
retcode = 0
executors = getattr(sa_proxy, "module_executors")
try:
if executors:
for name in executors:
ex_name = "{}.execute".format(name)
if ex_name not in sa_proxy.executors:
raise SaltInvocationError(
"Executor '{0}' is not available".format(name)
)
ret = sa_proxy.executors[ex_name](
opts, {"fun": salt_function}, salt_function, args, kwargs
)
if ret is not None:
break
else:
ret = sa_proxy.functions[salt_function](*args, **kwargs)
retcode = sa_proxy.functions.pack["__context__"].get("retcode", 0)
except Exception as err:
log.info("Exception while running %s on %s", salt_function, opts["id"])
if failed_devices is not None:
failed_devices.append(opts["id"])
ret = "The minion function caused an exception: {err}".format(
err=traceback.format_exc()
)
if not retcode:
retcode = 11
if failhard:
raise
finally:
if sa_proxy.connected:
shut_fun = "{}.shutdown".format(sa_proxy.opts["proxy"]["proxytype"])
sa_proxy.proxy[shut_fun](opts)
if returner:
returner_fun = "{}.returner".format(returner)
if returner_fun in sa_proxy.returners:
log.debug(
"Sending the response from %s to the %s Returner",
opts["id"],
returner,
)
ret_data = {
"id": opts["id"],
"jid": jid,
"fun": salt_function,
"fun_args": args,
"return": ret,
"ret_config": returner_config,
"ret_kwargs": returner_kwargs,
}
try:
sa_proxy.returners[returner_fun](ret_data)
except Exception as err:
log.error(
"Exception while sending the response from %s to the %s returner",
opts["id"],
returner,
)
log.error(err, exc_info=True)
else:
log.warning(
"Returner %s is not available. Check that the dependencies are properly installed"
)
cache_data = {}
if cache_grains:
log.debug("Caching Grains for %s", minion_id)
log.debug(sa_proxy.opts["grains"])
cache_data["grains"] = copy.deepcopy(sa_proxy.opts["grains"])
if cache_pillar:
log.debug("Caching Pillar for %s", minion_id)
cache_data["pillar"] = copy.deepcopy(sa_proxy.opts["pillar"])
cached_store = __salt__["cache.store"](
"minions/{}".format(minion_id), "data", cache_data
)
return ret, retcode
def execute_devices(
minions,
salt_function,
with_grains=True,
with_pillar=True,
preload_grains=True,
preload_pillar=True,
default_grains=None,
default_pillar=None,
args=(),
batch_size=None,
batch_wait=0,
static=False,
tgt=None,
tgt_type=None,
jid=None,
events=True,
cache_grains=True,
cache_pillar=True,
use_cached_grains=True,
use_cached_pillar=True,
use_existing_proxy=False,
existing_minions=None,
no_connect=False,
roster_targets=None,
test_ping=False,
preload_targeting=False,
invasive_targeting=False,
failhard=False,
timeout=60,
summary=False,
verbose=False,
progress=False,
hide_timeout=False,
returner="",
returner_config="",
returner_kwargs=None,
**kwargs
):
"""
Execute a Salt function on a group of network devices identified by their
Minion ID, as listed under the ``minions`` argument.
minions
A list of Minion IDs to invoke ``function`` on.
salt_function
The name of the Salt function to invoke.
preload_grains: ``True``
Whether to preload the Grains before establishing the connection with
the remote network device.
default_grains:
Dictionary of the default Grains to make available within the functions
loaded.
with_grains: ``False``
Whether to load the Grains modules and collect Grains data and make it
available inside the Execution Functions.
The Grains will be loaded after opening the connection with the remote
network device.
preload_pillar: ``True``
Whether to preload Pillar data before opening the connection with the
remote network device.
default_pillar:
Dictionary of the default Pillar data to make it available within the
functions loaded.
with_pillar: ``True``
Whether to load the Pillar modules and compile Pillar data and make it
available inside the Execution Functions.
args
The list of arguments to send to the Salt function.
kwargs
Key-value arguments to send to the Salt function.
batch_size: None
The size of each batch to execute.
static: ``False``
Whether to return the results synchronously (or return them as soon
as the device replies).
events: ``True``
Whether should push events on the Salt bus, similar to when executing
equivalent through the ``salt`` command.
use_cached_pillar: ``True``
Use cached Pillars whenever possible. If unable to gather cached data,
it falls back to compiling the Pillar.
use_cached_grains: ``True``
Use cached Grains whenever possible. If unable to gather cached data,
it falls back to collecting Grains.
cache_pillar: ``True``
Cache the compiled Pillar data before returning.
cache_grains: ``True``
Cache the collected Grains before returning.
use_existing_proxy: ``False``
Use the existing Proxy Minions when they are available (say on an
already running Master).
no_connect: ``False``
Don't attempt to initiate the connection with the remote device.
Default: ``False`` (it will initiate the connection).
test_ping: ``False``
When using the existing Proxy Minion with the ``use_existing_proxy``
option, can use this argument to verify also if the Minion is
responsive.
CLI Example:
.. code-block:: bash
salt-run proxy.execute "['172.17.17.1', '172.17.17.2']" test.ping driver=eos username=test password=test123
"""
resp = ""
retcode = 0
__pub_user = kwargs.get("__pub_user")
if not __pub_user:
__pub_user = __utils__["user.get_specific_user"]()
kwargs = clean_kwargs(**kwargs)
if not jid:
if salt.version.__version_info__ >= (2018, 3, 0):
jid = salt.utils.jid.gen_jid(__opts__)
else:
jid = salt.utils.jid.gen_jid() # pylint: disable=no-value-for-parameter
event_args = list(args[:])
if kwargs:
event_kwargs = {"__kwarg__": True}
event_kwargs.update(kwargs)
event_args.append(event_kwargs)
if not returner_kwargs:
returner_kwargs = {}
opts = {
"with_grains": with_grains,
"with_pillar": with_pillar,
"preload_grains": preload_grains,
"preload_pillar": preload_pillar,
"default_grains": default_grains,
"default_pillar": default_pillar,
"preload_targeting": preload_targeting,
"invasive_targeting": invasive_targeting,
"args": args,
"cache_grains": cache_grains,
"cache_pillar": cache_pillar,
"use_cached_grains": use_cached_grains,
"use_cached_pillar": use_cached_pillar,
"use_existing_proxy": use_existing_proxy,
"no_connect": no_connect,
"test_ping": test_ping,
"tgt": tgt,
"tgt_type": tgt_type,
"failhard": failhard,
"timeout": timeout,
"returner": returner,
"returner_config": returner_config,
"returner_kwargs": returner_kwargs,
}
opts.update(kwargs)
if events:
__salt__["event.send"](
"proxy/runner/{jid}/new".format(jid=jid),
{
"fun": salt_function,
"minions": minions,
"arg": event_args,
"jid": jid,
"tgt": tgt,
"tgt_type": tgt_type,
"user": __pub_user,
},
)
if not existing_minions:
existing_minions = []
down_minions = []
progress_bar = None
if progress and HAS_PROGRESSBAR:
progress_bar = progressbar.ProgressBar(
max_value=len(minions), enable_colors=True, redirect_stdout=True
)
ret_queue = multiprocessing.Queue()
done_queue = multiprocessing.Queue()
if not static:
thread = threading.Thread(
target=_receive_replies_async, args=(ret_queue, done_queue, progress_bar)
)
thread.daemon = True
thread.start()
else:
static_queue = multiprocessing.Queue()
thread = threading.Thread(
target=_receive_replies_sync,
args=(ret_queue, static_queue, done_queue, progress_bar),
)
thread.daemon = True
thread.start()
ret = {}
sproxy_minions = list(set(minions) - set(existing_minions))
if batch_size:
if "%" in str(batch_size):
percent = int(batch_size.replace("%", ""))
batch_size = len(minions) * percent / 100
batch_size = int(batch_size)
batch_count = int(len(minions) / batch_size) + (
1 if len(minions) % batch_size else 0
)
existing_batch_size = int(
math.ceil(len(existing_minions) * batch_size / float(len(minions)))
)
sproxy_batch_size = batch_size - existing_batch_size
else:
# when no explicit batch requested, we'll execute the command on the
# existing minions without any batching (i.e., on all the matched
# minions at once), while sproxy ones are executed in as many CPUs are
# available.
sproxy_batch_size = multiprocessing.cpu_count()
existing_batch_size = len(existing_minions)
batch_count = int(len(sproxy_minions) / sproxy_batch_size) + (
1 if len(sproxy_minions) % sproxy_batch_size else 0
)
cli_batch = None
if existing_batch_size > 0:
# When there are existing Minions matching the target, use the native
# batching function to execute against these Minions.
log.debug("Executing against the existing Minions")
log.debug(existing_minions)
batch_opts = copy.deepcopy(__opts__)
batch_opts["batch"] = str(existing_batch_size)
batch_opts["tgt"] = existing_minions
batch_opts["tgt_type"] = "list"
batch_opts["fun"] = salt_function
batch_opts["arg"] = event_args
batch_opts["batch_wait"] = batch_wait
batch_opts["selected_target_option"] = "list"
batch_opts["return"] = returner
batch_opts["ret_config"] = returner_config
batch_opts["ret_kwargs"] = returner_kwargs
if test_ping:
cli_batch = PingBatch(batch_opts, quiet=True)
(
cli_batch.minions,
cli_batch.ping_gen,
cli_batch.down_minions,
) = cli_batch.gather_minions()
cli_batch.gather_minions = cli_batch._gather_minions
else:
cli_batch = NoPingBatch(batch_opts, quiet=True)
log.debug("Batching detected the following Minions responsive")
log.debug(cli_batch.minions)
if cli_batch.down_minions:
log.warning(