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.

268 lines
11 KiB

  1. """Example for Cloud Computing Course Master AI / GSD"""
  2. # This script demonstrates how to use libcloud to start an instance in an OpenStack environment.
  3. # The script will create and install a new SSH key pair, create a security group, start an instance
  4. # and deploy a demo app (faafo) using cloud-init and assign a floating IP to the instance.
  5. #
  6. # cloud-init is a multi-distribution package that handles early initialization of a cloud instance.
  7. # It is supported by many major cloud providers, including OpenStack.
  8. # cloud-init documentation: https://cloudinit.readthedocs.io/en/latest/
  9. # Needed if the password should be prompted for:
  10. # import getpass
  11. import os
  12. import sys
  13. from libcloud.compute.providers import get_driver
  14. from libcloud.compute.types import Provider
  15. # For our new Charmed OpenStack private cloud, we need to specify the path to the root
  16. # CA certificate
  17. import libcloud.security
  18. libcloud.security.CA_CERTS_PATH = ['./root-ca.crt']
  19. # Disable SSL certificate verification (not recommended for production)
  20. # libcloud.security.VERIFY_SSL_CERT = False
  21. # Please use 1-29 as environment variable GROUP_NUMBER to specify your group number.
  22. # (will be used for the username, project etc., as coordinated in the lab sessions)
  23. group_number = os.environ.get('GROUP_NUMBER')
  24. if group_number is None:
  25. sys.exit('Please set the GROUP_NUMBER environment variable to your group number,\n'
  26. 'e.g., on Windows:\n'
  27. ' "$env:GROUP_NUMBER=0" or "set GROUP_NUMBER=0"\n'
  28. 'or on Linux/MacOS:\n'
  29. ' "export GROUP_NUMBER=0" or "set GROUP_NUMBER=0"')
  30. # web service endpoint of the private cloud infrastructure
  31. # auth_url = 'https://private-cloud.informatik.hs-fulda.de:5000'
  32. AUTH_URL = 'https://10.32.4.182:5000'
  33. # auth_url = 'https://private-cloud2.informatik.hs-fulda.de:5000'
  34. # your username in OpenStack
  35. AUTH_USERNAME = 'CloudComp' + str(group_number)
  36. print(f'Using username: {AUTH_USERNAME}\n')
  37. # your project in OpenStack
  38. PROJECT_NAME = 'CloudComp' + str(group_number)
  39. # A network in the project the started instance will be attached to
  40. PROJECT_NETWORK = 'CloudComp' + str(group_number) + '-net'
  41. # The image to look for and use for the started instance
  42. # ubuntu_image_name = "Ubuntu 18.04 - Bionic Beaver - 64-bit - Cloud Based Image"
  43. UBUNTU_IMAGE_NAME = "auto-sync/ubuntu-jammy-22.04-amd64-server-20240319-disk1.img"
  44. # The public key to be used for SSH connection, please make sure, that you have the
  45. # corresponding private key
  46. #
  47. # id_rsa.pub should look like this (standard sshd pubkey format):
  48. # ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAw+J...F3w2mleybgT1w== user@HOSTNAME
  49. KEYPAIR_NAME = 'srieger-pub'
  50. PUB_KEY_FILE = '~/.ssh/id_rsa.pub'
  51. FLAVOR_NAME = 'm1.small'
  52. # default region
  53. REGION_NAME = 'RegionOne'
  54. # domain to use, "default" for local accounts, formerly "hsfulda" for LDAP accounts etc.
  55. # domain_name = "default"
  56. def main(): # noqa: C901 pylint: disable=too-many-branches,too-many-statements,too-many-locals,missing-function-docstring
  57. ###########################################################################
  58. #
  59. # get credentials
  60. #
  61. ###########################################################################
  62. # if "OS_PASSWORD" in os.environ:
  63. # auth_password = os.environ["OS_PASSWORD"]
  64. # else:
  65. # auth_password = getpass.getpass("Enter your OpenStack password:")
  66. auth_password = "demo"
  67. ###########################################################################
  68. #
  69. # create connection
  70. #
  71. ###########################################################################
  72. provider = get_driver(Provider.OPENSTACK)
  73. conn = provider(AUTH_USERNAME,
  74. auth_password,
  75. ex_force_auth_url=AUTH_URL,
  76. ex_force_auth_version='3.x_password',
  77. ex_tenant_name=PROJECT_NAME,
  78. ex_force_service_region=REGION_NAME)
  79. # ex_domain_name=domain_name)
  80. ###########################################################################
  81. #
  82. # get image, flavor, network for instance creation
  83. #
  84. ###########################################################################
  85. images = conn.list_images()
  86. image = ''
  87. for img in images:
  88. if img.name == UBUNTU_IMAGE_NAME:
  89. image = img
  90. flavors = conn.list_sizes()
  91. flavor = ''
  92. for flav in flavors:
  93. if flav.name == FLAVOR_NAME:
  94. flavor = conn.ex_get_size(flav.id)
  95. networks = conn.ex_list_networks()
  96. network = ''
  97. for net in networks:
  98. if net.name == PROJECT_NETWORK:
  99. network = net
  100. ###########################################################################
  101. #
  102. # create keypair dependency
  103. #
  104. ###########################################################################
  105. print('Checking for existing SSH key pair...')
  106. keypair_exists = False
  107. for keypair in conn.list_key_pairs():
  108. if keypair.name == KEYPAIR_NAME:
  109. keypair_exists = True
  110. if keypair_exists:
  111. print('Keypair ' + KEYPAIR_NAME + ' already exists. Skipping import.')
  112. else:
  113. print('adding keypair...')
  114. conn.import_key_pair_from_file(KEYPAIR_NAME, PUB_KEY_FILE)
  115. for keypair in conn.list_key_pairs():
  116. print(keypair)
  117. ###########################################################################
  118. #
  119. # create security group dependency
  120. #
  121. ###########################################################################
  122. print('Checking for existing security group...')
  123. security_group_name = 'all-in-one'
  124. security_group_exists = False
  125. all_in_one_security_group = ''
  126. for security_group in conn.ex_list_security_groups():
  127. if security_group.name == security_group_name:
  128. all_in_one_security_group = security_group
  129. security_group_exists = True
  130. if security_group_exists:
  131. print('Security Group ' + all_in_one_security_group.name + ' already exists. '
  132. 'Skipping creation.')
  133. else:
  134. all_in_one_security_group = conn.ex_create_security_group(security_group_name,
  135. 'network access for '
  136. 'all-in-one application.')
  137. conn.ex_create_security_group_rule(all_in_one_security_group, 'TCP', 80, 80)
  138. conn.ex_create_security_group_rule(all_in_one_security_group, 'TCP', 22, 22)
  139. for security_group in conn.ex_list_security_groups():
  140. print(security_group)
  141. ###########################################################################
  142. #
  143. # create all-in-one instance
  144. #
  145. ###########################################################################
  146. hsfd_faafo_cloud_init_script = 'https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/master/faafo/contrib/install.sh' # noqa: E501 pylint: disable=line-too-long
  147. # testing / faafo dev branch:
  148. # hsfd_faafo_cloud_init_script = 'https://gogs.informatik.hs-fulda.de/srieger/cloud-computing-msc-ai-examples/raw/branch/dev_faafo/faafo/contrib/install.sh' # noqa: E501 pylint: disable=line-too-long
  149. userdata = '#!/usr/bin/env bash\n' \
  150. f'curl -L -s {hsfd_faafo_cloud_init_script} | bash -s -- ' \
  151. '-i faafo -i messaging -r api -r worker -r demo\n'
  152. print('\nUsing cloud-init userdata:\n"' + userdata + '"\n')
  153. print('Checking for existing instance...')
  154. instance_name = 'all-in-one'
  155. instance_exists = False
  156. testing_instance = ''
  157. for instance in conn.list_nodes():
  158. if instance.name == instance_name:
  159. testing_instance = instance
  160. instance_exists = True
  161. if instance_exists:
  162. print('Instance ' + testing_instance.name + ' already exists. Skipping creation.')
  163. exit()
  164. else:
  165. print('Starting new all-in-one instance and wait until it is running...')
  166. testing_instance = conn.create_node(name=instance_name,
  167. image=image,
  168. size=flavor,
  169. networks=[network],
  170. ex_keyname=KEYPAIR_NAME,
  171. ex_userdata=userdata,
  172. ex_security_groups=[all_in_one_security_group])
  173. conn.wait_until_running(nodes=[testing_instance], timeout=120, ssh_interface='private_ips')
  174. ###########################################################################
  175. #
  176. # assign all-in-one instance floating ip
  177. #
  178. ###########################################################################
  179. private_ip = None
  180. if len(testing_instance.private_ips):
  181. private_ip = testing_instance.private_ips[0]
  182. print(f'Private IP found: {private_ip}')
  183. public_ip = None
  184. if len(testing_instance.public_ips):
  185. public_ip = testing_instance.public_ips[0]
  186. print(f'Public IP found: {public_ip}')
  187. print('Checking for unused Floating IP...')
  188. unused_floating_ip = None
  189. for floating_ip in conn.ex_list_floating_ips():
  190. if not floating_ip.node_id:
  191. unused_floating_ip = floating_ip
  192. break
  193. if not unused_floating_ip and len(conn.ex_list_floating_ip_pools()):
  194. pool = conn.ex_list_floating_ip_pools()[0]
  195. print(f'Allocating new Floating IP from pool: {pool}')
  196. unused_floating_ip = pool.create_floating_ip()
  197. if public_ip:
  198. print('Instance ' + testing_instance.name + ' already has a public ip. Skipping attachment.')
  199. elif unused_floating_ip:
  200. conn.ex_attach_floating_ip_to_node(testing_instance, unused_floating_ip)
  201. actual_ip_address = None
  202. if public_ip:
  203. actual_ip_address = public_ip
  204. elif unused_floating_ip:
  205. actual_ip_address = unused_floating_ip.ip_address
  206. elif private_ip:
  207. actual_ip_address = private_ip
  208. print('\n\n#### Deployment finished\n\n')
  209. print('After some minutes, as soon as cloud-init installed required packages and the\n'
  210. 'faafo app, (First App Application For OpenStack) fractals demo will be available\n'
  211. f'at http://{actual_ip_address}\n')
  212. print('You can use ssh to login to the instance using your private key. Default user name for official Ubuntu\n'
  213. f'Cloud Images is: ubuntu, so you can use, e.g.: "ssh -i ~/.ssh/id_rsa ubuntu@{actual_ip_address}" if your\n'
  214. 'private key is in the default location.\n\n'
  215. 'After login, you can list available fractals using "faafo list". \n'
  216. 'To request the generation of new fractals, you can use "faafo create".\n\n'
  217. 'You can also see other options to use the faafo example cloud service using "faafo -h".\n\n'
  218. 'If you cannot start faafo command and/or do not see the webpage, you can check the Instance Console Log of\n'
  219. 'the instance, e.g., in OpenStack web interface or look at "tail -f /var/log/cloud-init*.log" for the\n'
  220. 'cloud-init log files.\n')
  221. if __name__ == '__main__':
  222. main()