当前位置: 首页>>代码示例>>Python>>正文


Python client.V1Pod方法代码示例

本文整理汇总了Python中kubernetes.client.V1Pod方法的典型用法代码示例。如果您正苦于以下问题:Python client.V1Pod方法的具体用法?Python client.V1Pod怎么用?Python client.V1Pod使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在kubernetes.client的用法示例。


在下文中一共展示了client.V1Pod方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: build_smartstack_location_dict

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def build_smartstack_location_dict(
    location: str,
    matched_backends_and_tasks: List[
        Tuple[
            Optional[HaproxyBackend],
            Optional[Union[marathon_tools.MarathonTask, V1Pod]],
        ]
    ],
    should_return_individual_backends: bool = False,
) -> MutableMapping[str, Any]:
    running_backends_count = 0
    backends = []
    for backend, task in matched_backends_and_tasks:
        if backend is None:
            continue
        if backend_is_up(backend):
            running_backends_count += 1
        if should_return_individual_backends:
            backends.append(build_smartstack_backend_dict(backend, task))

    return {
        "name": location,
        "running_backends_count": running_backends_count,
        "backends": backends,
    } 
开发者ID:Yelp,项目名称:paasta,代码行数:27,代码来源:smartstack_tools.py

示例2: get_events_for_object

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def get_events_for_object(
    kube_client: KubeClient,
    obj: Union[V1Pod, V1Deployment, V1StatefulSet, V1ReplicaSet],
    kind: str,  # for some reason, obj.kind isn't populated when this function is called so we pass it in by hand
) -> List[V1Event]:
    host = KubeConfiguration().host

    # The python kubernetes client doesn't support the V1Events API
    # yet, so we have to make the request by hand (we need the V1Events
    # API so that we can query by the involvedObject.name/kind)
    #
    # Also, as best as I can tell, the list_namespaced_event API call under the
    # CoreV1 API does _not_ return the events that we're interested in.
    events = kube_client.request(
        "GET",
        f"{host}/api/v1/namespaces/{obj.metadata.namespace}/events",
        query_params={
            "fieldSelector": f"involvedObject.name={obj.metadata.name},involvedObject.kind={kind}",
            "limit": MAX_EVENTS_TO_RETRIEVE,
        },
    )
    parsed_events = json.loads(events.data)
    return parsed_events["items"] 
开发者ID:Yelp,项目名称:paasta,代码行数:25,代码来源:kubernetes_tools.py

示例3: _create_k8s_job

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def _create_k8s_job(self, yaml_spec):
    """ _create_k8s_job creates a kubernetes job based on the yaml spec """
    pod = k8s_client.V1Pod(metadata=k8s_client.V1ObjectMeta(generate_name=yaml_spec['metadata']['generateName'],
                                                            annotations=yaml_spec['metadata']['annotations']))
    container = k8s_client.V1Container(name = yaml_spec['spec']['containers'][0]['name'],
                                       image = yaml_spec['spec']['containers'][0]['image'],
                                       args = yaml_spec['spec']['containers'][0]['args'])
    pod.spec = k8s_client.V1PodSpec(restart_policy=yaml_spec['spec']['restartPolicy'],
                                    containers = [container],
                                    service_account_name=yaml_spec['spec']['serviceAccountName'])
    try:
      api_response = self._corev1.create_namespaced_pod(yaml_spec['metadata']['namespace'], pod)
      return api_response.metadata.name, True
    except k8s_client.rest.ApiException as e:
      logging.exception("Exception when calling CoreV1Api->create_namespaced_pod: {}\n".format(str(e)))
      return '', False 
开发者ID:kubeflow,项目名称:pipelines,代码行数:18,代码来源:_k8s_job_helper.py

示例4: get_current_kfp_pod

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def get_current_kfp_pod(client: k8s_client.CoreV1Api) -> k8s_client.V1Pod:
  """Get manifest of the KFP pod in which this program is running.

  Args:
    client: A kubernetes CoreV1Api client.
  Raises:
    RuntimeError: If KFP pod cannot be determined from the environment, i.e.
        this program is not running inside the KFP.
  Returns:
    The manifest of the pod this program is running on.
  """
  try:
    namespace = os.environ[KFP_NAMESPACE]
    pod_name = os.environ[KFP_POD_NAME]
    return client.read_namespaced_pod(name=pod_name, namespace=namespace)
  except KeyError:
    raise RuntimeError('Cannot determine KFP pod from the environment.') 
开发者ID:tensorflow,项目名称:tfx,代码行数:19,代码来源:kube_utils.py

