You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

302 lines
9.5 KiB

4 years ago
  1. #!/home/alpcentaur/ProjektA/PrototypeWebApp/venv/bin/python3.5
  2. # Copyright (c) 2009 Chris Moyer http://coredumped.org/
  3. #
  4. # Permission is hereby granted, free of charge, to any person obtaining a
  5. # copy of this software and associated documentation files (the
  6. # "Software"), to deal in the Software without restriction, including
  7. # without limitation the rights to use, copy, modify, merge, publish, dis-
  8. # tribute, sublicense, and/or sell copies of the Software, and to permit
  9. # persons to whom the Software is furnished to do so, subject to the fol-
  10. # lowing conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included
  13. # in all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
  17. # ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  18. # SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  19. # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. #
  22. # Elastic Load Balancer Tool
  23. #
  24. VERSION = "0.2"
  25. usage = """%prog [options] [command]
  26. Commands:
  27. list|ls List all Elastic Load Balancers
  28. delete <name> Delete ELB <name>
  29. get <name> Get all instances associated with <name>
  30. create <name> Create an ELB; -z and -l are required
  31. add <name> <instances> Add <instances> in ELB <name>
  32. remove|rm <name> <instances> Remove <instances> from ELB <name>
  33. reap <name> Remove terminated instances from ELB <name>
  34. enable|en <name> <zone> Enable Zone <zone> for ELB <name>
  35. disable <name> <zone> Disable Zone <zone> for ELB <name>
  36. addl <name> Add listeners (specified by -l) to the ELB
  37. <name>
  38. rml <name> <port> Remove Listener(s) specified by the port on
  39. the ELB <name>
  40. """
  41. def find_elb(elb, name):
  42. try:
  43. elbs = elb.get_all_load_balancers(name)
  44. except boto.exception.BotoServerError as se:
  45. if se.code == 'LoadBalancerNotFound':
  46. elbs = []
  47. else:
  48. raise
  49. if len(elbs) < 1:
  50. print "No load balancer by the name of %s found" % name
  51. return None
  52. elif len(elbs) > 1:
  53. print "More than one elb matches %s?" % name
  54. return None
  55. # Should not happen
  56. if name not in elbs[0].name:
  57. print "No load balancer by the name of %s found" % name
  58. return None
  59. return elbs[0]
  60. def list(elb):
  61. """List all ELBs"""
  62. print "%-20s %s" % ("Name", "DNS Name")
  63. print "-" * 80
  64. for b in elb.get_all_load_balancers():
  65. print "%-20s %s" % (b.name, b.dns_name)
  66. def check_valid_region(conn, region):
  67. if conn is None:
  68. print 'Invalid region (%s)' % region
  69. sys.exit(1)
  70. def get(elb, name):
  71. """Get details about ELB <name>"""
  72. b = find_elb(elb, name)
  73. if b:
  74. print "=" * 80
  75. print "Name: %s" % b.name
  76. print "DNS Name: %s" % b.dns_name
  77. if b.canonical_hosted_zone_name:
  78. chzn = b.canonical_hosted_zone_name
  79. print "Canonical hosted zone name: %s" % chzn
  80. if b.canonical_hosted_zone_name_id:
  81. chznid = b.canonical_hosted_zone_name_id
  82. print "Canonical hosted zone name id: %s" % chznid
  83. print
  84. print "Health Check: %s" % b.health_check
  85. print
  86. print "Listeners"
  87. print "---------"
  88. print "%-8s %-8s %s" % ("IN", "OUT", "PROTO")
  89. for l in b.listeners:
  90. print "%-8s %-8s %s" % (l[0], l[1], l[2])
  91. print
  92. print " Zones "
  93. print "---------"
  94. for z in b.availability_zones:
  95. print z
  96. print
  97. # Make map of all instance Id's to Name tags
  98. import boto
  99. from boto.compat.six import iteritems
  100. if not options.region:
  101. ec2 = boto.connect_ec2()
  102. else:
  103. ec2 = boto.ec2.connect_to_region(options.region)
  104. check_valid_region(ec2, options.region)
  105. instance_health = b.get_instance_health()
  106. instances = [state.instance_id for state in instance_health]
  107. names = dict((k,'') for k in instances)
  108. for i in ec2.get_only_instances():
  109. if i.id in instances:
  110. names[i.id] = i.tags.get('Name', '')
  111. name_column_width = max([4] + [len(v) for k,v in iteritems(names)]) + 2
  112. print "Instances"
  113. print "---------"
  114. print "%-12s %-15s %-*s %s" % ("ID",
  115. "STATE",
  116. name_column_width, "NAME",
  117. "DESCRIPTION")
  118. for state in instance_health:
  119. print "%-12s %-15s %-*s %s" % (state.instance_id,
  120. state.state,
  121. name_column_width, names[state.instance_id],
  122. state.description)
  123. print
  124. def create(elb, name, zones, listeners):
  125. """Create an ELB named <name>"""
  126. l_list = []
  127. for l in listeners:
  128. l = l.split(",")
  129. if l[2] == 'HTTPS':
  130. l_list.append((int(l[0]), int(l[1]), l[2], l[3]))
  131. else:
  132. l_list.append((int(l[0]), int(l[1]), l[2]))
  133. b = elb.create_load_balancer(name, zones, l_list)
  134. return get(elb, name)
  135. def delete(elb, name):
  136. """Delete this ELB"""
  137. b = find_elb(elb, name)
  138. if b:
  139. b.delete()
  140. print "Load Balancer %s deleted" % name
  141. def add_instances(elb, name, instances):
  142. """Add <instance> to ELB <name>"""
  143. b = find_elb(elb, name)
  144. if b:
  145. b.register_instances(instances)
  146. return get(elb, name)
  147. def remove_instances(elb, name, instances):
  148. """Remove instance from elb <name>"""
  149. b = find_elb(elb, name)
  150. if b:
  151. b.deregister_instances(instances)
  152. return get(elb, name)
  153. def reap_instances(elb, name):
  154. """Remove terminated instances from elb <name>"""
  155. b = find_elb(elb, name)
  156. if b:
  157. for state in b.get_instance_health():
  158. if (state.state == 'OutOfService' and
  159. state.description == 'Instance is in terminated state.'):
  160. b.deregister_instances([state.instance_id])
  161. return get(elb, name)
  162. def enable_zone(elb, name, zone):
  163. """Enable <zone> for elb"""
  164. b = find_elb(elb, name)
  165. if b:
  166. b.enable_zones([zone])
  167. return get(elb, name)
  168. def disable_zone(elb, name, zone):
  169. """Disable <zone> for elb"""
  170. b = find_elb(elb, name)
  171. if b:
  172. b.disable_zones([zone])
  173. return get(elb, name)
  174. def add_listener(elb, name, listeners):
  175. """Add listeners to a given load balancer"""
  176. l_list = []
  177. for l in listeners:
  178. l = l.split(",")
  179. l_list.append((int(l[0]), int(l[1]), l[2]))
  180. b = find_elb(elb, name)
  181. if b:
  182. b.create_listeners(l_list)
  183. return get(elb, name)
  184. def rm_listener(elb, name, ports):
  185. """Remove listeners from a given load balancer"""
  186. b = find_elb(elb, name)
  187. if b:
  188. b.delete_listeners(ports)
  189. return get(elb, name)
  190. if __name__ == "__main__":
  191. try:
  192. import readline
  193. except ImportError:
  194. pass
  195. import boto
  196. import sys
  197. from optparse import OptionParser
  198. from boto.mashups.iobject import IObject
  199. parser = OptionParser(version=VERSION, usage=usage)
  200. parser.add_option("-z", "--zone",
  201. help="Operate on zone",
  202. action="append", default=[], dest="zones")
  203. parser.add_option("-l", "--listener",
  204. help="Specify Listener in,out,proto",
  205. action="append", default=[], dest="listeners")
  206. parser.add_option("-r", "--region",
  207. help="Region to connect to",
  208. action="store", dest="region")
  209. (options, args) = parser.parse_args()
  210. if len(args) < 1:
  211. parser.print_help()
  212. sys.exit(1)
  213. if not options.region:
  214. elb = boto.connect_elb()
  215. else:
  216. import boto.ec2.elb
  217. elb = boto.ec2.elb.connect_to_region(options.region)
  218. check_valid_region(elb, options.region)
  219. print "%s" % (elb.region.endpoint)
  220. command = args[0].lower()
  221. if command in ("ls", "list"):
  222. list(elb)
  223. elif command == "get":
  224. get(elb, args[1])
  225. elif command == "create":
  226. if not options.listeners:
  227. print "-l option required for command create"
  228. sys.exit(1)
  229. if not options.zones:
  230. print "-z option required for command create"
  231. sys.exit(1)
  232. create(elb, args[1], options.zones, options.listeners)
  233. elif command == "delete":
  234. delete(elb, args[1])
  235. elif command in ("add", "put"):
  236. add_instances(elb, args[1], args[2:])
  237. elif command in ("rm", "remove"):
  238. remove_instances(elb, args[1], args[2:])
  239. elif command == "reap":
  240. reap_instances(elb, args[1])
  241. elif command in ("en", "enable"):
  242. enable_zone(elb, args[1], args[2])
  243. elif command == "disable":
  244. disable_zone(elb, args[1], args[2])
  245. elif command == "addl":
  246. if not options.listeners:
  247. print "-l option required for command addl"
  248. sys.exit(1)
  249. add_listener(elb, args[1], options.listeners)
  250. elif command == "rml":
  251. if not args[2:]:
  252. print "port required"
  253. sys.exit(2)
  254. rm_listener(elb, args[1], args[2:])