services.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. """Services implemented by the AWS provider."""
  2. import logging
  3. import string
  4. from botocore.exceptions import ClientError
  5. import requests
  6. import cloudbridge.cloud.base.helpers as cb_helpers
  7. from cloudbridge.cloud.base.resources import ClientPagedResultList
  8. from cloudbridge.cloud.base.services import BaseBucketService
  9. from cloudbridge.cloud.base.services import BaseComputeService
  10. from cloudbridge.cloud.base.services import BaseImageService
  11. from cloudbridge.cloud.base.services import BaseInstanceService
  12. from cloudbridge.cloud.base.services import BaseKeyPairService
  13. from cloudbridge.cloud.base.services import BaseNetworkService
  14. from cloudbridge.cloud.base.services import BaseNetworkingService
  15. from cloudbridge.cloud.base.services import BaseRegionService
  16. from cloudbridge.cloud.base.services import BaseRouterService
  17. from cloudbridge.cloud.base.services import BaseSecurityService
  18. from cloudbridge.cloud.base.services import BaseSnapshotService
  19. from cloudbridge.cloud.base.services import BaseStorageService
  20. from cloudbridge.cloud.base.services import BaseSubnetService
  21. from cloudbridge.cloud.base.services import BaseVMFirewallService
  22. from cloudbridge.cloud.base.services import BaseVMTypeService
  23. from cloudbridge.cloud.base.services import BaseVolumeService
  24. from cloudbridge.cloud.interfaces.exceptions \
  25. import DuplicateResourceException, InvalidConfigurationException
  26. from cloudbridge.cloud.interfaces.resources import KeyPair
  27. from cloudbridge.cloud.interfaces.resources import MachineImage
  28. from cloudbridge.cloud.interfaces.resources import PlacementZone
  29. from cloudbridge.cloud.interfaces.resources import Snapshot
  30. from cloudbridge.cloud.interfaces.resources import VMFirewall
  31. from cloudbridge.cloud.interfaces.resources import VMType
  32. from cloudbridge.cloud.interfaces.resources import Volume
  33. from .helpers import BotoEC2Service
  34. from .helpers import BotoS3Service
  35. from .resources import AWSBucket
  36. from .resources import AWSInstance
  37. from .resources import AWSKeyPair
  38. from .resources import AWSLaunchConfig
  39. from .resources import AWSMachineImage
  40. from .resources import AWSNetwork
  41. from .resources import AWSPlacementZone
  42. from .resources import AWSRegion
  43. from .resources import AWSRouter
  44. from .resources import AWSSnapshot
  45. from .resources import AWSSubnet
  46. from .resources import AWSVMFirewall
  47. from .resources import AWSVMType
  48. from .resources import AWSVolume
  49. log = logging.getLogger(__name__)
  50. class AWSSecurityService(BaseSecurityService):
  51. def __init__(self, provider):
  52. super(AWSSecurityService, self).__init__(provider)
  53. # Initialize provider services
  54. self._key_pairs = AWSKeyPairService(provider)
  55. self._vm_firewalls = AWSVMFirewallService(provider)
  56. @property
  57. def key_pairs(self):
  58. return self._key_pairs
  59. @property
  60. def vm_firewalls(self):
  61. return self._vm_firewalls
  62. class AWSKeyPairService(BaseKeyPairService):
  63. def __init__(self, provider):
  64. super(AWSKeyPairService, self).__init__(provider)
  65. self.svc = BotoEC2Service(provider=self.provider,
  66. cb_resource=AWSKeyPair,
  67. boto_collection_name='key_pairs')
  68. def get(self, key_pair_id):
  69. log.debug("Getting Key Pair Service %s", key_pair_id)
  70. return self.svc.get(key_pair_id)
  71. def list(self, limit=None, marker=None):
  72. return self.svc.list(limit=limit, marker=marker)
  73. def find(self, **kwargs):
  74. name = kwargs.pop('name', None)
  75. # All kwargs should have been popped at this time.
  76. if len(kwargs) > 0:
  77. raise TypeError("Unrecognised parameters for search: %s."
  78. " Supported attributes: %s" % (kwargs, 'name'))
  79. log.debug("Searching for Key Pair %s", name)
  80. return self.svc.find(filter_name='key-name', filter_value=name)
  81. def create(self, name, public_key_material=None):
  82. log.debug("Creating Key Pair Service %s", name)
  83. AWSKeyPair.assert_valid_resource_name(name)
  84. private_key = None
  85. if not public_key_material:
  86. public_key_material, private_key = cb_helpers.generate_key_pair()
  87. try:
  88. kp = self.svc.create('import_key_pair', KeyName=name,
  89. PublicKeyMaterial=public_key_material)
  90. kp.material = private_key
  91. return kp
  92. except ClientError as e:
  93. if e.response['Error']['Code'] == 'InvalidKeyPair.Duplicate':
  94. raise DuplicateResourceException(
  95. 'Keypair already exists with name {0}'.format(name))
  96. else:
  97. raise e
  98. class AWSVMFirewallService(BaseVMFirewallService):
  99. def __init__(self, provider):
  100. super(AWSVMFirewallService, self).__init__(provider)
  101. self.svc = BotoEC2Service(provider=self.provider,
  102. cb_resource=AWSVMFirewall,
  103. boto_collection_name='security_groups')
  104. def get(self, firewall_id):
  105. log.debug("Getting Firewall Service with the id: %s", firewall_id)
  106. return self.svc.get(firewall_id)
  107. def list(self, limit=None, marker=None):
  108. return self.svc.list(limit=limit, marker=marker)
  109. def create(self, label, network_id, description=None):
  110. log.debug("Creating Firewall Service with the parameters "
  111. "[label: %s id: %s description: %s]", label, network_id,
  112. description)
  113. AWSVMFirewall.assert_valid_resource_label(label)
  114. name = AWSVMFirewall._generate_name_from_label(label, 'cb-fw')
  115. obj = self.svc.create('create_security_group', GroupName=name,
  116. Description=description or name,
  117. VpcId=network_id)
  118. obj.wait_till_ready()
  119. obj.label = label
  120. return obj
  121. def find(self, **kwargs):
  122. # Filter by name or label
  123. label = kwargs.pop('label', None)
  124. log.debug("Searching for Firewall Service %s", label)
  125. # All kwargs should have been popped at this time.
  126. if len(kwargs) > 0:
  127. raise TypeError("Unrecognised parameters for search: %s."
  128. " Supported attributes: %s" % (kwargs, 'label'))
  129. return self.svc.find(filter_name='tag:Name',
  130. filter_value=label)
  131. def delete(self, firewall_id):
  132. log.info("Deleting Firewall Service with the id %s", firewall_id)
  133. firewall = self.svc.get(firewall_id)
  134. if firewall:
  135. firewall.delete()
  136. class AWSStorageService(BaseStorageService):
  137. def __init__(self, provider):
  138. super(AWSStorageService, self).__init__(provider)
  139. # Initialize provider services
  140. self._volume_svc = AWSVolumeService(self.provider)
  141. self._snapshot_svc = AWSSnapshotService(self.provider)
  142. self._bucket_svc = AWSBucketService(self.provider)
  143. @property
  144. def volumes(self):
  145. return self._volume_svc
  146. @property
  147. def snapshots(self):
  148. return self._snapshot_svc
  149. @property
  150. def buckets(self):
  151. return self._bucket_svc
  152. class AWSVolumeService(BaseVolumeService):
  153. def __init__(self, provider):
  154. super(AWSVolumeService, self).__init__(provider)
  155. self.svc = BotoEC2Service(provider=self.provider,
  156. cb_resource=AWSVolume,
  157. boto_collection_name='volumes')
  158. def get(self, volume_id):
  159. log.debug("Getting AWS Volume Service with the id: %s",
  160. volume_id)
  161. return self.svc.get(volume_id)
  162. def find(self, **kwargs):
  163. label = kwargs.pop('label', None)
  164. # All kwargs should have been popped at this time.
  165. if len(kwargs) > 0:
  166. raise TypeError("Unrecognised parameters for search: %s."
  167. " Supported attributes: %s" % (kwargs, 'label'))
  168. log.debug("Searching for AWS Volume Service %s", label)
  169. return self.svc.find(filter_name='tag:Name', filter_value=label)
  170. def list(self, limit=None, marker=None):
  171. return self.svc.list(limit=limit, marker=marker)
  172. def create(self, label, size, zone, snapshot=None, description=None):
  173. log.debug("Creating AWS Volume Service with the parameters "
  174. "[label: %s size: %s zone: %s snapshot: %s "
  175. "description: %s]", label, size, zone, snapshot,
  176. description)
  177. AWSVolume.assert_valid_resource_label(label)
  178. zone_id = zone.id if isinstance(zone, PlacementZone) else zone
  179. snapshot_id = snapshot.id if isinstance(
  180. snapshot, AWSSnapshot) and snapshot else snapshot
  181. cb_vol = self.svc.create('create_volume', Size=size,
  182. AvailabilityZone=zone_id,
  183. SnapshotId=snapshot_id)
  184. # Wait until ready to tag instance
  185. cb_vol.wait_till_ready()
  186. cb_vol.label = label
  187. if description:
  188. cb_vol.description = description
  189. return cb_vol
  190. class AWSSnapshotService(BaseSnapshotService):
  191. def __init__(self, provider):
  192. super(AWSSnapshotService, self).__init__(provider)
  193. self.svc = BotoEC2Service(provider=self.provider,
  194. cb_resource=AWSSnapshot,
  195. boto_collection_name='snapshots')
  196. def get(self, snapshot_id):
  197. log.debug("Getting AWS Snapshot Service with the id: %s",
  198. snapshot_id)
  199. return self.svc.get(snapshot_id)
  200. def find(self, **kwargs):
  201. label = kwargs.pop('label', None)
  202. # All kwargs should have been popped at this time.
  203. if len(kwargs) > 0:
  204. raise TypeError("Unrecognised parameters for search: %s."
  205. " Supported attributes: %s" % (kwargs, 'label'))
  206. log.debug("Searching for AWS Snapshot Service %s", label)
  207. return self.svc.find(filter_name='tag:Name', filter_value=label,
  208. OwnerIds=['self'])
  209. def list(self, limit=None, marker=None):
  210. return self.svc.list(limit=limit, marker=marker,
  211. OwnerIds=['self'])
  212. def create(self, label, volume, description=None):
  213. """
  214. Creates a new snapshot of a given volume.
  215. """
  216. log.debug("Creating a new AWS snapshot Service with the "
  217. "parameters [label: %s volume: %s description: %s]",
  218. label, volume, description)
  219. AWSSnapshot.assert_valid_resource_label(label)
  220. volume_id = volume.id if isinstance(volume, AWSVolume) else volume
  221. cb_snap = self.svc.create('create_snapshot', VolumeId=volume_id)
  222. # Wait until ready to tag instance
  223. cb_snap.wait_till_ready()
  224. cb_snap.label = label
  225. if cb_snap.description:
  226. cb_snap.description = description
  227. return cb_snap
  228. class AWSBucketService(BaseBucketService):
  229. def __init__(self, provider):
  230. super(AWSBucketService, self).__init__(provider)
  231. self.svc = BotoS3Service(provider=self.provider,
  232. cb_resource=AWSBucket,
  233. boto_collection_name='buckets')
  234. def get(self, bucket_id):
  235. """
  236. Returns a bucket given its ID. Returns ``None`` if the bucket
  237. does not exist.
  238. """
  239. log.debug("Getting AWS Bucket Service with the id: %s", bucket_id)
  240. try:
  241. # Make a call to make sure the bucket exists. There's an edge case
  242. # where a 403 response can occur when the bucket exists but the
  243. # user simply does not have permissions to access it. See below.
  244. self.provider.s3_conn.meta.client.head_bucket(Bucket=bucket_id)
  245. return AWSBucket(self.provider,
  246. self.provider.s3_conn.Bucket(bucket_id))
  247. except ClientError as e:
  248. # If 403, it means the bucket exists, but the user does not have
  249. # permissions to access the bucket. However, limited operations
  250. # may be permitted (with a session token for example), so return a
  251. # Bucket instance to allow further operations.
  252. # http://stackoverflow.com/questions/32331456/using-boto-upload-file-to-s3-
  253. # sub-folder-when-i-have-no-permissions-on-listing-fo
  254. if e.response['Error']['Code'] == "403":
  255. log.warning("AWS Bucket %s already exists but user doesn't "
  256. "have enough permissions to access the bucket",
  257. bucket_id)
  258. bucket = self.provider.s3_conn.get_bucket(bucket_id,
  259. validate=False)
  260. return AWSBucket(self.provider, bucket)
  261. # For all other responses, it's assumed that the bucket does not exist.
  262. return None
  263. def find(self, **kwargs):
  264. obj_list = self
  265. filters = ['name']
  266. matches = cb_helpers.generic_find(filters, kwargs, obj_list)
  267. return ClientPagedResultList(self._provider, list(matches),
  268. limit=None, marker=None)
  269. def list(self, limit=None, marker=None):
  270. return self.svc.list(limit=limit, marker=marker)
  271. def create(self, name, location=None):
  272. log.debug("Creating AWS Bucket with the params "
  273. "[name: %s, location: %s]", name, location)
  274. AWSBucket.assert_valid_resource_name(name)
  275. loc_constraint = location or self.provider.region_name
  276. # Due to an API issue in S3, specifying us-east-1 as a
  277. # LocationConstraint results in an InvalidLocationConstraint.
  278. # Therefore, it must be special-cased and omitted altogether.
  279. # See: https://github.com/boto/boto3/issues/125
  280. # In addition, us-east-1 also behaves differently when it comes
  281. # to raising duplicate resource exceptions, so perform a manual
  282. # check
  283. if loc_constraint == 'us-east-1':
  284. try:
  285. # check whether bucket already exists
  286. self.provider.s3_conn.meta.client.head_bucket(Bucket=name)
  287. except ClientError as e:
  288. if e.response['Error']['Code'] == "404":
  289. # bucket doesn't exist, go ahead and create it
  290. return self.svc.create('create_bucket', Bucket=name)
  291. raise DuplicateResourceException(
  292. 'Bucket already exists with name {0}'.format(name))
  293. else:
  294. try:
  295. return self.svc.create('create_bucket', Bucket=name,
  296. CreateBucketConfiguration={
  297. 'LocationConstraint': loc_constraint
  298. })
  299. except ClientError as e:
  300. if e.response['Error']['Code'] == "BucketAlreadyOwnedByYou":
  301. raise DuplicateResourceException(
  302. 'Bucket already exists with name {0}'.format(name))
  303. else:
  304. raise
  305. class AWSImageService(BaseImageService):
  306. def __init__(self, provider):
  307. super(AWSImageService, self).__init__(provider)
  308. self.svc = BotoEC2Service(provider=self.provider,
  309. cb_resource=AWSMachineImage,
  310. boto_collection_name='images')
  311. def get(self, image_id):
  312. log.debug("Getting AWS Image Service with the id: %s", image_id)
  313. return self.svc.get(image_id)
  314. def find(self, **kwargs):
  315. # Filter by name or label
  316. name = kwargs.pop('name', None)
  317. if name:
  318. log.debug("Searching for AWS Image Service %s", name)
  319. obj_list = self.svc.find(filter_name='name', filter_value=name)
  320. else:
  321. obj_list = self
  322. filters = ['label']
  323. return cb_helpers.generic_find(filters, kwargs, obj_list)
  324. def list(self, filter_by_owner=True, limit=None, marker=None):
  325. return self.svc.list(Owners=['self'] if filter_by_owner else [],
  326. limit=limit, marker=marker)
  327. class AWSComputeService(BaseComputeService):
  328. def __init__(self, provider):
  329. super(AWSComputeService, self).__init__(provider)
  330. self._vm_type_svc = AWSVMTypeService(self.provider)
  331. self._instance_svc = AWSInstanceService(self.provider)
  332. self._region_svc = AWSRegionService(self.provider)
  333. self._images_svc = AWSImageService(self.provider)
  334. @property
  335. def images(self):
  336. return self._images_svc
  337. @property
  338. def vm_types(self):
  339. return self._vm_type_svc
  340. @property
  341. def instances(self):
  342. return self._instance_svc
  343. @property
  344. def regions(self):
  345. return self._region_svc
  346. class AWSInstanceService(BaseInstanceService):
  347. def __init__(self, provider):
  348. super(AWSInstanceService, self).__init__(provider)
  349. self.svc = BotoEC2Service(provider=self.provider,
  350. cb_resource=AWSInstance,
  351. boto_collection_name='instances')
  352. def create(self, label, image, vm_type, subnet, zone,
  353. key_pair=None, vm_firewalls=None, user_data=None,
  354. launch_config=None, **kwargs):
  355. log.debug("Creating AWS Instance Service with the params "
  356. "[label: %s image: %s type: %s subnet: %s zone: %s "
  357. "key pair: %s firewalls: %s user data: %s config %s "
  358. "others: %s]", label, image, vm_type, subnet, zone,
  359. key_pair, vm_firewalls, user_data, launch_config, kwargs)
  360. AWSInstance.assert_valid_resource_label(label)
  361. image_id = image.id if isinstance(image, MachineImage) else image
  362. vm_size = vm_type.id if \
  363. isinstance(vm_type, VMType) else vm_type
  364. subnet = (self.provider.networking.subnets.get(subnet)
  365. if isinstance(subnet, str) else subnet)
  366. zone_id = zone.id if isinstance(zone, PlacementZone) else zone
  367. key_pair_name = key_pair.name if isinstance(
  368. key_pair,
  369. KeyPair) else key_pair
  370. if launch_config:
  371. bdm = self._process_block_device_mappings(launch_config)
  372. else:
  373. bdm = None
  374. subnet_id, zone_id, vm_firewall_ids = \
  375. self._resolve_launch_options(subnet, zone_id, vm_firewalls)
  376. placement = {'AvailabilityZone': zone_id} if zone_id else None
  377. inst = self.svc.create('create_instances',
  378. ImageId=image_id,
  379. MinCount=1,
  380. MaxCount=1,
  381. KeyName=key_pair_name,
  382. SecurityGroupIds=vm_firewall_ids or None,
  383. UserData=str(user_data) or None,
  384. InstanceType=vm_size,
  385. Placement=placement,
  386. BlockDeviceMappings=bdm,
  387. SubnetId=subnet_id
  388. )
  389. if inst and len(inst) == 1:
  390. # Wait until the resource exists
  391. # pylint:disable=protected-access
  392. inst[0]._wait_till_exists()
  393. # Tag the instance w/ the name
  394. inst[0].label = label
  395. return inst[0]
  396. raise ValueError(
  397. 'Expected a single object response, got a list: %s' % inst)
  398. def _resolve_launch_options(self, subnet=None, zone_id=None,
  399. vm_firewalls=None):
  400. """
  401. Work out interdependent launch options.
  402. Some launch options are required and interdependent so make sure
  403. they conform to the interface contract.
  404. :type subnet: ``Subnet``
  405. :param subnet: Subnet object within which to launch.
  406. :type zone_id: ``str``
  407. :param zone_id: ID of the zone where the launch should happen.
  408. :type vm_firewalls: ``list`` of ``id``
  409. :param vm_firewalls: List of firewall IDs.
  410. :rtype: triplet of ``str``
  411. :return: Subnet ID, zone ID and VM firewall IDs for launch.
  412. :raise ValueError: In case a conflicting combination is found.
  413. """
  414. if subnet:
  415. # subnet's zone takes precedence
  416. zone_id = subnet.zone.id
  417. if isinstance(vm_firewalls, list) and isinstance(
  418. vm_firewalls[0], VMFirewall):
  419. vm_firewall_ids = [fw.id for fw in vm_firewalls]
  420. else:
  421. vm_firewall_ids = vm_firewalls
  422. return subnet.id, zone_id, vm_firewall_ids
  423. def _process_block_device_mappings(self, launch_config):
  424. """
  425. Processes block device mapping information
  426. and returns a Boto BlockDeviceMapping object. If new volumes
  427. are requested (source is None and destination is VOLUME), they will be
  428. created and the relevant volume ids included in the mapping.
  429. """
  430. bdml = []
  431. # Assign letters from f onwards
  432. # http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/device_naming.html
  433. next_letter = iter(list(string.ascii_lowercase[6:]))
  434. # assign ephemeral devices from 0 onwards
  435. ephemeral_counter = 0
  436. for device in launch_config.block_devices:
  437. bdm = {}
  438. if device.is_volume:
  439. # Generate the device path
  440. bdm['DeviceName'] = \
  441. '/dev/sd' + ('a1' if device.is_root else next(next_letter))
  442. ebs_def = {}
  443. if isinstance(device.source, Snapshot):
  444. ebs_def['SnapshotId'] = device.source.id
  445. elif isinstance(device.source, Volume):
  446. # TODO: We could create a snapshot from the volume
  447. # and use that instead.
  448. # Not supported
  449. pass
  450. elif isinstance(device.source, MachineImage):
  451. # Not supported
  452. pass
  453. else:
  454. # source is None, but destination is volume, therefore
  455. # create a blank volume. This requires a size though.
  456. if not device.size:
  457. raise InvalidConfigurationException(
  458. "The source is none and the destination is a"
  459. " volume. Therefore, you must specify a size.")
  460. ebs_def['DeleteOnTermination'] = device.delete_on_terminate \
  461. or True
  462. if device.size:
  463. ebs_def['VolumeSize'] = device.size
  464. if ebs_def:
  465. bdm['Ebs'] = ebs_def
  466. else: # device is ephemeral
  467. bdm['VirtualName'] = 'ephemeral%s' % ephemeral_counter
  468. # Append the config
  469. bdml.append(bdm)
  470. return bdml
  471. def create_launch_config(self):
  472. return AWSLaunchConfig(self.provider)
  473. def get(self, instance_id):
  474. return self.svc.get(instance_id)
  475. def find(self, **kwargs):
  476. label = kwargs.pop('label', None)
  477. # All kwargs should have been popped at this time.
  478. if len(kwargs) > 0:
  479. raise TypeError("Unrecognised parameters for search: %s."
  480. " Supported attributes: %s" % (kwargs, 'label'))
  481. return self.svc.find(filter_name='tag:Name', filter_value=label)
  482. def list(self, limit=None, marker=None):
  483. return self.svc.list(limit=limit, marker=marker)
  484. class AWSVMTypeService(BaseVMTypeService):
  485. def __init__(self, provider):
  486. super(AWSVMTypeService, self).__init__(provider)
  487. @property
  488. def instance_data(self):
  489. """
  490. Fetch info about the available instances.
  491. To update this information, update the file pointed to by the
  492. ``provider.AWS_INSTANCE_DATA_DEFAULT_URL`` above. The content for this
  493. file should be obtained from this repo:
  494. https://github.com/powdahound/ec2instances.info (in particular, this
  495. file: https://raw.githubusercontent.com/powdahound/ec2instances.info/
  496. master/www/instances.json).
  497. TODO: Needs a caching function with timeout
  498. """
  499. r = requests.get(self.provider.config.get(
  500. "aws_instance_info_url",
  501. self.provider.AWS_INSTANCE_DATA_DEFAULT_URL))
  502. return r.json()
  503. def list(self, limit=None, marker=None):
  504. vm_types = [AWSVMType(self.provider, vm_type)
  505. for vm_type in self.instance_data]
  506. return ClientPagedResultList(self.provider, vm_types,
  507. limit=limit, marker=marker)
  508. class AWSRegionService(BaseRegionService):
  509. def __init__(self, provider):
  510. super(AWSRegionService, self).__init__(provider)
  511. def get(self, region_id):
  512. log.debug("Getting AWS Region Service with the id: %s",
  513. region_id)
  514. region = [r for r in self if r.id == region_id]
  515. if region:
  516. return region[0]
  517. else:
  518. return None
  519. def list(self, limit=None, marker=None):
  520. regions = [
  521. AWSRegion(self.provider, region) for region in
  522. self.provider.ec2_conn.meta.client.describe_regions()
  523. .get('Regions', [])]
  524. return ClientPagedResultList(self.provider, regions,
  525. limit=limit, marker=marker)
  526. @property
  527. def current(self):
  528. return self.get(self._provider.region_name)
  529. class AWSNetworkingService(BaseNetworkingService):
  530. def __init__(self, provider):
  531. super(AWSNetworkingService, self).__init__(provider)
  532. self._network_service = AWSNetworkService(self.provider)
  533. self._subnet_service = AWSSubnetService(self.provider)
  534. self._router_service = AWSRouterService(self.provider)
  535. @property
  536. def networks(self):
  537. return self._network_service
  538. @property
  539. def subnets(self):
  540. return self._subnet_service
  541. @property
  542. def routers(self):
  543. return self._router_service
  544. class AWSNetworkService(BaseNetworkService):
  545. def __init__(self, provider):
  546. super(AWSNetworkService, self).__init__(provider)
  547. self.svc = BotoEC2Service(provider=self.provider,
  548. cb_resource=AWSNetwork,
  549. boto_collection_name='vpcs')
  550. def get(self, network_id):
  551. log.debug("Getting AWS Network Service with the id: %s",
  552. network_id)
  553. return self.svc.get(network_id)
  554. def list(self, limit=None, marker=None):
  555. return self.svc.list(limit=limit, marker=marker)
  556. def find(self, **kwargs):
  557. label = kwargs.pop('label', None)
  558. # All kwargs should have been popped at this time.
  559. if len(kwargs) > 0:
  560. raise TypeError("Unrecognised parameters for search: %s."
  561. " Supported attributes: %s" % (kwargs, 'label'))
  562. log.debug("Searching for AWS Network Service %s", label)
  563. return self.svc.find(filter_name='tag:Name', filter_value=label)
  564. def create(self, label, cidr_block):
  565. log.debug("Creating AWS Network Service with the params "
  566. "[label: %s block: %s]", label, cidr_block)
  567. AWSNetwork.assert_valid_resource_label(label)
  568. cb_net = self.svc.create('create_vpc', CidrBlock=cidr_block)
  569. # Wait until ready to tag instance
  570. cb_net.wait_till_ready()
  571. if label:
  572. cb_net.label = label
  573. return cb_net
  574. class AWSSubnetService(BaseSubnetService):
  575. def __init__(self, provider):
  576. super(AWSSubnetService, self).__init__(provider)
  577. self.svc = BotoEC2Service(provider=self.provider,
  578. cb_resource=AWSSubnet,
  579. boto_collection_name='subnets')
  580. def get(self, subnet_id):
  581. log.debug("Getting AWS Subnet Service with the id: %s", subnet_id)
  582. return self.svc.get(subnet_id)
  583. def list(self, network=None, limit=None, marker=None):
  584. network_id = network.id if isinstance(network, AWSNetwork) else network
  585. if network_id:
  586. return self.svc.find(
  587. filter_name='vpc-id', filter_value=network_id,
  588. limit=limit, marker=marker)
  589. else:
  590. return self.svc.list(limit=limit, marker=marker)
  591. def find(self, **kwargs):
  592. label = kwargs.pop('label', None)
  593. # All kwargs should have been popped at this time.
  594. if len(kwargs) > 0:
  595. raise TypeError("Unrecognised parameters for search: %s."
  596. " Supported attributes: %s" % (kwargs, 'label'))
  597. log.debug("Searching for AWS Subnet Service %s", label)
  598. return self.svc.find(filter_name='tag:Name', filter_value=label)
  599. def create(self, label, network, cidr_block, zone):
  600. log.debug("Creating AWS Subnet Service with the params "
  601. "[label: %s network: %s block: %s zone: %s]",
  602. label, network, cidr_block, zone)
  603. AWSSubnet.assert_valid_resource_label(label)
  604. network_id = network.id if isinstance(network, AWSNetwork) else network
  605. subnet = self.svc.create('create_subnet',
  606. VpcId=network_id,
  607. CidrBlock=cidr_block,
  608. AvailabilityZone=zone)
  609. if label:
  610. subnet.label = label
  611. return subnet
  612. def get_or_create_default(self, zone):
  613. zone_name = zone.name if isinstance(
  614. zone, AWSPlacementZone) else zone
  615. snl = self.svc.find('availabilityZone', zone_name)
  616. # Find first available default subnet by sorted order
  617. # of availability zone. (e.g. prefer us-east-1a over 1e,
  618. # This is because newer zones tend to have less compatibility
  619. # with different instance types. (e.g. c5.large not available
  620. # on us-east-1e as of 14 Dec. 2017
  621. # pylint:disable=protected-access
  622. snl.sort(key=lambda sn: sn._subnet.availability_zone)
  623. for sn in snl:
  624. # pylint:disable=protected-access
  625. if sn._subnet.default_for_az:
  626. return sn
  627. # No provider-default Subnet exists, look for a library-default one
  628. for sn in snl:
  629. # pylint:disable=protected-access
  630. for tag in sn._subnet.tags or {}:
  631. if (tag.get('Key') == 'Name' and
  632. tag.get('Value') == AWSSubnet.CB_DEFAULT_SUBNET_LABEL):
  633. return sn
  634. # No provider-default Subnet exists, try to create it (net + subnets)
  635. default_net = self.provider.networking.networks.create(
  636. label=AWSNetwork.CB_DEFAULT_NETWORK_LABEL,
  637. cidr_block='10.0.0.0/16')
  638. # Create a subnet in each of the region's zones
  639. region = self.provider.compute.regions.get(self.provider.region_name)
  640. default_sn = None
  641. for i, z in enumerate(region.zones):
  642. sn = self.create(AWSSubnet.CB_DEFAULT_SUBNET_LABEL, default_net,
  643. '10.0.{0}.0/24'.format(i), z)
  644. if zone and zone == z.name:
  645. default_sn = sn
  646. # No specific zone was supplied; return the last created subnet
  647. if not default_sn:
  648. default_sn = sn
  649. return default_sn
  650. def delete(self, subnet):
  651. log.debug("Deleting AWS Subnet Service: %s", subnet)
  652. subnet_id = subnet.id if isinstance(subnet, AWSSubnet) else subnet
  653. self.svc.delete(subnet_id)
  654. class AWSRouterService(BaseRouterService):
  655. """For AWS, a CloudBridge router corresponds to an AWS Route Table."""
  656. def __init__(self, provider):
  657. super(AWSRouterService, self).__init__(provider)
  658. self.svc = BotoEC2Service(provider=self.provider,
  659. cb_resource=AWSRouter,
  660. boto_collection_name='route_tables')
  661. def get(self, router_id):
  662. log.debug("Getting AWS Router Service with the id: %s", router_id)
  663. return self.svc.get(router_id)
  664. def find(self, **kwargs):
  665. label = kwargs.pop('label', None)
  666. # All kwargs should have been popped at this time.
  667. if len(kwargs) > 0:
  668. raise TypeError("Unrecognised parameters for search: %s."
  669. " Supported attributes: %s" % (kwargs, 'label'))
  670. log.debug("Searching for AWS Router Service %s", label)
  671. return self.svc.find(filter_name='tag:Name', filter_value=label)
  672. def list(self, limit=None, marker=None):
  673. return self.svc.list(limit=limit, marker=marker)
  674. def create(self, label, network):
  675. log.debug("Creating AWS Router Service with the params "
  676. "[label: %s network: %s]", label, network)
  677. AWSRouter.assert_valid_resource_label(label)
  678. network_id = network.id if isinstance(network, AWSNetwork) else network
  679. cb_router = self.svc.create('create_route_table', VpcId=network_id)
  680. if label:
  681. cb_router.label = label
  682. return cb_router