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.

382 lines
18 KiB

  1. # import getpass
  2. # import os
  3. # import libcloud.security
  4. import time
  5. from libcloud.compute.base import NodeImage
  6. from libcloud.compute.base import NodeState
  7. from libcloud.compute.providers import get_driver as compute_get_driver
  8. from libcloud.compute.types import Provider as compute_Provider
  9. from libcloud.loadbalancer.base import Member, Algorithm
  10. from libcloud.loadbalancer.types import Provider as loadbalancer_Provider
  11. from libcloud.loadbalancer.providers import get_driver as loadbalancer_get_driver
  12. # reqs:
  13. # services: EC2 (nova, glance, neutron)
  14. # resources: 2 instances, 2 elastic ips (1 keypair, 2 security groups)
  15. # The image to look for and use for the started instance
  16. # ubuntu_image_name = 'ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20200408'
  17. ubuntu_image_id = "ami-085925f297f89fce1" # local ami id for resent ubuntu 18.04 20200408 in us-west-1
  18. # The public key to be used for SSH connection, please make sure, that you have the corresponding private key
  19. #
  20. # id_rsa.pub should look like this (standard sshd pubkey format):
  21. # ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAw+J...F3w2mleybgT1w== user@HOSTNAME
  22. keypair_name = 'srieger-pub'
  23. pub_key_file = '~/.ssh/id_rsa.pub'
  24. flavor_name = 't2.nano'
  25. # default region
  26. # region_name = 'eu-central-1'
  27. # region_name = 'ap-south-1'
  28. # AWS Educate only allows us-east-1 see our AWS classroom at https://www.awseducate.com
  29. # e.g., https://www.awseducate.com/student/s/launch-classroom?classroomId=a1v3m000005mNm6AAE
  30. region_name = 'us-east-1'
  31. def main():
  32. ###########################################################################
  33. #
  34. # get credentials
  35. #
  36. ###########################################################################
  37. # see AWS Educate classroom, Account Details
  38. # access_id = getpass.win_getpass("Enter your access_id:")
  39. # secret_key = getpass.win_getpass("Enter your secret_key:")
  40. # session_token = getpass.win_getpass("Enter your session_token:")
  41. # access_id = "ASIAU..."
  42. # secret_key = "7lafW..."
  43. # session_token = "IQoJb3JpZ...EMb//..."
  44. access_id = "ASIA..."
  45. secret_key = "76lAj..."
  46. session_token = "IQoJ..."
  47. ###########################################################################
  48. #
  49. # create connection
  50. #
  51. ###########################################################################
  52. provider = compute_get_driver(compute_Provider.EC2)
  53. conn = provider(key=access_id,
  54. secret=secret_key,
  55. token=session_token,
  56. region=region_name)
  57. ###########################################################################
  58. #
  59. # get image, flavor, network for instance creation
  60. #
  61. ###########################################################################
  62. # print("Fetching images (AMI) list from AWS region. This will take a lot of seconds (AWS has a very long list of "
  63. # "supported operating systems and versions)... please be patient...")
  64. # images = conn.list_images()
  65. # fetch/select the image referenced with ubuntu_image_name above
  66. # image = [i for i in images if i.name == ubuntu_image_name][0]
  67. # print(image)
  68. # selecting the image based on defined AMI id
  69. image = NodeImage(id=ubuntu_image_id, name=None, driver=conn)
  70. flavors = conn.list_sizes()
  71. flavor = [s for s in flavors if s.id == flavor_name][0]
  72. print(flavor)
  73. # networks = conn.ex_list_networks()
  74. # network = ''
  75. # for net in networks:
  76. # if net.name == project_network:
  77. # network = net
  78. ###########################################################################
  79. #
  80. # create keypair dependency
  81. #
  82. ###########################################################################
  83. print('Checking for existing SSH key pair...')
  84. keypair_exists = False
  85. for keypair in conn.list_key_pairs():
  86. if keypair.name == keypair_name:
  87. keypair_exists = True
  88. if keypair_exists:
  89. print('Keypair ' + keypair_name + ' already exists. Skipping import.')
  90. else:
  91. print('adding keypair...')
  92. conn.import_key_pair_from_file(keypair_name, pub_key_file)
  93. for keypair in conn.list_key_pairs():
  94. print(keypair)
  95. ###########################################################################
  96. #
  97. # clean up resources from previous demos
  98. #
  99. ###########################################################################
  100. # destroy running demo instances
  101. for instance in conn.list_nodes():
  102. if instance.name in ['all-in-one', 'app-worker-1', 'app-worker-2', 'app-worker-3', 'app-controller',
  103. 'app-services', 'app-api-1', 'app-api-2']:
  104. if instance.state is not NodeState.TERMINATED:
  105. print('Destroying Instance: %s' % instance.name)
  106. conn.destroy_node(instance)
  107. # wait until all nodes are destroyed to be able to remove depended security groups
  108. nodes_still_running = True
  109. while nodes_still_running:
  110. nodes_still_running = False
  111. time.sleep(3)
  112. instances = conn.list_nodes()
  113. for instance in instances:
  114. # if we see any demo instances still running continue to wait for them to stop
  115. if instance.name in ['all-in-one', 'app-worker-1', 'app-worker-2', 'app-controller', 'app-services']:
  116. if instance.state is not NodeState.TERMINATED:
  117. nodes_still_running = True
  118. print('There are still instances running, waiting for them to be destroyed...')
  119. # delete security groups, respecting dependencies (hence deleting 'control' and 'services' first)
  120. for group in conn.ex_list_security_groups():
  121. if group in ['control', 'services']:
  122. print('Deleting security group: %s' % group)
  123. conn.ex_delete_security_group(group)
  124. # now we can delete security groups 'api' and 'worker', as 'control' and 'api' depended on them, otherwise AWS will
  125. # throw DependencyViolation: resource has a dependent object
  126. for group in conn.ex_list_security_groups():
  127. if group in ['api', 'worker']:
  128. print('Deleting security group: %s' % group)
  129. conn.ex_delete_security_group(group)
  130. ###########################################################################
  131. #
  132. # create security group dependency
  133. #
  134. ###########################################################################
  135. def get_security_group(connection, security_group_name):
  136. """A helper function to check if security group already exists"""
  137. print('Checking for existing ' + security_group_name + ' security group...')
  138. for security_grp in connection.ex_list_security_groups():
  139. if security_grp == security_group_name:
  140. print('Security Group ' + security_group_name + ' already exists. Skipping creation.')
  141. return security_grp['group_id']
  142. return False
  143. if not get_security_group(conn, "api"):
  144. api_security_group_result = conn.ex_create_security_group('api', 'for API services only')
  145. api_security_group_id = api_security_group_result['group_id']
  146. conn.ex_authorize_security_group_ingress(api_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  147. protocol='tcp')
  148. conn.ex_authorize_security_group_ingress(api_security_group_id, 80, 80, cidr_ips=['0.0.0.0/0'],
  149. protocol='tcp')
  150. else:
  151. api_security_group_id = get_security_group(conn, "api")
  152. if not get_security_group(conn, "worker"):
  153. worker_security_group_result = conn.ex_create_security_group('worker', 'for services that run on a worker node')
  154. worker_security_group_id = worker_security_group_result['group_id']
  155. conn.ex_authorize_security_group_ingress(worker_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  156. protocol='tcp')
  157. else:
  158. worker_security_group_id = get_security_group(conn, "worker")
  159. if not get_security_group(conn, "control"):
  160. controller_security_group_result = conn.ex_create_security_group('control',
  161. 'for services that run on a control node')
  162. controller_security_group_id = controller_security_group_result['group_id']
  163. conn.ex_authorize_security_group_ingress(controller_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  164. protocol='tcp')
  165. conn.ex_authorize_security_group_ingress(controller_security_group_id, 80, 80, cidr_ips=['0.0.0.0/0'],
  166. protocol='tcp')
  167. conn.ex_authorize_security_group_ingress(controller_security_group_id, 5672, 5672,
  168. group_pairs=[{'group_id': worker_security_group_id}], protocol='tcp')
  169. else:
  170. controller_security_group_id = get_security_group(conn, "control")
  171. if not get_security_group(conn, "services"):
  172. services_security_group_result = conn.ex_create_security_group('services', 'for DB and AMQP services only')
  173. services_security_group_id = services_security_group_result['group_id']
  174. conn.ex_authorize_security_group_ingress(services_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  175. protocol='tcp')
  176. conn.ex_authorize_security_group_ingress(services_security_group_id, 3306, 3306, cidr_ips=['0.0.0.0/0'],
  177. group_pairs=[{'group_id': api_security_group_id}], protocol='tcp')
  178. conn.ex_authorize_security_group_ingress(services_security_group_id, 5672, 5672,
  179. group_pairs=[{'group_id': worker_security_group_id}], protocol='tcp')
  180. conn.ex_authorize_security_group_ingress(services_security_group_id, 5672, 5672,
  181. group_pairs=[{'group_id': api_security_group_id}], protocol='tcp')
  182. else:
  183. services_security_group_id = get_security_group(conn, "services")
  184. for security_group in conn.ex_list_security_groups():
  185. print(security_group)
  186. ###########################################################################
  187. #
  188. # create app-services instance (database & messaging) (Amazon AWS EC2)
  189. #
  190. ###########################################################################
  191. # https://git.openstack.org/cgit/openstack/faafo/plain/contrib/install.sh
  192. # is currently broken, hence the "rabbitctl" lines were added in the example
  193. # below, see also https://bugs.launchpad.net/faafo/+bug/1679710
  194. #
  195. # Thanks to Stefan Friedmann for finding this fix ;)
  196. userdata_service = '''#!/usr/bin/env bash
  197. curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  198. -i database -i messaging
  199. rabbitmqctl add_user faafo guest
  200. rabbitmqctl set_user_tags faafo administrator
  201. rabbitmqctl set_permissions -p / faafo ".*" ".*" ".*"
  202. '''
  203. print('Starting new app-services instance and wait until it is running...')
  204. instance_services = conn.create_node(name='app-services',
  205. image=image,
  206. size=flavor,
  207. ex_keyname=keypair_name,
  208. ex_userdata=userdata_service,
  209. ex_security_groups=["services"])
  210. instance_services = conn.wait_until_running(nodes=[instance_services], timeout=120, ssh_interface='public_ips')
  211. services_ip = instance_services[0][0].private_ips[0]
  212. ###########################################################################
  213. #
  214. # create app-api instances (Amazon AWS EC2)
  215. #
  216. ###########################################################################
  217. userdata_api = '''#!/usr/bin/env bash
  218. curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  219. -i faafo -r api -m 'amqp://faafo:guest@%(services_ip)s:5672/' \
  220. -d 'mysql+pymysql://faafo:password@%(services_ip)s:3306/faafo'
  221. ''' % {'services_ip': services_ip}
  222. print('Starting new app-api-1 instance and wait until it is running...')
  223. instance_api_1 = conn.create_node(name='app-api-1',
  224. image=image,
  225. size=flavor,
  226. ex_keyname=keypair_name,
  227. ex_userdata=userdata_api,
  228. ex_security_groups=["api"])
  229. print('Starting new app-api-2 instance and wait until it is running...')
  230. instance_api_2 = conn.create_node(name='app-api-2',
  231. image=image,
  232. size=flavor,
  233. ex_keyname=keypair_name,
  234. ex_userdata=userdata_api,
  235. ex_security_groups=["api"])
  236. instance_api_1 = conn.wait_until_running(nodes=[instance_api_1], timeout=120, ssh_interface='public_ips')
  237. api_1_ip = instance_api_1[0][0].private_ips[0]
  238. instance_api_2 = conn.wait_until_running(nodes=[instance_api_2], timeout=120, ssh_interface='public_ips')
  239. api_2_ip = instance_api_2[0][0].private_ips[0]
  240. ###########################################################################
  241. #
  242. # create worker instances (Amazon AWS EC2)
  243. #
  244. ###########################################################################
  245. userdata_worker = '''#!/usr/bin/env bash
  246. curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  247. -i faafo -r worker -e 'http://%(api_1_ip)s' -m 'amqp://faafo:guest@%(services_ip)s:5672/'
  248. ''' % {'api_1_ip': api_1_ip, 'services_ip': services_ip}
  249. # userdata_api-api-2 = '''#!/usr/bin/env bash
  250. # curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  251. # -i faafo -r worker -e 'http://%(api_2_ip)s' -m 'amqp://faafo:guest@%(services_ip)s:5672/'
  252. # ''' % {'api_2_ip': api_2_ip, 'services_ip': services_ip}
  253. print('Starting new app-worker-1 instance and wait until it is running...')
  254. instance_worker_1 = conn.create_node(name='app-worker-1',
  255. image=image, size=flavor,
  256. ex_keyname=keypair_name,
  257. ex_userdata=userdata_worker,
  258. ex_security_groups=["worker"])
  259. print('Starting new app-worker-2 instance and wait until it is running...')
  260. instance_worker_2 = conn.create_node(name='app-worker-2',
  261. image=image, size=flavor,
  262. ex_keyname=keypair_name,
  263. ex_userdata=userdata_worker,
  264. ex_security_groups=["worker"])
  265. # do not start worker 3 initially, can be started using scale-out-add-worker.py demo
  266. # print('Starting new app-worker-3 instance and wait until it is running...')
  267. # instance_worker_3 = conn.create_node(name='app-worker-3',
  268. # image=image, size=flavor,
  269. # networks=[network],
  270. # ex_keyname=keypair_name,
  271. # ex_userdata=userdata_worker,
  272. # ex_security_groups=[worker_security_group])
  273. print(instance_worker_1)
  274. print(instance_worker_2)
  275. # print(instance_worker_3)
  276. ###########################################################################
  277. #
  278. # create load balancer (Amazon AWS ELB)
  279. #
  280. ###########################################################################
  281. elb_provider = loadbalancer_get_driver(loadbalancer_Provider.ELB)
  282. elb_conn = elb_provider(access_id,
  283. secret_key,
  284. token=session_token,
  285. region=region_name)
  286. print("Deleting previously created load balancers in: " + str(elb_conn.list_balancers()))
  287. for loadbalancer in elb_conn.list_balancers():
  288. if loadbalancer.name == "lb1":
  289. elb_conn.destroy_balancer(loadbalancer)
  290. # get suffix (a, b, c, ...) from all availability zones, available in the selected region
  291. all_availability_zones_in_region = []
  292. for az in conn.ex_list_availability_zones():
  293. all_availability_zones_in_region.append(az.name[-1])
  294. # create new load balancer
  295. # example uses "classic" ELB with default HTTP health. monitor, you can see the result in the EC2 console, after
  296. # running this script
  297. new_load_balancer = elb_conn.create_balancer(
  298. name='lb1',
  299. algorithm=Algorithm.ROUND_ROBIN,
  300. port=80,
  301. protocol='http',
  302. members=[],
  303. ex_members_availability_zones=all_availability_zones_in_region)
  304. # attach api instances as members to load balancer
  305. elb_conn.balancer_attach_compute_node(balancer=new_load_balancer, node=instance_api_1[0][0])
  306. elb_conn.balancer_attach_compute_node(balancer=new_load_balancer, node=instance_api_2[0][0])
  307. print("Created load balancer: " + str(new_load_balancer))
  308. # wait for the load balancer to be ready
  309. while new_load_balancer.state != 2:
  310. time.sleep(3)
  311. new_load_balancer = elb_conn.get_balancer(new_load_balancer.id)
  312. print("\n\nYou can see the instances created in EC2 in AWS Console. You'll also find the load balancer under ELB "
  313. "there.\n"
  314. " You can access the faafo application deployed to the loadbalancer at: http://" + new_load_balancer.ip +
  315. " as soon as instances are detected to be deployed and healthy by the load balancer.")
  316. if __name__ == '__main__':
  317. main()