byrd.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. from getpass import getpass
  2. from hashlib import md5
  3. from itertools import chain
  4. from collections import ChainMap, OrderedDict, defaultdict
  5. from string import Formatter
  6. import argparse
  7. import io
  8. import logging
  9. import os
  10. import posixpath
  11. import subprocess
  12. import sys
  13. import threading
  14. import keyring
  15. import paramiko
  16. import yaml
  17. __version__ = '0.0'
  18. log_fmt = '%(levelname)s:%(asctime).19s: %(message)s'
  19. logger = logging.getLogger('byrd')
  20. logger.setLevel(logging.INFO)
  21. log_handler = logging.StreamHandler()
  22. log_handler.setLevel(logging.INFO)
  23. log_handler.setFormatter(logging.Formatter(log_fmt))
  24. logger.addHandler(log_handler)
  25. basedir, _ = os.path.split(__file__)
  26. PKG_DIR = os.path.join(basedir, 'pkg')
  27. TAB = '\n '
  28. class ByrdException(Exception):
  29. pass
  30. class FmtException(ByrdException):
  31. pass
  32. class ExecutionException(ByrdException):
  33. pass
  34. class RemoteException(ExecutionException):
  35. pass
  36. class LocalException(ExecutionException):
  37. pass
  38. def enable_logging_color():
  39. try:
  40. import colorama
  41. except ImportError:
  42. return
  43. colorama.init()
  44. MAGENTA = colorama.Fore.MAGENTA
  45. RED = colorama.Fore.RED
  46. RESET = colorama.Style.RESET_ALL
  47. # We define custom handler ..
  48. class Handler(logging.StreamHandler):
  49. def format(self, record):
  50. if record.levelname == 'INFO':
  51. record.msg = MAGENTA + record.msg + RESET
  52. elif record.levelname in ('WARNING', 'ERROR', 'CRITICAL'):
  53. record.msg = RED + record.msg + RESET
  54. return super(Handler, self).format(record)
  55. # .. and plug it
  56. logger.removeHandler(log_handler)
  57. handler = Handler()
  58. handler.setFormatter(logging.Formatter(log_fmt))
  59. logger.addHandler(handler)
  60. logger.propagate = 0
  61. def yaml_load(stream):
  62. class OrderedLoader(yaml.Loader):
  63. pass
  64. def construct_mapping(loader, node):
  65. loader.flatten_mapping(node)
  66. return OrderedDict(loader.construct_pairs(node))
  67. OrderedLoader.add_constructor(
  68. yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
  69. construct_mapping)
  70. return yaml.load(stream, OrderedLoader)
  71. def edits(word):
  72. yield word
  73. splits = ((word[:i], word[i:]) for i in range(len(word) + 1))
  74. for left, right in splits:
  75. if right:
  76. yield left + right[1:]
  77. def gen_candidates(wordlist):
  78. candidates = defaultdict(set)
  79. for word in wordlist:
  80. for ed1 in edits(word):
  81. for ed2 in edits(ed1):
  82. candidates[ed2].add(word)
  83. return candidates
  84. def spell(candidates, word):
  85. matches = set(chain.from_iterable(
  86. candidates[ed] for ed in edits(word) if ed in candidates
  87. ))
  88. return matches
  89. def spellcheck(objdict, word):
  90. if word in objdict:
  91. return
  92. candidates = objdict.get('_candidates')
  93. if not candidates:
  94. candidates = gen_candidates(list(objdict))
  95. objdict._candidates = candidates
  96. msg = '"%s" not found in %s' % (word, objdict._path)
  97. matches = spell(candidates, word)
  98. if matches:
  99. msg += ', try: %s' % ' or '.join(matches)
  100. raise ByrdException(msg)
  101. class ObjectDict(dict):
  102. """
  103. Simple objet sub-class that allows to transform a dict into an
  104. object, like: `ObjectDict({'ham': 'spam'}).ham == 'spam'`
  105. """
  106. _meta = {}
  107. def copy(self):
  108. res = ObjectDict(super().copy())
  109. ObjectDict._meta[id(res)] = ObjectDict._meta.get(id(self), {}).copy()
  110. return res
  111. def __getattr__(self, key):
  112. if key.startswith('_'):
  113. return ObjectDict._meta[id(self), key]
  114. if key in self:
  115. return self[key]
  116. else:
  117. return None
  118. def __setattr__(self, key, value):
  119. if key.startswith('_'):
  120. ObjectDict._meta[id(self), key] = value
  121. else:
  122. self[key] = value
  123. class Node:
  124. @staticmethod
  125. def fail(path, kind):
  126. msg = 'Error while parsing config: expecting "%s" while parsing "%s"'
  127. raise ByrdException(msg % (kind, '->'.join(path)))
  128. @classmethod
  129. def parse(cls, cfg, path=tuple()):
  130. children = getattr(cls, '_children', None)
  131. type_name = children and type(children).__name__ \
  132. or ' or '.join((c.__name__ for c in cls._type))
  133. res = None
  134. if type_name == 'dict':
  135. if not isinstance(cfg, dict):
  136. cls.fail(path, type_name)
  137. res = ObjectDict()
  138. if '*' in children:
  139. assert len(children) == 1, "Don't mix '*' and other keys"
  140. child_class = children['*']
  141. for name, value in cfg.items():
  142. res[name] = child_class.parse(value, path + (name,))
  143. else:
  144. # Enforce known pre-defined
  145. for key in cfg:
  146. if key not in children:
  147. path = ' -> '.join(path)
  148. if path:
  149. msg = 'Attribute "%s" not understood in %s' % (
  150. key, path)
  151. else:
  152. msg = 'Top-level attribute "%s" not understood' % (
  153. key)
  154. candidates = gen_candidates(children.keys())
  155. matches = spell(candidates, key)
  156. if matches:
  157. msg += ', try: %s' % ' or '.join(matches)
  158. raise ByrdException(msg)
  159. for name, child_class in children.items():
  160. if name not in cfg:
  161. continue
  162. res[name] = child_class.parse(cfg[name], path + (name,))
  163. elif type_name == 'list':
  164. if not isinstance(cfg, list):
  165. cls.fail(path, type_name)
  166. child_class = children[0]
  167. res = [child_class.parse(c, path+ ('[%s]' % pos,))
  168. for pos, c in enumerate(cfg)]
  169. else:
  170. if not isinstance(cfg, cls._type):
  171. cls.fail(path, type_name)
  172. res = cfg
  173. return cls.setup(res, path)
  174. @classmethod
  175. def setup(cls, values, path):
  176. if isinstance(values, ObjectDict):
  177. values._path = '->'.join(path)
  178. return values
  179. class Atom(Node):
  180. _type = (str, bool)
  181. class AtomList(Node):
  182. _children = [Atom]
  183. class Hosts(Node):
  184. _children = [Atom]
  185. class Auth(Node):
  186. _children = {'*': Atom}
  187. class EnvNode(Node):
  188. _children = {'*': Atom}
  189. class HostGroup(Node):
  190. _children = {
  191. 'hosts': Hosts,
  192. }
  193. class Network(Node):
  194. _children = {
  195. '*': HostGroup,
  196. }
  197. class Multi(Node):
  198. _children = {
  199. 'task': Atom,
  200. 'export': Atom,
  201. 'network': Atom,
  202. }
  203. class MultiList(Node):
  204. _children = [Multi]
  205. class Task(Node):
  206. _children = {
  207. 'desc': Atom,
  208. 'local': Atom,
  209. 'python': Atom,
  210. 'once': Atom,
  211. 'run': Atom,
  212. 'sudo': Atom,
  213. 'send': Atom,
  214. 'to': Atom,
  215. 'assert': Atom,
  216. 'env': EnvNode,
  217. 'multi': MultiList,
  218. }
  219. @classmethod
  220. def setup(cls, values, path):
  221. values['name'] = path and path[-1] or ''
  222. if 'desc' not in values:
  223. values['desc'] = values.get('name', '')
  224. super().setup(values, path)
  225. return values
  226. # Multi can also accept any task attribute:
  227. Multi._children.update(Task._children)
  228. class TaskGroup(Node):
  229. _children = {
  230. '*': Task,
  231. }
  232. class LoadNode(Node):
  233. _children = {
  234. 'file': Atom,
  235. 'pkg': Atom,
  236. 'as': Atom,
  237. }
  238. class LoadList(Node):
  239. _children = [LoadNode]
  240. class ConfigRoot(Node):
  241. _children = {
  242. 'networks': Network,
  243. 'tasks': TaskGroup,
  244. 'auth': Auth,
  245. 'env': EnvNode,
  246. 'load': LoadList,
  247. }
  248. class Env(ChainMap):
  249. def __init__(self, *dicts):
  250. return super().__init__(*filter(lambda x: x is not None, dicts))
  251. def fmt_env(self, child_env):
  252. new_env = {}
  253. for key, val in child_env.items():
  254. # env wrap-around!
  255. new_val = self.fmt(val)
  256. if new_val == val:
  257. continue
  258. new_env[key] = new_val
  259. return Env(new_env, child_env)
  260. def fmt_string(self, string):
  261. try:
  262. return string.format(**self)
  263. except KeyError as exc:
  264. msg = 'Unable to format "%s" (missing: "%s")'% (string, exc.args[0])
  265. candidates = gen_candidates(self.keys())
  266. key = exc.args[0]
  267. matches = spell(candidates, key)
  268. if matches:
  269. msg += ', try: %s' % ' or '.join(matches)
  270. raise FmtException(msg )
  271. except IndexError as exc:
  272. msg = 'Unable to format "%s", positional argument not supported'
  273. raise FmtException(msg)
  274. def fmt(self, what):
  275. if isinstance(what, str):
  276. return self.fmt_string(what)
  277. return self.fmt_env(what)
  278. def get_secret(service, resource, resource_id=None):
  279. resource_id = resource_id or resource
  280. secret = keyring.get_password(service, resource_id)
  281. if not secret:
  282. secret = getpass('Password for %s: ' % resource)
  283. keyring.set_password(service, resource_id, secret)
  284. return secret
  285. def get_passphrase(key_path):
  286. service = 'SSH private key'
  287. csum = md5(open(key_path, 'rb').read()).digest().hex()
  288. return get_secret(service, key_path, csum)
  289. def get_password(host):
  290. service = 'SSH password'
  291. return get_secret(service, host)
  292. def get_sudo_passwd():
  293. service = "Sudo password"
  294. return get_secret(service, 'sudo')
  295. CONNECTION_CACHE = {}
  296. def connect(host, auth):
  297. if host in CONNECTION_CACHE:
  298. return CONNECTION_CACHE[host]
  299. private_key_file = password = None
  300. if auth and auth.get('ssh_private_key'):
  301. private_key_file = auth.ssh_private_key
  302. if not os.path.exists(auth.ssh_private_key):
  303. msg = 'Private key file "%s" not found' % auth.ssh_private_key
  304. raise ByrdException(msg)
  305. password = get_passphrase(auth.ssh_private_key)
  306. else:
  307. password = get_password(host)
  308. username, hostname = host.split('@', 1)
  309. client = paramiko.SSHClient()
  310. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  311. client.connect(hostname, username=username, password=password,
  312. key_filename=private_key_file,
  313. )
  314. CONNECTION_CACHE[host] = client
  315. return client
  316. def run_local(cmd, env, cli):
  317. # Run local task
  318. cmd = env.fmt(cmd)
  319. logger.info(env.fmt('{task_desc}'))
  320. if cli.dry_run:
  321. logger.info('[dry-run] ' + cmd)
  322. return None
  323. logger.debug(TAB + TAB.join(cmd.splitlines()))
  324. process = subprocess.Popen(
  325. cmd, shell=True,
  326. stdout=subprocess.PIPE,
  327. stderr=subprocess.STDOUT,
  328. env=env,
  329. )
  330. stdout, stderr = process.communicate()
  331. success = process.returncode == 0
  332. if stdout:
  333. logger.debug(TAB + TAB.join(stdout.decode().splitlines()))
  334. if not success:
  335. raise LocalException(stdout, stderr)
  336. return ObjectDict(stdout=stdout, stderr=stderr)
  337. def run_python(task, env, cli):
  338. # Execute a piece of python localy
  339. code = task.python
  340. logger.info(env.fmt('{task_desc}'))
  341. if cli.dry_run:
  342. logger.info('[dry-run] ' + code)
  343. return None
  344. logger.debug(TAB + TAB.join(code.splitlines()))
  345. cmd = 'python -c "import sys;exec(sys.stdin.read())"'
  346. if task.sudo:
  347. user = 'root' if task.sudo is True else task.sudo
  348. cmd = 'sudo -u {} -- {}'.format(user, cmd)
  349. process = subprocess.Popen(
  350. cmd,
  351. stdout=subprocess.PIPE,
  352. stderr=subprocess.PIPE,
  353. stdin=subprocess.PIPE,
  354. env=env,
  355. )
  356. # Plug io
  357. out_buff = io.StringIO()
  358. err_buff = io.StringIO()
  359. log_stream(process.stdout, out_buff)
  360. log_stream(process.stderr, err_buff)
  361. process.stdin.write(code.encode())
  362. process.stdin.flush()
  363. process.stdin.close()
  364. success = process.wait() == 0
  365. process.stdout.close()
  366. process.stderr.close()
  367. out = out_buff.getvalue()
  368. if out:
  369. logger.debug(TAB + TAB.join(out.splitlines()))
  370. if not success:
  371. raise LocalException(out + err_buff.getvalue())
  372. return ObjectDict(stdout=out, stderr=err_buff.getvalue())
  373. def log_stream(stream, buff):
  374. def _log():
  375. try:
  376. for chunk in iter(lambda: stream.readline(2048), ""):
  377. if isinstance(chunk, bytes):
  378. chunk = chunk.decode()
  379. buff.write(chunk)
  380. except ValueError:
  381. # read raises a ValueError on closed stream
  382. pass
  383. t = threading.Thread(target=_log)
  384. t.start()
  385. return t
  386. def run_helper(client, cmd, env=None, in_buff=None, sudo=False):
  387. chan = client.get_transport().open_session()
  388. if env:
  389. chan.update_environment(env)
  390. stdin = chan.makefile('wb')
  391. stdout = chan.makefile('r')
  392. stderr = chan.makefile_stderr('r')
  393. out_buff = io.StringIO()
  394. err_buff = io.StringIO()
  395. out_thread = log_stream(stdout, out_buff)
  396. err_thread = log_stream(stderr, err_buff)
  397. if sudo:
  398. assert not in_buff, 'in_buff and sudo can not be combined'
  399. if isinstance(sudo, str):
  400. sudo_cmd = 'sudo -u %s -s' % sudo
  401. else:
  402. sudo_cmd = 'sudo -s'
  403. chan.exec_command(sudo_cmd)
  404. in_buff = cmd
  405. else:
  406. chan.exec_command(cmd)
  407. if in_buff:
  408. # XXX use a real buff (not a simple str) ?
  409. stdin.write(in_buff)
  410. stdin.flush()
  411. stdin.close()
  412. chan.shutdown_write()
  413. success = chan.recv_exit_status() == 0
  414. out_thread.join()
  415. err_thread.join()
  416. if not success:
  417. raise RemoteException(out_buff.getvalue() + err_buff.getvalue())
  418. res = ObjectDict(
  419. stdout = out_buff.getvalue(),
  420. stderr = err_buff.getvalue(),
  421. )
  422. return res
  423. def run_remote(task, host, env, cli):
  424. res = None
  425. host = env.fmt(host)
  426. env.update({
  427. 'host': host,
  428. })
  429. if cli.dry_run:
  430. client = None
  431. else:
  432. client = connect(host, cli.cfg.auth)
  433. if task.run:
  434. cmd = env.fmt(task.run)
  435. prefix = ''
  436. if task.sudo:
  437. if task.sudo is True:
  438. prefix = '[sudo] '
  439. else:
  440. prefix = '[sudo as %s] ' % task.sudo
  441. msg = prefix + '{host}: {task_desc}'
  442. logger.info(env.fmt(msg))
  443. logger.debug(TAB + TAB.join(cmd.splitlines()))
  444. if cli.dry_run:
  445. logger.info('[dry-run] ' + cmd)
  446. else:
  447. res = run_helper(client, cmd, env=env, sudo=task.sudo)
  448. elif task.send:
  449. local_path = env.fmt(task.send)
  450. remote_path = env.fmt(task.to)
  451. logger.info(f'[send] {local_path} -> {host}:{remote_path}')
  452. if not os.path.exists(local_path):
  453. ByrdException('Path "%s" not found' % local_path)
  454. if cli.dry_run:
  455. logger.info('[dry-run]')
  456. return
  457. else:
  458. with client.open_sftp() as sftp:
  459. if os.path.isfile(local_path):
  460. sftp.put(os.path.abspath(local_path), remote_path)
  461. elif os.path.isdir(local_path):
  462. for root, subdirs, files in os.walk(local_path):
  463. rel_dir = os.path.relpath(root, local_path)
  464. rel_dirs = os.path.split(rel_dir)
  465. rem_dir = posixpath.join(remote_path, *rel_dirs)
  466. run_helper(client, 'mkdir -p {}'.format(rem_dir))
  467. for f in files:
  468. rel_f = os.path.join(root, f)
  469. rem_file = posixpath.join(rem_dir, f)
  470. sftp.put(os.path.abspath(rel_f), rem_file)
  471. else:
  472. msg = 'Unexpected path "%s" (not a file, not a directory)'
  473. ByrdException(msg % local_path)
  474. else:
  475. raise ByrdException('Unable to run task "%s"' % task.name)
  476. if res and res.stdout:
  477. logger.debug(TAB + TAB.join(res.stdout.splitlines()))
  478. return res
  479. def run_task(task, host, cli, parent_env=None):
  480. '''
  481. Execute one task on one host (or locally)
  482. '''
  483. # Prepare environment
  484. env = Env(
  485. {},
  486. # Env on the task itself
  487. task.get('env'),
  488. # Env from parent task
  489. parent_env,
  490. ).new_child()
  491. env.update({
  492. 'task_desc': env.fmt(task.desc),
  493. 'task_name': task.name,
  494. 'host': host or '',
  495. })
  496. if task.local:
  497. res = run_local(task.local, env, cli)
  498. elif task.python:
  499. res = run_python(task, env, cli)
  500. else:
  501. res = run_remote(task, host, env, cli)
  502. if task.get('assert'):
  503. eval_env = {
  504. 'stdout': res.stdout.strip(),
  505. 'stderr': res.stderr.strip(),
  506. }
  507. assert_ = env.fmt(task['assert'])
  508. ok = eval(assert_, eval_env)
  509. if ok:
  510. logger.info('Assert ok')
  511. else:
  512. raise ByrdException('Assert "%s" failed!' % assert_)
  513. return res
  514. def run_batch(task, hosts, cli, global_env=None):
  515. '''
  516. Run one task on a list of hosts
  517. '''
  518. out = None
  519. export_env = {}
  520. task_env = global_env.fmt(task.get('env', {}))
  521. parent_env = Env(export_env, task_env, global_env)
  522. if task.get('multi'):
  523. parent_sudo = task.sudo
  524. for pos, step in enumerate(task.multi):
  525. task_name = step.task
  526. if task_name:
  527. # _cfg contain "local" config wrt the task
  528. siblings = task._cfg.tasks
  529. spellcheck(siblings, task_name)
  530. sub_task = siblings[task_name]
  531. sudo = step.sudo or sub_task.sudo or parent_sudo
  532. else:
  533. # reify a task out of attributes
  534. sub_task = Task.parse(step)
  535. sub_task._path = '%s->[%s]' % (task._path, pos)
  536. sudo = sub_task.sudo or parent_sudo
  537. sub_task.sudo = sudo
  538. network = step.get('network')
  539. if network:
  540. spellcheck(cli.cfg.networks, network)
  541. hosts = cli.cfg.networks[network].hosts
  542. child_env = step.get('env', {})
  543. child_env = parent_env.fmt(child_env)
  544. out = run_batch(sub_task, hosts, cli, Env(child_env, parent_env))
  545. out = out.decode() if isinstance(out, bytes) else out
  546. export_env['_'] = out
  547. if step.export:
  548. export_env[step.export] = out
  549. else:
  550. res = None
  551. if task.once and (task.local or task.python):
  552. res = run_task(task, None, cli, parent_env)
  553. elif hosts:
  554. for host in hosts:
  555. res = run_task(task, host, cli, parent_env)
  556. if task.once:
  557. break
  558. else:
  559. logger.warning('Nothing to do for task "%s"' % task._path)
  560. out = res and res.stdout.strip() or ''
  561. return out
  562. def abort(msg):
  563. logger.error(msg)
  564. sys.exit(1)
  565. def load_cfg(path, prefix=None):
  566. load_sections = ('networks', 'tasks', 'auth', 'env')
  567. if os.path.isfile(path):
  568. logger.debug('Load config %s' % path)
  569. cfg = yaml_load(open(path))
  570. cfg = ConfigRoot.parse(cfg)
  571. else:
  572. raise ByrdException('Config file "%s" not found' % path)
  573. # Define useful defaults
  574. cfg.networks = cfg.networks or ObjectDict()
  575. cfg.tasks = cfg.tasks or ObjectDict()
  576. # Create backrefs between tasks to the local config
  577. if cfg.get('tasks'):
  578. items = cfg['tasks'].items()
  579. for k, v in items:
  580. v._cfg = ObjectDict(cfg.copy())
  581. if prefix:
  582. key_fn = lambda x: '/'.join(prefix + [x])
  583. # Apply prefix
  584. for section in load_sections:
  585. if not section in cfg:
  586. continue
  587. items = cfg[section].items()
  588. cfg[section] = {key_fn(k): v for k, v in items}
  589. # Recursive load
  590. if cfg.load:
  591. cfg_path = os.path.dirname(path)
  592. for item in cfg.load:
  593. if item.get('file'):
  594. rel_path = item.file
  595. child_path = os.path.join(cfg_path, item.file)
  596. elif item.get('pkg'):
  597. rel_path = item.pkg
  598. child_path = os.path.join(PKG_DIR, item.pkg)
  599. if item.get('as'):
  600. child_prefix = item['as']
  601. else:
  602. child_prefix, _ = os.path.splitext(rel_path)
  603. child_cfg = load_cfg(child_path, child_prefix.split('/'))
  604. for section in load_sections:
  605. if not section in cfg:
  606. continue
  607. cfg[section].update(child_cfg.get(section, {}))
  608. return cfg
  609. def load_cli(args=None):
  610. parser = argparse.ArgumentParser()
  611. parser.add_argument('names', nargs='*',
  612. help='Hosts and commands to run them on')
  613. parser.add_argument('-c', '--config', default='bd.yaml',
  614. help='Config file')
  615. parser.add_argument('-R', '--run', nargs='*', default=[],
  616. help='Run remote task')
  617. parser.add_argument('-L', '--run-local', nargs='*', default=[],
  618. help='Run local task')
  619. parser.add_argument('-P', '--run-python', nargs='*', default=[],
  620. help='Run python task')
  621. parser.add_argument('-d', '--dry-run', action='store_true',
  622. help='Do not run actual tasks, just print them')
  623. parser.add_argument('-e', '--env', nargs='*', default=[],
  624. help='Add value to execution environment '
  625. '(ex: -e foo=bar "name=John Doe")')
  626. parser.add_argument('-s', '--sudo', default='auto',
  627. help='Enable sudo (auto|yes|no')
  628. parser.add_argument('-v', '--verbose', action='count',
  629. default=0, help='Increase verbosity')
  630. parser.add_argument('-q', '--quiet', action='count',
  631. default=0, help='Decrease verbosity')
  632. parser.add_argument('-n', '--no-color', action='store_true',
  633. help='Disable colored logs')
  634. parser.add_argument('-i', '--info', action='store_true',
  635. help='Print info')
  636. cli = parser.parse_args(args=args)
  637. cli = ObjectDict(vars(cli))
  638. # Load config
  639. cfg = load_cfg(cli.config)
  640. cli.cfg = cfg
  641. cli.update(get_hosts_and_tasks(cli, cfg))
  642. # Transformt env string into dict
  643. cli.env = dict(e.split('=') for e in cli.env)
  644. return cli
  645. def get_hosts_and_tasks(cli, cfg):
  646. # Make sure we don't have overlap between hosts and tasks
  647. items = list(cfg.networks) + list(cfg.tasks)
  648. msg = 'Name collision between tasks and networks'
  649. assert len(set(items)) == len(items), msg
  650. # Build task list
  651. tasks = []
  652. networks = []
  653. for name in cli.names:
  654. if name in cfg.networks:
  655. host = cfg.networks[name]
  656. networks.append(host)
  657. elif name in cfg.tasks:
  658. task = cfg.tasks[name]
  659. tasks.append(task)
  660. else:
  661. msg = 'Name "%s" not understood' % name
  662. matches = spell(cfg.networks, name) | spell(cfg.tasks, name)
  663. if matches:
  664. msg += ', try: %s' % ' or '.join(matches)
  665. raise ByrdException (msg)
  666. # Collect custom tasks from cli
  667. customs = []
  668. for cli_key in ('run', 'run_local', 'run_python'):
  669. cmd_key = cli_key.rsplit('_', 1)[-1]
  670. customs.extend('%s: %s' % (cmd_key, ck) for ck in cli[cli_key])
  671. for custom_task in customs:
  672. task = Task.parse(yaml_load(custom_task))
  673. task.desc = 'Custom command'
  674. tasks.append(task)
  675. hosts = list(chain.from_iterable(n.hosts for n in networks))
  676. return dict(hosts=hosts, tasks=tasks)
  677. def info(cli):
  678. formatter = Formatter()
  679. for name, attr in cli.cfg.tasks.items():
  680. kind = 'remote'
  681. if attr.python:
  682. kind = 'python'
  683. elif attr.local:
  684. kind = 'local'
  685. elif attr.multi:
  686. kind = 'multi'
  687. elif attr.send:
  688. kind = 'send file'
  689. print(f'{name} [{kind}]:\n\tDescription: {attr.desc}')
  690. values = []
  691. for v in attr.values():
  692. if isinstance(v, list):
  693. values.extend(v)
  694. elif isinstance(v, dict):
  695. values.extend(v.values())
  696. else:
  697. values.append(v)
  698. values = filter(lambda x: isinstance(x, str), values)
  699. fmt_fields = [i[1] for v in values for i in formatter.parse(v) if i[1]]
  700. if fmt_fields:
  701. variables = ', '.join(sorted(set(fmt_fields)))
  702. else:
  703. variables = None
  704. if variables:
  705. print(f'\tVariables: {variables}')
  706. def main():
  707. cli = None
  708. try:
  709. cli = load_cli()
  710. if not cli.no_color:
  711. enable_logging_color()
  712. cli.verbose = max(0, 1 + cli.verbose - cli.quiet)
  713. level = ['WARNING', 'INFO', 'DEBUG'][min(cli.verbose, 2)]
  714. log_handler.setLevel(level)
  715. logger.setLevel(level)
  716. if cli.info:
  717. info(cli)
  718. return
  719. base_env = Env(
  720. cli.env, # Highest-priority
  721. cli.cfg.get('env'),
  722. os.environ, # Lowest
  723. )
  724. for task in cli.tasks:
  725. run_batch(task, cli.hosts, cli, base_env)
  726. except ByrdException as e:
  727. if cli and cli.verbose > 2:
  728. raise
  729. abort(str(e))
  730. if __name__ == '__main__':
  731. main()