PageRenderTime 39ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/boto-2.5.2/bin/cwutil

#
#! | 140 lines | 125 code | 15 blank | 0 comment | 0 complexity | 0db1a6a7de4f01616dd18aa076699f1a MD5 | raw file
  1. #!/usr/bin/env python
  2. # Author: Chris Moyer <cmoyer@newstex.com>
  3. # Description: CloudWatch Utility
  4. # For listing stats, creating alarms, and managing
  5. # other CloudWatch aspects
  6. import boto
  7. cw = boto.connect_cloudwatch()
  8. from datetime import datetime, timedelta
  9. def _parse_time(time_string):
  10. """Internal function to parse a time string"""
  11. def _parse_dict(d_string):
  12. result = {}
  13. if d_string:
  14. for d in d_string.split(","):
  15. d = d.split(":")
  16. result[d[0]] = d[1]
  17. return result
  18. def ls(namespace=None):
  19. """
  20. List metrics, optionally filtering by a specific namespace
  21. namespace: Optional Namespace to filter on
  22. """
  23. print "%-10s %-50s %s" % ("Namespace", "Metric Name", "Dimensions")
  24. print "-"*80
  25. for m in cw.list_metrics():
  26. if namespace is None or namespace.upper() in m.namespace:
  27. print "%-10s %-50s %s" % (m.namespace, m.name, m.dimensions)
  28. def stats(namespace, metric_name, dimensions=None, statistics="Average", start_time=None, end_time=None, period=60, unit=None):
  29. """
  30. Lists the statistics for a specific metric
  31. namespace: The namespace to use, usually "AWS/EC2", "AWS/SQS", etc.
  32. metric_name: The name of the metric to track, pulled from `ls`
  33. dimensions: The dimensions to use, formatted as Name:Value (such as QueueName:myQueue)
  34. statistics: The statistics to measure, defaults to "Average"
  35. 'Minimum', 'Maximum', 'Sum', 'Average', 'SampleCount'
  36. start_time: Start time, default to now - 1 day
  37. end_time: End time, default to now
  38. period: Period/interval for counts, default to 60 minutes
  39. unit: Unit to track, default depends on what metric is being tracked
  40. """
  41. # Parse the dimensions
  42. dimensions = _parse_dict(dimensions)
  43. # Parse the times
  44. if end_time:
  45. end_time = _parse_time(end_time)
  46. else:
  47. end_time = datetime.utcnow()
  48. if start_time:
  49. start_time = _parse_time(start_time)
  50. else:
  51. start_time = datetime.utcnow() - timedelta(days=1)
  52. print "%-30s %s" % ('Timestamp', statistics)
  53. print "-"*50
  54. data = {}
  55. for m in cw.get_metric_statistics(int(period), start_time, end_time, metric_name, namespace, statistics, dimensions, unit):
  56. data[m['Timestamp']] = m[statistics]
  57. keys = data.keys()
  58. keys.sort()
  59. for k in keys:
  60. print "%-30s %s" % (k, data[k])
  61. def put(namespace, metric_name, dimensions=None, value=None, unit=None, statistics=None, timestamp=None):
  62. """
  63. Publish custom metrics
  64. namespace: The namespace to use; values starting with "AWS/" are reserved
  65. metric_name: The name of the metric to update
  66. dimensions: The dimensions to use, formatted as Name:Value (such as QueueName:myQueue)
  67. value: The value to store, mutually exclusive with `statistics`
  68. statistics: The statistics to store, mutually exclusive with `value`
  69. (must specify all of "Minimum", "Maximum", "Sum", "SampleCount")
  70. timestamp: The timestamp of this measurement, default is current server time
  71. unit: Unit to track, default depends on what metric is being tracked
  72. """
  73. def simplify(lst):
  74. return lst[0] if len(lst) == 1 else lst
  75. print cw.put_metric_data(namespace, simplify(metric_name.split(';')),
  76. dimensions = simplify(map(_parse_dict, dimensions.split(';'))) if dimensions else None,
  77. value = simplify(value.split(';')) if value else None,
  78. statistics = simplify(map(_parse_dict, statistics.split(';'))) if statistics else None,
  79. timestamp = simplify(timestamp.split(';')) if timestamp else None,
  80. unit = simplify(unit.split(';')) if unit else None)
  81. def help(fnc=None):
  82. """
  83. Print help message, optionally about a specific function
  84. """
  85. import inspect
  86. self = sys.modules['__main__']
  87. if fnc:
  88. try:
  89. cmd = getattr(self, fnc)
  90. except:
  91. cmd = None
  92. if not inspect.isfunction(cmd):
  93. print "No function named: %s found" % fnc
  94. sys.exit(2)
  95. (args, varargs, varkw, defaults) = inspect.getargspec(cmd)
  96. print cmd.__doc__
  97. print "Usage: %s %s" % (fnc, " ".join([ "[%s]" % a for a in args]))
  98. else:
  99. print "Usage: cwutil [command]"
  100. for cname in dir(self):
  101. if not cname.startswith("_") and not cname == "cmd":
  102. cmd = getattr(self, cname)
  103. if inspect.isfunction(cmd):
  104. doc = cmd.__doc__
  105. print "\t%s - %s" % (cname, doc)
  106. sys.exit(1)
  107. if __name__ == "__main__":
  108. import sys
  109. self = sys.modules['__main__']
  110. if len(sys.argv) >= 2:
  111. try:
  112. cmd = getattr(self, sys.argv[1])
  113. except:
  114. cmd = None
  115. args = sys.argv[2:]
  116. else:
  117. cmd = help
  118. args = []
  119. if not cmd:
  120. cmd = help
  121. try:
  122. cmd(*args)
  123. except TypeError, e:
  124. print e
  125. help(cmd.__name__)