tasks.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. from __future__ import with_statement
  2. import inspect
  3. import sys
  4. import textwrap
  5. from fabric import state
  6. from fabric.utils import abort, warn, error
  7. from fabric.network import to_dict, disconnect_all
  8. from fabric.context_managers import settings
  9. from fabric.job_queue import JobQueue
  10. from fabric.task_utils import crawl, merge, parse_kwargs
  11. from fabric.exceptions import NetworkError
  12. if sys.version_info[:2] == (2, 5):
  13. # Python 2.5 inspect.getargspec returns a tuple
  14. # instead of ArgSpec namedtuple.
  15. class ArgSpec(object):
  16. def __init__(self, args, varargs, keywords, defaults):
  17. self.args = args
  18. self.varargs = varargs
  19. self.keywords = keywords
  20. self.defaults = defaults
  21. self._tuple = (args, varargs, keywords, defaults)
  22. def __getitem__(self, idx):
  23. return self._tuple[idx]
  24. def patched_get_argspec(func):
  25. return ArgSpec(*inspect._getargspec(func))
  26. inspect._getargspec = inspect.getargspec
  27. inspect.getargspec = patched_get_argspec
  28. def get_task_details(task):
  29. details = [
  30. textwrap.dedent(task.__doc__)
  31. if task.__doc__
  32. else 'No docstring provided']
  33. argspec = inspect.getargspec(task)
  34. default_args = [] if not argspec.defaults else argspec.defaults
  35. num_default_args = len(default_args)
  36. args_without_defaults = argspec.args[:len(argspec.args) - num_default_args]
  37. args_with_defaults = argspec.args[-1 * num_default_args:]
  38. details.append('Arguments: %s' % (
  39. ', '.join(
  40. args_without_defaults + [
  41. '%s=%r' % (arg, default)
  42. for arg, default in zip(args_with_defaults, default_args)
  43. ])
  44. ))
  45. return '\n'.join(details)
  46. def _get_list(env):
  47. def inner(key):
  48. return env.get(key, [])
  49. return inner
  50. class Task(object):
  51. """
  52. Abstract base class for objects wishing to be picked up as Fabric tasks.
  53. Instances of subclasses will be treated as valid tasks when present in
  54. fabfiles loaded by the :doc:`fab </usage/fab>` tool.
  55. For details on how to implement and use `~fabric.tasks.Task` subclasses,
  56. please see the usage documentation on :ref:`new-style tasks
  57. <new-style-tasks>`.
  58. .. versionadded:: 1.1
  59. """
  60. name = 'undefined'
  61. use_task_objects = True
  62. aliases = None
  63. is_default = False
  64. # TODO: make it so that this wraps other decorators as expected
  65. def __init__(self, alias=None, aliases=None, default=False, name=None,
  66. *args, **kwargs):
  67. if alias is not None:
  68. self.aliases = [alias, ]
  69. if aliases is not None:
  70. self.aliases = aliases
  71. if name is not None:
  72. self.name = name
  73. self.is_default = default
  74. def __details__(self):
  75. return get_task_details(self.run)
  76. def run(self):
  77. raise NotImplementedError
  78. def get_hosts_and_effective_roles(self, arg_hosts, arg_roles, arg_exclude_hosts, env=None):
  79. """
  80. Return a tuple containing the host list the given task should be using
  81. and the roles being used.
  82. See :ref:`host-lists` for detailed documentation on how host lists are
  83. set.
  84. .. versionchanged:: 1.9
  85. """
  86. env = env or {'hosts': [], 'roles': [], 'exclude_hosts': []}
  87. roledefs = env.get('roledefs', {})
  88. # Command line per-task takes precedence over anything else.
  89. if arg_hosts or arg_roles:
  90. return merge(arg_hosts, arg_roles, arg_exclude_hosts, roledefs), arg_roles
  91. # Decorator-specific hosts/roles go next
  92. func_hosts = getattr(self, 'hosts', [])
  93. func_roles = getattr(self, 'roles', [])
  94. if func_hosts or func_roles:
  95. return merge(func_hosts, func_roles, arg_exclude_hosts, roledefs), func_roles
  96. # Finally, the env is checked (which might contain globally set lists
  97. # from the CLI or from module-level code). This will be the empty list
  98. # if these have not been set -- which is fine, this method should
  99. # return an empty list if no hosts have been set anywhere.
  100. env_vars = map(_get_list(env), "hosts roles exclude_hosts".split())
  101. env_vars.append(roledefs)
  102. return merge(*env_vars), env.get('roles', [])
  103. def get_pool_size(self, hosts, default):
  104. # Default parallel pool size (calculate per-task in case variables
  105. # change)
  106. default_pool_size = default or len(hosts)
  107. # Allow per-task override
  108. # Also cast to int in case somebody gave a string
  109. from_task = getattr(self, 'pool_size', None)
  110. pool_size = int(from_task or default_pool_size)
  111. # But ensure it's never larger than the number of hosts
  112. pool_size = min((pool_size, len(hosts)))
  113. # Inform user of final pool size for this task
  114. if state.output.debug:
  115. print("Parallel tasks now using pool size of %d" % pool_size)
  116. return pool_size
  117. class WrappedCallableTask(Task):
  118. """
  119. Wraps a given callable transparently, while marking it as a valid Task.
  120. Generally used via `~fabric.decorators.task` and not directly.
  121. .. versionadded:: 1.1
  122. .. seealso:: `~fabric.docs.unwrap_tasks`, `~fabric.decorators.task`
  123. """
  124. def __init__(self, callable, *args, **kwargs):
  125. super(WrappedCallableTask, self).__init__(*args, **kwargs)
  126. self.wrapped = callable
  127. # Don't use getattr() here -- we want to avoid touching self.name
  128. # entirely so the superclass' value remains default.
  129. if hasattr(callable, '__name__'):
  130. if self.name == 'undefined':
  131. self.__name__ = self.name = callable.__name__
  132. else:
  133. self.__name__ = self.name
  134. if hasattr(callable, '__doc__'):
  135. self.__doc__ = callable.__doc__
  136. if hasattr(callable, '__module__'):
  137. self.__module__ = callable.__module__
  138. def __call__(self, *args, **kwargs):
  139. return self.run(*args, **kwargs)
  140. def run(self, *args, **kwargs):
  141. return self.wrapped(*args, **kwargs)
  142. def __getattr__(self, k):
  143. return getattr(self.wrapped, k)
  144. def __details__(self):
  145. orig = self
  146. while 'wrapped' in orig.__dict__:
  147. orig = orig.__dict__.get('wrapped')
  148. return get_task_details(orig)
  149. def requires_parallel(task):
  150. """
  151. Returns True if given ``task`` should be run in parallel mode.
  152. Specifically:
  153. * It's been explicitly marked with ``@parallel``, or:
  154. * It's *not* been explicitly marked with ``@serial`` *and* the global
  155. parallel option (``env.parallel``) is set to ``True``.
  156. """
  157. return (
  158. (state.env.parallel and not getattr(task, 'serial', False))
  159. or getattr(task, 'parallel', False)
  160. )
  161. def _parallel_tasks(commands_to_run):
  162. return any(map(
  163. lambda x: requires_parallel(crawl(x[0], state.commands)),
  164. commands_to_run
  165. ))
  166. def _is_network_error_ignored():
  167. return not state.env.use_exceptions_for['network'] and state.env.skip_bad_hosts
  168. def _execute(task, host, my_env, args, kwargs, jobs, queue, multiprocessing):
  169. """
  170. Primary single-host work body of execute()
  171. """
  172. # Log to stdout
  173. if state.output.running and not hasattr(task, 'return_value'):
  174. print("[%s] Executing task '%s'" % (host, my_env['command']))
  175. # Create per-run env with connection settings
  176. local_env = to_dict(host)
  177. local_env.update(my_env)
  178. # Set a few more env flags for parallelism
  179. if queue is not None:
  180. local_env.update({'parallel': True, 'linewise': True})
  181. # Handle parallel execution
  182. if queue is not None: # Since queue is only set for parallel
  183. name = local_env['host_string']
  184. # Wrap in another callable that:
  185. # * expands the env it's given to ensure parallel, linewise, etc are
  186. # all set correctly and explicitly. Such changes are naturally
  187. # insulted from the parent process.
  188. # * nukes the connection cache to prevent shared-access problems
  189. # * knows how to send the tasks' return value back over a Queue
  190. # * captures exceptions raised by the task
  191. def inner(args, kwargs, queue, name, env):
  192. state.env.update(env)
  193. def submit(result):
  194. queue.put({'name': name, 'result': result})
  195. try:
  196. state.connections.clear()
  197. submit(task.run(*args, **kwargs))
  198. except BaseException, e: # We really do want to capture everything
  199. # SystemExit implies use of abort(), which prints its own
  200. # traceback, host info etc -- so we don't want to double up
  201. # on that. For everything else, though, we need to make
  202. # clear what host encountered the exception that will
  203. # print.
  204. if e.__class__ is not SystemExit:
  205. if not (isinstance(e, NetworkError) and
  206. _is_network_error_ignored()):
  207. sys.stderr.write("!!! Parallel execution exception under host %r:\n" % name)
  208. submit(e)
  209. # Here, anything -- unexpected exceptions, or abort()
  210. # driven SystemExits -- will bubble up and terminate the
  211. # child process.
  212. if not (isinstance(e, NetworkError) and
  213. _is_network_error_ignored()):
  214. raise
  215. # Stuff into Process wrapper
  216. kwarg_dict = {
  217. 'args': args,
  218. 'kwargs': kwargs,
  219. 'queue': queue,
  220. 'name': name,
  221. 'env': local_env,
  222. }
  223. p = multiprocessing.Process(target=inner, kwargs=kwarg_dict)
  224. # Name/id is host string
  225. p.name = name
  226. # Add to queue
  227. jobs.append(p)
  228. # Handle serial execution
  229. else:
  230. with settings(**local_env):
  231. return task.run(*args, **kwargs)
  232. def _is_task(task):
  233. return isinstance(task, Task)
  234. def execute(task, *args, **kwargs):
  235. """
  236. Execute ``task`` (callable or name), honoring host/role decorators, etc.
  237. ``task`` may be an actual callable object, or it may be a registered task
  238. name, which is used to look up a callable just as if the name had been
  239. given on the command line (including :ref:`namespaced tasks <namespaces>`,
  240. e.g. ``"deploy.migrate"``.
  241. The task will then be executed once per host in its host list, which is
  242. (again) assembled in the same manner as CLI-specified tasks: drawing from
  243. :option:`-H`, :ref:`env.hosts <hosts>`, the `~fabric.decorators.hosts` or
  244. `~fabric.decorators.roles` decorators, and so forth.
  245. ``host``, ``hosts``, ``role``, ``roles`` and ``exclude_hosts`` kwargs will
  246. be stripped out of the final call, and used to set the task's host list, as
  247. if they had been specified on the command line like e.g. ``fab
  248. taskname:host=hostname``.
  249. Any other arguments or keyword arguments will be passed verbatim into
  250. ``task`` (the function itself -- not the ``@task`` decorator wrapping your
  251. function!) when it is called, so ``execute(mytask, 'arg1',
  252. kwarg1='value')`` will (once per host) invoke ``mytask('arg1',
  253. kwarg1='value')``.
  254. :returns:
  255. a dictionary mapping host strings to the given task's return value for
  256. that host's execution run. For example, ``execute(foo, hosts=['a',
  257. 'b'])`` might return ``{'a': None, 'b': 'bar'}`` if ``foo`` returned
  258. nothing on host `a` but returned ``'bar'`` on host `b`.
  259. In situations where a task execution fails for a given host but overall
  260. progress does not abort (such as when :ref:`env.skip_bad_hosts
  261. <skip-bad-hosts>` is True) the return value for that host will be the
  262. error object or message.
  263. .. seealso::
  264. :ref:`The execute usage docs <execute>`, for an expanded explanation
  265. and some examples.
  266. .. versionadded:: 1.3
  267. .. versionchanged:: 1.4
  268. Added the return value mapping; previously this function had no defined
  269. return value.
  270. """
  271. my_env = {'clean_revert': True}
  272. results = {}
  273. # Obtain task
  274. is_callable = callable(task)
  275. if not (is_callable or _is_task(task)):
  276. # Assume string, set env.command to it
  277. my_env['command'] = task
  278. task = crawl(task, state.commands)
  279. if task is None:
  280. msg = "%r is not callable or a valid task name" % (my_env['command'],)
  281. if state.env.get('skip_unknown_tasks', False):
  282. warn(msg)
  283. return
  284. else:
  285. abort(msg)
  286. # Set env.command if we were given a real function or callable task obj
  287. else:
  288. dunder_name = getattr(task, '__name__', None)
  289. my_env['command'] = getattr(task, 'name', dunder_name)
  290. # Normalize to Task instance if we ended up with a regular callable
  291. if not _is_task(task):
  292. task = WrappedCallableTask(task)
  293. # Filter out hosts/roles kwargs
  294. new_kwargs, hosts, roles, exclude_hosts = parse_kwargs(kwargs)
  295. # Set up host list
  296. my_env['all_hosts'], my_env['effective_roles'] = task.get_hosts_and_effective_roles(hosts, roles,
  297. exclude_hosts, state.env)
  298. parallel = requires_parallel(task)
  299. if parallel:
  300. # Import multiprocessing if needed, erroring out usefully
  301. # if it can't.
  302. try:
  303. import multiprocessing
  304. except ImportError:
  305. import traceback
  306. tb = traceback.format_exc()
  307. abort(tb + """
  308. At least one task needs to be run in parallel, but the
  309. multiprocessing module cannot be imported (see above
  310. traceback.) Please make sure the module is installed
  311. or that the above ImportError is fixed.""")
  312. else:
  313. multiprocessing = None
  314. # Get pool size for this task
  315. pool_size = task.get_pool_size(my_env['all_hosts'], state.env.pool_size)
  316. # Set up job queue in case parallel is needed
  317. queue = multiprocessing.Queue() if parallel else None
  318. jobs = JobQueue(pool_size, queue)
  319. if state.output.debug:
  320. jobs._debug = True
  321. # Call on host list
  322. if my_env['all_hosts']:
  323. # Attempt to cycle on hosts, skipping if needed
  324. for host in my_env['all_hosts']:
  325. try:
  326. results[host] = _execute(
  327. task, host, my_env, args, new_kwargs, jobs, queue,
  328. multiprocessing
  329. )
  330. except NetworkError, e:
  331. results[host] = e
  332. # Backwards compat test re: whether to use an exception or
  333. # abort
  334. if not state.env.use_exceptions_for['network']:
  335. func = warn if state.env.skip_bad_hosts else abort
  336. error(e.message, func=func, exception=e.wrapped)
  337. else:
  338. raise
  339. # If requested, clear out connections here and not just at the end.
  340. if state.env.eagerly_disconnect:
  341. disconnect_all()
  342. # If running in parallel, block until job queue is emptied
  343. if jobs:
  344. err = "One or more hosts failed while executing task '%s'" % (
  345. my_env['command']
  346. )
  347. jobs.close()
  348. # Abort if any children did not exit cleanly (fail-fast).
  349. # This prevents Fabric from continuing on to any other tasks.
  350. # Otherwise, pull in results from the child run.
  351. ran_jobs = jobs.run()
  352. for name, d in ran_jobs.iteritems():
  353. if d['exit_code'] != 0:
  354. if isinstance(d['results'], NetworkError) and \
  355. _is_network_error_ignored():
  356. error(d['results'].message, func=warn, exception=d['results'].wrapped)
  357. elif isinstance(d['results'], BaseException):
  358. error(err, exception=d['results'])
  359. else:
  360. error(err)
  361. results[name] = d['results']
  362. # Or just run once for local-only
  363. else:
  364. with settings(**my_env):
  365. results['<local-only>'] = task.run(*args, **new_kwargs)
  366. # Return what we can from the inner task executions
  367. return results