def _rest_callback(self, errorcode, reason, status, data=None): if status == req_code.ok and reason is None: if errorcode != '0': LOG.error(_LE("Raise MechanismDriverError.")) raise ml2_exc.MechanismDriverError( driver=ac_const.NW_HW_AC_DRIVER_NAME, method='_rest_callback') elif status == req_code.no_content: pass else: LOG.error(_LE("Raise MechanismDriverError."))
def _default_security_group_rest_callback(self, errorcode, reason, status, data=None): if status == req_code.ok and reason is None: if errorcode != '0': LOG.error(_LE("Raise MechanismDriverError.")) raise ml2_exc.MechanismDriverError( driver=ac_const.NW_HW_AC_DRIVER_NAME, method="_default_security_group_rest_callback") elif status == req_code.no_content: pass else: LOG.error(_LE("Default security group processing error."))
def __setSubNetinfo__(self, context): LOG.debug("The context current in subnet is %s.", context.current) try: subnet_info = { 'networkId': context.current['network_id'], 'tenant_id': context.current['tenant_id'], 'id': context.current['id'], 'name': context.current['name'], 'ipVersion': context.current['ip_version'], 'enableDhcp': context.current['enable_dhcp'], 'allocationPools': context.current['allocation_pools'], 'cidr': context.current['cidr'], 'gatewayIp': context.current['gateway_ip'], 'dnsNameservers': context.current['dns_nameservers'], 'hostRoutes': context.current['host_routes'] } subnet_info_list = {} if q_const.IP_VERSION_6 == context.current['ip_version']: subnet_info['ipv6AddressMode'] \ = context.current['ipv6_address_mode'] subnet_info['ipv6RaMode'] = context.current['ipv6_ra_mode'] except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError LOG.debug("The subnet_info is %s.", subnet_info) subnet_info_list['subnet'] = subnet_info return subnet_info_list
def __deal_port__(self, context, operation): LOG.debug("The context current in port is %s.", context.current) try: port_info = self.__setPortinfo__(context) except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError # if the port bind default security group and not sync to ac, # it need to be sync to ac if operation == 'create_port': for security_group_id in context.current['security_groups']: sg_group = self \ .securityGroupDb.get_security_group( self.ctx, security_group_id) security_group_info = self\ .secGroupSub.set_security_group(sg_group) if security_group_info['name'] == 'default': LOG.info(_LI("security_group_info is %s"), security_group_info) self.secGroupSub.rest_request( security_group_info['id'], {'securityGroup': security_group_info}, 'create_security_group') LOG.debug("The port_info is %s.", port_info) self.__restRequest__(port_info['port']['id'], port_info, operation)
def remove_router_interface(self, context, router_id, interface_info): router = super(HuaweiACL3RouterPlugin, self)\ .get_router(context, router_id) interface_info = super(HuaweiACL3RouterPlugin, self)\ .remove_router_interface(context, router_id, interface_info) LOG.debug('Interface info of remove_router_interface %s.', interface_info) LOG.debug('Router data of remove_router_interface %s.', router) service = RESTService() service_name = service.serviceName try: rest_info = { 'portId': interface_info['port_id'], 'id': router_id, 'serviceName': service_name, 'tenant_id': router['tenant_id'] } except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError self.__rest_request__(router_id, rest_info, 'delete_router_interface')
def add_router_interface(self, context, router_id, interface_info): interface_info = super(HuaweiACL3RouterPlugin, self)\ .add_router_interface(context, router_id, interface_info) router = super(HuaweiACL3RouterPlugin, self)\ .get_router(context, router_id) LOG.debug('Interface info of add_router_interface %s.', interface_info) LOG.debug('Router data of add_router_interface %s.', router) service = RESTService() service_name = service.serviceName rest_info = {} try: info = {'portId': interface_info['port_id'], 'routerId': router_id, 'serviceName': service_name, 'tenant_id': router['tenant_id']} except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError rest_info['routerInterface'] = info self.__rest_request__(router_id, rest_info, 'add_router_interface')
def _create_security_group_rollback(self, group_id): """Rollback the security group subscription :param group_id: Group id of the security group :return: None """ try: self.rest_request(group_id, {}, 'delete_security_group') except Exception: LOG.error(_LE("Rollback for create security group failed."))
def process_request(self, method, auth, url, headers, data): timeout_retry = self.timeout_retry ret = None temp_ret = None while True: try: if (method == 'get') or (method == 'GET'): ret = requests.request(method, url=url, headers=headers, auth=auth, verify=False, timeout=self.timeout) else: ret = requests.request(method, url=url, headers=headers, data=data, auth=auth, verify=False, timeout=self.timeout) break except requests.exceptions.Timeout: temp_ret = "Timeout Exceptions" LOG.error(_LE("Exception: AC time out, " "traceback: %s"), traceback.format_exc()) timeout_retry -= 1 if timeout_retry < 0: ret = "Timeout Exceptions" break except Exception: LOG.error(_LE("Exception: AC exception, traceback: %s"), traceback.format_exc()) timeout_retry -= 1 if timeout_retry < 0: if temp_ret == "Timeout Exceptions": ret = "Timeout Exceptions" else: ret = "Exceptions" break if ("Timeout Exceptions" == ret) or ("Exceptions" == ret): LOG.error(_LE('Request to AC failed, error code: %s'), ret) return ret
def delete_port_postcommit(self, context): """This function sends port delete message to AC :param context: DB context for the port delete :return: None """ try: port_info = self.__setPortinfo__(context) except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError self.__restRequest__(port_info['port']['id'], port_info, 'delete_port')
def __restRequest__(self, id, entry_info, operation): if operation in ac_const.NW_HW_NEUTRON_RESOURCES: isneedservicename = \ ac_const.NW_HW_NEUTRON_RESOURCES[operation][ 'needSvcNameUpdate'] methodname = ac_const.NW_HW_NEUTRON_RESOURCES[operation]['method'] url = '%s%s%s' % (ac_const.NW_HW_URL, '/', ac_const. NW_HW_NEUTRON_RESOURCES[operation]['rsrc']) service = RESTService() service.requestService(methodname, url, id, entry_info, isneedservicename, self.__callBack__) else: LOG.error(_LE("The operation is wrong.")) raise ml2_exc.MechanismDriverError( driver=ac_const.NW_HW_AC_DRIVER_NAME, method='__restRequest__')
def delete_security_group_rule(self, resource, event, trigger, **kwargs): """Subscribed for security group rule delete :param resource: Security group resources :param event: Event :param trigger: Trigger for the call :param kwargs: Args :return: None """ rule_id = kwargs['security_group_rule_id'] try: self.rest_request(rule_id, {}, 'delete_security_group_rule') except Exception: LOG.error(_LE("Delete security group rule failed.")) LOG.debug("End delete security group rule.")
def delete_snat(self, resource, event, trigger, **kwargs): """Subscribed for source NAT deletion :param resource: Security group resources :param event: Event :param trigger: Trigger for the call :param kwargs: Args :return: None """ router_id = kwargs['router_id'] try: self.rest_request(router_id, {}, 'delete_snat') except Exception: LOG.error(_LE("Delete SNAT failed.")) LOG.debug("End delete SNAT.")
def delete_security_group(self, resource, event, trigger, **kwargs): """Subscribed for security group delete :param resource: Security group resources :param event: Event :param trigger: Trigger for the call :param kwargs: Args :return: None """ group_id = kwargs['security_group_id'] LOG.debug("The group id is %s.", group_id) try: self.rest_request(group_id, {}, 'delete_security_group') except Exception: LOG.error(_LE("Delete security group fail.")) LOG.debug("End delete security group.")
def __setNetWorkInfo__(self, context): LOG.debug("The context current in network is %s.", context.current) try: network_info = { 'id': context.current['id'], 'status': context.current['status'], 'segmentationId': context.current['provider:' 'segmentation' '_id'], 'tenant_id': context.current['tenant_id'], 'name': context.current['name'], 'adminStateUp': context.current['admin_state_up'], 'shared': context.current['shared'], 'networkType': context.current['provider:' 'network_type'], 'physicalNetwork': context.current['provider:' 'physical_' 'network'] } except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError if 'router:external' in context.current \ and context.current['router:external']: network_info['routerExternal'] = True LOG.debug("The request if for an external network.") else: network_info['routerExternal'] = False LOG.debug("The request if for an internal network.") LOG.debug("The network_info is %s.", network_info) network_info1 = {'network': network_info} return network_info1
def update_security_group(self, resource, event, trigger, **kwargs): """Subscribed for security group update :param resource: Security group resources :param event: Event :param trigger: Trigger for the call :param kwargs: Args :return: None """ security_group = kwargs['security_group'] security_group_info = self.set_security_group(security_group) LOG.debug("The group is %s.", security_group_info) try: self.rest_request(security_group_info['id'], {'securityGroup': security_group_info}, 'update_security_group') except Exception: LOG.error(_LE("Update security group failed.")) LOG.debug("End update security group.")
def create_router(self, context, router): router_db = super(HuaweiACL3RouterPlugin, self)\ .create_router(context, router) LOG.debug('Create router db %s.', router_db) try: routerinfo = {'id': router_db['id'], 'name': router_db['name'], 'adminStateUp': router_db['admin_state_up'], 'tenant_id': router_db['tenant_id'], 'externalGatewayInfo': router_db['external_' 'gateway_info'], 'distributed': router_db['distributed'], 'ha': router_db['ha'], 'routes': router_db['routes']} except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError info = {'router': routerinfo} self.__rest_request__("", info, 'create_router') return router_db
def create_router(self, context, router): router_db = super(HuaweiACL3RouterPlugin, self)\ .create_router(context, router) LOG.debug('Create router db %s.', router_db) try: routerinfo = { 'id': router_db['id'], 'name': router_db['name'], 'adminStateUp': router_db['admin_state_up'], 'tenant_id': router_db['tenant_id'], 'externalGatewayInfo': router_db['external_' 'gateway_info'], 'distributed': router_db['distributed'], 'ha': router_db['ha'], 'routes': router_db['routes'] } except KeyError as e: LOG.error(_LE("Key Error, doesn't contain all fields %s."), e) raise KeyError info = {'router': routerinfo} self.__rest_request__("", info, 'create_router') return router_db
def create_security_group_rule(self, resource, event, trigger, **kwargs): """Subscribed for security group rule creation :param resource: Security group resources :param event: Event :param trigger: Trigger for the call :param kwargs: Args :return: None """ rule = kwargs['security_group_rule'] rule_info = self._set_security_group_rule(rule) LOG.debug("The group rule is %s.", rule_info) try: self.rest_request(rule_info['id'], {'securityGroupRule': rule_info}, 'create_security_group_rule') except Exception: LOG.error( _LE("Create \ security group rule failed, rollback.")), self._create_security_group_rule_rollback(rule_info['id']) LOG.debug("End create security group rule.")
def rest_request(self, id, entry_info, operation): if operation in ac_const.NW_HW_NEUTRON_RESOURCES: methodname = ac_const.NW_HW_NEUTRON_RESOURCES[operation]['method'] url = '%s%s%s' % (ac_const.NW_HW_URL, '/', ac_const. NW_HW_NEUTRON_RESOURCES[operation]['rsrc']) service = RESTService() LOG.debug("The ac data is: %s.", jsonutils.dumps(entry_info)) try: if operation == 'create_security_group' \ and entry_info['securityGroup']['name'] == 'default': service.requestService( methodname, url, id, entry_info, False, self._default_security_group_rest_callback) else: service.requestService(methodname, url, id, entry_info, False, self._rest_callback) except Exception as e: LOG.error(_LE("Exception is %s."), e) else: LOG.debug("The operation is wrong.") raise ml2_exc.MechanismDriverError( driver=ac_const.NW_HW_AC_DRIVER_NAME, method='rest_request')
def send(self, host, port, method, url, resrc_id, body, callback=None): result = {} if method.upper() == 'GET' or method.upper() == 'DELETE' \ or method.upper() == 'PUT': url = '%s%s%s' % (url, "/", resrc_id) params = jsonutils.dumps(body) headers = {"Content-type": "application/json", "Accept": "application/json"} LOG.debug('Send the request information, method: %s, url: %s, ' 'headers: %s, data:%s', method, url, headers, params) ret = self.process_request(method, self.auth, url, headers, params) if ("Timeout Exceptions" == ret) or ("Exceptions" == ret): LOG.error(_LE("Request to AC failed, error: %s"), ret) result['response'] = None result['status'] = -1 result['errorCode'] = None result['reason'] = None return result LOG.debug("AC request response, status_code: %s, content: %s, " "headers: %s", ret.status_code, ret.content, ret.headers) res_code = int(ret.status_code) res_content = ret.content try: if requests.codes.ok <= res_code < requests.codes.multiple_choices: LOG.debug('AC processed request successfully.') res = self.fix_json(res_content) LOG.debug("Send: response body is %s", res) if not res_content.strip(): result['response'] = None result['status'] = ret.status_code result['errorCode'] = None result['reason'] = None else: res1 = jsonutils.loads(res) result['response'] = res1['result'] result['status'] = ret.status_code result['errorCode'] = res1['errorCode'] result['reason'] = res1['errorMsg'] else: LOG.error(_LE('AC process request failed.')) if self.retry_count > 0 and \ requests.codes.unauthorized == res_code: LOG.debug('Retrying the request to AC') self.retry_count -= 1 (res_code, res_content) = self.send(host, port, method, url, resrc_id, body, callback) else: LOG.error(_LE('Max retry of request to AC has reached.')) result['response'] = None result['status'] = ret.status_code result['errorCode'] = None result['reason'] = None except Exception: result['response'] = '' result['status'] = ret.status_code result['reason'] = -1 result['errorCode'] = -1 raise Exception if callback is not None: callback(result['errorCode'], result['reason'], result['status']) else: LOG.debug("Call back for the REST is not set.") return result