Debian Codegraph @

pepper/cli.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 '''
2 A CLI interface to a remote salt-api instance
3
4 '''
5 from __future__ import print_function
6 import json
7 import logging
8 import optparse
9 import os
10 import textwrap
11 import getpass
12 import time
13 try:
14 # Python 3
15 from configparser import ConfigParser, RawConfigParser
16 except ImportError:
17 # Python 2
18 from ConfigParser import ConfigParser, RawConfigParser
19
20 try:
21 input = raw_input
22 except NameError:
23 pass
24
25 import pepper
26
27 try:
28 from logging import NullHandler
29 except ImportError: # Python < 2.7
30 class NullHandler(logging.Handler):
31 def emit(self, record): pass
32
33 logging.basicConfig(format='%(levelname)s %(asctime)s %(module)s: %(message)s')
34 logger = logging.getLogger('pepper')
35 logger.addHandler(NullHandler())
36
37
38 class PepperCli(object):
39 def __init__(self, seconds_to_wait=3):
40 self.seconds_to_wait = seconds_to_wait
41 self.parser = self.get_parser()
42 self.parser.option_groups.extend([self.add_globalopts(),
43 self.add_tgtopts(),
44 self.add_authopts()])
45
46 def get_parser(self):
47 return optparse.OptionParser(
48 description=__doc__,
49 usage='%prog [opts]',
50 version=pepper.__version__)
51
52 def parse(self):
53 '''
54 Parse all args
55 '''
56 self.parser.add_option('-c', dest='config',
57 default=os.environ.get('PEPPERRC',
58 os.path.join(os.path.expanduser('~'), '.pepperrc')),
59 help=textwrap.dedent('''\
60 Configuration file location. Default is a file path in the
61 "PEPPERRC" environment variable or ~/.pepperrc.'''))
62
63 self.parser.add_option('-v', dest='verbose', default=0, action='count',
64 help=textwrap.dedent('''\
65 Increment output verbosity; may be specified multiple times'''))
66
67 self.parser.add_option('-H', '--debug-http', dest='debug_http', default=False,
68 action='store_true', help=textwrap.dedent('''\
69 Output the HTTP request/response headers on stderr'''))
70
71 self.parser.add_option('--ignore-ssl-errors', action='store_true',
72 dest='ignore_ssl_certificate_errors',
73 default=False,
74 help=textwrap.dedent('''\
75 Ignore any SSL certificate that may be encountered. Note that it is
76 recommended to resolve certificate errors for production.'''))
77
78 self.options, self.args = self.parser.parse_args()
79
80 def add_globalopts(self):
81 '''
82 Misc global options
83 '''
84 optgroup = optparse.OptionGroup(self.parser, "Pepper ``salt`` Options",
85 "Mimic the ``salt`` CLI")
86
87 optgroup.add_option('-t', '--timeout', dest='timeout', type='int',
88 default=60, help=textwrap.dedent('''\
89 Specify wait time (in seconds) before returning control to the
90 shell'''))
91
92 optgroup.add_option('--client', dest='client', default='local',
93 help=textwrap.dedent('''\
94 specify the salt-api client to use (local, local_async,
95 runner, etc)'''))
96
97 optgroup.add_option('--json', dest='json_input',
98 help=textwrap.dedent('''\
99 Enter JSON at the CLI instead of positional (text) arguments. This
100 is useful for arguments that need complex data structures.
101 Specifying this argument will cause positional arguments to be
102 ignored.'''))
103
104 optgroup.add_option('--json-file', dest='json_file',
105 help=textwrap.dedent('''\
106 Specify file containing the JSON to be used by pepper'''))
107
108 # optgroup.add_option('--out', '--output', dest='output',
109 # help="Specify the output format for the command output")
110
111 # optgroup.add_option('--return', default='', metavar='RETURNER',
112 # help="Redirect the output from a command to a persistent data store")
113
114 optgroup.add_option('--fail-if-incomplete', action='store_true',
115 dest='fail_if_minions_dont_respond', default=False,
116 help=textwrap.dedent('''\
117 Return a failure exit code if not all minions respond. This option
118 requires the authenticated user have access to run the
119 `jobs.list_jobs` runner function.'''))
120
121 return optgroup
122
123 def add_tgtopts(self):
124 '''
125 Targeting
126 '''
127 optgroup = optparse.OptionGroup(self.parser, "Targeting Options",
128 "Target which minions to run commands on")
129
130 optgroup.defaults.update({'expr_form': 'glob'})
131
132 optgroup.add_option('-E', '--pcre', dest='expr_form',
133 action='store_const', const='pcre',
134 help="Target hostnames using PCRE regular expressions")
135
136 optgroup.add_option('-L', '--list', dest='expr_form',
137 action='store_const', const='list',
138 help="Specify a comma delimited list of hostnames")
139
140 optgroup.add_option('-G', '--grain', dest='expr_form',
141 action='store_const', const='grain',
142 help="Target based on system properties")
143
144 optgroup.add_option('--grain-pcre', dest='expr_form',
145 action='store_const', const='grain_pcre',
146 help="Target based on PCRE matches on system properties")
147
148 optgroup.add_option('-I', '--pillar', dest='expr_form',
149 action='store_const', const='pillar',
150 help="Target based on pillar values")
151
152 optgroup.add_option('--pillar-pcre', dest='expr_form',
153 action='store_const', const='pillar_pcre',
154 help="Target based on PCRE matches on pillar values")
155
156 optgroup.add_option('-R', '--range', dest='expr_form',
157 action='store_const', const='range',
158 help="Target based on range expression")
159
160 optgroup.add_option('-C', '--compound', dest='expr_form',
161 action='store_const', const='compound',
162 help="Target based on compound expression")
163
164 optgroup.add_option('-N', '--nodegroup', dest='expr_form',
165 action='store_const', const='nodegroup',
166 help="Target based on a named nodegroup")
167
168 optgroup.add_option('--batch', dest='batch', default=None)
169
170 return optgroup
171
172 def add_authopts(self):
173 '''
174 Authentication options
175 '''
176 optgroup = optparse.OptionGroup(self.parser, "Authentication Options",
177 textwrap.dedent("""\
178 Authentication credentials can optionally be supplied via the
179 environment variables:
180 SALTAPI_URL, SALTAPI_USER, SALTAPI_PASS, SALTAPI_EAUTH.
181 """))
182
183 optgroup.add_option('-u', '--saltapi-url', dest='saltapiurl',
184 help="Specify the host url. Defaults to https://localhost:8080")
185
186 optgroup.add_option('-a', '--auth', '--eauth', '--extended-auth',
187 dest='eauth', help=textwrap.dedent("""\
188 Specify the external_auth backend to authenticate against and
189 interactively prompt for credentials"""))
190
191 optgroup.add_option('--username',
192 dest='username', help=textwrap.dedent("""\
193 Optional, defaults to user name. will be prompt if empty unless --non-interactive"""))
194
195 optgroup.add_option('--password',
196 dest='password', help=textwrap.dedent("""\
197 Optional, but will be prompted unless --non-interactive"""))
198
199 optgroup.add_option('--token-expire',
200 dest='token_expire', help=textwrap.dedent("""\
201 Set eauth token expiry in seconds. Must be allowed per
202 user. See the `token_expire_user_override` Master setting
203 for more info."""))
204
205 optgroup.add_option('--non-interactive',
206 action='store_false', dest='interactive', help=textwrap.dedent("""\
207 Optional, fail rather than waiting for input"""), default=True)
208
209 optgroup.add_option('-T', '--make-token', default=False,
210 dest='mktoken', action='store_true',
211 help=textwrap.dedent("""\
212 Generate and save an authentication token for re-use. The token is
213 generated and made available for the period defined in the Salt
214 Master."""))
215
216 optgroup.add_option('-r', '--run-uri', default=False,
217 dest='userun', action='store_true',
218 help=textwrap.dedent("""\
219 Use an eauth token from /token and send commands through the
220 /run URL instead of the traditional session token
221 approach."""))
222
223 optgroup.add_option('-x', dest='cache',
224 default=os.environ.get('PEPPERCACHE',
225 os.path.join(os.path.expanduser('~'), '.peppercache')),
226 help=textwrap.dedent('''\
227 Cache file location. Default is a file path in the
228 "PEPPERCACHE" environment variable or ~/.peppercache.'''))
229
230 return optgroup
231
232 def get_login_details(self):
233 '''
234 This parses the config file, environment variables and command line options
235 and returns the config values
236 Order of parsing:
237 command line options, ~/.pepperrc, environment, defaults
238 '''
239
240 # setting default values
241 results = {
242 'SALTAPI_USER': None,
243 'SALTAPI_PASS': None,
244 'SALTAPI_EAUTH': 'auto',
245 }
246
247 try:
248 config = ConfigParser(interpolation=None)
249 except TypeError:
250 config = RawConfigParser()
251 config.read(self.options.config)
252
253 # read file
254 profile = 'main'
255 if config.has_section(profile):
256 for key, value in list(results.items()):
257 if config.has_option(profile, key):
258 results[key] = config.get(profile, key)
259
260 # get environment values
261 for key, value in list(results.items()):
262 results[key] = os.environ.get(key, results[key])
263
264 if results['SALTAPI_EAUTH'] == 'kerberos':
265 results['SALTAPI_PASS'] = None
266
267 if self.options.eauth:
268 results['SALTAPI_EAUTH'] = self.options.eauth
269 if self.options.token_expire:
270 results['SALTAPI_TOKEN_EXPIRE'] = self.options.token_expire
271 if self.options.username is None and results['SALTAPI_USER'] is None:
272 if self.options.interactive:
273 results['SALTAPI_USER'] = input('Username: ')
274 else:
275 logger.error("SALTAPI_USER required")
276 raise SystemExit(1)
277 else:
278 if self.options.username is not None:
279 results['SALTAPI_USER'] = self.options.username
280 if self.options.password is None and results['SALTAPI_PASS'] is None:
281 if self.options.interactive:
282 results['SALTAPI_PASS'] = getpass.getpass(prompt='Password: ')
283 else:
284 logger.error("SALTAPI_PASS required")
285 raise SystemExit(1)
286 else:
287 if self.options.password is not None:
288 results['SALTAPI_PASS'] = self.options.password
289
290 return results
291
292 def parse_url(self):
293 '''
294 Determine api url
295 '''
296 url = 'https://localhost:8000/'
297
298 try:
299 config = ConfigParser(interpolation=None)
300 except TypeError:
301 config = RawConfigParser()
302 config.read(self.options.config)
303
304 # read file
305 profile = 'main'
306 if config.has_section(profile):
307 if config.has_option(profile, "SALTAPI_URL"):
308 url = config.get(profile, "SALTAPI_URL")
309
310 # get environment values
311 url = os.environ.get("SALTAPI_URL", url)
312
313 # get eauth prompt options
314 if self.options.saltapiurl:
315 url = self.options.saltapiurl
316
317 return url
318
319 def parse_login(self):
320 '''
321 Extract the authentication credentials
322 '''
323 login_details = self.get_login_details()
324
325 # Auth values placeholder; grab interactively at CLI or from config
326 username = login_details['SALTAPI_USER']
327 password = login_details['SALTAPI_PASS']
328 eauth = login_details['SALTAPI_EAUTH']
329
330 ret = dict(username=username, password=password, eauth=eauth)
331
332 token_expire = login_details.get('SALTAPI_TOKEN_EXPIRE', None)
333 if token_expire:
334 ret['token_expire'] = int(token_expire)
335
336 return ret
337
338 def parse_cmd(self):
339 '''
340 Extract the low data for a command from the passed CLI params
341 '''
342 # Short-circuit if JSON was given.
343 if self.options.json_input:
344 try:
345 return json.loads(self.options.json_input)
346 except ValueError:
347 logger.error("Invalid JSON given.")
348 raise SystemExit(1)
349
350 if self.options.json_file:
351 try:
352 with open(self.options.json_file, 'r') as json_content:
353 try:
354 return json.load(json_content)
355 except ValueError:
356 logger.error("Invalid JSON given.")
357 raise SystemExit(1)
358 except Exception as e:
359 logger.error(
360 'Cannot open file: {0}, {1}'.format(
361 self.options.json_file, repr(e)
362 )
363 )
364 raise SystemExit(1)
365
366 args = list(self.args)
367
368 client = self.options.client if not self.options.batch else 'local_batch'
369 low = {'client': client}
370
371 if client.startswith('local'):
372 if len(args) < 2:
373 self.parser.error("Command or target not specified")
374
375 low['expr_form'] = self.options.expr_form
376 low['tgt'] = args.pop(0)
377 low['fun'] = args.pop(0)
378 low['batch'] = self.options.batch
379 low['arg'] = args
380 elif client.startswith('runner'):
381 low['fun'] = args.pop(0)
382 for arg in args:
383 if '=' in arg:
384 key, value = arg.split('=', 1)
385 low[key] = value
386 else:
387 low.setdefault('args', []).append(arg)
388 elif client.startswith('wheel'):
389 low['fun'] = args.pop(0)
390 for arg in args:
391 if '=' in arg:
392 key, value = arg.split('=', 1)
393 low[key] = value
394 else:
395 low.setdefault('args', []).append(arg)
396 elif client.startswith('ssh'):
397 if len(args) < 2:
398 self.parser.error("Command or target not specified")
399
400 low['expr_form'] = self.options.expr_form
401 low['tgt'] = args.pop(0)
402 low['fun'] = args.pop(0)
403 low['batch'] = self.options.batch
404 low['arg'] = args
405 else:
406 if len(args) < 1:
407 self.parser.error("Command not specified")
408
409 low['fun'] = args.pop(0)
410 low['arg'] = args
411
412 return [low]
413
414 def poll_for_returns(self, api, load):
415 '''
416 Run a command with the local_async client and periodically poll the job
417 cache for returns for the job.
418 '''
419 load[0]['client'] = 'local_async'
420 async_ret = self.low(api, load)
421 jid = async_ret['return'][0]['jid']
422 nodes = async_ret['return'][0]['minions']
423 ret_nodes = []
424 exit_code = 1
425
426 # keep trying until all expected nodes return
427 total_time = 0
428 start_time = time.time()
429 ret = {}
430 exit_code = 0
431 while True:
432 total_time = time.time() - start_time
433 if total_time > self.options.timeout:
434 exit_code = 1
435 break
436
437 jid_ret = self.low(api, [{
438 'client': 'runner',
439 'fun': 'jobs.lookup_jid',
440 'kwarg': {
441 'jid': jid,
442 },
443 }])
444
445 responded = set(jid_ret['return'][0].keys()) ^ set(ret_nodes)
446 for node in responded:
447 yield None, "{{{}: {}}}".format(
448 node,
449 jid_ret['return'][0][node])
450 ret_nodes = list(jid_ret['return'][0].keys())
451
452 if set(ret_nodes) == set(nodes):
453 exit_code = 0
454 break
455 else:
456 time.sleep(self.seconds_to_wait)
457
458 exit_code = exit_code if self.options.fail_if_minions_dont_respond else 0
459 yield exit_code, "{{Failed: {}}}".format(
460 list(set(ret_nodes) ^ set(nodes)))
461
462 def login(self, api):
463 login = api.token if self.options.userun else api.login
464
465 if self.options.mktoken:
466 token_file = self.options.cache
467 try:
468 with open(token_file, 'rt') as f:
469 auth = json.load(f)
470 if auth['expire'] < time.time()+30:
471 logger.error('Login token expired')
472 raise Exception('Login token expired')
473 except Exception as e:
474 if e.args[0] is not 2:
475 logger.error('Unable to load login token from {0} {1}'
476 .format(token_file, str(e)))
477 auth = login(**self.parse_login())
478 try:
479 oldumask = os.umask(0)
480 fdsc = os.open(token_file, os.O_WRONLY | os.O_CREAT, 0o600)
481 with os.fdopen(fdsc, 'wt') as f:
482 json.dump(auth, f)
483 except Exception as e:
484 logger.error('Unable to save token to {0} {1}'
485 .format(token_file, str(e)))
486 finally:
487 os.umask(oldumask)
488 else:
489 auth = login(**self.parse_login())
490
491 api.auth = auth
492 self.auth = auth
493 return auth
494
495 def low(self, api, load):
496 path = '/run' if self.options.userun else '/'
497
498 if self.options.userun:
499 for i in load:
500 i['token'] = self.auth['token']
501
502 return api.low(load, path=path)
503
504 def run(self):
505 '''
506 Parse all arguments and call salt-api
507 '''
508 self.parse()
509
510 # move logger instantiation to method?
511 logger.addHandler(logging.StreamHandler())
512 logger.setLevel(max(logging.ERROR - (self.options.verbose * 10), 1))
513
514 load = self.parse_cmd()
515
516 api = pepper.Pepper(
517 self.parse_url(),
518 debug_http=self.options.debug_http,
519 ignore_ssl_errors=self.options.ignore_ssl_certificate_errors)
520
521 self.login(api)
522
523 if self.options.fail_if_minions_dont_respond:
524 for exit_code, ret in self.poll_for_returns(api, load):
525 yield exit_code, json.dumps(ret, sort_keys=True, indent=4)
526 else:
527 ret = self.low(api, load)
528 exit_code = 0
529 yield exit_code, json.dumps(ret, sort_keys=True, indent=4)