info.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import math
  2. from celery.messaging import establish_connection
  3. QUEUE_FORMAT = """
  4. . %(name)s -> exchange:%(exchange)s (%(exchange_type)s) \
  5. binding:%(binding_key)s
  6. """
  7. BROKER_FORMAT = "%(carrot_backend)s://%(userid)s@%(host)s%(port)s%(vhost)s"
  8. TIME_UNITS = (("day", 60 * 60 * 24, lambda n: int(math.ceil(n))),
  9. ("hour", 60 * 60, lambda n: int(math.ceil(n))),
  10. ("minute", 60, lambda n: int(math.ceil(n))),
  11. ("second", 1, lambda n: "%.2f" % n))
  12. def humanize_seconds(secs, prefix=""):
  13. """Show seconds in human form, e.g. 60 is "1 minute", 7200 is "2
  14. hours"."""
  15. for unit, divider, formatter in TIME_UNITS:
  16. if secs >= divider:
  17. w = secs / divider
  18. punit = w > 1 and unit+"s" or unit
  19. return "%s%s %s" % (prefix, formatter(w), punit)
  20. return "now"
  21. def textindent(t, indent=0):
  22. """Indent text."""
  23. return "\n".join(" " * indent + p for p in t.split("\n"))
  24. def format_queues(queues, indent=0):
  25. """Format routing table into string for log dumps."""
  26. format = lambda **queue: QUEUE_FORMAT.strip() % queue
  27. info = "\n".join(format(name=name, **config)
  28. for name, config in queues.items())
  29. return textindent(info, indent=indent)
  30. def get_broker_info():
  31. broker_connection = establish_connection()
  32. carrot_backend = broker_connection.backend_cls
  33. if carrot_backend and not isinstance(carrot_backend, str):
  34. carrot_backend = carrot_backend.__name__
  35. carrot_backend = carrot_backend or "amqp"
  36. port = broker_connection.port or \
  37. broker_connection.get_backend_cls().default_port
  38. port = port and ":%s" % port or ""
  39. vhost = broker_connection.virtual_host
  40. if not vhost.startswith("/"):
  41. vhost = "/" + vhost
  42. return {"carrot_backend": carrot_backend,
  43. "userid": broker_connection.userid,
  44. "host": broker_connection.hostname,
  45. "port": port,
  46. "vhost": vhost}
  47. def format_broker_info(info=None):
  48. """Get message broker connection info string for log dumps."""
  49. return BROKER_FORMAT % get_broker_info()