baker.py 24 KB

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