python k8s sdk调用示例(四)pod

1,566 阅读2分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

# 依赖库
kubernetes==12.0.1

获取pod列表,根据标签过滤

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from kubernetes import client, config

# 根据labels过滤pod列表
# 参数说明:
# config_path:k8s集群token文件路径
# namespace:k8s namespace
# labels:过滤条件,是dict,比如{"appid": "xxx", "appname": "yyy"}    
def list_pod_by_labels(config_path, namespace, labels=None):
    # load k8s集群token信息
    config.load_kube_config(config_path)
    v1 = client.CoreV1Api()

    # 拼接过滤条件,将过滤条件{"appid": "xxx", "appname": "yyy"}凭借成字符串,格式为appid=xxx,appname=yyy
    labels_str = ''
    if labels:
        labels_list = []
        for key, value in labels.items():
            labels_list.append('{0}={1}'.format(key, value))
        labels_str = ','.join(labels_list)

    # 根据label读取pod列表
    pod_list = []
    ret = v1.list_namespaced_pod(namespace=namespace, label_selector=labels_str)
    for item in ret.items:
        # print(type(item)) # <class 'kubernetes.client.models.v1_pod.V1Pod'>
        pod_list.append(item.to_dict())
    return pod_list

获取pod详情

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import yaml
from datetime import datetime
from kubernetes import client, config

# 1.递归对数据进行简化
# 2.把一些value为None的key去掉,把datetime的转为字符串
# 3.把api_version改为apiVersion
def simple_data(data):
    if isinstance(data, dict):
        tmp_dict = {}
        for key, value in data.items():
            if key == 'api_version':
                key = 'apiVersion'
            if value is None:
                continue
            tmp_dict[key] = simple_data(value)
        return tmp_dict
    elif isinstance(data, datetime):
        return data.strftime("%Y-%m-%dT%H:%M:%SZ")
    else:
        return data
        
    
# 获取pod详情,可以按照json或者yaml格式返回
# 参数说明:
# config_path:k8s集群token文件路径
# namespace:k8s namespace
# name:pod名称
def describe_namespaced_pod(config_path, namespace, name):
    # load k8s集群token信息
    config.load_kube_config(config_path)
    v1 = client.CoreV1Api()

    # 获取pod详情
    ret = v1.read_namespaced_pod(namespace=namespace, name=name)

    """
    如果返回json格式的,直接返回即可
    return ret.to_dict()
    """
    
    """
    如果返回yaml的
    """
    # 把一些value为None的key去掉
    data = simple_data(ret.to_dict())

    # 转为yaml格式
    pod_yaml = yaml.dump(data)
    return pod_yaml

获取Pod事件信息

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from kubernetes import client, config

# 获取pod事件信息
# 参数说明:
# config_path:k8s集群token文件路径
# namespace:k8s namespace
# name:pod名称
def list_pod_event(config_path, namespace, name):
# load k8s集群token信息
    config.load_kube_config(config_path)
    v1 = client.CoreV1Api()
    # v1 = client.EventsV1beta1Api()    # 注意不要用这个api,这个api很多种event的查询方式都不支持

    # 获取event列表
    ret = v1.list_namespaced_event(namespace=namespace, field_selector='involvedObject.name={0}'.format(name))
    return ret.to_dict()

获取容器日志

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from kubernetes import client, config

# 获取容器日志
# 参数说明:
# config_path:k8s集群token文件路径
# namespace:k8s namespace
# pod_name:pod名称
# container:容器名称
# previous:是否获取重启前的容器日志
def read_pod_container_log(config_path, namespace, pod_name, container="", previous=False):
    # load k8s集群token信息
    config.load_kube_config(config_path)
    v1 = client.CoreV1Api()

    # 获取Pod/container日志
    ret = v1.read_namespaced_pod_log(namespace=namespace, name=pod_name,
                                    container=container, previous=previous, pretty=True)
    return ret

删除/重启pod

#!/usr/bin/env python
# -*- coding:utf-8 -*-

# 参数说明:
# config_path:k8s集群token文件路径
# namespace:k8s namespace
# name:pod名称
# grace_period_seconds:优雅退出时间,0s就是立即删除
def delete_pod(config_path, namespace, name, grace_period_seconds=None):
    # load k8s集群token信息
    config.load_kube_config(config_path)
    v1 = client.CoreV1Api()

    # 删除pod
    ret = v1.delete_namespaced_pod(namespace=namespace, name=pod_name,
                                    grace_period_seconds=grace_period_seconds)
    return