test_compute_service.py 21 KB

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