test_compute_service.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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], "private ip should"
  109. " 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. @helpers.skipIfNoService(['compute.instances', 'compute.images',
  157. 'compute.vm_types'])
  158. def test_block_device_mapping_launch_config(self):
  159. lc = self.provider.compute.instances.create_launch_config()
  160. # specifying an invalid size should raise
  161. # an exception
  162. with self.assertRaises(InvalidConfigurationException):
  163. lc.add_volume_device(size=-1)
  164. # Attempting to add a blank volume without specifying a size
  165. # should raise an exception
  166. with self.assertRaises(InvalidConfigurationException):
  167. lc.add_volume_device(source=None)
  168. # block_devices should be empty so far
  169. self.assertListEqual(
  170. lc.block_devices, [], "No block devices should have been"
  171. " added to mappings list since the configuration was"
  172. " invalid")
  173. # Add a new volume
  174. lc.add_volume_device(size=1, delete_on_terminate=True)
  175. # Override root volume size
  176. image_id = helpers.get_provider_test_data(self.provider, "image")
  177. img = self.provider.compute.images.get(image_id)
  178. # The size should be greater then the ami size
  179. # and therefore, img.min_disk is used.
  180. lc.add_volume_device(
  181. is_root=True,
  182. source=img,
  183. size=img.min_disk if img and img.min_disk else 30,
  184. delete_on_terminate=True)
  185. # Attempting to add more than one root volume should raise an
  186. # exception.
  187. with self.assertRaises(InvalidConfigurationException):
  188. lc.add_volume_device(size=1, is_root=True)
  189. # Attempting to add an incorrect source should raise an exception
  190. with self.assertRaises(InvalidConfigurationException):
  191. lc.add_volume_device(
  192. source="invalid_source",
  193. delete_on_terminate=True)
  194. # Add all available ephemeral devices
  195. vm_type_name = helpers.get_provider_test_data(
  196. self.provider,
  197. "vm_type")
  198. vm_type = self.provider.compute.vm_types.find(
  199. name=vm_type_name)[0]
  200. for _ in range(vm_type.num_ephemeral_disks):
  201. lc.add_ephemeral_device()
  202. # block_devices should be populated
  203. self.assertTrue(
  204. len(lc.block_devices) == 2 + vm_type.num_ephemeral_disks,
  205. "Expected %d total block devices bit found %d" %
  206. (2 + vm_type.num_ephemeral_disks, len(lc.block_devices)))
  207. @helpers.skipIfNoService(['compute.instances', 'compute.images',
  208. 'compute.vm_types', 'storage.volumes'])
  209. def test_block_device_mapping_attachments(self):
  210. label = "cb-blkattch-{0}".format(helpers.get_uuid())
  211. if self.provider.PROVIDER_ID == ProviderList.OPENSTACK:
  212. raise self.skipTest("Not running BDM tests because OpenStack is"
  213. " not stable enough yet")
  214. test_vol = self.provider.storage.volumes.create(
  215. label, 1)
  216. with cb_helpers.cleanup_action(lambda: test_vol.delete()):
  217. test_vol.wait_till_ready()
  218. test_snap = test_vol.create_snapshot(label=label,
  219. description=label)
  220. def cleanup_snap(snap):
  221. if snap:
  222. snap.delete()
  223. snap.wait_for([SnapshotState.UNKNOWN],
  224. terminal_states=[SnapshotState.ERROR])
  225. with cb_helpers.cleanup_action(lambda: cleanup_snap(test_snap)):
  226. test_snap.wait_till_ready()
  227. lc = self.provider.compute.instances.create_launch_config()
  228. # Add a new blank volume
  229. lc.add_volume_device(size=1, delete_on_terminate=True)
  230. # Attach an existing volume
  231. lc.add_volume_device(size=1, source=test_vol,
  232. delete_on_terminate=True)
  233. # Add a new volume based on a snapshot
  234. lc.add_volume_device(size=1, source=test_snap,
  235. delete_on_terminate=True)
  236. # Override root volume size
  237. image_id = helpers.get_provider_test_data(
  238. self.provider,
  239. "image")
  240. img = self.provider.compute.images.get(image_id)
  241. # The size should be greater then the ami size
  242. # and therefore, img.min_disk is used.
  243. lc.add_volume_device(
  244. is_root=True,
  245. source=img,
  246. size=img.min_disk if img and img.min_disk else 30,
  247. delete_on_terminate=True)
  248. # Add all available ephemeral devices
  249. vm_type_name = helpers.get_provider_test_data(
  250. self.provider,
  251. "vm_type")
  252. vm_type = self.provider.compute.vm_types.find(
  253. name=vm_type_name)[0]
  254. # Some providers, e.g. GCP, has a limit on total number of
  255. # attached disks; it does not matter how many of them are
  256. # ephemeral or persistent. So, wee keep in mind that we have
  257. # attached 4 disks already, and add ephemeral disks accordingly
  258. # to not exceed the limit.
  259. for _ in range(vm_type.num_ephemeral_disks - 4):
  260. lc.add_ephemeral_device()
  261. subnet = helpers.get_or_create_default_subnet(
  262. self.provider)
  263. inst = None
  264. with cb_helpers.cleanup_action(
  265. lambda: helpers.delete_instance(inst)):
  266. inst = helpers.create_test_instance(
  267. self.provider,
  268. label,
  269. subnet=subnet,
  270. launch_config=lc)
  271. try:
  272. inst.wait_till_ready()
  273. except WaitStateException as e:
  274. self.fail("The block device mapped launch did not "
  275. " complete successfully: %s" % e)
  276. # TODO: Check instance attachments and make sure they
  277. # correspond to requested mappings
  278. @helpers.skipIfNoService(['compute.instances', 'networking.networks',
  279. 'security.vm_firewalls'])
  280. def test_instance_methods(self):
  281. label = "cb-instmethods-{0}".format(helpers.get_uuid())
  282. # Declare these variables and late binding will allow
  283. # the cleanup method access to the most current values
  284. net = None
  285. test_inst = None
  286. fw = None
  287. with cb_helpers.cleanup_action(lambda: helpers.cleanup_test_resources(
  288. instance=test_inst, vm_firewall=fw, network=net)):
  289. net = self.provider.networking.networks.create(
  290. label=label, cidr_block=BaseNetwork.CB_DEFAULT_IPV4RANGE)
  291. cidr = '10.0.1.0/24'
  292. subnet = net.subnets.create(label=label, cidr_block=cidr)
  293. test_inst = helpers.get_test_instance(self.provider, label,
  294. subnet=subnet)
  295. fw = self.provider.security.vm_firewalls.create(
  296. label=label, description=label, network=net.id)
  297. # Check adding a VM firewall to a running instance
  298. test_inst.add_vm_firewall(fw)
  299. test_inst.refresh()
  300. self.assertTrue(
  301. fw in test_inst.vm_firewalls, "Expected VM firewall '%s'"
  302. " to be among instance vm_firewalls: [%s]" %
  303. (fw, test_inst.vm_firewalls))
  304. # Check removing a VM firewall from a running instance
  305. test_inst.remove_vm_firewall(fw)
  306. test_inst.refresh()
  307. self.assertTrue(
  308. fw not in test_inst.vm_firewalls, "Expected VM firewall"
  309. " '%s' to be removed from instance vm_firewalls: [%s]" %
  310. (fw, test_inst.vm_firewalls))
  311. # check floating ips
  312. router = self.provider.networking.routers.create(label, net)
  313. gateway = net.gateways.get_or_create()
  314. def cleanup_router(router, gateway):
  315. with cb_helpers.cleanup_action(lambda: router.delete()):
  316. with cb_helpers.cleanup_action(lambda: gateway.delete()):
  317. router.detach_subnet(subnet)
  318. router.detach_gateway(gateway)
  319. with cb_helpers.cleanup_action(lambda: cleanup_router(router,
  320. gateway)):
  321. router.attach_subnet(subnet)
  322. router.attach_gateway(gateway)
  323. fip = None
  324. with cb_helpers.cleanup_action(
  325. lambda: helpers.cleanup_fip(fip)):
  326. # check whether adding an elastic ip works
  327. fip = gateway.floating_ips.create()
  328. self.assertFalse(
  329. fip.in_use,
  330. "Newly created floating IP %s should not be in use." %
  331. fip.public_ip)
  332. with cb_helpers.cleanup_action(
  333. lambda: test_inst.remove_floating_ip(fip)):
  334. test_inst.add_floating_ip(fip)
  335. test_inst.refresh()
  336. # On Devstack, FloatingIP is listed under private_ips.
  337. self.assertIn(fip.public_ip, test_inst.public_ips +
  338. test_inst.private_ips)
  339. fip.refresh()
  340. self.assertTrue(
  341. fip.in_use,
  342. "Attached floating IP %s address should be in use."
  343. % fip.public_ip)
  344. test_inst.refresh()
  345. test_inst.reboot()
  346. test_inst.wait_till_ready()
  347. self.assertNotIn(
  348. fip.public_ip,
  349. test_inst.public_ips + test_inst.private_ips)