1 # -*- coding: utf-8 -*-
4 # Copyright 2017 xFlow Research Pvt. Ltd
5 # This file is part of openmano
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
12 # http://www.apache.org/licenses/LICENSE-2.0
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: saboor.ahmad@xflowresearch.com
25 AWS-connector implements all the methods to interact with AWS using the BOTO client
28 __author__
= "Saboor Ahmad"
29 __date__
= "10-Apr-2017"
31 from osm_ro_plugin
import vimconn
42 class vimconnector(vimconn
.VimConnector
):
43 def __init__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
=None, user
=None, passwd
=None, log_level
=None,
44 config
={}, persistent_info
={}):
45 """ Params: uuid - id asigned to this VIM
46 name - name assigned to this VIM, can be used for logging
47 tenant_id - ID to be used for tenant
48 tenant_name - name of tenant to be used VIM tenant to be used
49 url_admin - optional, url used for administrative tasks
50 user - credentials of the VIM user
51 passwd - credentials of the VIM user
52 log_level - if must use a different log_level than the general one
53 config - dictionary with misc VIM information
54 region_name - name of region to deploy the instances
55 vpc_cidr_block - default CIDR block for VPC
56 security_groups - default security group to specify this instance
57 persistent_info - dict where the class can store information that will be available among class
58 destroy/creation cycles. This info is unique per VIM/credential. At first call it will contain an
59 empty dict. Useful to store login/tokens information for speed up communication
62 vimconn
.VimConnector
.__init
__(self
, uuid
, name
, tenant_id
, tenant_name
, url
, url_admin
, user
, passwd
, log_level
,
63 config
, persistent_info
)
65 self
.persistent_info
= persistent_info
68 self
.a_creds
['aws_access_key_id'] = user
70 raise vimconn
.VimConnAuthException("Username is not specified")
72 self
.a_creds
['aws_secret_access_key'] = passwd
74 raise vimconn
.VimConnAuthException("Password is not specified")
75 if 'region_name' in config
:
76 self
.region
= config
.get('region_name')
78 raise vimconn
.VimConnException("AWS region_name is not specified at config")
84 self
.account_id
= None
86 self
.vpc_id
= self
.get_tenant_list()[0]['id']
87 # we take VPC CIDR block if specified, otherwise we use the default CIDR
88 # block suggested by AWS while creating instance
89 self
.vpc_cidr_block
= '10.0.0.0/24'
92 self
.vpc_id
= tenant_id
93 if 'vpc_cidr_block' in config
:
94 self
.vpc_cidr_block
= config
['vpc_cidr_block']
96 self
.security_groups
= None
97 if 'security_groups' in config
:
98 self
.security_groups
= config
['security_groups']
101 if 'key_pair' in config
:
102 self
.key_pair
= config
['key_pair']
104 self
.flavor_info
= None
105 if 'flavor_info' in config
:
106 flavor_data
= config
.get('flavor_info')
107 if isinstance(flavor_data
, str):
109 if flavor_data
[0] == "@": # read from a file
110 with
open(flavor_data
[1:], 'r') as stream
:
111 self
.flavor_info
= yaml
.load(stream
, Loader
=yaml
.Loader
)
113 self
.flavor_info
= yaml
.load(flavor_data
, Loader
=yaml
.Loader
)
114 except yaml
.YAMLError
as e
:
115 self
.flavor_info
= None
116 raise vimconn
.VimConnException("Bad format at file '{}': {}".format(flavor_data
[1:], e
))
118 raise vimconn
.VimConnException("Error reading file '{}': {}".format(flavor_data
[1:], e
))
119 elif isinstance(flavor_data
, dict):
120 self
.flavor_info
= flavor_data
122 self
.logger
= logging
.getLogger('openmano.vim.aws')
124 self
.logger
.setLevel(getattr(logging
, log_level
))
126 def __setitem__(self
, index
, value
):
127 """Params: index - name of value of set
131 self
.a_creds
['aws_access_key_id'] = value
132 elif index
== 'passwd':
133 self
.a_creds
['aws_secret_access_key'] = value
134 elif index
== 'region':
137 vimconn
.VimConnector
.__setitem
__(self
, index
, value
)
139 def _reload_connection(self
):
140 """Returns: sets boto.EC2 and boto.VPC connection to work with AWS services
144 self
.conn
= boto
.ec2
.connect_to_region(self
.region
, aws_access_key_id
=self
.a_creds
['aws_access_key_id'],
145 aws_secret_access_key
=self
.a_creds
['aws_secret_access_key'])
146 self
.conn_vpc
= boto
.vpc
.connect_to_region(self
.region
, aws_access_key_id
=self
.a_creds
['aws_access_key_id'],
147 aws_secret_access_key
=self
.a_creds
['aws_secret_access_key'])
148 # client = boto3.client("sts", aws_access_key_id=self.a_creds['aws_access_key_id'],
149 # aws_secret_access_key=self.a_creds['aws_secret_access_key'])
150 # self.account_id = client.get_caller_identity()["Account"]
151 except Exception as e
:
152 self
.format_vimconn_exception(e
)
154 def format_vimconn_exception(self
, e
):
155 """Params: an Exception object
156 Returns: Raises the exception 'e' passed in mehtod parameters
161 raise vimconn
.VimConnConnectionException(type(e
).__name
__ + ": " + str(e
))
163 def get_availability_zones_list(self
):
164 """Obtain AvailabilityZones from AWS
168 self
._reload
_connection
()
170 for az
in self
.conn
.get_all_zones():
171 az_list
.append(az
.name
)
173 except Exception as e
:
174 self
.format_vimconn_exception(e
)
176 def get_tenant_list(self
, filter_dict
={}):
177 """Obtain tenants of VIM
178 filter_dict dictionary that can contain the following keys:
179 name: filter by tenant name
180 id: filter by tenant uuid/id
182 Returns the tenant list of dictionaries, and empty list if no tenant match all the filers:
183 [{'name':'<name>, 'id':'<id>, ...}, ...]
187 self
._reload
_connection
()
190 if filter_dict
!= {}:
191 if 'id' in filter_dict
:
192 vpc_ids
.append(filter_dict
['id'])
193 tfilters
['name'] = filter_dict
['id']
194 tenants
= self
.conn_vpc
.get_all_vpcs(vpc_ids
, tfilters
)
196 for tenant
in tenants
:
197 tenant_list
.append({'id': str(tenant
.id), 'name': str(tenant
.id), 'status': str(tenant
.state
),
198 'cidr_block': str(tenant
.cidr_block
)})
200 except Exception as e
:
201 self
.format_vimconn_exception(e
)
203 def new_tenant(self
, tenant_name
, tenant_description
):
204 """Adds a new tenant to VIM with this name and description, this is done using admin_url if provided
205 "tenant_name": string max lenght 64
206 "tenant_description": string max length 256
207 returns the tenant identifier or raise exception
210 self
.logger
.debug("Adding a new VPC")
212 self
._reload
_connection
()
213 vpc
= self
.conn_vpc
.create_vpc(self
.vpc_cidr_block
)
214 self
.conn_vpc
.modify_vpc_attribute(vpc
.id, enable_dns_support
=True)
215 self
.conn_vpc
.modify_vpc_attribute(vpc
.id, enable_dns_hostnames
=True)
217 gateway
= self
.conn_vpc
.create_internet_gateway()
218 self
.conn_vpc
.attach_internet_gateway(gateway
.id, vpc
.id)
219 route_table
= self
.conn_vpc
.create_route_table(vpc
.id)
220 self
.conn_vpc
.create_route(route_table
.id, '0.0.0.0/0', gateway
.id)
222 self
.vpc_data
[vpc
.id] = {'gateway': gateway
.id, 'route_table': route_table
.id,
223 'subnets': self
.subnet_sizes(len(self
.get_availability_zones_list()),
224 self
.vpc_cidr_block
)}
226 except Exception as e
:
227 self
.format_vimconn_exception(e
)
229 def delete_tenant(self
, tenant_id
):
230 """Delete a tenant from VIM
231 tenant_id: returned VIM tenant_id on "new_tenant"
232 Returns None on success. Raises and exception of failure. If tenant is not found raises vimconnNotFoundException
235 self
.logger
.debug("Deleting specified VPC")
237 self
._reload
_connection
()
238 vpc
= self
.vpc_data
.get(tenant_id
)
239 if 'gateway' in vpc
and 'route_table' in vpc
:
240 gateway_id
, route_table_id
= vpc
['gateway'], vpc
['route_table']
241 self
.conn_vpc
.detach_internet_gateway(gateway_id
, tenant_id
)
242 self
.conn_vpc
.delete_vpc(tenant_id
)
243 self
.conn_vpc
.delete_route(route_table_id
, '0.0.0.0/0')
245 self
.conn_vpc
.delete_vpc(tenant_id
)
246 except Exception as e
:
247 self
.format_vimconn_exception(e
)
249 def subnet_sizes(self
, availability_zones
, cidr
):
250 """Calcualtes possible subnets given CIDR value of VPC
253 if availability_zones
!= 2 and availability_zones
!= 3:
254 self
.logger
.debug("Number of AZs should be 2 or 3")
255 raise vimconn
.VimConnNotSupportedException("Number of AZs should be 2 or 3")
257 netmasks
= ('255.255.252.0', '255.255.254.0', '255.255.255.0', '255.255.255.128')
258 ip
= netaddr
.IPNetwork(cidr
)
261 if str(mask
) not in netmasks
:
262 self
.logger
.debug("Netmask " + str(mask
) + " not found")
263 raise vimconn
.VimConnNotFoundException("Netmask " + str(mask
) + " not found")
265 if availability_zones
== 2:
266 for n
, netmask
in enumerate(netmasks
):
267 if str(mask
) == netmask
:
268 subnets
= list(ip
.subnet(n
+ 24))
270 for n
, netmask
in enumerate(netmasks
):
271 if str(mask
) == netmask
:
272 pub_net
= list(ip
.subnet(n
+ 24))
273 pri_subs
= pub_net
[1:]
274 pub_mask
= pub_net
[0].netmask
275 pub_split
= list(ip
.subnet(26)) if (str(pub_mask
) == '255.255.255.0') else list(ip
.subnet(27))
276 pub_subs
= pub_split
[:3]
277 subnets
= pub_subs
+ pri_subs
279 return map(str, subnets
)
281 def new_network(self
, net_name
, net_type
, ip_profile
=None, shared
=False, provider_network_profile
=None):
282 """Adds a tenant network to VIM
284 'net_name': name of the network
286 'bridge': overlay isolated network
287 'data': underlay E-LAN network for Passthrough and SRIOV interfaces
288 'ptp': underlay E-LINE network for Passthrough and SRIOV interfaces.
289 'ip_profile': is a dict containing the IP parameters of the network (Currently only IPv4 is implemented)
290 'ip-version': can be one of ["IPv4","IPv6"]
291 'subnet-address': ip_prefix_schema, that is X.X.X.X/Y
292 'gateway-address': (Optional) ip_schema, that is X.X.X.X
293 'dns-address': (Optional) ip_schema,
294 'dhcp': (Optional) dict containing
295 'enabled': {"type": "boolean"},
296 'start-address': ip_schema, first IP to grant
297 'count': number of IPs to grant.
298 'shared': if this network can be seen/use by other tenants/organization
299 Returns a tuple with the network identifier and created_items, or raises an exception on error
300 created_items can be None or a dictionary where this method can include key-values that will be passed to
301 the method delete_network. Can be used to store created segments, created l2gw connections, etc.
302 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
306 self
.logger
.debug("Adding a subnet to VPC")
309 self
._reload
_connection
()
312 if self
.vpc_data
.get(vpc_id
, None):
313 cidr_block
= list(set(self
.vpc_data
[vpc_id
]['subnets']) -
314 set(self
.get_network_details({'tenant_id': vpc_id
}, detail
='cidr_block')))[0]
316 vpc
= self
.get_tenant_list({'id': vpc_id
})[0]
317 subnet_list
= self
.subnet_sizes(len(self
.get_availability_zones_list()), vpc
['cidr_block'])
318 cidr_block
= list(set(subnet_list
) - set(self
.get_network_details({'tenant_id': vpc
['id']},
319 detail
='cidr_block')))[0]
320 subnet
= self
.conn_vpc
.create_subnet(vpc_id
, cidr_block
)
321 return subnet
.id, created_items
322 except Exception as e
:
323 self
.format_vimconn_exception(e
)
325 def get_network_details(self
, filters
, detail
):
326 """Get specified details related to a subnet
329 subnet_list
= self
.get_network_list(filters
)
330 for net
in subnet_list
:
331 detail_list
.append(net
[detail
])
334 def get_network_list(self
, filter_dict
={}):
335 """Obtain tenant networks of VIM
337 'filter_dict' (optional) contains entries to return only networks that matches ALL entries:
338 name: string => returns only networks with this name
339 id: string => returns networks with this VIM id, this imply returns one network at most
340 shared: boolean >= returns only networks that are (or are not) shared
341 tenant_id: sting => returns only networks that belong to this tenant/project
342 ,#(not used yet) admin_state_up: boolean => returns only networks that are (or are not) in admin
344 #(not used yet) status: 'ACTIVE','ERROR',... => filter networks that are on this status
345 Returns the network list of dictionaries. each dictionary contains:
346 'id': (mandatory) VIM network id
347 'name': (mandatory) VIM network name
348 'status': (mandatory) can be 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
349 'error_msg': (optional) text that explains the ERROR status
350 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
351 List can be empty if no network map the filter_dict. Raise an exception only upon VIM connectivity,
352 authorization, or some other unspecific error
355 self
.logger
.debug("Getting all subnets from VIM")
357 self
._reload
_connection
()
359 if filter_dict
!= {}:
360 if 'tenant_id' in filter_dict
:
361 tfilters
['vpcId'] = filter_dict
['tenant_id']
362 subnets
= self
.conn_vpc
.get_all_subnets(subnet_ids
=filter_dict
.get('name', None), filters
=tfilters
)
366 {'id': str(net
.id), 'name': str(net
.id), 'status': str(net
.state
), 'vpc_id': str(net
.vpc_id
),
367 'cidr_block': str(net
.cidr_block
), 'type': 'bridge'})
369 except Exception as e
:
370 self
.format_vimconn_exception(e
)
372 def get_network(self
, net_id
):
373 """Obtain network details from the 'net_id' VIM network
374 Return a dict that contains:
375 'id': (mandatory) VIM network id, that is, net_id
376 'name': (mandatory) VIM network name
377 'status': (mandatory) can be 'ACTIVE', 'INACTIVE', 'DOWN', 'BUILD', 'ERROR', 'VIM_ERROR', 'OTHER'
378 'error_msg': (optional) text that explains the ERROR status
379 other VIM specific fields: (optional) whenever possible using the same naming of filter_dict param
380 Raises an exception upon error or when network is not found
383 self
.logger
.debug("Getting Subnet from VIM")
385 self
._reload
_connection
()
386 subnet
= self
.conn_vpc
.get_all_subnets(net_id
)[0]
387 return {'id': str(subnet
.id), 'name': str(subnet
.id), 'status': str(subnet
.state
),
388 'vpc_id': str(subnet
.vpc_id
), 'cidr_block': str(subnet
.cidr_block
)}
389 except Exception as e
:
390 self
.format_vimconn_exception(e
)
392 def delete_network(self
, net_id
, created_items
=None):
394 Removes a tenant network from VIM and its associated elements
395 :param net_id: VIM identifier of the network, provided by method new_network
396 :param created_items: dictionary with extra items to be deleted. provided by method new_network
397 Returns the network identifier or raises an exception upon error or when network is not found
400 self
.logger
.debug("Deleting subnet from VIM")
402 self
._reload
_connection
()
403 self
.logger
.debug("DELETING NET_ID: " + str(net_id
))
404 self
.conn_vpc
.delete_subnet(net_id
)
406 except Exception as e
:
407 self
.format_vimconn_exception(e
)
409 def refresh_nets_status(self
, net_list
):
410 """Get the status of the networks
412 'net_list': a list with the VIM network id to be get the status
413 Returns a dictionary with:
414 'net_id': #VIM id of this network
415 status: #Mandatory. Text with one of:
416 # DELETED (not found at vim)
417 # VIM_ERROR (Cannot connect to VIM, authentication problems, VIM response error, ...)
418 # OTHER (Vim reported other status not understood)
419 # ERROR (VIM indicates an ERROR status)
420 # ACTIVE, INACTIVE, DOWN (admin down),
421 # BUILD (on building process)
422 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
423 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
427 self
._reload
_connection
()
430 for net_id
in net_list
:
434 subnet
= self
.conn_vpc
.get_all_subnets(net_id
)[0]
435 if subnet
.state
== "pending":
436 subnet_dict
['status'] = "BUILD"
437 elif subnet
.state
== "available":
438 subnet_dict
['status'] = 'ACTIVE'
440 subnet_dict
['status'] = 'ERROR'
441 subnet_dict
['error_msg'] = ''
443 subnet_dict
['status'] = 'DELETED'
444 subnet_dict
['error_msg'] = 'Network not found'
447 subnet_dict
['vim_info'] = yaml
.safe_dump(subnet
, default_flow_style
=True, width
=256)
448 except yaml
.YAMLError
:
449 subnet_dict
['vim_info'] = str(subnet
)
450 dict_entry
[net_id
] = subnet_dict
452 except Exception as e
:
453 self
.format_vimconn_exception(e
)
455 def get_flavor(self
, flavor_id
):
456 """Obtain flavor details from the VIM
457 Returns the flavor dict details {'id':<>, 'name':<>, other vim specific }
458 Raises an exception upon error or if not found
461 self
.logger
.debug("Getting instance type")
463 if flavor_id
in self
.flavor_info
:
464 return self
.flavor_info
[flavor_id
]
466 raise vimconn
.VimConnNotFoundException("Cannot find flavor with this flavor ID/Name")
467 except Exception as e
:
468 self
.format_vimconn_exception(e
)
470 def get_flavor_id_from_data(self
, flavor_dict
):
471 """Obtain flavor id that match the flavor description
473 'flavor_dict': dictionary that contains:
474 'disk': main hard disk in GB
476 'vcpus': number of virtual cpus
477 #todo: complete parameters for EPA
478 Returns the flavor_id or raises a vimconnNotFoundException
481 self
.logger
.debug("Getting flavor id from data")
484 for key
, values
in self
.flavor_info
.items():
485 if (values
["ram"], values
["cpus"], values
["disk"]) == (
486 flavor_dict
["ram"], flavor_dict
["vcpus"], flavor_dict
["disk"]):
487 flavor
= (key
, values
)
489 elif (values
["ram"], values
["cpus"], values
["disk"]) >= (
490 flavor_dict
["ram"], flavor_dict
["vcpus"], flavor_dict
["disk"]):
492 flavor
= (key
, values
)
494 if (flavor
[1]["ram"], flavor
[1]["cpus"], flavor
[1]["disk"]) >= (
495 values
["ram"], values
["cpus"], values
["disk"]):
496 flavor
= (key
, values
)
499 raise vimconn
.VimConnNotFoundException("Cannot find flavor with this flavor ID/Name")
500 except Exception as e
:
501 self
.format_vimconn_exception(e
)
503 def new_image(self
, image_dict
):
504 """ Adds a tenant image to VIM
506 name (string) - The name of the AMI. Valid only for EBS-based images.
507 description (string) - The description of the AMI.
508 image_location (string) - Full path to your AMI manifest in Amazon S3 storage. Only used for S3-based AMI’s.
509 architecture (string) - The architecture of the AMI. Valid choices are: * i386 * x86_64
510 kernel_id (string) - The ID of the kernel with which to launch the instances
511 root_device_name (string) - The root device name (e.g. /dev/sdh)
512 block_device_map (boto.ec2.blockdevicemapping.BlockDeviceMapping) - A BlockDeviceMapping data structure
513 describing the EBS volumes associated with the Image.
514 virtualization_type (string) - The virutalization_type of the image. Valid choices are: * paravirtual * hvm
515 sriov_net_support (string) - Advanced networking support. Valid choices are: * simple
516 snapshot_id (string) - A snapshot ID for the snapshot to be used as root device for the image. Mutually
517 exclusive with block_device_map, requires root_device_name
518 delete_root_volume_on_termination (bool) - Whether to delete the root volume of the image after instance
519 termination. Only applies when creating image from snapshot_id. Defaults to False. Note that leaving
520 volumes behind after instance termination is not free
521 Returns: image_id - image ID of the newly created image
525 self
._reload
_connection
()
526 image_location
= image_dict
.get('image_location', None)
528 image_location
= str(self
.account_id
) + str(image_location
)
530 image_id
= self
.conn
.register_image(image_dict
.get('name', None), image_dict
.get('description', None),
531 image_location
, image_dict
.get('architecture', None),
532 image_dict
.get('kernel_id', None),
533 image_dict
.get('root_device_name', None),
534 image_dict
.get('block_device_map', None),
535 image_dict
.get('virtualization_type', None),
536 image_dict
.get('sriov_net_support', None),
537 image_dict
.get('snapshot_id', None),
538 image_dict
.get('delete_root_volume_on_termination', None))
540 except Exception as e
:
541 self
.format_vimconn_exception(e
)
543 def delete_image(self
, image_id
):
544 """Deletes a tenant image from VIM
545 Returns the image_id if image is deleted or raises an exception on error"""
548 self
._reload
_connection
()
549 self
.conn
.deregister_image(image_id
)
551 except Exception as e
:
552 self
.format_vimconn_exception(e
)
554 def get_image_id_from_path(self
, path
):
556 Params: path - location of the image
557 Returns: image_id - ID of the matching image
559 self
._reload
_connection
()
563 tokens
= path
.split('/')
564 filters
['owner_id'] = tokens
[0]
565 filters
['name'] = '/'.join(tokens
[1:])
566 image
= self
.conn
.get_all_images(filters
=filters
)[0]
568 except Exception as e
:
569 self
.format_vimconn_exception(e
)
571 def get_image_list(self
, filter_dict
={}):
572 """Obtain tenant images from VIM
576 checksum: image checksum
578 Returns the image list of dictionaries:
579 [{<the fields at Filter_dict plus some VIM specific>}, ...]
583 self
.logger
.debug("Getting image list from VIM")
585 self
._reload
_connection
()
588 if 'id' in filter_dict
:
589 image_id
= filter_dict
['id']
590 if 'name' in filter_dict
:
591 filters
['name'] = filter_dict
['name']
592 if 'location' in filter_dict
:
593 filters
['location'] = filter_dict
['location']
594 # filters['image_type'] = 'machine'
595 # filter_dict['owner_id'] = self.account_id
596 images
= self
.conn
.get_all_images(image_id
, filters
=filters
)
599 image_list
.append({'id': str(image
.id), 'name': str(image
.name
), 'status': str(image
.state
),
600 'owner': str(image
.owner_id
), 'location': str(image
.location
),
601 'is_public': str(image
.is_public
), 'architecture': str(image
.architecture
),
602 'platform': str(image
.platform
)})
604 except Exception as e
:
605 self
.format_vimconn_exception(e
)
607 def new_vminstance(self
, name
, description
, start
, image_id
, flavor_id
, net_list
, cloud_config
=None,
608 disk_list
=None, availability_zone_index
=None, availability_zone_list
=None):
609 """Create a new VM/instance in AWS
612 start: (boolean) indicates if VM must start or created in pause mode.
613 image_id - image ID in AWS
614 flavor_id - instance type ID in AWS
617 net_id - subnet_id from AWS
618 vpci - (optional) virtual vPCI address to assign at the VM. Can be ignored depending on VIM
620 model: (optional and only have sense for type==virtual) interface model: virtio, e1000, ...
621 mac_address: (optional) mac address to assign to this interface
622 type: (mandatory) can be one of:
623 virtual, in this case always connected to a network of type 'net_type=bridge'
624 'PCI-PASSTHROUGH' or 'PF' (passthrough): depending on VIM capabilities it can be connected to a
625 data/ptp network ot it
626 can created unconnected
627 'SR-IOV' or 'VF' (SRIOV with VLAN tag): same as PF for network connectivity.
628 VFnotShared - (SRIOV without VLAN tag) same as PF for network connectivity. VF where no other
629 VFs are allocated on the same physical NIC
630 bw': (optional) only for PF/VF/VFnotShared. Minimal Bandwidth required for the interface in GBPS
631 port_security': (optional) If False it must avoid any traffic filtering at this interface.
632 If missing or True, it must apply the default VIM behaviour
633 vim_id': must be filled/added by this method with the VIM identifier generated by the VIM for this
634 interface. 'net_list' is modified
635 elastic_ip - True/False to define if an elastic_ip is required
636 cloud_config': (optional) dictionary with:
637 key-pairs': (optional) list of strings with the public key to be inserted to the default user
638 users': (optional) list of users to be inserted, each item is a dict with:
639 name': (mandatory) user name,
640 key-pairs': (optional) list of strings with the public key to be inserted to the user
641 user-data': (optional) string is a text script to be passed directly to cloud-init
642 config-files': (optional). List of files to be transferred. Each item is a dict with:
643 dest': (mandatory) string with the destination absolute path
644 encoding': (optional, by default text). Can be one of:
645 b64', 'base64', 'gz', 'gz+b64', 'gz+base64', 'gzip+b64', 'gzip+base64'
646 content' (mandatory): string with the content of the file
647 permissions': (optional) string with file permissions, typically octal notation '0644'
648 owner: (optional) file owner, string with the format 'owner:group'
649 boot-data-drive: boolean to indicate if user-data must be passed using a boot drive (hard disk)
653 disk_list': (optional) list with additional disks to the VM. Each item is a dict with:
654 image_id': (optional). VIM id of an existing image. If not provided an empty disk must be mounted
655 size': (mandatory) string with the size of the disk in GB
656 Returns a tuple with the instance identifier and created_items or raises an exception on error
657 created_items can be None or a dictionary where this method can include key-values that will be passed to
658 the method delete_vminstance and action_vminstance. Can be used to store created ports, volumes, etc.
659 Format is vimconnector dependent, but do not use nested dictionaries and a value of None should be the same
663 self
.logger
.debug("Creating a new VM instance")
665 self
._reload
_connection
()
667 _
, userdata
= self
._create
_user
_data
(cloud_config
)
670 reservation
= self
.conn
.run_instances(
672 key_name
=self
.key_pair
,
673 instance_type
=flavor_id
,
674 security_groups
=self
.security_groups
,
678 for index
, subnet
in enumerate(net_list
):
679 net_intr
= boto
.ec2
.networkinterface
.NetworkInterfaceSpecification(subnet_id
=subnet
.get('net_id'),
681 associate_public_ip_address
=True)
683 if subnet
.get('elastic_ip'):
684 eip
= self
.conn
.allocate_address()
685 self
.conn
.associate_address(allocation_id
=eip
.allocation_id
, network_interface_id
=net_intr
.id)
688 reservation
= self
.conn
.run_instances(
690 key_name
=self
.key_pair
,
691 instance_type
=flavor_id
,
692 security_groups
=self
.security_groups
,
693 network_interfaces
=boto
.ec2
.networkinterface
.NetworkInterfaceCollection(net_intr
),
699 self
.conn
.attach_network_interface(
700 network_interface_id
=boto
.ec2
.networkinterface
.NetworkInterfaceCollection(net_intr
),
701 instance_id
=instance
.id, device_index
=0)
705 net_list
[index
]['vim_id'] = reservation
.instances
[0].interfaces
[index
].id
707 instance
= reservation
.instances
[0]
708 return instance
.id, None
709 except Exception as e
:
710 self
.format_vimconn_exception(e
)
712 def get_vminstance(self
, vm_id
):
713 """Returns the VM instance information from VIM"""
716 self
._reload
_connection
()
717 reservation
= self
.conn
.get_all_instances(vm_id
)
718 return reservation
[0].instances
[0].__dict
__
719 except Exception as e
:
720 self
.format_vimconn_exception(e
)
722 def delete_vminstance(self
, vm_id
, created_items
=None):
723 """Removes a VM instance from VIM
724 Returns the instance identifier"""
727 self
._reload
_connection
()
728 self
.logger
.debug("DELETING VM_ID: " + str(vm_id
))
729 self
.conn
.terminate_instances(vm_id
)
731 except Exception as e
:
732 self
.format_vimconn_exception(e
)
734 def refresh_vms_status(self
, vm_list
):
735 """ Get the status of the virtual machines and their interfaces/ports
736 Params: the list of VM identifiers
737 Returns a dictionary with:
738 vm_id: #VIM id of this Virtual Machine
739 status: #Mandatory. Text with one of:
740 # DELETED (not found at vim)
741 # VIM_ERROR (Cannot connect to VIM, VIM response error, ...)
742 # OTHER (Vim reported other status not understood)
743 # ERROR (VIM indicates an ERROR status)
744 # ACTIVE, PAUSED, SUSPENDED, INACTIVE (not running),
745 # BUILD (on building process), ERROR
746 # ACTIVE:NoMgmtIP (Active but any of its interface has an IP address
748 error_msg: #Text with VIM error message, if any. Or the VIM connection ERROR
749 vim_info: #Text with plain information obtained from vim (yaml.safe_dump)
750 interfaces: list with interface info. Each item a dictionary with:
751 vim_interface_id - The ID of the ENI.
752 vim_net_id - The ID of the VPC subnet.
753 mac_address - The MAC address of the interface.
754 ip_address - The IP address of the interface within the subnet.
756 self
.logger
.debug("Getting VM instance information from VIM")
758 self
._reload
_connection
()
759 reservation
= self
.conn
.get_all_instances(vm_list
)[0]
762 for instance
in reservation
.instances
:
764 if instance
.state
in ("pending"):
765 instance_dict
['status'] = "BUILD"
766 elif instance
.state
in ("available", "running", "up"):
767 instance_dict
['status'] = 'ACTIVE'
769 instance_dict
['status'] = 'ERROR'
770 instance_dict
['error_msg'] = ""
771 instance_dict
['interfaces'] = []
773 for interface
in instance
.interfaces
:
774 interface_dict
['vim_interface_id'] = interface
.id
775 interface_dict
['vim_net_id'] = interface
.subnet_id
776 interface_dict
['mac_address'] = interface
.mac_address
777 if hasattr(interface
, 'publicIp') and interface
.publicIp
is not None:
778 interface_dict
['ip_address'] = interface
.publicIp
+ ";" + interface
.private_ip_address
780 interface_dict
['ip_address'] = interface
.private_ip_address
781 instance_dict
['interfaces'].append(interface_dict
)
782 except Exception as e
:
783 self
.logger
.error("Exception getting vm status: %s", str(e
), exc_info
=True)
784 instance_dict
['status'] = "DELETED"
785 instance_dict
['error_msg'] = str(e
)
788 instance_dict
['vim_info'] = yaml
.safe_dump(instance
, default_flow_style
=True, width
=256)
789 except yaml
.YAMLError
:
790 # self.logger.error("Exception getting vm status: %s", str(e), exc_info=True)
791 instance_dict
['vim_info'] = str(instance
)
792 instances
[instance
.id] = instance_dict
794 except Exception as e
:
795 self
.logger
.error("Exception getting vm status: %s", str(e
), exc_info
=True)
796 self
.format_vimconn_exception(e
)
798 def action_vminstance(self
, vm_id
, action_dict
, created_items
={}):
799 """Send and action over a VM instance from VIM
800 Returns the vm_id if the action was successfully sent to the VIM"""
802 self
.logger
.debug("Action over VM '%s': %s", vm_id
, str(action_dict
))
804 self
._reload
_connection
()
805 if "start" in action_dict
:
806 self
.conn
.start_instances(vm_id
)
807 elif "stop" in action_dict
or "stop" in action_dict
:
808 self
.conn
.stop_instances(vm_id
)
809 elif "terminate" in action_dict
:
810 self
.conn
.terminate_instances(vm_id
)
811 elif "reboot" in action_dict
:
812 self
.conn
.reboot_instances(vm_id
)
814 except Exception as e
:
815 self
.format_vimconn_exception(e
)