baker.py 23 KB

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