示例5: _get_pod

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def _get_pod(self, core_api: client.CoreV1Api, pod_name: Text,
               namespace: Text) -> Optional[client.V1Pod]:
    """Get a pod from Kubernetes metadata API.

    Args:
      core_api: Client of Core V1 API of Kubernetes API.
      pod_name: The name of the POD.
      namespace: The namespace of the POD.

    Returns:
      The found POD object. None if it's not found.

    Raises:
      RuntimeError: When it sees unexpected errors from Kubernetes API.
    """
    try:
      return core_api.read_namespaced_pod(name=pod_name, namespace=namespace)
    except client.rest.ApiException as e:
      if e.status != 404:
        raise RuntimeError('Unknown error! \nReason: %s\nBody: %s' %
                           (e.reason, e.body))
      return None 
开发者ID:tensorflow,项目名称:tfx,代码行数:24,代码来源:kubernetes_component_launcher.py

示例6: pod3

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def pod3():
    return V1Pod(
        metadata=V1ObjectMeta(name='pod3', annotations=dict()),
        status=V1PodStatus(
            phase='Pending',
            conditions=[
                V1PodCondition(status='False', type='PodScheduled', reason='Unschedulable')
            ]
        ),
        spec=V1PodSpec(
            containers=[
                V1Container(
                    name='container2',
                    resources=V1ResourceRequirements(requests={'cpu': '1.5'})
                )
            ],
            node_selector={'clusterman.com/pool': 'bar'}
        )
    ) 
开发者ID:Yelp,项目名称:clusterman,代码行数:21,代码来源:kubernetes_cluster_connector_test.py

示例7: pod5

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def pod5():
    return V1Pod(
        metadata=V1ObjectMeta(name='pod5', annotations=dict()),
        status=V1PodStatus(
            phase='Pending',
            conditions=None,
        ),
        spec=V1PodSpec(
            containers=[
                V1Container(
                    name='container2',
                    resources=V1ResourceRequirements(requests={'cpu': '1.5'})
                )
            ],
            node_selector={'clusterman.com/pool': 'bar'}
        )
    ) 
开发者ID:Yelp,项目名称:clusterman,代码行数:19,代码来源:kubernetes_cluster_connector_test.py

示例8: touch_member

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def touch_member(self, data, permanent=False):
        cluster = self.cluster
        if cluster and cluster.leader and cluster.leader.name == self._name:
            role = 'promoted' if data['role'] in ('replica', 'promoted') else 'master'
        elif data['state'] == 'running' and data['role'] != 'master':
            role = data['role']
        else:
            role = None

        member = cluster and cluster.get_member(self._name, fallback_to_leader=False)
        pod_labels = member and member.data.pop('pod_labels', None)
        ret = pod_labels is not None and pod_labels.get(self._role_label) == role and deep_compare(data, member.data)

        if not ret:
            metadata = {'namespace': self._namespace, 'name': self._name, 'labels': {self._role_label: role},
                        'annotations': {'status': json.dumps(data, separators=(',', ':'))}}
            body = k8s_client.V1Pod(metadata=k8s_client.V1ObjectMeta(**metadata))
            ret = self._api.patch_namespaced_pod(self._name, self._namespace, body)
            if ret:
                self._pods.set(self._name, ret)
        if self._should_create_config_service:
            self._create_config_service()
        return ret 
开发者ID:zalando,项目名称:patroni,代码行数:25,代码来源:kubernetes.py

示例9: allocated_node_resources

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def allocated_node_resources(pods: Sequence[V1Pod]) -> Mapping[str, float]:
    cpus = mem = disk = 0
    for pod in pods:
        cpus += sum(
            ResourceParser.cpus(c.resources.requests) for c in pod.spec.containers
        )
        mem += sum(
            ResourceParser.mem(c.resources.requests) for c in pod.spec.containers
        )
        disk += sum(
            ResourceParser.disk(c.resources.requests) for c in pod.spec.containers
        )
    return {"cpu": cpus, "memory": mem, "ephemeral-storage": disk} 
开发者ID:Yelp,项目名称:paasta,代码行数:15,代码来源:metastatus_lib.py

示例10: match_backends_and_pods

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def match_backends_and_pods(
    backends: Iterable[HaproxyBackend], pods: Iterable[V1Pod]
) -> List[Tuple[Optional[HaproxyBackend], Optional[V1Pod]]]:
    """Returns tuples of matching (backend, pod) pairs, as matched by IP. Each backend will be listed exactly
    once. If a backend does not match with a pod, (backend, None) will be included.
    If a pod's IP does not match with any backends, (None, pod) will be included.

    :param backends: An iterable of haproxy backend dictionaries, e.g. the list returned by
                     smartstack_tools.get_multiple_backends.
    :param pods: An iterable of V1Pod objects.
    """

    # { ip : [backend1, backend2], ... }
    backends_by_ip: DefaultDict[str, List[HaproxyBackend]] = collections.defaultdict(
        list
    )
    backend_pod_pairs = []

    for backend in backends:
        ip, port, _ = ip_port_hostname_from_svname(backend["svname"])
        backends_by_ip[ip].append(backend)

    for pod in pods:
        ip = pod.status.pod_ip
        for backend in backends_by_ip.pop(ip, [None]):
            backend_pod_pairs.append((backend, pod))

    # we've been popping in the above loop, so anything left didn't match a k8s pod.
    for backends in backends_by_ip.values():
        for backend in backends:
            backend_pod_pairs.append((backend, None))

    return backend_pod_pairs 
