test_compute_service.py 18 KB

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