baker.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. from getpass import getpass
  2. from hashlib import md5
  3. from itertools import chain
  4. from collections import ChainMap, OrderedDict, defaultdict
  5. import argparse
  6. import io
  7. import logging
  8. import os
  9. import posixpath
  10. import subprocess
  11. import sys
  12. import threading
  13. import paramiko
  14. import yaml
  15. try:
  16. import keyring
  17. except ImportError:
  18. keyring = None
  19. __version__ = '0.0'
  20. log_fmt = '%(levelname)s:%(asctime).19s: %(message)s'
  21. logger = logging.getLogger('baker')
  22. logger.setLevel(logging.INFO)
  23. log_handler = logging.StreamHandler()
  24. log_handler.setLevel(logging.INFO)
  25. log_handler.setFormatter(logging.Formatter(log_fmt))
  26. logger.addHandler(log_handler)
  27. TAB = '\n '
  28. class BakerException(Exception):
  29. pass
  30. class FmtException(BakerException):
  31. pass
  32. class ExecutionException(BakerException):
  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 BakerException(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 __getattr__(self, key):
  108. if key.startswith('_'):
  109. return ObjectDict._meta[id(self), key]
  110. if key in self:
  111. return self[key]
  112. else:
  113. return None
  114. def __setattr__(self, key, value):
  115. if key.startswith('_'):
  116. ObjectDict._meta[id(self), key] = value
  117. else:
  118. self[key] = value
  119. class Node:
  120. @staticmethod
  121. def fail(path, kind):
  122. msg = 'Error while parsing config: expecting "%s" while parsing "%s"'
  123. raise BakerException(msg % (kind, '->'.join(path)))
  124. @classmethod
  125. def parse(cls, cfg, path=tuple()):
  126. children = getattr(cls, '_children', None)
  127. type_name = children and type(children).__name__ \
  128. or ' or '.join((c.__name__ for c in cls._type))
  129. res = None
  130. if type_name == 'dict':
  131. if not isinstance(cfg, dict):
  132. cls.fail(path, type_name)
  133. res = ObjectDict()
  134. if '*' in children:
  135. assert len(children) == 1, "Don't mix '*' and other keys"
  136. child_class = children['*']
  137. for name, value in cfg.items():
  138. res[name] = child_class.parse(value, path + (name,))
  139. else:
  140. # Enforce known pre-defined
  141. for key in cfg:
  142. if key not in children:
  143. path = ' -> '.join(path)
  144. if path:
  145. msg = 'Attribute "%s" not understood in %s' % (
  146. key, path)
  147. else:
  148. msg = 'Top-level attribute "%s" not understood' % (
  149. key)
  150. candidates = gen_candidates(children.keys())
  151. matches = spell(candidates, key)
  152. if matches:
  153. msg += ', try: %s' % ' or '.join(matches)
  154. raise BakerException(msg)
  155. for name, child_class in children.items():
  156. if name not in cfg:
  157. continue
  158. res[name] = child_class.parse(cfg.pop(name), path + (name,))
  159. elif type_name == 'list':
  160. if not isinstance(cfg, list):
  161. cls.fail(path, type_name)
  162. child_class = children[0]
  163. res = [child_class.parse(c, path+ ('[]',)) for c in cfg]
  164. else:
  165. if not isinstance(cfg, cls._type):
  166. cls.fail(path, type_name)
  167. res = cfg
  168. return cls.setup(res, path)
  169. @classmethod
  170. def setup(cls, values, path):
  171. if isinstance(values, ObjectDict):
  172. values._path = '->'.join(path)
  173. return values
  174. class Atom(Node):
  175. _type = (str, bool)
  176. class AtomList(Node):
  177. _children = [Atom]
  178. class Hosts(Node):
  179. _children = [Atom]
  180. class Auth(Node):
  181. _children = {'*': Atom}
  182. class EnvNode(Node):
  183. _children = {'*': Atom}
  184. class HostGroup(Node):
  185. _children = {
  186. 'hosts': Hosts,
  187. }
  188. class Network(Node):
  189. _children = {
  190. '*': HostGroup,
  191. }
  192. class Multi(Node):
  193. _children = {
  194. 'task': Atom,
  195. 'export': Atom,
  196. 'python': Atom,
  197. 'network': Atom,
  198. 'env': EnvNode,
  199. }
  200. class MultiList(Node):
  201. _children = [Multi]
  202. class Command(Node):
  203. _children = {
  204. 'desc': Atom,
  205. 'local': Atom,
  206. 'python': Atom,
  207. 'once': Atom,
  208. 'run': Atom,
  209. 'send': Atom,
  210. 'to': Atom,
  211. 'assert': Atom,
  212. 'env': EnvNode,
  213. 'multi': MultiList,
  214. }
  215. @classmethod
  216. def setup(cls, values, path):
  217. values['name'] = path and path[-1] or ''
  218. if 'desc' not in values:
  219. values['desc'] = values.get('name', '')
  220. super().setup(values, path)
  221. return values
  222. class Task(Node):
  223. _children = {
  224. '*': Command,
  225. }
  226. class LoadNode(Node):
  227. _children = {
  228. 'file': Atom,
  229. 'as': Atom,
  230. }
  231. class LoadList(Node):
  232. _children = [LoadNode]
  233. class ConfigRoot(Node):
  234. _children = {
  235. 'networks': Network,
  236. 'tasks': Task,
  237. 'auth': Auth,
  238. 'env': EnvNode,
  239. 'load': LoadList,
  240. }
  241. class Env(ChainMap):
  242. def __init__(self, *dicts):
  243. return super().__init__(*filter(lambda x: x is not None, dicts))
  244. def fmt(self, string):
  245. try:
  246. return string.format(**self)
  247. except KeyError as exc:
  248. msg = 'Unable to format "%s" (missing: "%s")'% (string, exc.args[0])
  249. candidates = gen_candidates(self.keys())
  250. key = exc.args[0]
  251. matches = spell(candidates, key)
  252. if matches:
  253. msg += ', try: %s' % ' or '.join(matches)
  254. raise FmtException(msg )
  255. except IndexError as exc:
  256. msg = 'Unable to format "%s", positional argument not supported'
  257. raise FmtException(msg)
  258. def get_passphrase(key_path):
  259. service = 'SSH private key'
  260. csum = md5(open(key_path, 'rb').read()).digest().hex()
  261. ssh_pass = keyring.get_password(service, csum)
  262. if not ssh_pass:
  263. ssh_pass = getpass('Password for %s: ' % key_path)
  264. keyring.set_password(service, csum, ssh_pass)
  265. return ssh_pass
  266. def get_password(host):
  267. service = 'SSH password'
  268. ssh_pass = keyring.get_password(service, host)
  269. if not ssh_pass:
  270. ssh_pass = getpass('Password for %s: ' % host)
  271. keyring.set_password(service, host, ssh_pass)
  272. return ssh_pass
  273. def get_sudo_passwd():
  274. service = "Sudo password"
  275. passwd = keyring.get_password(service, '-')
  276. if not passwd:
  277. passwd = getpass('Sudo password:')
  278. keyring.set_password(service, '-', passwd)
  279. return passwd
  280. CONNECTION_CACHE = {}
  281. def connect(host, auth):
  282. if host in CONNECTION_CACHE:
  283. return CONNECTION_CACHE[host]
  284. private_key_file = password = None
  285. if auth and auth.get('ssh_private_key'):
  286. private_key_file = auth.ssh_private_key
  287. if not os.path.exists(auth.ssh_private_key):
  288. msg = 'Private key file "%s" not found' % auth.ssh_private_key
  289. raise BakerException(msg)
  290. password = get_passphrase(auth.ssh_private_key)
  291. else:
  292. password = get_password(host)
  293. username, hostname = host.split('@', 1)
  294. client = paramiko.SSHClient()
  295. client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  296. client.connect(hostname, username=username, password=password,
  297. key_filename=private_key_file,
  298. )
  299. CONNECTION_CACHE[host] = client
  300. return client
  301. def run_local(cmd, env, cli):
  302. # Run local task
  303. cmd = env.fmt(cmd)
  304. logger.info(env.fmt('{task_desc}'))
  305. if cli.dry_run:
  306. logger.info('[DRY-RUN] ' + cmd)
  307. return None
  308. logger.debug(TAB + TAB.join(cmd.splitlines()))
  309. process = subprocess.Popen(
  310. cmd, shell=True,
  311. stdout=subprocess.PIPE,
  312. stderr=subprocess.STDOUT,
  313. env=env,
  314. )
  315. stdout, stderr = process.communicate()
  316. success = process.returncode == 0
  317. logger.debug(TAB + TAB.join(stdout.decode().splitlines()))
  318. if not success:
  319. raise LocalException(stdout, stderr)
  320. return ObjectDict(stdout=stdout, stderr=stderr)
  321. def run_python(code, env, cli):
  322. # Execute a piece of python localy
  323. logger.info(env.fmt('{task_desc}'))
  324. if cli.dry_run:
  325. logger.info('[DRY-RUN] ' + code)
  326. return None
  327. logger.debug(TAB + TAB.join(code.splitlines()))
  328. cmd = 'python -c "import sys;exec(sys.stdin.read())"'
  329. process = subprocess.Popen(
  330. cmd,
  331. stdout=subprocess.PIPE,
  332. stderr=subprocess.PIPE,
  333. stdin=subprocess.PIPE,
  334. env=env,
  335. )
  336. # Plug io
  337. out_buff = io.StringIO()
  338. err_buff = io.StringIO()
  339. log_stream(process.stdout, out_buff)
  340. log_stream(process.stderr, err_buff)
  341. process.stdin.write(code.encode())
  342. process.stdin.flush()
  343. process.stdin.close()
  344. success = process.wait() == 0
  345. process.stdout.close()
  346. process.stderr.close()
  347. out = out_buff.getvalue()
  348. logger.debug(TAB + TAB.join(out.splitlines()))
  349. if not success:
  350. raise LocalException(out + err_buff.getvalue())
  351. return ObjectDict(stdout=out, stderr=err_buff.getvalue())
  352. def log_stream(stream, buff):
  353. def _log():
  354. try:
  355. for chunk in iter(lambda: stream.readline(2048), ""):
  356. if isinstance(chunk, bytes):
  357. chunk = chunk.decode()
  358. buff.write(chunk)
  359. except ValueError:
  360. # read raises a ValueError on closed stream
  361. pass
  362. t = threading.Thread(target=_log)
  363. t.start()
  364. return t
  365. def run_helper(client, cmd, env=None, in_buff=None, sudo=False):
  366. assert not sudo, 'Not implemented'
  367. # stdin, stdout, stderr = client.exec_command(cmd)
  368. chan = client.get_transport().open_session()
  369. if env:
  370. chan.update_environment(env)
  371. chan.exec_command(cmd)
  372. stdin = chan.makefile('wb')
  373. stdout = chan.makefile('r')
  374. stderr = chan.makefile_stderr('r')
  375. out_buff = io.StringIO()
  376. err_buff = io.StringIO()
  377. out_thread = log_stream(stdout, out_buff)
  378. err_thread = log_stream(stderr, err_buff)
  379. if in_buff:
  380. # XXX use a real buff (not a simple str)
  381. stdin.write(in_buff)
  382. stdin.close()
  383. out_thread.join()
  384. err_thread.join()
  385. success = chan.recv_exit_status() == 0
  386. if not success:
  387. raise RemoteException(out_buff.getvalue() + err_buff.getvalue())
  388. res = ObjectDict(
  389. stdout = out_buff.getvalue(),
  390. stderr = err_buff.getvalue(),
  391. )
  392. return res
  393. def run_remote(task, host, env, cli):
  394. res = None
  395. host = env.fmt(host)
  396. env.update({
  397. 'host': host,
  398. })
  399. if cli.dry_run:
  400. client = None
  401. else:
  402. client = connect(host, cli.cfg.auth)
  403. if task.run:
  404. cmd = env.fmt(task.run)
  405. logger.info(env.fmt('{host}: {task_desc}'))
  406. logger.debug(TAB + TAB.join(cmd.splitlines()))
  407. if cli.dry_run:
  408. logger.info('[DRY-RUN] ' + cmd)
  409. else:
  410. res = run_helper(client, cmd, env=env)
  411. elif task.sudo:
  412. cmd = env.fmt(task.sudo)
  413. logger.info(env.fmt('[SUDO] {host}: {task_desc}'))
  414. if cli.dry_run:
  415. logger.info('[DRY-RUN] %s' + cmd)
  416. else:
  417. res = run_helper(client, cmd, env=env, sudo=True)
  418. elif task.send:
  419. local_path = env.fmt(task.send)
  420. remote_path = env.fmt(task.to)
  421. logger.info(f'[SEND] {local_path} -> {host}:{remote_path}')
  422. if cli.dry_run:
  423. logger.info('[DRY-RUN]')
  424. return
  425. else:
  426. with client.open_sftp() as sftp:
  427. if os.path.isfile(local_path):
  428. sftp.put(local_path, remote_path)
  429. else:
  430. for root, subdirs, files in os.walk(local_path):
  431. rel_dir = os.path.relpath(root, local_path)
  432. rem_dir = posixpath.join(remote_path, rel_dir)
  433. run_helper(client, 'mkdir -p {}'.format(rem_dir))
  434. for f in files:
  435. rel_f = os.path.join(root, f)
  436. rem_file = posixpath.join(rem_dir, f)
  437. sftp.put(os.path.abspath(rel_f), rem_file)
  438. else:
  439. raise BakerException('Unable to run task "%s"' % task.name)
  440. if res:
  441. logger.debug(TAB + TAB.join(res.stdout.splitlines()))
  442. return res
  443. def run_task(task, host, cli, parent_env=None):
  444. '''
  445. Execute one task on one host (or locally)
  446. '''
  447. # Prepare environment
  448. env = Env(
  449. # Env from parent task
  450. parent_env,
  451. # Env on the task itself
  452. task.get('env'),
  453. # Top-level env
  454. cli.cfg.get('env'),
  455. # OS env
  456. os.environ,
  457. ).new_child()
  458. env.update({
  459. 'task_desc': env.fmt(task.desc),
  460. 'task_name': task.name,
  461. 'host': host or '',
  462. })
  463. if task.local:
  464. res = run_local(task.local, env, cli)
  465. elif task.python:
  466. res = run_python(task.python, env, cli)
  467. else:
  468. res = run_remote(task, host, env, cli)
  469. if task.get('assert'):
  470. env.update({
  471. 'stdout': res.stdout.strip(),
  472. 'stderr': res.stderr.strip(),
  473. })
  474. assert_ = env.fmt(task['assert'])
  475. ok = eval(assert_, dict(env))
  476. if ok:
  477. logger.info('Assert ok')
  478. else:
  479. raise BakerException('Assert "%s" failed!' % assert_)
  480. return res
  481. def run_batch(task, hosts, cli, env=None):
  482. '''
  483. Run one task on a list of hosts
  484. '''
  485. out = None
  486. export_env = {}
  487. env = Env(export_env, task.get('env'), env)
  488. if task.get('multi'):
  489. for multi in task.multi:
  490. task = multi.task
  491. spellcheck(cli.cfg.tasks, task)
  492. sub_task = cli.cfg.tasks[task]
  493. network = multi.get('network')
  494. if network:
  495. spellcheck(cli.cfg.networks, network)
  496. hosts = cli.cfg.networks[network].hosts
  497. child_env = Env(multi.get('env', {}), env)
  498. for k, v in child_env.items():
  499. # env wrap-around!
  500. child_env[k] = child_env.fmt(child_env[k])
  501. out = run_batch(sub_task, hosts, cli, child_env)
  502. out = out.decode() if isinstance(out, bytes) else out
  503. export_env['_'] = out
  504. if multi.export:
  505. export_env[multi.export] = out
  506. else:
  507. res = None
  508. if task.once and (task.local or task.python):
  509. res = run_task(task, None, cli, env)
  510. else:
  511. for host in hosts:
  512. res = run_task(task, host, cli, env)
  513. if task.once:
  514. break
  515. out = res and res.stdout.strip() or ''
  516. return out
  517. def abort(msg):
  518. logger.error(msg)
  519. sys.exit(1)
  520. def load_cfg(path, prefix=None):
  521. load_sections = ('networks', 'tasks', 'auth', 'env')
  522. if os.path.isfile(path):
  523. logger.info('Load config %s' % path)
  524. cfg = yaml_load(open(path))
  525. cfg = ConfigRoot.parse(cfg)
  526. else:
  527. raise BakerException('Config file "%s" not found' % path)
  528. # Define useful defaults
  529. cfg.networks = cfg.networks or ObjectDict()
  530. cfg.tasks = cfg.tasks or ObjectDict()
  531. if prefix:
  532. fn = lambda x: '/'.join(prefix + [x])
  533. # Apply prefix
  534. for section in load_sections:
  535. if not cfg.get(section):
  536. continue
  537. items = cfg[section].items()
  538. cfg[section] = {fn(k): v for k, v in items}
  539. # Recursive load
  540. if cfg.load:
  541. cfg_path = os.path.dirname(path)
  542. for item in cfg.load:
  543. if item.get('as'):
  544. child_prefix = item['as']
  545. else:
  546. child_prefix, _ = os.path.splitext(item.file)
  547. child_path = os.path.join(cfg_path, item.file)
  548. child_cfg = load_cfg(child_path, child_prefix.split('/'))
  549. for section in load_sections:
  550. if not cfg.get(section):
  551. cfg[section] = {}
  552. cfg[section].update(child_cfg.get(section, {}))
  553. return cfg
  554. def load_cli(args=None):
  555. parser = argparse.ArgumentParser()
  556. parser.add_argument('names', nargs='*',
  557. help='Hosts and commands to run them on')
  558. parser.add_argument('-c', '--config', default='bk.yaml',
  559. help='Config file')
  560. parser.add_argument('-R', '--run', nargs='*', default=[],
  561. help='Run remote task')
  562. parser.add_argument('-L', '--run-local', nargs='*', default=[],
  563. help='Run local task')
  564. parser.add_argument('-P', '--run-python', nargs='*', default=[],
  565. help='Run python task')
  566. parser.add_argument('-d', '--dry-run', action='store_true',
  567. help='Do not run actual tasks, just print them')
  568. parser.add_argument('-e', '--env', nargs='*', default=[],
  569. help='Add value to execution environment '
  570. '(ex: -e foo=bar "name=John Doe")')
  571. parser.add_argument('-s', '--sudo', default='auto',
  572. help='Enable sudo (auto|yes|no')
  573. parser.add_argument('-v', '--verbose', action='count',
  574. default=0, help='Increase verbosity')
  575. parser.add_argument('-q', '--quiet', action='count',
  576. default=0, help='Decrease verbosity')
  577. parser.add_argument('-n', '--no-color', action='store_true',
  578. help='Disable colored logs')
  579. cli = parser.parse_args(args=args)
  580. cli = ObjectDict(vars(cli))
  581. # Load config
  582. cfg = load_cfg(cli.config)
  583. cli.cfg = cfg
  584. cli.update(get_hosts_and_tasks(cli, cfg))
  585. # Transformt env string into dict
  586. cli.env = dict(e.split('=') for e in cli.env)
  587. return cli
  588. def get_hosts_and_tasks(cli, cfg):
  589. # Make sure we don't have overlap between hosts and tasks
  590. items = list(cfg.networks) + list(cfg.tasks)
  591. msg = 'Name collision between tasks and networks'
  592. assert len(set(items)) == len(items), msg
  593. # Build task list
  594. tasks = []
  595. networks = []
  596. for name in cli.names:
  597. if name in cfg.networks:
  598. host = cfg.networks[name]
  599. networks.append(host)
  600. elif name in cfg.tasks:
  601. task = cfg.tasks[name]
  602. tasks.append(task)
  603. else:
  604. msg = 'Name "%s" not understood' % name
  605. matches = spell(cfg.networks, name) | spell(cfg.tasks, name)
  606. if matches:
  607. msg += ', try: %s' % ' or '.join(matches)
  608. raise BakerException (msg)
  609. # Collect custom tasks from cli
  610. customs = []
  611. for cli_key in ('run', 'run_local', 'run_python'):
  612. cmd_key = cli_key.rsplit('_', 1)[-1]
  613. customs.extend('%s: %s' % (cmd_key, ck) for ck in cli[cli_key])
  614. for custom_task in customs:
  615. task = Command.parse(yaml_load(custom_task))
  616. task.desc = 'Custom command'
  617. tasks.append(task)
  618. hosts = list(chain.from_iterable(n.hosts for n in networks))
  619. return dict(hosts=hosts, tasks=tasks)
  620. def main():
  621. cli = None
  622. try:
  623. cli = load_cli()
  624. if not cli.no_color:
  625. enable_logging_color()
  626. cli.verbose = max(0, 1 + cli.verbose - cli.quiet)
  627. level = ['WARNING', 'INFO', 'DEBUG'][min(cli.verbose, 2)]
  628. log_handler.setLevel(level)
  629. logger.setLevel(level)
  630. for task in cli.tasks:
  631. run_batch(task, cli.hosts, cli, cli.env)
  632. except BakerException as e:
  633. if cli and cli.verbose > 2:
  634. raise
  635. abort(str(e))
  636. if __name__ == '__main__':
  637. main()