开发者ID:Yelp,项目名称:paasta,代码行数:35,代码来源:smartstack_tools.py

示例11: build_smartstack_backend_dict

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def build_smartstack_backend_dict(
    smartstack_backend: HaproxyBackend,
    task: Union[V1Pod, Optional[marathon_tools.MarathonTask]],
) -> MutableMapping[str, Any]:
    svname = smartstack_backend["svname"]
    if isinstance(task, V1Pod):
        node_hostname = svname.split("_")[0]
        pod_ip = svname.split("_")[1].split(":")[0]
        hostname = f"{node_hostname}:{pod_ip}"
    else:
        hostname = svname.split("_")[0]
    port = svname.split("_")[-1].split(":")[-1]

    smartstack_backend_dict = {
        "hostname": hostname,
        "port": int(port),
        "status": smartstack_backend["status"],
        "check_status": smartstack_backend["check_status"],
        "check_code": smartstack_backend["check_code"],
        "last_change": int(smartstack_backend["lastchg"]),
        "has_associated_task": task is not None,
    }

    check_duration = smartstack_backend["check_duration"]
    if check_duration:
        smartstack_backend_dict["check_duration"] = int(check_duration)

    return smartstack_backend_dict 
开发者ID:Yelp,项目名称:paasta,代码行数:30,代码来源:smartstack_tools.py

示例12: get_tail_lines_for_kubernetes_container

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def get_tail_lines_for_kubernetes_container(
    kube_client: KubeClient,
    pod: V1Pod,
    container: V1ContainerStatus,
    num_tail_lines: int,
) -> MutableMapping[str, Any]:
    tail_lines: MutableMapping[str, Any] = {
        "stdout": [],
        "stderr": [],
        "error_message": "",
    }

    if container.name != HACHECK_POD_NAME:
        error = ""
        if container.state.waiting:
            error = container.state.waiting.message or ""
        elif container.state.terminated:
            error = container.state.terminated.message or ""
        tail_lines["error_message"] = error

        try:
            if num_tail_lines > 0:
                log = kube_client.core.read_namespaced_pod_log(
                    name=pod.metadata.name,
                    namespace=pod.metadata.namespace,
                    container=container.name,
                    tail_lines=num_tail_lines,
                )
                tail_lines["stdout"].extend(log.split("\n"))
        except ApiException as e:
            # there is a potential race condition in which a pod's containers
            # have not failed, but have when we get the container's logs. in this
            # case, use the error from the exception, though it is less accurate.
            if error == "":
                body = json.loads(e.body)
                error = body.get("message", "")
            tail_lines["error_message"] = f"couldn't read stdout/stderr: '{error}'"

    return tail_lines 
开发者ID:Yelp,项目名称:paasta,代码行数:41,代码来源:kubernetes_tools.py

示例13: get_pod_events

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def get_pod_events(kube_client: KubeClient, pod: V1Pod) -> List[V1Event]:
    try:
        pod_events = kube_client.core.list_namespaced_event(
            namespace=pod.metadata.namespace,
            field_selector=f"involvedObject.name={pod.metadata.name}",
        )
        return pod_events.items if pod_events else []
    except ApiException:
        return [] 
开发者ID:Yelp,项目名称:paasta,代码行数:11,代码来源:kubernetes_tools.py

示例14: get_pod_event_messages

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def get_pod_event_messages(kube_client: KubeClient, pod: V1Pod) -> List[Dict]:
    pod_events = get_pod_events(kube_client, pod)
    pod_event_messages = []
    if pod_events:
        for event in pod_events:
            message = {
                "message": event.message,
                "timeStamp": str(event.last_timestamp),
            }
            pod_event_messages.append(message)
    return pod_event_messages 
开发者ID:Yelp,项目名称:paasta,代码行数:13,代码来源:kubernetes_tools.py

示例15: pods_for_service_instance

# 需要导入模块: from kubernetes import client [as 别名]
# 或者: from kubernetes.client import V1Pod [as 别名]
def pods_for_service_instance(
    service: str, instance: str, kube_client: KubeClient, namespace: str = "paasta"
) -> Sequence[V1Pod]:
    return kube_client.core.list_namespaced_pod(
        label_selector=f"paasta.yelp.com/service={service},paasta.yelp.com/instance={instance}",
        namespace=namespace,
    ).items 
开发者ID:Yelp,项目名称:paasta,代码行数:9,代码来源:kubernetes_tools.py


注:本文中的kubernetes.client.V1Pod方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。