2
0

test_compute_service.py 21 KB

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