def call_reservation_operation(self, ctx, arg): result = True reserved_candidates = None method = arg["method"] candidate_list = arg["candidate_list"] reservation_name = arg["reservation_name"] reservation_type = arg["reservation_type"] controller = arg["controller"] request = arg["request"] if controller == "SDN-C": results = self.sc_ext_manager.map_method( 'call_reservation_operation', method=method, candidate_list=candidate_list, reservation_name=reservation_name, reservation_type=reservation_type, request=request) if results and len(results) > 0: reserved_candidates = results[0] else: LOG.error(_LE("Unknown service controller: {}").format(controller)) if reserved_candidates is None or not reserved_candidates: result = False LOG.debug( _LW("Unable to {} for " "candidate {}.").format(method, reserved_candidates)) return {'response': result, 'error': not result} else: LOG.debug("{} for the candidate: " "{}".format(method, reserved_candidates)) return {'response': result, 'error': not result}
def get_candidates_from_service(self, ctx, arg): candidate_list = arg["candidate_list"] constraint_name = arg["constraint_name"] constraint_type = arg["constraint_type"] controller = arg["controller"] request = arg["request"] request_type = arg["request_type"] error = False filtered_candidates = [] # call service and fetch candidates # TODO(jdandrea): Get rid of the SDN-C reference (outside of plugin!) if controller == "SDN-C": service_model = request.get("service_model") results = self.sc_ext_manager.map_method( 'filter_candidates', request=request, candidate_list=candidate_list, constraint_name=constraint_name, constraint_type=constraint_type, request_type=request_type) if results and len(results) > 0: filtered_candidates = results[0] else: LOG.warn( _LW("No candidates returned by service " "controller: {}; may be a new service " "instantiation.").format(controller)) else: LOG.error(_LE("Unknown service controller: {}").format(controller)) # if response from service controller is empty if filtered_candidates is None: if service_model == "ADIOD": LOG.error("No capacity found from SDN-GC for candidates: " "{}".format(candidate_list)) return {'response': [], 'error': error} else: LOG.debug("Filtered candidates: {}".format(filtered_candidates)) candidate_list = [ c for c in candidate_list if c in filtered_candidates ] return {'response': candidate_list, 'error': error}
def get_candidates_with_hpa(self, ctx, arg): ''' RPC for getting candidates flavor mapping for matching hpa :param ctx: context :param arg: contains input passed from client side for RPC call :return: response candidate_list with matching label to flavor mapping ''' error = False candidate_list = arg["candidate_list"] id = arg["id"] type = arg["type"] directives = arg["directives"] attr = directives[0].get("attributes") label_name = attr[0].get("attribute_name") flavorProperties = arg["flavorProperties"] discard_set = set() for i in range(len(candidate_list)): # perform this check only for cloud candidates if candidate_list[i]["inventory_type"] != "cloud": continue # Check if flavor mapping for current label_name already # exists. This is an invalid condition. if candidate_list[i].get( "directives") and attr[0].get("attribute_value") != "": LOG.error( _LE("Flavor mapping for label name {} already" "exists").format(label_name)) continue # RPC call to inventory provider for matching hpa capabilities results = self.ip_ext_manager.map_method( 'match_hpa', candidate=candidate_list[i], features=flavorProperties) flavor_name = None if results and len(results) > 0 and results[0] is not None: LOG.debug("Find results {} and results length {}".format( results, len(results))) flavor_info = results[0].get("flavor_map") req_directives = results[0].get("directives") LOG.debug("Get directives {}".format(req_directives)) else: flavor_info = None LOG.info( _LW("No flavor mapping returned by " "inventory provider: {} for candidate: {}").format( self.ip_ext_manager.names()[0], candidate_list[i].get("candidate_id"))) # Metrics to Prometheus m_vim_id = candidate_list[i].get("vim-id") if not flavor_info: discard_set.add(candidate_list[i].get("candidate_id")) PC.HPA_CLOUD_REGION_UNSUCCESSFUL.labels( 'ONAP', 'N/A', m_vim_id).inc() else: if not flavor_info.get("flavor-name"): discard_set.add(candidate_list[i].get("candidate_id")) PC.HPA_CLOUD_REGION_UNSUCCESSFUL.labels( 'ONAP', 'N/A', m_vim_id).inc() else: if not candidate_list[i].get("flavor_map"): candidate_list[i]["flavor_map"] = {} # Create flavor mapping for label_name to flavor flavor_name = flavor_info.get("flavor-name") flavor_id = flavor_info.get("flavor-id") candidate_list[i]["flavor_map"][label_name] = flavor_name candidate_list[i]["flavor_map"]["flavorId"] = flavor_id # Create directives if not exist already if not candidate_list[i].get("all_directives"): candidate_list[i]["all_directives"] = {} candidate_list[i]["all_directives"]["directives"] = [] # Create flavor mapping and merge directives self.merge_directives(candidate_list, i, id, type, directives, req_directives) if not candidate_list[i].get("hpa_score"): candidate_list[i]["hpa_score"] = 0 candidate_list[i]["hpa_score"] += flavor_info.get("score") # Metrics to Prometheus PC.HPA_CLOUD_REGION_SUCCESSFUL.labels( 'ONAP', 'N/A', m_vim_id).inc() # return candidates not in discard set candidate_list[:] = [ c for c in candidate_list if c['candidate_id'] not in discard_set ] LOG.info( _LI("Candidates with matching hpa capabilities: {}, " "inventory provider: {}").format( candidate_list, self.ip_ext_manager.names()[0])) return {'response': candidate_list, 'error': error}
def request(self, method='get', content_type='application/json', path='', headers=None, data=None): """Performs HTTP request. Returns a requests.Response object.""" if method not in ('post', 'get', 'put', 'delete'): method = 'get' method_fn = getattr(self.session, method) full_headers = { 'Accept': content_type, 'Content-Type': content_type, } if headers: full_headers.update(headers) full_url = '{}/{}'.format(self.server_url, path.lstrip('/').rstrip('/')) # Prepare the request args try: data_str = json.dumps(data) if data else None except (TypeError, ValueError): data_str = data kwargs = { 'data': data_str, 'headers': full_headers, 'timeout': self.timeout, 'cert': (self.cert, self.key), 'verify': self.verify, 'stream': False, } if self.username or self.password: LOG.debug("Using HTTPBasicAuth") kwargs['auth'] = HTTPBasicAuth(self.username, self.password) if self.cert and self.key: LOG.debug("Using SSL/TLS Certificate/Key") if self.log_debug: LOG.debug("Request: {} {}".format(method.upper(), full_url)) if data: LOG.debug("Request Body: {}".format(json.dumps(data))) response = None for attempt in range(self.retries): if attempt > 0: # No need to show 400 bad requests from Music - Ignorable when lock cannot be received at one particular point in time if "MUSIC" not in full_url: LOG.warn( _LW("Retry #{}/{}").format(attempt + 1, self.retries)) try: response = method_fn(full_url, **kwargs) # We shouldn't have to do this since stream is set to False, # but we're gonna anyway. See "Body Content Workflow" here: # http://docs.python-requests.org/en/master/user/advanced/ response.close() if not response.ok: # No need to show 400 bad requests from Music - Ignorable when lock cannot be received at one particular point in time if "MUSIC" not in full_url: LOG.warn("Response Status: {} {}".format( response.status_code, response.reason)) if self.log_debug and response.text: try: response_dict = json.loads(response.text) LOG.debug("Response JSON: {}".format( json.dumps(response_dict))) except ValueError: LOG.debug("Response Body: {}".format(response.text)) #response._content = response._content.decode() if response.ok: break except requests.exceptions.RequestException as err: LOG.error("Exception: %s", err.args) # Response.__bool__ returns false if status is not ok. Ruh roh! # That means we must check the object type vs treating it as a bool. # More info: https://github.com/kennethreitz/requests/issues/2002 if isinstance(response, requests.models.Response) and not response.ok: # No need to show 400 bad requests from Music - Ignorable when lock cannot be received at one particular point in time if "MUSIC" not in full_url: LOG.error( _LE("Status {} {} after {} retries for URL: {}").format( response.status_code, response.reason, self.retries, full_url)) return response