baker.py 24 KB

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