实现Kubernetes的自定义调度器

一、集群状态

root@k8s-control-plane:~# kubectl get nodes
NAME                STATUS   ROLES    AGE    VERSION
k8s-control-plane   Ready    master   4h5m   v1.15.3
k8s-worker          Ready    <none>   4h4m   v1.15.3
k8s-worker2         Ready    <none>   4h4m   v1.15.3

二、新建pod

nginx.yaml的内容如下

apiVersion: v1
kind: Pod
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  schedulerName: my-scheduler
  containers:
  - name: nginx
    image: nginx:1.10

执行创建命令

# kubectl create -f nginx.yaml
pod/nginx created
# kubectl get pods
NAME       READY   STATUS    RESTARTS   AGE
nginx      0/1     Pending   0          10s
vm-57nwl   1/1     Running   2          162m
vm-9hjwc   1/1     Running   2          161m
vm-9sgtl   1/1     Running   2          162m

如果自定义的调度器还未在系统中部署,则默认的调度器会忽略这个Pod,这个Pod将会永远处于Pending状态。

三、自定义调度器
调度器的主要作用就是把未分配node的pod,自动绑定一个node。下面是我们使用api完成手动绑定

export PODNAME=nginx
export NODENAME=k8s-worker2

curl --cacert /etc/kubernetes/pki/ca.crt  \
    --cert /etc/kubernetes/pki/apiserver-kubelet-client.crt  \
    --key  /etc/kubernetes/pki/apiserver-kubelet-client.key \
    --header "Content-Type:application/json" \
    --request POST \
    --data '{"apiVersion":"v1","kind":"Binding","metadata": {"name":"'$PODNAME'"},"target": {"apiVersion":"v1","kind": "Node", "name": "'$NODENAME'"}}' \
    https://127.0.0.1:6443/api/v1/namespaces/default/pods/$PODNAME/binding/

查看执行结果

# kubectl get pods -o wide
NAME       READY   STATUS    RESTARTS   AGE     IP           NODE                NOMINATED NODE   READINESS GATES
nginx      1/1     Running   0          4m32s   10.244.1.8   k8s-worker2         <none>           <none>
vm-57nwl   1/1     Running   2          166m    10.244.1.5   k8s-worker2         <none>           <none>
vm-9hjwc   1/1     Running   2          165m    10.244.0.4   k8s-control-plane   <none>           <none>
vm-9sgtl   1/1     Running   2          166m    10.244.2.4   k8s-worker          <none>           <none>

刚才处于Pending状态的nginx已经变成Running状态了,说明已经完成调度。

这样来看,用 shell很容易编写一个简单的调度器。

推荐阅读更多精彩内容