def refresh(self): print("start refresh token...") request = QueryTokenForMnsQueueRequest() request.set_MessageType(msgtype) # 数据提交方式 # smsRequest.set_method(MT.POST) # 数据提交格式 # smsRequest.set_accept_format(FT.JSON) response = acs_client.do_action_with_exception(request) # print response if response is None: raise ServerException("GET_TOKEN_FAIL", "获取token时无响应") #response = response.decode('utf-8') response_body = json.loads(response.decode('utf-8')) if response_body.get("Code") != "OK": raise ServerException("GET_TOKEN_FAIL", "获取token失败") self.__tmp_access_key = response_body.get("MessageTokenDTO").get( "AccessKeySecret") self.__tmp_access_id = response_body.get("MessageTokenDTO").get( "AccessKeyId") self.__expire_time = response_body.get("MessageTokenDTO").get( "ExpireTime") self.__token = response_body.get("MessageTokenDTO").get( "SecurityToken") print(("key=%s, id=%s, expire_time=%s, token=%s" \ % (self.__tmp_access_key, self.__tmp_access_id, self.__expire_time, self.__token))) print("finsh refresh token...")
def test_resolver_with_server_exception_invalid_regionid(self): client = Mock() client.do_action_with_exception.side_effect = ServerException( "InvalidRegionId", "The specified region does not exist.") resolver = LocationServiceEndpointResolver(client) request = ResolveEndpointRequest("region_id", "product", "servicecode", "") self.assertEqual(resolver.resolve(request), None) client.do_action_with_exception.side_effect = ServerException( "Illegal Parameter", "Please check the parameters") resolver = LocationServiceEndpointResolver(client) request = ResolveEndpointRequest("region_id", "product", "servicecode", "") self.assertEqual(resolver.resolve(request), None)
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) request_id = body_obj.get('RequestId') except ValueError or TypeError or AttributeError: # in case the response body is not a json string, return the raw # data instead pass if status < httplib.OK or status >= httplib.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 _get_server_exception(self, http_status, response_body, endpoint, string_to_sign): request_id = None try: body_obj = json.loads(response_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 logger.warning( 'Failed to parse response as json format. Response:%s', response_body) if http_status < codes.OK or http_status >= codes.MULTIPLE_CHOICES: server_error_code, server_error_message = self._parse_error_info_from_response_body( response_body.decode('utf-8')) if http_status == codes.BAD_REQUEST and server_error_code == 'SignatureDoesNotMatch': if string_to_sign == server_error_message.split(':')[1]: server_error_code = 'InvalidAccessKeySecret' server_error_message = 'The AccessKeySecret is incorrect. ' \ 'Please check your AccessKeyId and AccessKeySecret.' exception = ServerException(server_error_code, server_error_message, http_status=http_status, request_id=request_id) logger.error( "ServerException occurred. Host:%s SDK-Version:%s ServerException:%s", endpoint, aliyunsdkcore.__version__, str(exception)) return exception
def test_rsa_key_pair_signer_other_exception(self): public_key_path = os.path.join(os.path.dirname( __file__), "..", "..", "fixtures", "id_rsa.pub") public_key_id = open(public_key_path).read() private_key_path = os.path.join(os.path.dirname( __file__), "..", "..", "fixtures", "id_rsa") private_key_id = open(private_key_path).read() # ok credential = RsaKeyPairCredential( public_key_id, private_key_id, session_period=3600) signer = RsaKeyPairSigner(credential, "region_id") # for rpc request = RpcRequest("product", "version", "action_name") self.assertIsNone(request.get_query_params().get("SecurityToken")) signer._sts_client = Mock() do_action = Mock() do_action.side_effect = ServerException( "BOOM", "msg") signer._sts_client.do_action_with_exception = do_action with self.assertRaises(ServerException) as se: signer.sign('cn-hangzhou', request) self.assertEqual("BOOM", se.exception.error_code) self.assertEqual( "msg", se.exception.message)
def _get_server_exception(self, http_status, response_body, endpoint): request_id = None try: body_obj = json.loads(response_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 logger.warning( 'Failed to parse response as json format. Response:%s', response_body) if http_status < codes.OK or http_status >= codes.MULTIPLE_CHOICES: server_error_code, server_error_message = self._parse_error_info_from_response_body( response_body.decode('utf-8')) exception = ServerException(server_error_code, server_error_message, http_status=http_status, request_id=request_id) logger.error( "ServerException occurred. Host:%s SDK-Version:%s ServerException:%s", endpoint, aliyunsdkcore.__version__, str(exception)) return exception
def refresh(self): logger.info(f'{self.tk_desc} start refresh token ...') request = QueryTokenForMnsQueueRequest() request.set_MessageType(self.queue_cfg.msg_type) request.set_QueueName(self.queue_cfg.queue_name) response = acs_client.do_action_with_exception(request) logger.info(f'{self.tk_desc} QueryTokenForMnsQueueRequest response: {response}') if response is None: raise ServerException('GET_TOKEN_FAIL', f'{self.tk_desc} 获取token时无响应') response_body = json.loads(response) if response_body.get('Code') != 'OK': raise ServerException('GET_TOKEN_FAIL', f'{self.tk_desc} 获取token失败') sts_token = response_body.get('MessageTokenDTO') self.tmp_access_key = sts_token.get('AccessKeySecret') self.tmp_access_id = sts_token.get('AccessKeyId') self.expire_time = sts_token.get('ExpireTime') self.token = sts_token.get('SecurityToken') logger.info(f'{self.tk_desc} finish refresh token')
def test_resolver_with_server_exception(self): client = Mock() client.do_action_with_exception.side_effect = ServerException( "OTHER_ERROR_CODE", "msg") resolver = LocationServiceEndpointResolver(client) request = ResolveEndpointRequest("region_id", "product", "servicecode", "") with self.assertRaises(ServerException) as ex: resolver.resolve(request) self.assertEqual(ex.exception.error_code, "OTHER_ERROR_CODE") self.assertEqual(ex.exception.message, "msg")
def refresh(self): print "start refresh token..." request = QueryTokenForMnsQueueRequest() request.set_MessageType(msgtype) response = acs_client.do_action_with_exception(request) # print response if response is None: raise ServerException("GET_TOKEN_FAIL", "获取token时无响应") response_body = json.loads(response) if response_body.get("Code") != "OK": raise ServerException("GET_TOKEN_FAIL", "获取token失败") self.__tmp_access_key = response_body.get("MessageTokenDTO").get("AccessKeySecret") self.__tmp_access_id = response_body.get("MessageTokenDTO").get("AccessKeyId") self.__expire_time = response_body.get("MessageTokenDTO").get("ExpireTime") self.__token = response_body.get("MessageTokenDTO").get("SecurityToken") print "finsh refresh token..."
def _refresh_session_ak_and_sk(self): 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.decode('utf-8')) if response.get("Code") != "Success": message = 'refresh Ecs sts token err, code is ' + \ response.get("Code") raise ServerException( response.get("Code"), message, None) session_ak = response.get("AccessKeyId") session_sk = response.get("AccessKeySecret") token = response.get("SecurityToken") self._session_credential = session_ak, session_sk, token self._last_update_time = int(time.time())
def do_action_with_exception(acs_request): """Checks parameters returns fake response and raise exceptions""" # Checks request assert acs_request.get_action_name() == action acs_request_params = acs_request.get_query_params() for param in parameters: assert param in acs_request_params assert isinstance(acs_request_params[param], str) assert 'ClientToken' in acs_request_params assert acs_request.get_protocol_type() == "https" # Raises fake exceptions if raises_exception: raise ServerException(*raises_exception) # Returns fake response return json.dumps(response)
def get_server_exception(self, http_status, response_body): try: body_obj = json.loads(response_body.decode('utf-8')) request_id = body_obj.get('RequestId') except (ValueError, TypeError, AttributeError): raise RuntimeError( 'Failed to parse response as json format. Response:%s', response_body) if http_status < codes.OK or http_status >= codes.MULTIPLE_CHOICES: server_error_code, server_error_message = self._parse_error_info_from_response_body( response_body.decode('utf-8')) exception = ServerException(server_error_code, server_error_message, http_status=http_status, request_id=request_id) return exception
def _get_server_exception(self, http_status, response_body): request_id = None try: body_obj = json.loads(response_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 http_status < codes.OK or http_status >= codes.MULTIPLE_CHOICES: server_error_code, server_error_message = self._parse_error_info_from_response_body( response_body.decode('utf-8')) return ServerException(server_error_code, server_error_message, http_status=http_status, request_id=request_id)
def test_server_exception(self, log_mock, client_mock): """AliyunApp - Gather Logs, Exception""" client_mock.side_effect = ServerException("error", "bad server response") assert_false(self._app._gather_logs()) log_mock.assert_called_with("%s error occurred", "Server")
def SE(code): return ServerException(code, "some error")
def _handle_single_request(endpoint, request, request_timeout, signer=None): return 400, {}, None, ServerException("Throttling", "some error")
def do_action_with_exception(self, req): action = req.action params = req.params response = None if action == 'DescribeInstances': response = '{"Instances":{"Instance":[{"ZoneId":"' + availability_zone + '"}]}}' return response.encode('utf-8') elif action == 'CreateSnapshot': assert params['DiskId'] in (valid_disk_name, invalid_disk_name, invalid_exc_disk, invalid_duplicate_disk) assert params['SnapshotName'] is not None assert params['Description'] == 'test-backup' if params['DiskId'] == invalid_exc_disk: raise Exception('Failed to create snapshot') snapshot_return_id = snapshot_id if params[ 'DiskId'] == valid_disk_name else snapshot_duplicate_id if params[ 'DiskId'] == invalid_duplicate_disk else snapshot_failed_id response = '{"SnapshotId": "' + snapshot_return_id + '"}' return response.encode('utf-8') elif action == 'DescribeSnapshots': assert params['PageSize'] == 10 assert params['RegionId'] == region_id assert len(params['SnapshotIds']) == 1 assert params['SnapshotIds'][0] in (snapshot_id, snapshot_delete_id, snapshot_failed_id, snapshot_duplicate_id) if params['SnapshotIds'][0] == snapshot_delete_id: response = '{"Snapshots":{"Snapshot":[]}}' elif params['SnapshotIds'][0] == snapshot_failed_id: # to handle failed snapshot and then delete case response = '{"Snapshots":{"Snapshot":[{"SnapshotId":"'\ +snapshot_failed_id+'", "SourceDiskSize": '+source_disk_size+', "CreationTime": "'+snapshot_creation_time+'", "Status":"failed"}]}}' response = response if self.describe_failed_delete_snapshot_call_count <= 1 else '{"Snapshots":{"Snapshot":[]}}' self.describe_failed_delete_snapshot_call_count += 1 elif params['SnapshotIds'][0] == snapshot_duplicate_id: response = '{"Snapshots":{"Snapshot":[{}, {}]}}' response = response if self.describe_duplicate_delete_snapshot_call_count <= 1 else '{"Snapshots":{"Snapshot":[]}}' self.describe_duplicate_delete_snapshot_call_count += 1 else: response = '{"Snapshots":{"Snapshot":[{"SnapshotId":"'\ +snapshot_id+'", "SourceDiskSize": '+source_disk_size+', "CreationTime": "'+snapshot_creation_time+'", "Status":"accomplished"}]}}' return response.encode('utf-8') elif action == 'DeleteSnapshot': assert params['SnapshotId'] in (snapshot_id, snapshot_delete_id, snapshot_failed_id, snapshot_duplicate_id, snapshot_exc_id, snapshot_404_id) if params['SnapshotId'] == snapshot_exc_id: raise ServerException('SDK.InvalidRequest', 'Failed to delete snapshot', 500) elif params['SnapshotId'] == snapshot_404_id: raise ServerException('SDK.InvalidRequest', 'Failed to delete snapshot', 404) return elif action == 'DescribeDisks': assert params['PageSize'] == 10 assert params['RegionId'] == region_id assert "InstanceId" in params or "DiskIds" in params if "InstanceId" in params: assert params['InstanceId'] in (valid_vm_id, invalid_vm_id) response = '{"Disks":{"Disk":[{"DiskId":"'\ +ephemeral_disk_id+'", "Size": '+ephemeral_disk_size+', "Device": "'+ephemeral_disk_device_id+'", "Status":"In_use"}, {"DiskId":"'\ +persistent_disk_id+'", "Size": '+persistent_disk_size+', "Device": "'+persistent_disk_device_id+'", "Status":"In_use"}]}}' if params['InstanceId'] == invalid_vm_id: raise Exception('Failed to get disk information') elif "DiskIds" in params: disk_id = params['DiskIds'][0] status = 'Available' if disk_id == disk_detach_id else 'In_use' assert disk_id in (ephemeral_disk_id, disk_delete_id, disk_detach_id, disk_duplicate_id, disk_exc_id, disk_create_duplicate_id, disk_attach_error_id) if disk_id == disk_delete_id: response = '{"Disks":{"Disk":[]}}' elif disk_id == disk_attach_error_id: response = '{"Disks":{"Disk":[{"DiskId":"'\ +disk_id+'", "Size": '+ephemeral_disk_size+', "Device": "", "Status":"In_use"}]}}' elif disk_id == disk_exc_id: raise Exception('Failed to get disk information') elif disk_id == disk_duplicate_id: response = '{"Disks":{"Disk":[{}, {}]}}' elif disk_id == disk_create_duplicate_id: response = '{"Disks":{"Disk":[{}, {}]}}' response = response if self.create_duplicate_disk_call_count <= 1 else '{"Disks":{"Disk":[]}}' self.create_duplicate_disk_call_count += 1 else: response = '{"Disks":{"Disk":[{"DiskId":"'\ +disk_id+'", "Size": '+ephemeral_disk_size+', "Device": "'+ephemeral_disk_device_id+'", "Status":"'+status+'"}]}}' return response.encode('utf-8') elif action == 'CreateDisk': disk_category = params['DiskCategory'] assert params['RegionId'] == region_id assert params['ZoneId'] == availability_zone assert 'DiskName' in params assert disk_category in ('cloud_ssd', 'duplicate') assert params['Encrypted'] == True assert params['Size'] == 20 response = '{"DiskId": "' + ephemeral_disk_id + '"}' if disk_category == 'duplicate': response = '{"DiskId": "' + disk_create_duplicate_id + '"}' return response.encode('utf-8') elif action == 'DeleteDisk': assert params['DiskId'] in (disk_delete_id, disk_create_duplicate_id, disk_exc_id, disk_404_id) if params['DiskId'] == disk_exc_id: raise ServerException('SDK.InvalidRequest', 'Failed to delete disk', 500) elif params['DiskId'] == disk_404_id: raise ServerException('SDK.InvalidRequest', 'Failed to delete disk', 404) return elif action == 'AttachDisk': assert params['InstanceId'] in (valid_vm_id, invalid_vm_id) assert params['DiskId'] in (ephemeral_disk_id, disk_attach_error_id) if params['InstanceId'] == invalid_vm_id: raise Exception('Failed to create attachment') return elif action == 'DetachDisk': assert params['InstanceId'] in (valid_vm_id, invalid_vm_id, notfound_vm_id) assert params['DiskId'] in (disk_detach_id, disk_attach_error_id) if params['InstanceId'] == invalid_vm_id: raise ServerException('SDK.InvalidRequest', 'Failed to delete attachment', 500) elif params['InstanceId'] == notfound_vm_id: raise ServerException('SDK.InvalidRequest', 'Failed to delete attachment', 404) return return response
def test_constructor(self): ex = ServerException("code", "message", 400, "requestid") self.assertEqual(ex.get_error_type(), "Server") self.assertEqual(ex.get_error_msg(), "message") self.assertEqual(ex.get_error_code(), "code") self.assertEqual(ex.get_http_status(), 400) self.assertEqual(ex.get_request_id(), "requestid") self.assertEqual( str(ex), "HTTP Status: 400 Error:code message RequestID: requestid") ex.set_error_code("newCode") self.assertEqual(ex.get_error_code(), "newCode") ex.set_error_msg("new message") self.assertEqual(ex.get_error_msg(), "new message") self.assertEqual( str(ex), "HTTP Status: 400 Error:newCode new message RequestID: requestid")