赞
踩
1、集群是kubernetes1.19,关于集群搭建等之前有记录过。
2、使用python3之kubernetes-client-python自定义kubernetes集群的调度器,代码如下:
from kubernetes import client import kubernetes as k8s import numpy as np # k8s自定义调度器 # python : 3.8 # kubernetes : V17.14.0a1 # numpy : V1.20.1 # 获取可用节点node def getUseNode(k8sCoreV1api): # 获取所有节点 nodeInstance = k8sCoreV1api.list_node() # 存放可用节点的节点名称 useNodeName = [] for i in nodeInstance.items: if i.status.conditions[-1].status == "True" and i.status.conditions[-1].type == "Ready": useNodeName.append(i.metadata.name) return useNodeName # 获取需要调度的pod def getScheduledPod(k8sCoreV1api,namespace): podInstance = k8sCoreV1api.list_namespaced_pod(namespace) # 获取需要调度的pod,也就是处于pending状态的pod scheduledPodName = [] for i in podInstance.items: if i.status.phase == 'Pending' and i.spec.node_name is None: scheduledPodName.append(i.metadata.name) return scheduledPodName # 调度pod,将pod调度到随机抽取的一个node上去(这里没有使用什么算法,只是随机抽取一个可用节点) def podBinding(k8sCoreV1api,podName, nodeName, namespace): target = client.V1ObjectReference() target.kind = "Node" target.api_version = "v1" target.name = nodeName meta = client.V1ObjectMeta() meta.name = podName body = client.V1Binding(target=target) body.target = target body.metadata = meta # 下面会抛出异常,所以必须加try,不然程序就终止 try: k8sCoreV1api.create_namespaced_binding(namespace, body) return True except Exception as e: """ 注意这段话!! create_namespaced_binding() throws exception: Invalid value for `target`, must not be `None` or despite the fact this exception is being thrown, Pod is bound to a Node and Pod is running """ print('exception' + str(e)) return False # 4、将节点绑定上去 def podScheduling(k8sCoreV1api,useNodeName,scheduledPodName,namespace): nodeName = np.random.choice(useNodeName) print("选中节点:",nodeName) for podNAame in scheduledPodName: print("开始调度") re = podBinding(k8sCoreV1api,podNAame ,nodeName,namespace) print("完成一个pod的调度") # 主方法,是入口 if __name__ == '__main__': namespace = "default" # 1、加载配置文件 这里的配置文件是集群中的.kube/config 文件,直接去集群中粘贴过来即可 k8s.config.load_kube_config(config_file="kubeconfig.yaml") k8sCoreV1api = client.CoreV1Api() # 2、获取可用节点 useNodeName = getUseNode(k8sCoreV1api) # 3、获取指定命名空间中处于待调度的pod scheduledPodName = getScheduledPod(k8sCoreV1api,namespace) # 4、将待调度的pod绑定到可用节点上,随机选取一个可用节点绑定上去 podScheduling(k8sCoreV1api,useNodeName,scheduledPodName,namespace)
已经测试过了,可行。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。