def do_action_with_exception(self, acs_request): # set server response format as json, because thie function will # parse the response so which format doesn't matter acs_request.set_accept_format('JSON') status, headers, body = self.implementation_of_do_action(acs_request) request_id = None try: body_obj = json.loads(body.decode('utf-8')) request_id = body_obj.get('RequestId') except (ValueError, TypeError, AttributeError): # in case the response body is not a json string, return the raw # data instead pass if status < http_client.OK or status >= http_client.MULTIPLE_CHOICES: server_error_code, server_error_message = self._parse_error_info_from_response_body( body) raise ServerException( server_error_code, server_error_message, http_status=status, request_id=request_id) return body
def _refresh_session_ak_and_sk(self): request = CommonRequest(product="Sts", version='2015-04-01', action_name='AssumeRole') request.set_method('POST') request.set_protocol_type('https') request.add_query_param('RoleArn', self._credential.role_arn) request.add_query_param('RoleSessionName', self._credential.session_role_name) request.add_query_param('DurationSeconds', self._SESSION_PERIOD) request.set_accept_format('JSON') access_key_credential = AccessKeyCredential( self._credential.sts_access_key_id, self._credential.sts_access_key_secret) signer = AccessKeySigner(access_key_credential) status, headers, body = self._doAction(request, signer) if status == 200: response = json.loads(body.decode('utf-8')) session_ak = response.get("Credentials").get("AccessKeyId") session_sk = response.get("Credentials").get("AccessKeySecret") token = response.get("Credentials").get("SecurityToken") self._session_credential = session_ak, session_sk, token self._last_update_time = int(time.time()) else: code = error_code.SDK_GET_SESSION_CREDENTIAL_FAILED message = "refresh session token failed, server return: " + body http_status = status raise exceptions.ServerException(code, message, http_status)
def __init__(self, config_json_str=None): EndpointResolverBase.__init__(self) self._valid_region_ids = [] self._location_code_mapping = dict() self._regional_endpoint_data = dict() if config_json_str: obj = json.loads(config_json_str) else: obj = self._read_from_endpoints_json() self._init_local_config(obj)
def _parse_error_info_from_response_body(response_body): try: body_obj = json.loads(response_body) if 'Code' in body_obj and 'Message' in body_obj: return body_obj['Code'], body_obj['Message'] except ValueError: pass finally: # failed to parse body as json format # TODO handle if response_body is too big error_message = "ServerResponseBody: " + str(response_body) return error_code.SDK_UNKNOWN_SERVER_ERROR, error_message
def _refresh_session_ak_and_sk(self): try: request_url = "http://100.100.100.200/latest/meta-data/ram/security-credentials/" + self._credential.role_name content = urlopen(request_url).read() response = json.loads(content.deconde('utf-8')) if response.get("Code") != "Success": logging.error('refresh Ecs sts token err, code is ' + response.get("Code")) return session_ak = response.get("AccessKeyId") session_sk = response.get("AccessKeySecret") token = response.get("SecurityToken") self._session_credential = session_ak, session_sk, token self._expiration = response.get("Expiration") except IOError as e: # logging.error('refresh Ecs sts token err', e) logging.error('refresh Ecs sts token err:%s', e)
def _call_location_service(self, key, raw_request): request = DescribeEndpointsRequest() request.set_protocol_type("https") request.set_accept_format("json") request.set_Id(raw_request.region_id) request.set_ServiceCode(raw_request.location_service_code) request.set_Type(raw_request.endpoint_type) request.endpoint = self._location_service_endpoint try: response = self._client.do_action_with_exception(request) except ServerException as e: if "InvalidRegionId" == e.get_error_code() and "The specified region does not exist." == e.get_error_msg(): # No such region` self._invalid_region_ids.add(raw_request.region_id) self.put_endpoint_entry(key, None) return elif "Illegal Parameter" == e.get_error_code() and "Please check the parameters" == e.get_error_msg(): # No such product self._invalid_product_codes.add(raw_request.product_code_lower) self.put_endpoint_entry(key, None) return else: raise e # As long as code gets here # the product code and the region id is valid # the endpoint can be still not found self._valid_product_codes.add(raw_request.product_code_lower) self._valid_region_ids.add(raw_request.region_id) found_flag = False for item in json.loads(response.decode('utf-8'))["Endpoints"]["Endpoint"]: # Location return data has a typo: SerivceCode # We still try to expect ServiceCode in case this typo would be fixed in the future service_code = item.get("ServiceCode") or item.get("SerivceCode") if service_code and item.get("Type") == raw_request.endpoint_type: found_flag = True self.put_endpoint_entry(key, item.get("Endpoint")) break if not found_flag: self.put_endpoint_entry(key, None)
def _get_session_ak_and_sk(self): request = GetSessionAkRequest() request.set_method("GET") request.set_duration_seconds(self._session_period) try: response_str = self._sts_client.do_action_with_exception(request) response = json.loads(response_str.decode('utf-8')) session_ak = str( response.get("SessionAccessKey").get("SessionAccessKeyId")) session_sk = str( response.get("SessionAccessKey").get("SessionAccessKeySecret")) self._session_credential = session_ak, session_sk except exceptions.ServerException as srv_ex: if srv_ex.error_code == 'InvalidAccessKeyId.NotFound' or srv_ex.error_code == 'SignatureDoesNotMatch': raise exceptions.ClientException( error_code.SDK_INVALID_CREDENTIAL, error_msg.get_msg('SDK_INVALID_CREDENTIAL')) else: raise
def _read_from_endpoints_json(self): with open(self.ENDPOINT_JSON) as fp: return json.loads(fp.read())