test_compute_service.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  1. import datetime
  2. import ipaddress
  3. from cloudbridge.base import helpers as cb_helpers
  4. from cloudbridge.base.resources import BaseNetwork
  5. from cloudbridge.factory import ProviderList
  6. from cloudbridge.interfaces import InstanceState
  7. from cloudbridge.interfaces import InvalidConfigurationException
  8. from cloudbridge.interfaces.exceptions import WaitStateException
  9. from cloudbridge.interfaces.resources import Instance
  10. from cloudbridge.interfaces.resources import SnapshotState
  11. from cloudbridge.interfaces.resources import VMType
  12. from tests import helpers
  13. from tests.helpers import ProviderTestBase
  14. from tests.helpers import standard_interface_tests as sit
  15. class CloudComputeServiceTestCase(ProviderTestBase):
  16. _multiprocess_can_split_ = True
  17. @helpers.skipIfNoService(['compute.instances'])
  18. def test_storage_services_event_pattern(self):
  19. # pylint:disable=protected-access
  20. self.assertEqual(
  21. self.provider.compute.instances._service_event_pattern,
  22. "provider.compute.instances",
  23. "Event pattern for {} service should be '{}', "
  24. "but found '{}'.".format("instances",
  25. "provider.compute.instances",
  26. self.provider.compute.instances.
  27. _service_event_pattern))
  28. # moto 5.x regression: DescribeInstances returns an empty list
  29. # immediately after RunInstances completes, so the list-after-create
  30. # check in standard_interface_tests.check_list fails. A secondary
  31. # symptom shows in cleanup, where post-delete state remains
  32. # "deleted" instead of becoming UNKNOWN. Pinned to the latest moto
  33. # release where this was observed (5.2.1); newer releases re-run the
  34. # test so we notice if it's fixed. Bump the pin if it's still broken.
  35. @helpers.skipIfMockMotoVersion(
  36. "==5.2.1",
  37. "moto 5.2.1 RunInstances/DescribeInstances state-sync bug")
  38. @helpers.skipIfNoService(['compute.instances', 'networking.networks'])
  39. def test_crud_instance(self):
  40. label = "cb-instcrud-{0}".format(helpers.get_uuid())
  41. # Declare these variables and late binding will allow
  42. # the cleanup method access to the most current values
  43. subnet = None
  44. def create_inst(label):
  45. # Also test whether sending in an empty_dict for user_data
  46. # results in an automatic conversion to string.
  47. return helpers.get_test_instance(self.provider, label,
  48. subnet=subnet, user_data={})
  49. def cleanup_inst(inst):
  50. if inst:
  51. inst.delete()
  52. inst.wait_for([InstanceState.DELETED, InstanceState.UNKNOWN])
  53. inst.refresh()
  54. self.assertTrue(
  55. inst.state == InstanceState.UNKNOWN,
  56. "Instance.state must be unknown when refreshing after a "
  57. "delete but got %s"
  58. % inst.state)
  59. def check_deleted(inst):
  60. deleted_inst = self.provider.compute.instances.get(
  61. inst.id)
  62. self.assertTrue(
  63. deleted_inst is None or deleted_inst.state in (
  64. InstanceState.DELETED,
  65. InstanceState.UNKNOWN),
  66. "Instance %s should have been deleted but still exists." %
  67. label)
  68. subnet = helpers.get_or_create_default_subnet(self.provider)
  69. sit.check_crud(self, self.provider.compute.instances, Instance,
  70. "cb-instcrud", create_inst, cleanup_inst,
  71. custom_check_delete=check_deleted)
  72. def _is_valid_ip(self, address):
  73. try:
  74. ipaddress.ip_address(address)
  75. except ValueError:
  76. return False
  77. return True
  78. @helpers.skipIfNoService(['compute.instances', 'networking.networks',
  79. 'security.vm_firewalls',
  80. 'security.key_pairs'])
  81. def test_instance_properties(self):
  82. label = "cb-inst-props-{0}".format(helpers.get_uuid())
  83. # Declare these variables and late binding will allow
  84. # the cleanup method access to the most current values
  85. test_instance = None
  86. fw = None
  87. kp = None
  88. with cb_helpers.cleanup_action(lambda: helpers.cleanup_test_resources(
  89. test_instance, fw, kp)):
  90. subnet = helpers.get_or_create_default_subnet(self.provider)
  91. net = subnet.network
  92. kp = self.provider.security.key_pairs.create(name=label)
  93. fw = self.provider.security.vm_firewalls.create(
  94. label=label, description=label, network=net.id)
  95. test_instance = helpers.get_test_instance(self.provider,
  96. label, key_pair=kp,
  97. vm_firewalls=[fw],
  98. subnet=subnet)
  99. self.assertEqual(
  100. test_instance.label, label,
  101. "Instance label {0} is not equal to the expected label"
  102. " {1}".format(test_instance.label, label))
  103. image_id = helpers.get_provider_test_data(self.provider, "image")
  104. self.assertEqual(test_instance.image_id, image_id,
  105. "Image id {0} is not equal to the expected id"
  106. " {1}".format(test_instance.image_id, image_id))
  107. self.assertIsInstance(test_instance.zone_id,
  108. str)
  109. self.assertEqual(
  110. test_instance.image_id,
  111. helpers.get_provider_test_data(self.provider, "image"))
  112. self.assertIsInstance(test_instance.public_ips, list)
  113. if test_instance.public_ips:
  114. self.assertTrue(
  115. test_instance.public_ips[0], "public ip should contain a"
  116. " valid value if a list of public_ips exist")
  117. self.assertIsInstance(test_instance.private_ips, list)
  118. self.assertTrue(test_instance.private_ips[0],
  119. "private ip should contain a valid value")
  120. self.assertEqual(
  121. test_instance.key_pair_id,
  122. kp.id)
  123. self.assertIsInstance(test_instance.vm_firewalls, list)
  124. self.assertEqual(
  125. test_instance.vm_firewalls[0],
  126. fw)
  127. self.assertIsInstance(test_instance.vm_firewall_ids, list)
  128. self.assertEqual(
  129. test_instance.vm_firewall_ids[0],
  130. fw.id)
  131. # Must have either a public or a private ip
  132. ip_private = test_instance.private_ips[0] \
  133. if test_instance.private_ips else None
  134. ip_address = test_instance.public_ips[0] \
  135. if test_instance.public_ips and test_instance.public_ips[0] \
  136. else ip_private
  137. ip_address = str(ip_address)
  138. self.assertIsNotNone(
  139. ip_address,
  140. "Instance must have either a public IP or a private IP")
  141. self.assertTrue(
  142. self._is_valid_ip(ip_address),
  143. "Instance must have a valid IP address. Got: %s" % ip_address)
  144. self.assertIsInstance(test_instance.vm_type_id,
  145. str)
  146. vm_type = self.provider.compute.vm_types.get(
  147. test_instance.vm_type_id)
  148. self.assertEqual(
  149. vm_type, test_instance.vm_type,
  150. "VM type {0} does not match expected type {1}".format(
  151. vm_type.name, test_instance.vm_type))
  152. self.assertIsInstance(vm_type, VMType)
  153. expected_type = helpers.get_provider_test_data(self.provider,
  154. 'vm_type')
  155. self.assertEqual(
  156. vm_type.name, expected_type,
  157. "VM type {0} does not match expected type {1}".format(
  158. vm_type.name, expected_type))
  159. find_zone = [zone for zone in
  160. self.provider.compute.regions.current.zones
  161. if zone.id == test_instance.zone_id]
  162. self.assertEqual(len(find_zone), 1,
  163. "Instance's placement zone could not be "
  164. " found in zones list")
  165. self.assertIsNotNone(
  166. test_instance.create_time,
  167. "Instance must have its creation time")
  168. self.assertIsInstance(
  169. test_instance.create_time,
  170. datetime.datetime)
  171. @helpers.skipIfNoService(['compute.instances', 'compute.images',
  172. 'compute.vm_types'])
  173. def test_block_device_mapping_launch_config(self):
  174. lc = self.provider.compute.instances.create_launch_config()
  175. # specifying an invalid size should raise
  176. # an exception
  177. with self.assertRaises(InvalidConfigurationException):
  178. lc.add_volume_device(size=-1)
  179. # Attempting to add a blank volume without specifying a size
  180. # should raise an exception
  181. with self.assertRaises(InvalidConfigurationException):
  182. lc.add_volume_device(source=None)
  183. # block_devices should be empty so far
  184. self.assertListEqual(
  185. lc.block_devices, [], "No block devices should have been"
  186. " added to mappings list since the configuration was invalid")
  187. # Add a new volume
  188. lc.add_volume_device(size=1, delete_on_terminate=True)
  189. # Override root volume size
  190. image_id = helpers.get_provider_test_data(self.provider, "image")
  191. img = self.provider.compute.images.get(image_id)
  192. # The size should be greater then the ami size
  193. # and therefore, img.min_disk is used.
  194. lc.add_volume_device(
  195. is_root=True,
  196. source=img,
  197. size=img.min_disk if img and img.min_disk else 30,
  198. delete_on_terminate=True)
  199. # Attempting to add more than one root volume should raise an
  200. # exception.
  201. with self.assertRaises(InvalidConfigurationException):
  202. lc.add_volume_device(size=1, is_root=True)
  203. # Attempting to add an incorrect source should raise an exception
  204. with self.assertRaises(InvalidConfigurationException):
  205. lc.add_volume_device(
  206. source="invalid_source",
  207. delete_on_terminate=True)
  208. # Add all available ephemeral devices
  209. vm_type_name = helpers.get_provider_test_data(
  210. self.provider,
  211. "vm_type")
  212. vm_type = self.provider.compute.vm_types.find(
  213. name=vm_type_name)[0]
  214. for _ in range(vm_type.num_ephemeral_disks):
  215. lc.add_ephemeral_device()
  216. # block_devices should be populated
  217. self.assertTrue(
  218. len(lc.block_devices) == 2 + vm_type.num_ephemeral_disks,
  219. "Expected %d total block devices bit found %d" %
  220. (2 + vm_type.num_ephemeral_disks, len(lc.block_devices)))
  221. @helpers.skipIfNoService(['compute.instances', 'compute.images',
  222. 'compute.vm_types', 'storage.volumes'])
  223. def test_block_device_mapping_attachments(self):
  224. label = "cb-blkattch-{0}".format(helpers.get_uuid())
  225. if self.provider.PROVIDER_ID == ProviderList.OPENSTACK:
  226. raise self.skipTest("Not running BDM tests because OpenStack is"
  227. " not stable enough yet")
  228. test_vol = self.provider.storage.volumes.create(
  229. label, 1)
  230. with cb_helpers.cleanup_action(lambda: test_vol.delete()):
  231. test_vol.wait_till_ready()
  232. test_snap = test_vol.create_snapshot(label=label,
  233. description=label)
  234. def cleanup_snap(snap):
  235. if snap:
  236. snap.delete()
  237. snap.wait_for([SnapshotState.UNKNOWN],
  238. terminal_states=[SnapshotState.ERROR])
  239. with cb_helpers.cleanup_action(lambda: cleanup_snap(test_snap)):
  240. test_snap.wait_till_ready()
  241. lc = self.provider.compute.instances.create_launch_config()
  242. # Add a new blank volume
  243. lc.add_volume_device(size=1, delete_on_terminate=True)
  244. # Attach an existing volume
  245. lc.add_volume_device(size=1, source=test_vol,
  246. delete_on_terminate=True)
  247. # Add a new volume based on a snapshot
  248. lc.add_volume_device(size=1, source=test_snap,
  249. delete_on_terminate=True)
  250. # Override root volume size
  251. image_id = helpers.get_provider_test_data(
  252. self.provider,
  253. "image")
  254. img = self.provider.compute.images.get(image_id)
  255. # The size should be greater then the ami size
  256. # and therefore, img.min_disk is used.
  257. lc.add_volume_device(
  258. is_root=True,
  259. source=img,
  260. size=img.min_disk if img and img.min_disk else 30,
  261. delete_on_terminate=True)
  262. # Add all available ephemeral devices
  263. vm_type_name = helpers.get_provider_test_data(
  264. self.provider,
  265. "vm_type")
  266. vm_type = self.provider.compute.vm_types.find(
  267. name=vm_type_name)[0]
  268. # Some providers, e.g. GCP, has a limit on total number of
  269. # attached disks; it does not matter how many of them are
  270. # ephemeral or persistent. So, wee keep in mind that we have
  271. # attached 4 disks already, and add ephemeral disks accordingly
  272. # to not exceed the limit.
  273. for _ in range(vm_type.num_ephemeral_disks - 4):
  274. lc.add_ephemeral_device()
  275. subnet = helpers.get_or_create_default_subnet(
  276. self.provider)
  277. inst = None
  278. with cb_helpers.cleanup_action(
  279. lambda: helpers.delete_instance(inst)):
  280. inst = helpers.create_test_instance(
  281. self.provider,
  282. label,
  283. subnet=subnet,
  284. launch_config=lc)
  285. try:
  286. inst.wait_till_ready()
  287. except WaitStateException as e:
  288. self.fail("The block device mapped launch did not "
  289. " complete successfully: %s" % e)
  290. # TODO: Check instance attachments and make sure they
  291. # correspond to requested mappings
  292. @helpers.skipIfNoService(['compute.instances', 'networking.networks',
  293. 'security.vm_firewalls'])
  294. def test_instance_methods(self):
  295. label = "cb-instmethods-{0}".format(helpers.get_uuid())
  296. # Declare these variables and late binding will allow
  297. # the cleanup method access to the most current values
  298. net = None
  299. test_inst = None
  300. fw = None
  301. with cb_helpers.cleanup_action(lambda: helpers.cleanup_test_resources(
  302. instance=test_inst, vm_firewall=fw, network=net)):
  303. net = self.provider.networking.networks.create(
  304. label=label, cidr_block=BaseNetwork.CB_DEFAULT_IPV4RANGE)
  305. cidr = '10.0.1.0/24'
  306. subnet = net.subnets.create(label=label, cidr_block=cidr)
  307. test_inst = helpers.get_test_instance(self.provider, label,
  308. subnet=subnet)
  309. fw = self.provider.security.vm_firewalls.create(
  310. label=label, description=label, network=net.id)
  311. # Check adding a VM firewall to a running instance
  312. test_inst.add_vm_firewall(fw)
  313. test_inst.refresh()
  314. self.assertTrue(
  315. fw in test_inst.vm_firewalls, "Expected VM firewall '%s'"
  316. " to be among instance vm_firewalls: [%s]" %
  317. (fw, test_inst.vm_firewalls))
  318. # Check removing a VM firewall from a running instance
  319. test_inst.remove_vm_firewall(fw)
  320. test_inst.refresh()
  321. self.assertTrue(
  322. fw not in test_inst.vm_firewalls, "Expected VM firewall"
  323. " '%s' to be removed from instance vm_firewalls: [%s]" %
  324. (fw, test_inst.vm_firewalls))
  325. # check floating ips
  326. router = self.provider.networking.routers.create(label, net)
  327. gateway = net.gateways.get_or_create()
  328. def cleanup_router(router, gateway):
  329. with cb_helpers.cleanup_action(lambda: router.delete()):
  330. with cb_helpers.cleanup_action(lambda: gateway.delete()):
  331. router.detach_subnet(subnet)
  332. router.detach_gateway(gateway)
  333. with cb_helpers.cleanup_action(lambda: cleanup_router(router,
  334. gateway)):
  335. router.attach_subnet(subnet)
  336. router.attach_gateway(gateway)
  337. fip = None
  338. with cb_helpers.cleanup_action(
  339. lambda: helpers.cleanup_fip(fip)):
  340. # check whether adding an elastic ip works
  341. fip = gateway.floating_ips.create()
  342. self.assertFalse(
  343. fip.in_use,
  344. "Newly created floating IP %s should not be in use." %
  345. fip.public_ip)
  346. with cb_helpers.cleanup_action(
  347. lambda: test_inst.remove_floating_ip(fip)):
  348. test_inst.add_floating_ip(fip)
  349. test_inst.refresh()
  350. # On Devstack, FloatingIP is listed under private_ips.
  351. self.assertIn(fip.public_ip, test_inst.public_ips +
  352. test_inst.private_ips)
  353. fip.refresh()
  354. self.assertTrue(
  355. fip.in_use,
  356. "Attached floating IP %s address should be in use."
  357. % fip.public_ip)
  358. test_inst.refresh()
  359. test_inst.reboot()
  360. test_inst.wait_till_ready()
  361. self.assertNotIn(
  362. fip.public_ip,
  363. test_inst.public_ips + test_inst.private_ips)
  364. with cb_helpers.cleanup_action(
  365. lambda: test_inst.remove_floating_ip(fip.id)):
  366. test_inst.add_floating_ip(fip.id)
  367. test_inst.refresh()
  368. # On Devstack, FloatingIP is listed under private_ips.
  369. self.assertIn(fip.public_ip, test_inst.public_ips +
  370. test_inst.private_ips)
  371. fip.refresh()
  372. self.assertTrue(
  373. fip.in_use,
  374. "Attached floating IP %s address should be in use."
  375. % fip.public_ip)
  376. @helpers.skipIfNoService(['compute.instances', 'networking.networks',
  377. 'security.vm_firewalls'])
  378. def test_instance_start_stop_methods(self):
  379. label = "cb-instmethods-{0}".format(helpers.get_uuid())
  380. if self.provider.PROVIDER_ID != ProviderList.AWS:
  381. raise self.skipTest(f"Instance start/stop methods not implemented"
  382. f"for provider: {self.provider.PROVIDER_ID}")
  383. # Declare these variables and late binding will allow
  384. # the cleanup method access to the most current values
  385. subnet = None
  386. test_inst = None
  387. with cb_helpers.cleanup_action(lambda: helpers.cleanup_test_resources(
  388. instance=test_inst)):
  389. subnet = helpers.get_or_create_default_subnet(self.provider)
  390. test_inst = helpers.get_test_instance(self.provider, label,
  391. subnet=subnet)
  392. # check whether stopping aws instance works
  393. resp = test_inst.stop()
  394. test_inst.wait_for([InstanceState.STOPPED])
  395. test_inst.refresh()
  396. self.assertTrue(
  397. test_inst.state == InstanceState.STOPPED,
  398. "Instance state must be stopped when refreshing after a "
  399. "'stop' operation but got %s"
  400. % test_inst.state)
  401. self.assertTrue(resp, "Response from method was suppose to be"
  402. + " True but got False")
  403. # check whether starting aws instance works
  404. resp = test_inst.start()
  405. test_inst.wait_for([InstanceState.RUNNING])
  406. test_inst.refresh()
  407. self.assertTrue(
  408. test_inst.state == InstanceState.RUNNING,
  409. "Instance state must be running when refreshing after a "
  410. "'start' operation but got %s"
  411. % test_inst.state)
  412. self.assertTrue(resp, "Response from method was suppose to be"
  413. + " True but got False")