test_compute_service.py 21 KB

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