- Constructor for KeystoneDriver base class
- Arguments: None
- Returns: None
- """
- self.ksclient = ksclient
-
- def get_username(self):
- """
- Returns the username associated with keystoneclient connection
- """
- return self._username
-
- def get_password(self):
- """
- Returns the password associated with keystoneclient connection
- """
- return self._password
-
- def get_tenant_name(self):
- """
- Returns the tenant name associated with keystoneclient connection
- """
- return self._tenant_name
-
- def get_user_domain_name(self):
- """
- Returns None as this field does not exist for v2.
- """
- return None;
-
- def get_project_domain_name(self):
- """
- Returns None as this field does not exist for v2.
- """
- return None;
-
- def _get_keystone_connection(self):
- """
- Returns object of class python-keystoneclient class
- """
- if not hasattr(self, '_keystone_connection'):
- self._keystone_connection = self.ksclient(**self._get_keystone_credentials())
- return self._keystone_connection
-
- def is_auth_token_valid(self, token_expiry, time_fmt):
- """
- Performs validity on auth_token
- Arguments:
- token_expiry (string): Expiry time for token
- time_fmt (string) : Format for expiry string in auth_ref
-
- Returns:
- True/False (Boolean): (auth_token is valid or auth_token is invalid)
- """
- import time
- import datetime
- import dateutil.parser
- try:
- now = datetime.datetime.timetuple(datetime.datetime.utcnow())
- expires_at = dateutil.parser.parse(token_expiry)
- t_now = time.mktime(now)
- t_expiry = time.mktime(expires_at.timetuple())
-
- if (t_expiry <= t_now) or ((t_expiry - t_now) < 300 ):
- ### Token has expired or about to expire (5 minute)
- delattr(self, '_keystone_connection')
- return False
- else:
- return True
- except Exception as e:
- logger.error("Received except %s during auth_token validity check" %str(e))
- logger.info("Can not validate the auth_token. Assuming invalid")
- return False
-
-
- def get_service_endpoint(self, service_type, endpoint_type):
- """
- Returns requested type of endpoint for requested service type
- Arguments:
- service_type (string): Service Type (e.g. computev3, image, network)
- endpoint_type(string): Endpoint Type (e.g. publicURL,adminURL,internalURL)
- Returns:
- service_endpoint(string): Service endpoint string
- """
- endpoint_kwargs = {'service_type' : service_type,
- 'endpoint_type' : endpoint_type}
- try:
- ksconn = self._get_keystone_connection()
- service_endpoint = ksconn.service_catalog.url_for(**endpoint_kwargs)
- except (KeystoneExceptions.Unauthorized, KeystoneExceptions.AuthorizationFailure) as e:
- raise
- except Exception as e:
- logger.error("OpenstackDriver: Service Catalog discovery operation failed for service_type: %s, endpoint_type: %s. Exception: %s" %(service_type, endpoint_type, str(e)))
- raise
- return service_endpoint
-
-
- def get_raw_token(self):
- """
- Returns a valid raw_auth_token string
-
- Returns (string): raw_auth_token string
- """
- ksconn = self._get_keystone_connection()
- try:
- raw_token = ksconn.get_raw_token_from_identity_service(auth_url = self._auth_url,
- token = self.get_auth_token())
- except KeystoneExceptions.AuthorizationFailure as e:
- logger.error("OpenstackDriver: get_raw_token_from_identity_service Failure. Exception: %s" %(str(e)))
- return None
-
- except Exception as e:
- logger.error("OpenstackDriver: Could not retrieve raw_token. Exception: %s" %(str(e)))
-
- return raw_token
-
- def get_tenant_id(self):
- """
- Returns tenant_id for the project/tenant. Tenant name is provided during
- class instantiation
-
- Returns (string): Tenant ID
- """
- ksconn = self._get_keystone_connection()
- return ksconn.tenant_id
-
- def get_security_mode(self):
- """
- Returns certificate_validation policy in case of SSL/TLS connection.
- This policy is provided during class instantiation
-
- Returns (boolean):
- The boolean returned are designed to match the python-client class instantiation ("insecure") value.
- for nova/neutron/glance/keystone clients
-
- True: No certificate validation required -- Insecure mode
- False: Certificate validation required -- Secure mode
- """
- return self._insecure
-
- def tenant_list(self):
- """
- Returns list of tenants
- """
- pass
-
- def tenant_create(self, name):
- """
- Create a new tenant
- """
- pass
-
- def tenant_delete(self, tenant_id):
- """
- Deletes a tenant identified by tenant_id
- """
- pass
-
- def roles_list(self):
- pass
-
- def roles_create(self):
- pass
-
- def roles_delete(self):
- pass
-
-class KeystoneDriverV2(KeystoneDriver):
- """
- Driver class for keystoneclient V2 APIs
- """
- def __init__(self, username, password, auth_url,tenant_name, insecure, region):
- """
- Constructor for KeystoneDriverV3 class
- Arguments:
- username (string) : Username
- password (string) : Password
- auth_url (string) : Authentication URL
- tenant_name(string): Tenant Name
- region (string) : Region name
- Returns: None
- """
- self._username = username
- self._password = password
- self._auth_url = auth_url
- self._tenant_name = tenant_name
- self._insecure = insecure
- self._region = region
- super(KeystoneDriverV2, self).__init__(ksclientv2.Client)
-
- def _get_keystone_credentials(self):
- """
- Returns the dictionary of kwargs required to instantiate python-keystoneclient class
- """
- creds = {}
- #creds['user_domain'] = self._domain_name
- creds['username'] = self._username
- creds['password'] = self._password
- creds['auth_url'] = self._auth_url
- creds['tenant_name'] = self._tenant_name
- creds['insecure'] = self.get_security_mode()
- creds['region_name'] = self._region
- return creds
-
- def get_auth_token(self):
- """
- Returns a valid auth_token
-
- Returns (string): auth_token string
- """
- ksconn = self._get_keystone_connection()
- return ksconn.auth_token
-
- def is_auth_token_valid(self):
- """
- Performs validity on auth_token
- Arguments:
-
- Returns:
- True/False (Boolean): (auth_token is valid or auth_token is invalid)
- """
- ksconn = self._get_keystone_connection()
- result = super(KeystoneDriverV2, self).is_auth_token_valid(ksconn.auth_ref['token']['expires'],
- "%Y-%m-%dT%H:%M:%SZ")
- return result
-
-
-class KeystoneDriverV3(KeystoneDriver):
- """
- Driver class for keystoneclient V3 APIs
- """
- def __init__(self, username,
- password,
- auth_url,
- tenant_name,
- insecure,
- user_domain_name = None,
- project_domain_name = None,
- region = None):
- """
- Constructor for KeystoneDriverV3 class
- Arguments:
- username (string) : Username
- password (string) : Password
- auth_url (string) : Authentication URL
- tenant_name(string): Tenant Name
- user_domain_name (string) : User domain name
- project_domain_name (string): Project domain name
- region (string) : Region name
- Returns: None
- """
- self._username = username
- self._password = password
- self._auth_url = auth_url
- self._tenant_name = tenant_name
- self._insecure = insecure
- self._user_domain_name = user_domain_name
- self._project_domain_name = project_domain_name
- self._region = region
- super(KeystoneDriverV3, self).__init__(ksclientv3.Client)
-
- def _get_keystone_credentials(self):
- """
- Returns the dictionary of kwargs required to instantiate python-keystoneclient class
- """
- creds = {}
- creds['username'] = self._username
- creds['password'] = self._password
- creds['auth_url'] = self._auth_url
- creds['project_name'] = self._tenant_name
- creds['insecure'] = self._insecure
- creds['user_domain_name'] = self._user_domain_name
- creds['project_domain_name'] = self._project_domain_name
- creds['region_name'] = self._region
- return creds
-
- def get_user_domain_name(self):
- """
- Returns the domain_name of the associated OpenStack user account
- """
- return self._user_domain_name;
-
- def get_project_domain_name(self):
- """
- Returns the domain_name of the associated OpenStack project
- """
- return self._project_domain_name;
-
- def get_auth_token(self):
- """
- Returns a valid auth_token
-
- Returns (string): auth_token string
- """
- ksconn = self._get_keystone_connection()
- return ksconn.auth_ref['auth_token']
-
- def is_auth_token_valid(self):
- """
- Performs validity on auth_token
- Arguments:
-
- Returns:
- True/False (Boolean): (auth_token is valid or auth_token is invalid)
- """
- ksconn = self._get_keystone_connection()
- result = super(KeystoneDriverV3, self).is_auth_token_valid(ksconn.auth_ref['expires_at'],
- "%Y-%m-%dT%H:%M:%S.%fZ")
- return result
-
-class NovaDriver(object):
- """
- Driver for openstack nova_client
- """
- def __init__(self, ks_drv, service_name, version):
- """
- Constructor for NovaDriver
- Arguments: KeystoneDriver class object
- """
- self.ks_drv = ks_drv
- self._service_name = service_name
- self._version = version
-
- def _get_nova_credentials(self):
- """
- Returns a dictionary of kwargs required to instantiate python-novaclient class
- """
- creds = {}
- creds['version'] = self._version
- creds['bypass_url'] = self.ks_drv.get_service_endpoint(self._service_name, "publicURL")
- creds['username'] = self.ks_drv.get_username()
- creds['project_id'] = self.ks_drv.get_tenant_name()
- creds['auth_token'] = self.ks_drv.get_auth_token()
- creds['insecure'] = self.ks_drv.get_security_mode()
- #creds['user_domain_name'] = self.ks_drv.get_user_domain_name()
- #creds['project_domain_name'] = self.ks_drv.get_project_domain_name()
-
- return creds
-
- def _get_nova_connection(self):
- """
- Returns an object of class python-novaclient
- """
- if not hasattr(self, '_nova_connection'):
- self._nova_connection = nova_client.Client(**self._get_nova_credentials())
- else:
- # Reinitialize if auth_token is no longer valid
- if not self.ks_drv.is_auth_token_valid():
- self._nova_connection = nova_client.Client(**self._get_nova_credentials())
- return self._nova_connection
-
- def _flavor_get(self, flavor_id):
- """
- Get flavor by flavor_id
- Arguments:
- flavor_id(string): UUID of flavor_id
-
- Returns:
- dictionary of flavor parameters
- """
- nvconn = self._get_nova_connection()
- try:
- flavor = nvconn.flavors.get(flavor_id)
- except Exception as e:
- logger.info("OpenstackDriver: Did not find flavor with flavor_id : %s. Exception: %s"%(flavor_id, str(e)))
- raise
-
- try:
- extra_specs = flavor.get_keys()
- except Exception as e:
- logger.info("OpenstackDriver: Could not get the EPA attributes for flavor with flavor_id : %s. Exception: %s"%(flavor_id, str(e)))
- raise
-
- response = flavor.to_dict()
- assert 'extra_specs' not in response, "Key extra_specs present as flavor attribute"
- response['extra_specs'] = extra_specs
- return response
-
- def flavor_get(self, flavor_id):
- """
- Get flavor by flavor_id
- Arguments:
- flavor_id(string): UUID of flavor_id
-
- Returns:
- dictionary of flavor parameters
- """
- return self._flavor_get(flavor_id)
-
- def flavor_list(self):
- """
- Returns list of all flavors (dictionary per flavor)
-
- Arguments:
- None
- Returns:
- A list of dictionaries. Each dictionary contains attributes for a single flavor instance
- """
- flavors = []
- flavor_info = []
- nvconn = self._get_nova_connection()
- try:
- flavors = nvconn.flavors.list()
- except Exception as e:
- logger.error("OpenstackDriver: List Flavor operation failed. Exception: %s"%(str(e)))
- raise
- if flavors:
- flavor_info = [ self.flavor_get(flv.id) for flv in flavors ]
- return flavor_info
-
- def flavor_create(self, name, ram, vcpu, disk, extra_specs):
- """
- Create a new flavor
-
- Arguments:
- name (string): Name of the new flavor
- ram (int) : Memory in MB
- vcpus (int) : Number of VCPUs
- disk (int) : Secondary storage size in GB
- extra_specs (dictionary): EPA attributes dictionary
-
- Returns:
- flavor_id (string): UUID of flavor created
- """
- nvconn = self._get_nova_connection()
- try:
- flavor = nvconn.flavors.create(name = name,
- ram = ram,
- vcpus = vcpu,
- disk = disk,
- flavorid = 'auto',
- ephemeral = 0,
- swap = 0,
- rxtx_factor = 1.0,
- is_public = True)
- except Exception as e:
- logger.error("OpenstackDriver: Create Flavor operation failed. Exception: %s"%(str(e)))
- raise
-
- if extra_specs:
- try:
- flavor.set_keys(extra_specs)
- except Exception as e:
- logger.error("OpenstackDriver: Set Key operation failed for flavor: %s. Exception: %s" %(flavor.id, str(e)))
- raise
- return flavor.id
-
- def flavor_delete(self, flavor_id):
- """
- Deletes a flavor identified by flavor_id
-
- Arguments:
- flavor_id (string): UUID of flavor to be deleted
-
- Returns: None
- """
- assert flavor_id == self._flavor_get(flavor_id)['id']
- nvconn = self._get_nova_connection()
- try:
- nvconn.flavors.delete(flavor_id)
- except Exception as e:
- logger.error("OpenstackDriver: Delete flavor operation failed for flavor: %s. Exception: %s" %(flavor_id, str(e)))
- raise
-
-
- def server_list(self):
- """
- Returns a list of available VMs for the project
-
- Arguments: None
-
- Returns:
- A list of dictionaries. Each dictionary contains attributes associated
- with individual VM
- """
- servers = []
- server_info = []
- nvconn = self._get_nova_connection()
- try:
- servers = nvconn.servers.list()
- except Exception as e:
- logger.error("OpenstackDriver: List Server operation failed. Exception: %s" %(str(e)))
- raise
- server_info = [ server.to_dict() for server in servers]
- return server_info
-
- def _nova_server_get(self, server_id):
- """
- Returns a dictionary of attributes associated with VM identified by service_id
-
- Arguments:
- server_id (string): UUID of the VM/server for which information is requested
-
- Returns:
- A dictionary object with attributes associated with VM identified by server_id
- """
- nvconn = self._get_nova_connection()
- try:
- server = nvconn.servers.get(server = server_id)
- except Exception as e:
- logger.info("OpenstackDriver: Get Server operation failed for server_id: %s. Exception: %s" %(server_id, str(e)))
- raise
- else:
- return server.to_dict()
-
- def server_get(self, server_id):
- """
- Returns a dictionary of attributes associated with VM identified by service_id
-
- Arguments:
- server_id (string): UUID of the VM/server for which information is requested
-
- Returns:
- A dictionary object with attributes associated with VM identified by server_id
- """
- return self._nova_server_get(server_id)
-
- def server_create(self, **kwargs):
- """
- Creates a new VM/server instance
-
- Arguments:
- A dictionary of following key-value pairs
- {
- server_name(string) : Name of the VM/Server
- flavor_id (string) : UUID of the flavor to be used for VM
- image_id (string) : UUID of the image to be used VM/Server instance,
- This could be None if volumes (with images) are being used
- network_list(List) : A List of network_ids. A port will be created in these networks
- port_list (List) : A List of port-ids. These ports will be added to VM.
- metadata (dict) : A dictionary of arbitrary key-value pairs associated with VM/server
- userdata (string) : A script which shall be executed during first boot of the VM
- availability_zone (string) : A name of the availability zone where instance should be launched
- scheduler_hints (string) : Openstack scheduler_hints to be passed to nova scheduler
- }
- Returns:
- server_id (string): UUID of the VM/server created
-
- """
- nics = []
- if 'network_list' in kwargs:
- for network_id in kwargs['network_list']:
- nics.append({'net-id': network_id})
-
- if 'port_list' in kwargs:
- for port_id in kwargs['port_list']:
- nics.append({'port-id': port_id})
-
- nvconn = self._get_nova_connection()
-
-
- try:
- server = nvconn.servers.create(kwargs['name'],
- kwargs['image_id'],
- kwargs['flavor_id'],
- meta = kwargs['metadata'],
- files = kwargs['files'],
- reservation_id = None,
- min_count = None,
- max_count = None,
- userdata = kwargs['userdata'],
- security_groups = kwargs['security_groups'],
- availability_zone = kwargs['availability_zone'],
- block_device_mapping_v2 = kwargs['block_device_mapping_v2'],
- nics = nics,
- scheduler_hints = kwargs['scheduler_hints'],
- config_drive = kwargs['config_drive'])
- except Exception as e:
- logger.info("OpenstackDriver: Create Server operation failed. Exception: %s" %(str(e)))
- raise
- return server.to_dict()['id']
-
- def server_delete(self, server_id):
- """
- Deletes a server identified by server_id
-
- Arguments:
- server_id (string): UUID of the server to be deleted
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.delete(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Delete server operation failed for server_id: %s. Exception: %s" %(server_id, str(e)))
- raise
-
- def server_start(self, server_id):
- """
- Starts a server identified by server_id
-
- Arguments:
- server_id (string): UUID of the server to be started
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.start(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Start Server operation failed for server_id : %s. Exception: %s" %(server_id, str(e)))
- raise
-
- def server_stop(self, server_id):
- """
- Arguments:
- server_id (string): UUID of the server to be stopped
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.stop(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Stop Server operation failed for server_id : %s. Exception: %s" %(server_id, str(e)))
- raise
-
- def server_pause(self, server_id):
- """
- Arguments:
- server_id (string): UUID of the server to be paused
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.pause(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Pause Server operation failed for server_id : %s. Exception: %s" %(server_id, str(e)))
- raise
-
- def server_unpause(self, server_id):
- """
- Arguments:
- server_id (string): UUID of the server to be unpaused
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.unpause(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Resume Server operation failed for server_id : %s. Exception: %s" %(server_id, str(e)))
- raise
-
-
- def server_suspend(self, server_id):
- """
- Arguments:
- server_id (string): UUID of the server to be suspended
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.suspend(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Suspend Server operation failed for server_id : %s. Exception: %s" %(server_id, str(e)))
-
-
- def server_resume(self, server_id):
- """
- Arguments:
- server_id (string): UUID of the server to be resumed
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.resume(server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Resume Server operation failed for server_id : %s. Exception: %s" %(server_id, str(e)))
- raise
-
- def server_reboot(self, server_id, reboot_type):
- """
- Arguments:
- server_id (string) : UUID of the server to be rebooted
- reboot_type(string):
- 'SOFT': Soft Reboot
- 'HARD': Hard Reboot
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.reboot(server_id, reboot_type)
- except Exception as e:
- logger.error("OpenstackDriver: Reboot Server operation failed for server_id: %s. Exception: %s" %(server_id, str(e)))
- raise
-
- def server_console(self, server_id, console_type = 'novnc'):
- """
- Arguments:
- server_id (string) : UUID of the server to be rebooted
- console_type(string):
- 'novnc',
- 'xvpvnc'
- Returns:
- A dictionary object response for console information
- """
- nvconn = self._get_nova_connection()
- try:
- console_info = nvconn.servers.get_vnc_console(server_id, console_type)
- except Exception as e:
- logger.error("OpenstackDriver: Server Get-Console operation failed for server_id: %s. Exception: %s" %(server_id, str(e)))
- raise
- return console_info
-
- def server_rebuild(self, server_id, image_id):
- """
- Arguments:
- server_id (string) : UUID of the server to be rebooted
- image_id (string) : UUID of the image to use
- Returns: None
- """
-
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.rebuild(server_id, image_id)
- except Exception as e:
- logger.error("OpenstackDriver: Rebuild Server operation failed for server_id: %s. Exception: %s" %(server_id, str(e)))
- raise
-
-
- def server_add_port(self, server_id, port_id):
- """
- Arguments:
- server_id (string): UUID of the server
- port_id (string): UUID of the port to be attached
-
- Returns: None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.interface_attach(server_id,
- port_id,
- net_id = None,
- fixed_ip = None)
- except Exception as e:
- logger.error("OpenstackDriver: Server Port Add operation failed for server_id : %s, port_id : %s. Exception: %s" %(server_id, port_id, str(e)))
- raise
-
- def server_delete_port(self, server_id, port_id):
- """
- Arguments:
- server_id (string): UUID of the server
- port_id (string): UUID of the port to be deleted
- Returns: None
-
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.interface_detach(server_id, port_id)
- except Exception as e:
- logger.error("OpenstackDriver: Server Port Delete operation failed for server_id : %s, port_id : %s. Exception: %s" %(server_id, port_id, str(e)))
- raise
-
- def floating_ip_list(self):
- """
- Arguments:
- None
- Returns:
- List of objects of floating IP nova class (novaclient.v2.floating_ips.FloatingIP)
- """
- nvconn = self._get_nova_connection()
- try:
- ip_list = nvconn.floating_ips.list()
- except Exception as e:
- logger.error("OpenstackDriver: Floating IP List operation failed. Exception: %s" %str(e))
- raise
-
- return ip_list
-
- def floating_ip_create(self, pool):
- """
- Arguments:
- pool (string): Name of the pool (optional)
- Returns:
- An object of floating IP nova class (novaclient.v2.floating_ips.FloatingIP)
- """
- nvconn = self._get_nova_connection()
- try:
- floating_ip = nvconn.floating_ips.create(pool)
- except Exception as e:
- logger.error("OpenstackDriver: Floating IP Create operation failed. Exception: %s" %str(e))
- raise
-
- return floating_ip
-
- def floating_ip_delete(self, floating_ip):
- """
- Arguments:
- floating_ip: An object of floating IP nova class (novaclient.v2.floating_ips.FloatingIP)
- Returns:
- None
- """
- nvconn = self._get_nova_connection()
- try:
- floating_ip = nvconn.floating_ips.delete(floating_ip)
- except Exception as e:
- logger.error("OpenstackDriver: Floating IP Delete operation failed. Exception: %s" %str(e))
- raise
-
- def floating_ip_assign(self, server_id, floating_ip, fixed_ip):
- """
- Arguments:
- server_id (string) : UUID of the server
- floating_ip (string): IP address string for floating-ip
- fixed_ip (string) : IP address string for the fixed-ip with which floating ip will be associated
- Returns:
- None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.add_floating_ip(server_id, floating_ip, fixed_ip)
- except Exception as e:
- logger.error("OpenstackDriver: Assign Floating IP operation failed. Exception: %s" %str(e))
- raise
-
- def floating_ip_release(self, server_id, floating_ip):
- """
- Arguments:
- server_id (string) : UUID of the server
- floating_ip (string): IP address string for floating-ip
- Returns:
- None
- """
- nvconn = self._get_nova_connection()
- try:
- nvconn.servers.remove_floating_ip(server_id, floating_ip)
- except Exception as e:
- logger.error("OpenstackDriver: Release Floating IP operation failed. Exception: %s" %str(e))
- raise
-
- def volume_list(self, server_id):
- """
- List of volumes attached to the server
-
- Arguments:
- None
- Returns:
- List of dictionary objects where dictionary is representation of class (novaclient.v2.volumes.Volume)
- """
- nvconn = self._get_nova_connection()
- try:
- volumes = nvconn.volumes.get_server_volumes(server_id=server_id)
- except Exception as e:
- logger.error("OpenstackDriver: Get volume information failed. Exception: %s" %str(e))
- raise
-
- volume_info = [v.to_dict() for v in volumes]
- return volume_info
-
-
- def group_list(self):
- """
- List of Server Affinity and Anti-Affinity Groups
-
- Arguments:
- None
- Returns:
- List of dictionary objects where dictionary is representation of class (novaclient.v2.server_groups.ServerGroup)
- """
- nvconn = self._get_nova_connection()
- try:
- group_list = nvconn.server_groups.list()
- except Exception as e:
- logger.error("OpenstackDriver: Server Group List operation failed. Exception: %s" %str(e))
- raise
-
- group_info = [ group.to_dict() for group in group_list ]
- return group_info
-
-
-
-class NovaDriverV2(NovaDriver):
- """
- Driver class for novaclient V2 APIs
- """
- def __init__(self, ks_drv):
- """
- Constructor for NovaDriver
- Arguments: KeystoneDriver class object
- """
- super(NovaDriverV2, self).__init__(ks_drv, 'compute', '2.0')
-
-class NovaDriverV21(NovaDriver):
- """
- Driver class for novaclient V2 APIs
- """
- def __init__(self, ks_drv):
- """
- Constructor for NovaDriver
- Arguments: KeystoneDriver class object
- """
- super(NovaDriverV21, self).__init__(ks_drv, 'compute', '2.1')
-
-class GlanceDriver(object):
- """
- Driver for openstack glance-client
- """
- def __init__(self, ks_drv, service_name, version):
- """
- Constructor for GlanceDriver
- Arguments: KeystoneDriver class object
- """
- self.ks_drv = ks_drv
- self._service_name = service_name
- self._version = version
-
- def _get_glance_credentials(self):
- """
- Returns a dictionary of kwargs required to instantiate python-glanceclient class
-
- Arguments: None
-
- Returns:
- A dictionary object of arguments
- """
- creds = {}
- creds['version'] = self._version
- creds['endpoint'] = self.ks_drv.get_service_endpoint(self._service_name, 'publicURL')
- creds['token'] = self.ks_drv.get_auth_token()
- creds['insecure'] = self.ks_drv.get_security_mode()
- return creds
-
- def _get_glance_connection(self):
- """
- Returns a object of class python-glanceclient
- """
- if not hasattr(self, '_glance_connection'):
- self._glance_connection = glclient.Client(**self._get_glance_credentials())
- else:
- # Reinitialize if auth_token is no longer valid
- if not self.ks_drv.is_auth_token_valid():
- self._glance_connection = glclient.Client(**self._get_glance_credentials())
- return self._glance_connection
-
- def image_list(self):
- """
- Returns list of dictionaries. Each dictionary contains attributes associated with
- image
-
- Arguments: None
-
- Returns: List of dictionaries.
- """
- glconn = self._get_glance_connection()
- images = []
- try:
- image_info = glconn.images.list()
- except Exception as e:
- logger.error("OpenstackDriver: List Image operation failed. Exception: %s" %(str(e)))
- raise
- images = [ img for img in image_info ]
- return images
-
- def image_create(self, **kwargs):
- """
- Creates an image
- Arguments:
- A dictionary of kwargs with following keys
- {
- 'name'(string) : Name of the image
- 'location'(string) : URL (http://....) where image is located
- 'disk_format'(string) : Disk format
- Possible values are 'ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 'qcow2', 'vdi', 'iso'
- 'container_format'(string): Container format
- Possible values are 'ami', 'ari', 'aki', 'bare', 'ovf'
- 'tags' : A list of user tags
- 'checksum' : The image md5 checksum
- }
- Returns:
- image_id (string) : UUID of the image
-
- """
- glconn = self._get_glance_connection()
- try:
- image = glconn.images.create(**kwargs)
- except Exception as e:
- logger.error("OpenstackDriver: Create Image operation failed. Exception: %s" %(str(e)))
- raise
-
- return image.id
-
- def image_upload(self, image_id, fd):
- """
- Upload the image
-
- Arguments:
- image_id: UUID of the image
- fd : File descriptor for the image file
- Returns: None
- """
- glconn = self._get_glance_connection()
- try:
- glconn.images.upload(image_id, fd)
- except Exception as e:
- logger.error("OpenstackDriver: Image upload operation failed. Exception: %s" %(str(e)))
- raise
-
- def image_add_location(self, image_id, location, metadata):
- """
- Add image URL location
-
- Arguments:
- image_id : UUID of the image
- location : http URL for the image
-
- Returns: None
- """
- glconn = self._get_glance_connection()
- try:
- image = glconn.images.add_location(image_id, location, metadata)
- except Exception as e:
- logger.error("OpenstackDriver: Image location add operation failed. Exception: %s" %(str(e)))
- raise
-
- def image_update(self):
- pass
-
- def image_delete(self, image_id):
- """
- Delete an image
-
- Arguments:
- image_id: UUID of the image
-
- Returns: None
-
- """
- assert image_id == self._image_get(image_id)['id']
- glconn = self._get_glance_connection()
- try:
- glconn.images.delete(image_id)
- except Exception as e:
- logger.error("OpenstackDriver: Delete Image operation failed for image_id : %s. Exception: %s" %(image_id, str(e)))
- raise
-
-
- def _image_get(self, image_id):
- """
- Returns a dictionary object of VM image attributes
-
- Arguments:
- image_id (string): UUID of the image
-
- Returns:
- A dictionary of the image attributes
- """
- glconn = self._get_glance_connection()
- try:
- image = glconn.images.get(image_id)
- except GlanceException.HTTPBadRequest:
- # RIFT-14241: The get image request occasionally returns the below message. Retry in case of bad request exception.
- # Error code 400.: Message: Bad request syntax ('0').: Error code explanation: 400 = Bad request syntax or unsupported method. (HTTP 400)
- logger.warning("OpenstackDriver: Got bad request response during get_image request. Retrying.")
- image = glconn.images.get(image_id)
- except Exception as e:
- logger.error("OpenstackDriver: Get Image operation failed for image_id : %s. Exception: %s" %(image_id, str(e)))
- raise
-
- return image
-
- def image_get(self, image_id):
- """
- Returns a dictionary object of VM image attributes
-
- Arguments:
- image_id (string): UUID of the image
-
- Returns:
- A dictionary of the image attributes
- """
- return self._image_get(image_id)
-
-class GlanceDriverV2(GlanceDriver):
- """
- Driver for openstack glance-client V2
- """
- def __init__(self, ks_drv):
- super(GlanceDriverV2, self).__init__(ks_drv, 'image', 2)
-
-class NeutronDriver(object):
- """
- Driver for openstack neutron neutron-client
- """
- def __init__(self, ks_drv, service_name, version):
- """
- Constructor for NeutronDriver
- Arguments: KeystoneDriver class object
- """
- self.ks_drv = ks_drv
- self._service_name = service_name
- self._version = version
-
- def _get_neutron_credentials(self):
- """
- Returns a dictionary of kwargs required to instantiate python-neutronclient class
-
- Returns:
- Dictionary of kwargs
- """
- creds = {}
- creds['api_version'] = self._version
- creds['endpoint_url'] = self.ks_drv.get_service_endpoint(self._service_name, 'publicURL')
- creds['token'] = self.ks_drv.get_auth_token()
- creds['tenant_name'] = self.ks_drv.get_tenant_name()
- creds['insecure'] = self.ks_drv.get_security_mode()
- return creds
-
- def _get_neutron_connection(self):
- """
- Returns an object of class python-neutronclient
- """
- if not hasattr(self, '_neutron_connection'):
- self._neutron_connection = ntclient.Client(**self._get_neutron_credentials())
- else:
- # Reinitialize if auth_token is no longer valid
- if not self.ks_drv.is_auth_token_valid():
- self._neutron_connection = ntclient.Client(**self._get_neutron_credentials())
- return self._neutron_connection
-
- def network_list(self):
- """
- Returns list of dictionaries. Each dictionary contains the attributes for a network
- under project
-
- Arguments: None
-
- Returns:
- A list of dictionaries
- """
- networks = []
- ntconn = self._get_neutron_connection()
- try:
- networks = ntconn.list_networks()
- except Exception as e:
- logger.error("OpenstackDriver: List Network operation failed. Exception: %s" %(str(e)))
- raise
- return networks['networks']
-
- def network_create(self, **kwargs):
- """
- Creates a new network for the project
-
- Arguments:
- A dictionary with following key-values
- {
- name (string) : Name of the network
- admin_state_up(Boolean) : True/False (Defaults: True)
- external_router(Boolean) : Connectivity with external router. True/False (Defaults: False)
- shared(Boolean) : Shared among tenants. True/False (Defaults: False)
- physical_network(string) : The physical network where this network object is implemented (optional).
- network_type : The type of physical network that maps to this network resource (optional).
- Possible values are: 'flat', 'vlan', 'vxlan', 'gre'
- segmentation_id : An isolated segment on the physical network. The network_type attribute
- defines the segmentation model. For example, if the network_type value
- is vlan, this ID is a vlan identifier. If the network_type value is gre,
- this ID is a gre key.
- }
- """
- params = {'network':
- {'name' : kwargs['name'],
- 'admin_state_up' : kwargs['admin_state_up'],
- 'tenant_id' : self.ks_drv.get_tenant_id(),
- 'shared' : kwargs['shared'],
- #'port_security_enabled': port_security_enabled,
- 'router:external' : kwargs['external_router']}}
-
- if 'physical_network' in kwargs:
- params['network']['provider:physical_network'] = kwargs['physical_network']
- if 'network_type' in kwargs:
- params['network']['provider:network_type'] = kwargs['network_type']
- if 'segmentation_id' in kwargs:
- params['network']['provider:segmentation_id'] = kwargs['segmentation_id']
-
- ntconn = self._get_neutron_connection()
- try:
- logger.debug("Calling neutron create_network() with params: %s", str(params))
- net = ntconn.create_network(params)
- except Exception as e:
- logger.error("OpenstackDriver: Create Network operation failed. Exception: %s" %(str(e)))
- raise
- logger.debug("Got create_network response from neutron connection: %s", str(net))
- network_id = net['network']['id']
- if not network_id:
- raise Exception("Empty network id returned from create_network. (params: %s)" % str(params))
-
- return network_id
-
- def network_delete(self, network_id):
- """
- Deletes a network identified by network_id
-
- Arguments:
- network_id (string): UUID of the network
-
- Returns: None
- """
- assert network_id == self._network_get(network_id)['id']
- ntconn = self._get_neutron_connection()
- try:
- ntconn.delete_network(network_id)
- except Exception as e:
- logger.error("OpenstackDriver: Delete Network operation failed. Exception: %s" %(str(e)))
- raise
-
- def _network_get(self, network_id):
- """
- Returns a dictionary object describing the attributes of the network
-
- Arguments:
- network_id (string): UUID of the network
-
- Returns:
- A dictionary object of the network attributes
- """
- ntconn = self._get_neutron_connection()
- network = ntconn.list_networks(id = network_id)['networks']
- if not network:
- raise NeutronException.NotFound("Network with id %s not found"%(network_id))
-
- return network[0]
-
- def network_get(self, network_id):
- """
- Returns a dictionary object describing the attributes of the network
-
- Arguments:
- network_id (string): UUID of the network
-
- Returns:
- A dictionary object of the network attributes
- """
- return self._network_get(network_id)
-
- def subnet_create(self, **kwargs):
- """
- Creates a subnet on the network
-