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.

445 lines
21 KiB

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