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.

439 lines
21 KiB

  1. import configparser
  2. from os.path import expanduser
  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. home = expanduser("~")
  13. # requirements:
  14. # services: EC2, ELB
  15. # resources: 2 instances, (1 keypair, 2 security groups),
  16. # 1 (Classic) Elastic Load Balancer, expensive! delete it after you used it!
  17. # The image to look for and use for the started instance
  18. ubuntu_image_name = 'ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20210128'
  19. # ubuntu_image_name = 'ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-20210128'
  20. # TODO: 18.04, currently still needed for faafo, need to port faafo demo app to 20.04 or higher and python3...
  21. # The public key to be used for SSH connection, please make sure, that you have the corresponding private key
  22. #
  23. # id_rsa.pub should look like this (standard sshd pubkey format):
  24. # ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAw+J...F3w2mleybgT1w== user@HOSTNAME
  25. keypair_name = 'srieger-pub'
  26. pub_key_file = home + '/.ssh/id_rsa.pub'
  27. # flavor_name = 't2.nano'
  28. flavor_name = 't2.micro'
  29. # default region
  30. # region_name = 'eu-central-1'
  31. # region_name = 'ap-south-1'
  32. # AWS Academy Labs only allow us-east-1 and us-west-1 see our AWS Academy Lab Guide, https://awsacademy.instructure.com/login/
  33. region_name = 'us-east-1'
  34. # region_name = 'us-west-1'
  35. # starting instances in AWS Academy takes significantly longer compared to paid AWS accounts, allow ~ >2 minutes timeout
  36. timeout = 600
  37. def main():
  38. ###########################################################################
  39. #
  40. # get credentials
  41. #
  42. ###########################################################################
  43. # see AWS Academy Lab for Account Details
  44. # read credentials from file
  45. config = configparser.ConfigParser()
  46. config.read_file(open(home + '/.aws/credentials'))
  47. aws_access_key_id = config['default']['aws_access_key_id']
  48. aws_secret_access_key = config['default']['aws_secret_access_key']
  49. aws_session_token = config['default']['aws_session_token']
  50. # hard coded AWS credentials using vars
  51. # aws_access_key_id = "ASIAX..."
  52. # aws_secret_access_key = "WLxxXK+..."
  53. # aws_session_token = "FwoGZXIvYXdzEMb//////////wEaDE5rX.......0SleZ+L75I9iEri9LA4hovWul8HvexhCBK8.......................Ae/T+VkUbcQRtJEDwg+gYCABuk0JlSj5Wk7YA65r3BSNJXZFpkhbek6VBjvE/cEt5fKZEhENcdFxjAcAJLd6bOWi/oGXU5e3PX3mcXgm0oJpz6h3wqD1LvSDtw5GDwn0BHiF1Mu.......................cm/VukK5F"
  54. ###########################################################################
  55. #
  56. # create connection
  57. #
  58. ###########################################################################
  59. provider = compute_get_driver(compute_Provider.EC2)
  60. conn = provider(key=aws_access_key_id,
  61. secret=aws_secret_access_key,
  62. token=aws_session_token,
  63. region=region_name)
  64. ###########################################################################
  65. #
  66. # get image, flavor, network for instance creation
  67. #
  68. ###########################################################################
  69. # print("Search for AMI...")
  70. # image = conn.list_images(ex_filters={"name": ubuntu_image_name})[0]
  71. # print("Using image: %s" % image)
  72. # print("Fetching images (AMI) list from AWS region. This will take a lot of seconds (AWS has a very long list of "
  73. # "supported operating systems and versions)... please be patient...")
  74. # image = ''
  75. # for img in images:
  76. # # if img.name == ubuntu_image_name:
  77. # if img.extra['owner_alias'] == 'amazon':
  78. # print(img)
  79. # if img.id == ubuntu_image_name:
  80. # image = img
  81. # select image directly to save time, as retrieving the image list takes several minutes now,
  82. # need to change ami id here if updated or for other regions, id is working for course in
  83. # summer term 2022, in region: us-east-1 and pointing to ubuntu 18.04 used in the instance wizard,
  84. # to update AMI id use the create instance wizard and copy amd64 image id for ubuntu 18.04 in the
  85. # desired region
  86. #
  87. print("Selecting AMI...")
  88. # us-east-1 examples as of 9.5.2022:
  89. #
  90. # Canonical, Ubuntu, 18.04 LTS, amd64 bionic image build on 2022-04-11
  91. image_id = "ami-005de95e8ff495156"
  92. #
  93. # Canonical, Ubuntu, 20.04 LTS, amd64 focal image build on 2022-04-19
  94. # image_id = "ami-0c4f7023847b90238"
  95. #
  96. # Canonical, Ubuntu, 22.04 LTS, amd64 jammy image build on 2022-04-20
  97. # image_id = "ami-09d56f8956ab235b3"
  98. #
  99. image = conn.list_images(ex_image_ids=[image_id])[0]
  100. print("Using image: %s" % image)
  101. flavors = conn.list_sizes()
  102. flavor = [s for s in flavors if s.id == flavor_name][0]
  103. print(flavor)
  104. # networks = conn.ex_list_networks()
  105. # network = ''
  106. # for net in networks:
  107. # if net.name == project_network:
  108. # network = net
  109. ###########################################################################
  110. #
  111. # create keypair dependency
  112. #
  113. ###########################################################################
  114. print('Checking for existing SSH key pair...')
  115. keypair_exists = False
  116. for keypair in conn.list_key_pairs():
  117. if keypair.name == keypair_name:
  118. keypair_exists = True
  119. if keypair_exists:
  120. print('Keypair ' + keypair_name + ' already exists. Skipping import.')
  121. else:
  122. print('adding keypair...')
  123. conn.import_key_pair_from_file(keypair_name, pub_key_file)
  124. for keypair in conn.list_key_pairs():
  125. print(keypair)
  126. ###########################################################################
  127. #
  128. # clean up resources from previous demos
  129. #
  130. ###########################################################################
  131. # destroy running demo instances
  132. for instance in conn.list_nodes():
  133. if instance.name in ['all-in-one', 'app-worker-1', 'app-worker-2', 'app-worker-3', 'app-controller',
  134. 'app-services', 'app-api-1', 'app-api-2']:
  135. if instance.state is not NodeState.TERMINATED:
  136. print('Destroying Instance: %s' % instance.name)
  137. conn.destroy_node(instance)
  138. # wait until all nodes are destroyed to be able to remove dependent security groups
  139. nodes_still_running = True
  140. while nodes_still_running:
  141. nodes_still_running = False
  142. time.sleep(3)
  143. instances = conn.list_nodes()
  144. for instance in instances:
  145. # if we see any demo instances still running continue to wait for them to stop
  146. if instance.name in ['all-in-one', 'app-worker-1', 'app-worker-2', 'app-worker-3', 'app-controller',
  147. 'app-services', 'app-api-1', 'app-api-2']:
  148. if instance.state is not NodeState.TERMINATED:
  149. nodes_still_running = True
  150. if nodes_still_running is True:
  151. print('There are still instances running, waiting for them to be destroyed...')
  152. else:
  153. print('No instances running')
  154. # delete security groups, respecting dependencies (hence deleting 'control' and 'services' first)
  155. for group in conn.ex_list_security_groups():
  156. if group in ['control', 'services']:
  157. print('Deleting security group: %s' % group)
  158. conn.ex_delete_security_group(group)
  159. # now we can delete security groups 'api' and 'worker', as 'control' and 'api' depended on them, otherwise AWS will
  160. # throw DependencyViolation: resource has a dependent object
  161. for group in conn.ex_list_security_groups():
  162. if group in ['api', 'worker']:
  163. print('Deleting security group: %s' % group)
  164. conn.ex_delete_security_group(group)
  165. ###########################################################################
  166. #
  167. # create security group dependency
  168. #
  169. ###########################################################################
  170. def get_security_group(connection, security_group_name):
  171. """A helper function to check if security group already exists"""
  172. print('Checking for existing ' + security_group_name + ' security group...')
  173. for security_grp in connection.ex_list_security_groups():
  174. if security_grp == security_group_name:
  175. print('Security Group ' + security_group_name + ' already exists. Skipping creation.')
  176. return security_grp['group_id']
  177. return False
  178. if not get_security_group(conn, "api"):
  179. api_security_group_result = conn.ex_create_security_group('api', 'for API services only')
  180. api_security_group_id = api_security_group_result['group_id']
  181. conn.ex_authorize_security_group_ingress(api_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  182. protocol='tcp')
  183. conn.ex_authorize_security_group_ingress(api_security_group_id, 80, 80, cidr_ips=['0.0.0.0/0'],
  184. protocol='tcp')
  185. else:
  186. api_security_group_id = get_security_group(conn, "api")
  187. if not get_security_group(conn, "worker"):
  188. worker_security_group_result = conn.ex_create_security_group('worker', 'for services that run on a worker node')
  189. worker_security_group_id = worker_security_group_result['group_id']
  190. conn.ex_authorize_security_group_ingress(worker_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  191. protocol='tcp')
  192. else:
  193. worker_security_group_id = get_security_group(conn, "worker")
  194. if not get_security_group(conn, "control"):
  195. controller_security_group_result = conn.ex_create_security_group('control',
  196. 'for services that run on a control node')
  197. controller_security_group_id = controller_security_group_result['group_id']
  198. conn.ex_authorize_security_group_ingress(controller_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  199. protocol='tcp')
  200. conn.ex_authorize_security_group_ingress(controller_security_group_id, 80, 80, cidr_ips=['0.0.0.0/0'],
  201. protocol='tcp')
  202. conn.ex_authorize_security_group_ingress(controller_security_group_id, 5672, 5672,
  203. group_pairs=[{'group_id': worker_security_group_id}], protocol='tcp')
  204. else:
  205. controller_security_group_id = get_security_group(conn, "control")
  206. if not get_security_group(conn, "services"):
  207. services_security_group_result = conn.ex_create_security_group('services', 'for DB and AMQP services only')
  208. services_security_group_id = services_security_group_result['group_id']
  209. conn.ex_authorize_security_group_ingress(services_security_group_id, 22, 22, cidr_ips=['0.0.0.0/0'],
  210. protocol='tcp')
  211. # conn.ex_authorize_security_group_ingress(services_security_group_id, 3306, 3306, cidr_ips=['0.0.0.0/0'],
  212. # group_pairs=[{'group_id': api_security_group_id}], protocol='tcp')
  213. conn.ex_authorize_security_group_ingress(services_security_group_id, 3306, 3306,
  214. group_pairs=[{'group_id': api_security_group_id}], protocol='tcp')
  215. conn.ex_authorize_security_group_ingress(services_security_group_id, 5672, 5672,
  216. group_pairs=[{'group_id': worker_security_group_id}], protocol='tcp')
  217. conn.ex_authorize_security_group_ingress(services_security_group_id, 5672, 5672,
  218. group_pairs=[{'group_id': api_security_group_id}], protocol='tcp')
  219. else:
  220. services_security_group_id = get_security_group(conn, "services")
  221. for security_group in conn.ex_list_security_groups():
  222. print(security_group)
  223. # get availability zones
  224. az = conn.list_locations()
  225. print(az)
  226. ###########################################################################
  227. #
  228. # create app-services instance (database & messaging) (Amazon AWS EC2)
  229. #
  230. ###########################################################################
  231. # https://git.openstack.org/cgit/openstack/faafo/plain/contrib/install.sh
  232. # is currently broken, hence the "rabbitctl" lines were added in the example
  233. # below, see also https://bugs.launchpad.net/faafo/+bug/1679710
  234. #
  235. # Thanks to Stefan Friedmann for finding this fix ;)
  236. userdata_service = '''#!/usr/bin/env bash
  237. curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  238. -i database -i messaging
  239. rabbitmqctl add_user faafo guest
  240. rabbitmqctl set_user_tags faafo administrator
  241. rabbitmqctl set_permissions -p / faafo ".*" ".*" ".*"
  242. '''
  243. print('Starting new app-services instance and wait until it is running...')
  244. instance_services = conn.create_node(location=az[0],
  245. name='app-services',
  246. image=image,
  247. size=flavor,
  248. ex_keyname=keypair_name,
  249. ex_userdata=userdata_service,
  250. ex_security_groups=["services"])
  251. instance_services = conn.wait_until_running(nodes=[instance_services], timeout=120, ssh_interface='public_ips')
  252. services_ip = instance_services[0][0].private_ips[0]
  253. ###########################################################################
  254. #
  255. # create app-api instances (Amazon AWS EC2)
  256. #
  257. ###########################################################################
  258. userdata_api = '''#!/usr/bin/env bash
  259. curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  260. -i faafo -r api -m 'amqp://faafo:guest@%(services_ip)s:5672/' \
  261. -d 'mysql+pymysql://faafo:password@%(services_ip)s:3306/faafo'
  262. ''' % {'services_ip': services_ip}
  263. print('Starting new app-api-1 instance and wait until it is running...')
  264. instance_api_1 = conn.create_node(location=az[0],
  265. name='app-api-1',
  266. image=image,
  267. size=flavor,
  268. ex_keyname=keypair_name,
  269. ex_userdata=userdata_api,
  270. ex_security_groups=["api"])
  271. print('Starting new app-api-2 instance and wait until it is running...')
  272. instance_api_2 = conn.create_node(location=az[1],
  273. name='app-api-2',
  274. image=image,
  275. size=flavor,
  276. ex_keyname=keypair_name,
  277. ex_userdata=userdata_api,
  278. ex_security_groups=["api"])
  279. instance_api_1 = conn.wait_until_running(nodes=[instance_api_1], timeout=120, ssh_interface='public_ips')
  280. api_1_ip = instance_api_1[0][0].private_ips[0]
  281. print("app-api-1 public ip: " + instance_api_1[0][1][0])
  282. instance_api_2 = conn.wait_until_running(nodes=[instance_api_2], timeout=120, ssh_interface='public_ips')
  283. # currently only api_1_ip is used
  284. api_2_ip = instance_api_2[0][0].private_ips[0]
  285. print("app-api-2 public ip: " + instance_api_2[0][1][0])
  286. ###########################################################################
  287. #
  288. # create worker instances (Amazon AWS EC2)
  289. #
  290. ###########################################################################
  291. userdata_worker = '''#!/usr/bin/env bash
  292. curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  293. -i faafo -r worker -e 'http://%(api_1_ip)s' -m 'amqp://faafo:guest@%(services_ip)s:5672/'
  294. ''' % {'api_1_ip': api_1_ip, 'services_ip': services_ip}
  295. # userdata_api-api-2 = '''#!/usr/bin/env bash
  296. # curl -L -s https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh | bash -s -- \
  297. # -i faafo -r worker -e 'http://%(api_2_ip)s' -m 'amqp://faafo:guest@%(services_ip)s:5672/'
  298. # ''' % {'api_2_ip': api_2_ip, 'services_ip': services_ip}
  299. print('Starting new app-worker-1 instance and wait until it is running...')
  300. instance_worker_1 = conn.create_node(location=az[0],
  301. name='app-worker-1',
  302. image=image, size=flavor,
  303. ex_keyname=keypair_name,
  304. ex_userdata=userdata_worker,
  305. ex_security_groups=["worker"])
  306. print('Starting new app-worker-2 instance and wait until it is running...')
  307. instance_worker_2 = conn.create_node(location=az[1],
  308. name='app-worker-2',
  309. image=image, size=flavor,
  310. ex_keyname=keypair_name,
  311. ex_userdata=userdata_worker,
  312. ex_security_groups=["worker"])
  313. # do not start worker 3 initially, can be started using scale-out-add-worker.py demo
  314. # print('Starting new app-worker-3 instance and wait until it is running...')
  315. # instance_worker_3 = conn.create_node(name='app-worker-3',
  316. # image=image, size=flavor,
  317. # networks=[network],
  318. # ex_keyname=keypair_name,
  319. # ex_userdata=userdata_worker,
  320. # ex_security_groups=[worker_security_group])
  321. print(instance_worker_1)
  322. print(instance_worker_2)
  323. # print(instance_worker_3)
  324. ###########################################################################
  325. #
  326. # create load balancer (Amazon AWS ELB)
  327. #
  328. ###########################################################################
  329. elb_provider = loadbalancer_get_driver(loadbalancer_Provider.ELB)
  330. elb_conn = elb_provider(aws_access_key_id,
  331. aws_secret_access_key,
  332. token=aws_session_token,
  333. region=region_name)
  334. print("Deleting previously created load balancers in: " + str(elb_conn.list_balancers()))
  335. for loadbalancer in elb_conn.list_balancers():
  336. if loadbalancer.name == "lb1":
  337. print("Deleting Load Balancer: " + str(loadbalancer))
  338. elb_conn.destroy_balancer(loadbalancer)
  339. # get suffix (a, b, c, ...) from all availability zones, available in the selected region
  340. all_availability_zones_in_region = []
  341. for az in conn.ex_list_availability_zones():
  342. all_availability_zones_in_region.append(az.name[-1])
  343. # create new load balancer
  344. # example uses "classic" ELB with default HTTP health. monitor, you can see the result in the EC2 console, after
  345. # running this script
  346. new_load_balancer = elb_conn.create_balancer(
  347. name='lb1',
  348. algorithm=Algorithm.ROUND_ROBIN,
  349. port=80,
  350. protocol='http',
  351. members=[],
  352. ex_members_availability_zones=all_availability_zones_in_region)
  353. # attach api instances as members to load balancer
  354. elb_conn.balancer_attach_compute_node(balancer=new_load_balancer, node=instance_api_1[0][0])
  355. elb_conn.balancer_attach_compute_node(balancer=new_load_balancer, node=instance_api_2[0][0])
  356. print("Created load balancer: " + str(new_load_balancer))
  357. # wait for the load balancer to be ready
  358. while new_load_balancer.state != 2:
  359. time.sleep(3)
  360. new_load_balancer = elb_conn.get_balancer(new_load_balancer.id)
  361. print("\n\nYou can see the instances created in EC2 in AWS Console. You'll also find the load balancer under ELB "
  362. "there.\n"
  363. " You can access the faafo application deployed to the loadbalancer at: http://" + new_load_balancer.ip +
  364. " as soon as instances are detected to be deployed and healthy by the load balancer.")
  365. if __name__ == '__main__':
  366. main()