本文整理汇总了Python中kubernetes.client.rest.ApiException方法的典型用法代码示例。如果您正苦于以下问题:Python rest.ApiException方法的具体用法?Python rest.ApiException怎么用?Python rest.ApiException使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kubernetes.client.rest
的用法示例。
在下文中一共展示了rest.ApiException方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: stop
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def stop(self, wait=False, timeout=0):
from kubernetes.client import CoreV1Api
api = CoreV1Api(self._api_client)
api.delete_namespace(self._namespace)
if wait:
start_time = time.time()
while True:
try:
api.read_namespace(self._namespace)
except K8SApiException as ex:
if ex.status != 404: # pragma: no cover
raise
break
else:
time.sleep(1)
if timeout and time.time() - start_time > timeout: # pragma: no cover
raise TimeoutError
示例2: scale_statefulset
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def scale_statefulset(name: str, replicas: int, ns: str = "default",
secrets: Secrets = None):
"""
Scale a stateful set up or down. The `name` is the name of the stateful
set.
"""
api = create_k8s_api_client(secrets)
v1 = client.AppsV1Api(api)
body = {"spec": {"replicas": replicas}}
try:
v1.patch_namespaced_stateful_set(name, namespace=ns, body=body)
except ApiException as e:
raise ActivityFailed(
"failed to scale '{s}' to {r} replicas: {e}".format(
s=name, r=replicas, e=str(e)))
示例3: delete_node
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def delete_node(node_name):
"""
Deletes a kubernetes node from the cluster
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
configuration = client.Configuration()
# create an instance of the API class
k8s_api = client.CoreV1Api(client.ApiClient(configuration))
logger.info("Deleting k8s node {}...".format(node_name))
try:
if not app_config['DRY_RUN']:
k8s_api.delete_node(node_name)
else:
k8s_api.delete_node(node_name, dry_run="true")
logger.info("Node deleted")
except ApiException as e:
logger.info("Exception when calling CoreV1Api->delete_node: {}".format(e))
示例4: api_exception
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def api_exception(e):
"""
Returns the proper Exception class for the given kubernetes.client.rest.ApiException object
https://github.com/kubernetes/community/blob/master/contributors/devel/api-conventions.md#success-codes
"""
_, _, exc_traceback = sys.exc_info()
tb = '\n'.join(traceback.format_tb(exc_traceback))
return {
400: BadRequestError,
401: UnauthorizedError,
403: ForbiddenError,
404: NotFoundError,
405: MethodNotAllowedError,
409: ConflictError,
410: GoneError,
422: UnprocessibleEntityError,
429: TooManyRequestsError,
500: InternalServerError,
503: ServiceUnavailableError,
504: ServerTimeoutError,
}.get(e.status, DynamicApiError)(e, tb)
示例5: meta_request
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def meta_request(func):
""" Handles parsing response structure and translating API Exceptions """
def inner(self, *args, **kwargs):
serialize_response = kwargs.pop('serialize', True)
serializer = kwargs.pop('serializer', ResourceInstance)
try:
resp = func(self, *args, **kwargs)
except ApiException as e:
raise api_exception(e)
if serialize_response:
try:
if six.PY2:
return serializer(self, json.loads(resp.data))
return serializer(self, json.loads(resp.data.decode('utf8')))
except ValueError:
if six.PY2:
return resp.data
return resp.data.decode('utf8')
return resp
return inner
示例6: get_component_status
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def get_component_status(self):
component_data = []
try:
components = self.api_instance.list_component_status()
for c in components.items:
status, msg = '', ''
for condition in c.conditions:
if condition.type == 'Healthy':
msg = condition.message
if condition.status == 'True':
status = 'RUNNING'
elif condition.status == 'False':
status = 'ERROR'
else:
status = condition.status
component = ClusterHealthData(namespace='component', name=c.metadata.name, status=status,
ready='1/1', age=0, msg=msg, restart_count=0)
component_data.append(component.__dict__)
except ApiException as e:
logger.error(msg='list component error ' + e.reason, exc_info=True)
return component_data
示例7: get
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def get(self):
self._validate()
try:
if self.namespace:
return self.api.get_namespaced_custom_object(
self.group, self.version, self.namespace, self.plural, self.name
)
return self.api.get_cluster_custom_object(self.group, self.version, self.plural, self.name)
except ApiException as e:
if e.reason == 'Not Found':
return None
log.error('{}'.format(add_indent(e.body)))
raise ProvisioningError(e)
示例8: delete
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def delete(self):
self._validate()
try:
if self.namespace:
return self.api.delete_namespaced_custom_object(
self.group, self.version, self.namespace, self.plural, self.name,
client.V1DeleteOptions(propagation_policy='Foreground')
)
return self.api.delete_cluster_custom_object(
self.group, self.version, self.plural, self.name,
client.V1DeleteOptions(propagation_policy='Foreground')
)
except ApiException as e:
if e.reason == 'Not Found':
return None
log.error(
'{}'.format(add_indent(e.body)))
raise ProvisioningError(e)
示例9: list_api_resources
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def list_api_resources(self, version):
try:
return self.api_client.call_api(
resource_path='/api/{}'.format(version),
method='GET',
header_params={
'Accept': self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']
),
'Content-Type': self.api_client.select_header_content_type(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']
)
},
response_type='V1APIResourceList',
auth_settings=['BearerToken'],
_return_http_data_only=True,
_preload_content=True,
)
except ApiException as e:
if e.reason == 'Not Found':
log.error('The resource definition with the specified version was not found')
return None
log.error('{}'.format(add_indent(e.body)))
raise ProvisioningError(e)
示例10: delete_namespaced_deployment
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def delete_namespaced_deployment(self, name, body, namespace):
if self.name == 'fail':
raise ApiException('Delete deployment fail')
if self.name == '404' or name == '404':
raise ApiException(reason='Not Found')
if self.name == 'test1' or name == 'test1':
my_response = namedtuple('my_response', 'message')
return my_response(message='Failed')
if self.name == 'test2' or name == 'test2':
my_response = namedtuple('my_response', 'message')
return my_response(message=None)
return {'key1': 'value1'}
# Service
示例11: read_namespaced_job
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def read_namespaced_job(self, name, namespace):
if self.name == 'fail':
raise ApiException('Get daemonset fail')
if self.name == '404':
raise ApiException(reason='Not Found')
my_response = namedtuple('my_response', 'metadata status')
my_status = namedtuple('my_status', 'failed conditions')
if self.name == 'test1':
return my_response(metadata={}, status=my_status(failed='Failed',
conditions=[]))
if self.name == 'test2':
my_conditions = namedtuple('my_conditions', 'type')
return my_response(metadata={}, status=my_status(failed=None,
conditions=[my_conditions(type='Failed')]))
if self.name == 'test3':
my_conditions = namedtuple('my_conditions', 'type')
return my_response(metadata={}, status=my_status(failed=None,
conditions=[my_conditions(type='Complete')]))
return my_response(metadata={'key1': 'value1'}, status={'key1': 'value1'})
# StorageClass
示例12: read_storage_class
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def read_storage_class(self, name):
if self.name == 'fail':
raise ApiException('Get storage class fail')
if self.name == '404' or name == '404':
raise ApiException(reason='Not Found')
my_response = namedtuple('my_response', 'metadata status')
my_status = namedtuple('my_status',
'replicas available_replicas ready_replicas updated_replicas unavailable_replicas')
if self.name == 'test1':
return my_response(metadata={}, status=my_status(replicas=3,
available_replicas=2,
ready_replicas=1,
updated_replicas=None,
unavailable_replicas=1))
if self.name == 'test2' or name == 'test2':
return my_response(metadata={}, status=my_status(replicas=1,
available_replicas=1,
ready_replicas=1,
updated_replicas=1,
unavailable_replicas=None))
return my_response(metadata={'key1': 'value1'}, status={'key1': 'value1'})
示例13: delete_storage_class
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def delete_storage_class(self, name, body):
if self.name == 'fail':
raise ApiException('Delete storage class fail')
if self.name == '404' or name == '404':
raise ApiException(reason='Not Found')
if self.name == 'test1' or name == 'test1':
my_response = namedtuple('my_response', 'message')
return my_response(message='Failed')
if self.name == 'test2' or name == 'test2':
my_response = namedtuple('my_response', 'message')
return my_response(message=None)
return {'key1': 'value1'}
# PersistentVolumeClaim
示例14: test_faulty_service_account
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def test_faulty_service_account(self):
bad_service_account_name = "foobar"
k = KubernetesPodOperator(
namespace='default',
image="ubuntu:16.04",
cmds=["bash", "-cx"],
arguments=["echo 10"],
labels={"foo": "bar"},
name="test",
task_id="task",
in_cluster=False,
do_xcom_push=False,
startup_timeout_seconds=5,
service_account_name=bad_service_account_name,
)
with self.assertRaises(ApiException):
context = create_context(k)
k.execute(context)
actual_pod = self.api_client.sanitize_for_serialization(k.pod)
self.expected_pod['spec']['serviceAccountName'] = bad_service_account_name
self.assertEqual(self.expected_pod, actual_pod)
示例15: _inject_secrets
# 需要导入模块: from kubernetes.client import rest [as 别名]
# 或者: from kubernetes.client.rest import ApiException [as 别名]
def _inject_secrets(self) -> None:
def _create_or_update_secret(secret_name, secret_path):
try:
return self.kube_client.create_namespaced_secret(
self.kube_config.executor_namespace, kubernetes.client.V1Secret(
data={
'key.json': base64.b64encode(open(secret_path, 'r').read())},
metadata=kubernetes.client.V1ObjectMeta(name=secret_name)),
**self.kube_config.kube_client_request_args)
except ApiException as e:
if e.status == 409:
return self.kube_client.replace_namespaced_secret(
secret_name, self.kube_config.executor_namespace,
kubernetes.client.V1Secret(
data={'key.json': base64.b64encode(
open(secret_path, 'r').read())},
metadata=kubernetes.client.V1ObjectMeta(name=secret_name)),
**self.kube_config.kube_client_request_args)
self.log.exception(
'Exception while trying to inject secret. '
'Secret name: %s, error details: %s',
secret_name, e
)
raise