test_compute_service.py 21 KB

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