test_compute_service.py 18 KB

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