本文整理汇总了Python中kubernetes.client.CoreV1Api方法的典型用法代码示例。如果您正苦于以下问题:Python client.CoreV1Api方法的具体用法?Python client.CoreV1Api怎么用?Python client.CoreV1Api使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类kubernetes.client
的用法示例。
在下文中一共展示了client.CoreV1Api方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def main():
contexts, active_context = config.list_kube_config_contexts()
if not contexts:
print("Cannot find any context in kube-config file.")
return
contexts = [context['name'] for context in contexts]
active_index = contexts.index(active_context['name'])
option, _ = pick(contexts, title="Pick the context to load",
default_index=active_index)
# Configs can be set in Configuration class directly or using helper
# utility
config.load_kube_config(context=option)
print("Active host is %s" % configuration.Configuration().host)
v1 = client.CoreV1Api()
print("Listing pods with their IPs:")
ret = v1.list_pod_for_all_namespaces(watch=False)
for item in ret.items:
print(
"%s\t%s\t%s" %
(item.status.pod_ip,
item.metadata.namespace,
item.metadata.name))
示例2: stop
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [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
示例3: __init__
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def __init__(self, k8s_config=None, k8s_namespace=None, label_selector=None):
from kubernetes import config, client
from gevent.threadpool import ThreadPool
if k8s_config is not None:
self._k8s_config = k8s_config
elif os.environ.get('KUBE_API_ADDRESS'):
self._k8s_config = client.Configuration()
self._k8s_config.host = os.environ['KUBE_API_ADDRESS']
else:
self._k8s_config = config.load_incluster_config()
self._k8s_namespace = k8s_namespace or os.environ.get('MARS_K8S_POD_NAMESPACE') or 'default'
self._label_selector = label_selector
self._client = client.CoreV1Api(client.ApiClient(self._k8s_config))
self._pool = ThreadPool(1)
self._pod_to_ep = None
示例4: delete_pods
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def delete_pods(name: str, ns: str = "default",
label_selector: str = "name in ({name})",
secrets: Secrets = None):
"""
Delete pods by `name` in the namespace `ns`.
The pods are deleted without a graceful period to trigger an abrupt
termination.
The selected resources are matched by the given `label_selector`.
"""
label_selector = label_selector.format(name=name)
api = create_k8s_api_client(secrets)
v1 = client.CoreV1Api(api)
if label_selector:
ret = v1.list_namespaced_pod(ns, label_selector=label_selector)
else:
ret = v1.list_namespaced_pod(ns)
logger.debug("Found {d} pods named '{n}'".format(
d=len(ret.items), n=name))
body = client.V1DeleteOptions()
for p in ret.items:
v1.delete_namespaced_pod(p.metadata.name, ns, body=body)
示例5: create_service_endpoint
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def create_service_endpoint(spec_path: str, ns: str = "default",
secrets: Secrets = None):
"""
Create a service endpoint described by the service config, which must be
the path to the JSON or YAML representation of the service.
"""
api = create_k8s_api_client(secrets)
with open(spec_path) as f:
p, ext = os.path.splitext(spec_path)
if ext == '.json':
service = json.loads(f.read())
elif ext in ['.yml', '.yaml']:
service = yaml.safe_load(f.read())
else:
raise ActivityFailed(
"cannot process {path}".format(path=spec_path))
v1 = client.CoreV1Api(api)
v1.create_namespaced_service(ns, body=service)
示例6: service_is_initialized
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def service_is_initialized(name: str, ns: str = "default",
label_selector: str = "name in ({name})",
secrets: Secrets = None):
"""
Lookup a service endpoint by its name and raises :exc:`FailedProbe` when
the service was not found or not initialized.
"""
label_selector = label_selector.format(name=name)
api = create_k8s_api_client(secrets)
v1 = client.CoreV1Api(api)
if label_selector:
ret = v1.list_namespaced_service(ns, label_selector=label_selector)
else:
ret = v1.list_namespaced_service(ns)
logger.debug("Found {d} service(s) named '{n}' ins ns '{s}'".format(
d=len(ret.items), n=name, s=ns))
if not ret.items:
raise ActivityFailed(
"service '{name}' is not initialized".format(name=name))
return True
示例7: get_k8s_nodes
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def get_k8s_nodes(exclude_node_label_key=app_config["EXCLUDE_NODE_LABEL_KEY"]):
"""
Returns a list of kubernetes nodes
"""
try:
config.load_incluster_config()
except config.ConfigException:
try:
config.load_kube_config()
except config.ConfigException:
raise Exception("Could not configure kubernetes python client")
k8s_api = client.CoreV1Api()
logger.info("Getting k8s nodes...")
response = k8s_api.list_node()
if exclude_node_label_key is not None:
nodes = []
for node in response.items:
if exclude_node_label_key not in node.metadata.labels:
nodes.append(node)
response.items = nodes
logger.info("Current k8s node count is {}".format(len(response.items)))
return response.items
示例8: delete_node
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [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))
示例9: __init__
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def __init__(self,
kube_client: client.CoreV1Api = None,
in_cluster: bool = True,
cluster_context: Optional[str] = None,
extract_xcom: bool = False):
"""
Creates the launcher.
:param kube_client: kubernetes client
:param in_cluster: whether we are in cluster
:param cluster_context: context of the cluster
:param extract_xcom: whether we should extract xcom
"""
super().__init__()
self._client = kube_client or get_kube_client(in_cluster=in_cluster,
cluster_context=cluster_context)
self._watch = watch.Watch()
self.extract_xcom = extract_xcom
示例10: run
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def run(self) -> None:
"""Performs watching"""
kube_client: client.CoreV1Api = get_kube_client()
if not self.worker_uuid:
raise AirflowException(NOT_STARTED_MESSAGE)
while True:
try:
self.resource_version = self._run(kube_client, self.resource_version,
self.worker_uuid, self.kube_config)
except ReadTimeoutError:
self.log.warning("There was a timeout error accessing the Kube API. "
"Retrying request.", exc_info=True)
time.sleep(1)
except Exception:
self.log.exception('Unknown error in KubernetesJobWatcher. Failing')
raise
else:
self.log.warning('Watch died gracefully, starting back up with: '
'last resource_version: %s', self.resource_version)
示例11: start
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def start(self) -> None:
"""Starts the executor"""
self.log.info('Start Kubernetes executor')
self.worker_uuid = KubeWorkerIdentifier.get_or_create_current_kube_worker_uuid()
if not self.worker_uuid:
raise AirflowException("Could not get worker uuid")
self.log.debug('Start with worker_uuid: %s', self.worker_uuid)
# always need to reset resource version since we don't know
# when we last started, note for behavior below
# https://github.com/kubernetes-client/python/blob/master/kubernetes/docs
# /CoreV1Api.md#list_namespaced_pod
KubeResourceVersion.reset_resource_version()
self.kube_client = get_kube_client()
self.kube_scheduler = AirflowKubernetesScheduler(
self.kube_config, self.task_queue, self.result_queue,
self.kube_client, self.worker_uuid
)
self._inject_secrets()
self.clear_not_launched_queued_tasks()
示例12: main
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def main():
config.load_kube_config()
api_instance = client.CoreV1Api()
body = {
"metadata": {
"labels": {
"foo": "bar",
"baz": None}
}
}
api_response = api_instance.patch_node("minikube", body)
pprint(api_response)
示例13: create_service
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def create_service():
core_v1_api = client.CoreV1Api()
body = client.V1Service(
api_version="v1",
kind="Service",
metadata=client.V1ObjectMeta(
name="service-example"
),
spec=client.V1ServiceSpec(
selector={"app": "deployment"},
ports=[client.V1ServicePort(
port=5678,
target_port=5678
)]
)
)
# Creation of the Deployment in specified namespace
# (Can replace "default" with a namespace you may have created)
core_v1_api.create_namespaced_service(namespace="default", body=body)
示例14: test_create_deployment_non_default_namespace_from_yaml
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def test_create_deployment_non_default_namespace_from_yaml(self):
"""
Should be able to create a namespace "dep",
and then create a deployment in the just-created namespace.
"""
k8s_client = client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "dep-namespace.yaml")
utils.create_from_yaml(
k8s_client, self.path_prefix + "dep-deployment.yaml")
core_api = client.CoreV1Api(k8s_client)
ext_api = client.AppsV1Api(k8s_client)
nmsp = core_api.read_namespace(name="dep")
self.assertIsNotNone(nmsp)
dep = ext_api.read_namespaced_deployment(name="nginx-deployment",
namespace="dep")
self.assertIsNotNone(dep)
ext_api.delete_namespaced_deployment(
name="nginx-deployment", namespace="dep",
body={})
core_api.delete_namespace(name="dep", body={})
示例15: test_create_general_list_from_yaml
# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import CoreV1Api [as 别名]
def test_create_general_list_from_yaml(self):
"""
Should be able to create a service and a deployment
from a kind: List yaml file
"""
k8s_client = client.api_client.ApiClient(configuration=self.config)
utils.create_from_yaml(
k8s_client, self.path_prefix + "list.yaml")
core_api = client.CoreV1Api(k8s_client)
ext_api = client.AppsV1Api(k8s_client)
svc = core_api.read_namespaced_service(name="list-service-test",
namespace="default")
self.assertIsNotNone(svc)
dep = ext_api.read_namespaced_deployment(name="list-deployment-test",
namespace="default")
self.assertIsNotNone(dep)
core_api.delete_namespaced_service(name="list-service-test",
namespace="default", body={})
ext_api.delete_namespaced_deployment(name="list-deployment-test",
namespace="default", body={})