baker.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763
  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. abort(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. abort(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. abort(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. abort(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. client = connect(host, cli.cfg.auth)
  400. if task.run:
  401. cmd = env.fmt(task.run)
  402. logger.info(env.fmt('{host}: {task_desc}'))
  403. logger.debug(TAB + TAB.join(cmd.splitlines()))
  404. if cli.dry_run:
  405. logger.info('[DRY-RUN] ' + cmd)
  406. else:
  407. res = run_helper(client, cmd, env=env)
  408. elif task.sudo:
  409. cmd = env.fmt(task.sudo)
  410. logger.info(env.fmt('[SUDO] {host}: {task_desc}'))
  411. if cli.dry_run:
  412. logger.info('[DRY-RUN] %s' + cmd)
  413. else:
  414. res = run_helper(client, cmd, env=env, sudo=True)
  415. elif task.send:
  416. local_path = env.fmt(task.send)
  417. remote_path = env.fmt(task.to)
  418. logger.info(f'[SEND] {local_path} -> {host}:{remote_path}')
  419. if cli.dry_run:
  420. logger.info('[DRY-RUN]')
  421. return
  422. else:
  423. with client.open_sftp() as sftp:
  424. if os.path.isfile(local_path):
  425. sftp.put(local_path, remote_path)
  426. else:
  427. for root, subdirs, files in os.walk(local_path):
  428. rel_dir = os.path.relpath(root, local_path)
  429. rem_dir = posixpath.join(remote_path, rel_dir)
  430. run_helper(client, 'mkdir -p {}'.format(rem_dir))
  431. for f in files:
  432. rel_f = os.path.join(root, f)
  433. rem_file = posixpath.join(rem_dir, f)
  434. sftp.put(os.path.abspath(rel_f), rem_file)
  435. else:
  436. abort('Unable to run task "%s"' % task.name)
  437. if res:
  438. logger.debug(TAB + TAB.join(res.stdout.splitlines()))
  439. return res
  440. def run_task(task, host, cli, parent_env=None):
  441. '''
  442. Execute one task on one host (or locally)
  443. '''
  444. # Prepare environment
  445. env = Env(
  446. # Env from parent task
  447. parent_env,
  448. # Env on the task itself
  449. task.get('env'),
  450. # Top-level env
  451. cli.cfg.get('env'),
  452. # OS env
  453. os.environ,
  454. ).new_child()
  455. env.update({
  456. 'task_desc': env.fmt(task.desc),
  457. 'task_name': task.name,
  458. 'host': host or '',
  459. })
  460. if task.local:
  461. res = run_local(task.local, env, cli)
  462. elif task.python:
  463. res = run_python(task.python, env, cli)
  464. else:
  465. res = run_remote(task, host, env, cli)
  466. if task.get('assert'):
  467. env.update({
  468. 'stdout': res.stdout.strip(),
  469. 'stderr': res.stderr.strip(),
  470. })
  471. assert_ = env.fmt(task['assert'])
  472. ok = eval(assert_, dict(env))
  473. if ok:
  474. logger.info('Assert ok')
  475. else:
  476. abort('Assert "%s" failed!' % assert_)
  477. return res
  478. def run_batch(task, hosts, cli, env=None):
  479. '''
  480. Run one task on a list of hosts
  481. '''
  482. env = Env(task.get('env'), env)
  483. out = None
  484. export_env = {}
  485. if task.get('multi'):
  486. for multi in task.multi:
  487. task = multi.task
  488. spellcheck(cli.cfg.tasks, task)
  489. sub_task = cli.cfg.tasks[task]
  490. network = multi.get('network')
  491. if network:
  492. spellcheck(cli.cfg.networks, network)
  493. hosts = cli.cfg.networks[network].hosts
  494. child_env = multi.get('env', {}).copy()
  495. for k, v in child_env.items():
  496. # env wrap-around!
  497. child_env[k] = env.fmt(child_env[k])
  498. run_env = Env(export_env, child_env, env)
  499. out = run_batch(sub_task, hosts, cli, run_env)
  500. out = out.decode() if isinstance(out, bytes) else out
  501. export_env['_'] = out
  502. if multi.export:
  503. export_env[multi.export] = out
  504. else:
  505. res = None
  506. if task.once and (task.local or task.python):
  507. res = run_task(task, None, cli, env)
  508. else:
  509. for host in hosts:
  510. res = run_task(task, host, cli, env)
  511. if task.once:
  512. break
  513. out = res and res.stdout.strip() or ''
  514. return out
  515. def abort(msg):
  516. logger.error(msg)
  517. sys.exit(1)
  518. def load_cfg(path, prefix=None):
  519. load_sections = ('networks', 'tasks', 'auth', 'env')
  520. if os.path.isfile(path):
  521. logger.info('Load config %s' % path)
  522. cfg = yaml_load(open(path))
  523. cfg = ConfigRoot.parse(cfg)
  524. else:
  525. abort('Config file "%s" not found' % path)
  526. # Define useful defaults
  527. cfg.networks = cfg.networks or ObjectDict()
  528. cfg.tasks = cfg.tasks or ObjectDict()
  529. if prefix:
  530. fn = lambda x: '/'.join(prefix + [x])
  531. # Apply prefix
  532. for section in load_sections:
  533. if not cfg.get(section):
  534. continue
  535. items = cfg[section].items()
  536. cfg[section] = {fn(k): v for k, v in items}
  537. # Recursive load
  538. if cfg.load:
  539. cfg_path = os.path.dirname(path)
  540. for item in cfg.load:
  541. if item.get('as'):
  542. child_prefix = item['as']
  543. else:
  544. child_prefix, _ = os.path.splitext(item.file)
  545. child_path = os.path.join(cfg_path, item.file)
  546. child_cfg = load_cfg(child_path, child_prefix.split('/'))
  547. for section in load_sections:
  548. if not cfg.get(section):
  549. cfg[section] = {}
  550. cfg[section].update(child_cfg.get(section, {}))
  551. return cfg
  552. def load_cli(args=None):
  553. parser = argparse.ArgumentParser()
  554. parser.add_argument('names', nargs='*',
  555. help='Hosts and commands to run them on')
  556. parser.add_argument('-c', '--config', default='bk.yaml',
  557. help='Config file')
  558. parser.add_argument('-R', '--run', nargs='*', default=[],
  559. help='Run remote task')
  560. parser.add_argument('-L', '--run-local', nargs='*', default=[],
  561. help='Run local task')
  562. parser.add_argument('-P', '--run-python', nargs='*', default=[],
  563. help='Run python task')
  564. parser.add_argument('-d', '--dry-run', action='store_true',
  565. help='Do not run actual tasks, just print them')
  566. parser.add_argument('-e', '--env', nargs='*', default=[],
  567. help='Add value to execution environment '
  568. '(ex: -e foo=bar "name=John Doe")')
  569. parser.add_argument('-s', '--sudo', default='auto',
  570. help='Enable sudo (auto|yes|no')
  571. parser.add_argument('-v', '--verbose', action='count',
  572. default=0, help='Increase verbosity')
  573. parser.add_argument('-q', '--quiet', action='count',
  574. default=0, help='Decrease verbosity')
  575. parser.add_argument('-n', '--no-color', action='store_true',
  576. help='Disable colored logs')
  577. cli = parser.parse_args(args=args)
  578. cli = ObjectDict(vars(cli))
  579. # Load config
  580. cfg = load_cfg(cli.config)
  581. cli.cfg = cfg
  582. cli.update(get_hosts_and_tasks(cli, cfg))
  583. # Transformt env string into dict
  584. cli.env = dict(e.split('=') for e in cli.env)
  585. return cli
  586. def get_hosts_and_tasks(cli, cfg):
  587. # Make sure we don't have overlap between hosts and tasks
  588. items = list(cfg.networks) + list(cfg.tasks)
  589. msg = 'Name collision between tasks and networks'
  590. assert len(set(items)) == len(items), msg
  591. # Build task list
  592. tasks = []
  593. networks = []
  594. for name in cli.names:
  595. if name in cfg.networks:
  596. host = cfg.networks[name]
  597. networks.append(host)
  598. elif name in cfg.tasks:
  599. task = cfg.tasks[name]
  600. tasks.append(task)
  601. else:
  602. msg = 'Name "%s" not understood' % name
  603. matches = spell(cfg.networks, name) | spell(cfg.tasks, name)
  604. if matches:
  605. msg += ', try: %s' % ' or '.join(matches)
  606. raise BakerException (msg)
  607. # Collect custom tasks from cli
  608. customs = []
  609. for cli_key in ('run', 'run_local', 'run_python'):
  610. cmd_key = cli_key.rsplit('_', 1)[-1]
  611. customs.extend('%s: %s' % (cmd_key, ck) for ck in cli[cli_key])
  612. for custom_task in customs:
  613. task = Command.parse(yaml_load(custom_task))
  614. task.desc = 'Custom command'
  615. tasks.append(task)
  616. hosts = list(chain.from_iterable(n.hosts for n in networks))
  617. return dict(hosts=hosts, tasks=tasks)
  618. def main():
  619. cli = load_cli()
  620. if not cli.no_color:
  621. enable_logging_color()
  622. cli.verbose = max(0, 1 + cli.verbose - cli.quiet)
  623. level = ['WARNING', 'INFO', 'DEBUG'][min(cli.verbose, 2)]
  624. log_handler.setLevel(level)
  625. logger.setLevel(level)
  626. try:
  627. for task in cli.tasks:
  628. run_batch(task, cli.hosts, cli, cli.env)
  629. except BakerException as e:
  630. if cli.verbose > 2:
  631. raise
  632. abort(str(e))
  633. if __name__ == '__main__':
  634. main()