改造 Kubernetes 自定義排程器

JaydenChang發表於2024-05-26

原文出處:改造 Kubernetes 自定義排程器 | Jayden's Blog (jaydenchang.top)

Overview

Kubernetes 預設排程器在排程 Pod 時並不關心特殊資源例如磁碟、GPU 等,因此突發奇想來改造排程器,在翻閱官方排程器框架[1]、排程器配置[2]和參考大佬的文章[3]後,自己也來嘗試改寫一下。

環境配置

相關軟體版本:

  • Kubernetes 版本:v1.19.0
  • Docker 版本:v26.1.2
  • Prometheus 版本:v2.49
  • Node Exporter 版本:v1.7.0

叢集內有 1 個 master 和 3 個 node。

實驗部分

專案總覽

專案結構如下:

.
├── Dockerfile
├── deployment.yaml
├── go.mod
├── go.sum
├── main.go
├── pkg
│   ├── cpu
│   │   └── cputraffic.go
│   ├── disk
│   │   └── disktraffic.go
│   ├── diskspace
│   │   └── diskspacetraffic.go
│   ├── memory
│   │   └── memorytraffic.go
│   ├── network
│   │   └── networktraffic.go
│   └── prometheus.go
├── scheduler
├── scheduler.conf
└── scheduler.yaml

外掛部分

下面以構建記憶體外掛為例。

定義外掛名稱、變數和結構體

const MemoryPlugin = "MemoryTraffic"
var _ = framework.ScorePlugin(&MemoryTraffic{})

type MemoryTraffic struct {
    prometheus *pkg.PrometheusHandle
    handle framework.FrameworkHandle
}

下面來實現 framework.FrameworkHandle 的介面。

先定義外掛初始化入口

func New(plArgs runtime.Object, h framework.FrameworkHandle) (framework.Plugin, error) {
    args := &MemoryTrafficArgs{}
    if err := fruntime.DecodeInto(plArgs, args); err != nil {
        return nil, err
    }

    klog.Infof("[MemoryTraffic] args received. Device: %s; TimeRange: %d, Address: %s", args.DeviceName, args.TimeRange, args.IP)

    return &MemoryTraffic{
        handle:     h,
        prometheus: pkg.NewProme(args.IP, args.DeviceName, time.Minute*time.Duration(args.TimeRange)),
    }, nil
}

實現 Score 介面,Score 進行初步打分

func (n *MemoryTraffic) Score(ctx context.Context, state *framework.CycleState, p *corev1.Pod, nodeName string) (int64, *framework.Status) {
    nodeBandwidth, err := n.prometheus.MemoryGetGauge(nodeName)
    if err != nil {
        return 0, framework.NewStatus(framework.Error, fmt.Sprintf("error getting node bandwidth measure: %s", err))
    }
    bandWidth := int64(nodeBandwidth.Value)
    klog.Infof("[MemoryTraffic] node '%s' bandwidth: %v", nodeName, bandWidth)
    return bandWidth, nil
}

實現 NormalizeScore,對上一步 Score 的打分進行修正

func (n *MemoryTraffic) NormalizeScore(ctx context.Context, state *framework.CycleState, pod *corev1.Pod, scores framework.NodeScoreList) *framework.Status {
    var higherScore int64
    for _, node := range scores {
        if higherScore < node.Score {
            higherScore = node.Score
        }
    }
    // 計算公式為,滿分 - (當前記憶體使用 / 總記憶體 * 100)
    // 公式的計算結果為,記憶體使用率越大的節點,分數越低
    for i, node := range scores {
        scores[i].Score = node.Score * 100 / higherScore
        klog.Infof("[MemoryTraffic] Nodes final score: %v", scores[i].Score)
    }

    klog.Infof("[MemoryTraffic] Nodes final score: %v", scores)
    return nil
}

配置外掛名稱和返回 ScoreExtension

func (n *MemoryTraffic) Name() string {
    return MemoryPlugin
}

// 如果返回framework.ScoreExtensions 就需要實現framework.ScoreExtensions
func (n *MemoryTraffic) ScoreExtensions() framework.ScoreExtensions {
    return n
}

Prometheus 部分

首先來編寫查詢記憶體可用率的 PromQL

const memoryMeasureQueryTemplate = ` (avg_over_time(node_memory_MemAvailable_bytes[30m]) / avg_over_time(node_memory_MemTotal_bytes[30m])) * 100 * on(instance) group_left(nodename) (node_uname_info{nodename="%s"})`

然後來宣告 PrometheusHandle

type PrometheusHandle struct {
    deviceName string
    timeRange  time.Duration
    ip         string
    client     v1.API
}

另外在外掛部分也要宣告查詢 Prometheus 的引數結構體

type MemoryTrafficArgs struct {
    IP         string `json:"ip"`
    DeviceName string `json:"deviceName"`
    TimeRange  int    `json:"timeRange"`
}

編寫初始化 Prometheus 外掛入口

func NewProme(ip, deviceName string, timeRace time.Duration) *PrometheusHandle {
    client, err := api.NewClient(api.Config{Address: ip})
    if err != nil {
        klog.Fatalf("[Prometheus Plugin] FatalError creating prometheus client: %s", err.Error())
    }
    return &PrometheusHandle{
        deviceName: deviceName,
        ip:         ip,
        timeRange:  timeRace,
        client:     v1.NewAPI(client),
    }
}

編寫通用查詢介面,可供其他型別資源查詢

func (p *PrometheusHandle) query(promQL string) (model.Value, error) {
    results, warnings, err := p.client.Query(context.Background(), promQL, time.Now())
    if len(warnings) > 0 {
        klog.Warningf("[Prometheus Query Plugin] Warnings: %v\n", warnings)
    }

    return results, err
}

獲取記憶體可用率介面

func (p *PrometheusHandle) MemoryGetGauge(node string) (*model.Sample, error) {
    value, err := p.query(fmt.Sprintf(memoryMeasureQueryTemplate, node))
    fmt.Println(fmt.Sprintf(memoryMeasureQueryTemplate, node))
    if err != nil {
        return nil, fmt.Errorf("[MemoryTraffic Plugin] Error querying prometheus: %w", err)
    }

    nodeMeasure := value.(model.Vector)
    if len(nodeMeasure) != 1 {
        return nil, fmt.Errorf("[MemoryTraffic Plugin] Invalid response, expected 1 value, got %d", len(nodeMeasure))
    }
    return nodeMeasure[0], nil

}

然後在程式入口裡啟用外掛並執行

func main() {
    rand.Seed(time.Now().UnixNano())
    command := app.NewSchedulerCommand(
        app.WithPlugin(network.NetworkPlugin, network.New),
        app.WithPlugin(disk.DiskPlugin, disk.New),
        app.WithPlugin(diskspace.DiskSpacePlugin, diskspace.New),
        app.WithPlugin(cpu.CPUPlugin, cpu.New),
        app.WithPlugin(memory.MemoryPlugin, memory.New),
    )
    // 對於外部註冊一個plugin
    // command := app.NewSchedulerCommand(
    // 	app.WithPlugin("example-plugin1", ExamplePlugin1.New))

    if err := command.Execute(); err != nil {
        fmt.Fprintf(os.Stderr, "%v\n", err)
        os.Exit(1)
    }
}

配置部分

為方便觀察,這裡使用二進位制方式執行,準備執行時的配置檔案

apiVersion: kubescheduler.config.k8s.io/v1beta1
kind: KubeSchedulerConfiguration
clientConnection:
  kubeconfig: /etc/kubernetes/scheduler.conf
profiles:
- schedulerName: custom-scheduler
  plugins:
    score:
      enabled:
      - name: "CPUTraffic"
        weight: 3
      - name: "MemoryTraffic"
        weight: 4
      - name: "DiskSpaceTraffic"
        weight: 3
      - name: "NetworkTraffic"
        weight: 2
      disabled:
      - name: "*"
  pluginConfig:
    - name: "NetworkTraffic"
      args:
        ip: "http://172.19.32.140:9090"
        deviceName: "eth0"
        timeRange: 60   
    - name: "CPUTraffic"
      args:
        ip: "http://172.19.32.140:9090"
        deviceName: "eth0"
        timeRange: 0
    - name: "MemoryTraffic"
      args:
        ip: "http://172.19.32.140:9090"
        deviceName: "eth0"
        timeRange: 0
    - name: "DiskSpaceTraffic"
      args:
        ip: "http://172.19.32.140:9090"
        deviceName: "eth0"
        timeRange: 0

kubeconfig 處為 master 節點的 scheduler.conf,以實際路徑為準,內包含叢集的證書雜湊,ip 為部署 Prometheus 節點的 ip,埠為 Promenade 配置中對外暴露的埠。

將二進位制檔案和 scheduler.yaml 放至 master 同一目錄下執行:

./scheduler --logtostderr=true \
	--address=127.0.0.1 \
	--v=6 \
	--config=`pwd`/scheduler.yaml \
	--kubeconfig="/etc/kubernetes/scheduler.conf" \

驗證結果

準備一個要部署的 Pod,使用指定的排程器名稱

apiVersion: apps/v1
kind: Deployment
metadata:
  name: gin
  namespace: default
  labels:
    app: gin
spec:
  replicas: 2
  selector:
    matchLabels:
      app: gin
  template:
    metadata:
      labels:
        app: gin
    spec:
      schedulerName: my-custom-scheduler  # 使用自定義排程器
      containers:
      - name: gin
        image: jaydenchang/k8s_test:latest
        imagePullPolicy: Always
        command: ["./app"]
        ports:
        - containerPort: 9999
          protocol: TCP

最後的可以檢視日誌,部分日誌如下:

I0808 17:32:35.138289   27131 memorytraffic.go:83] [MemoryTraffic] node 'node1' bandwidth: %!s(int64=2680340)
I0808 17:32:35.138763   27131 memorytraffic.go:70] [MemoryTraffic] Nodes final score: [{node1 2680340} {node2 0}]
I0808 17:32:35.138851   27131 memorytraffic.go:70] [MemoryTraffic] Nodes final score: [{node1 71} {node2 0}]
I0808 17:32:35.138911   27131 memorytraffic.go:73] [MemoryTraffic] Nodes final score: [{node1 71} {node2 0}]
I0808 17:32:35.139565   27131 default_binder.go:51] Attempting to bind default/go-deployment-66878c4885-b4b7k to node1
I0808 17:32:35.141114   27131 eventhandlers.go:225] add event for scheduled pod default/go-deployment-66878c4885-b4b7k
I0808 17:32:35.141714   27131 eventhandlers.go:205] delete event for unscheduled pod default/go-deployment-66878c4885-b4b7k
I0808 17:32:35.143504   27131 scheduler.go:609] "Successfully bound pod to node" pod="default/go-deployment-66878c4885-b4b7k" node="no
de1" evaluatedNodes=2 feasibleNodes=2
I0808 17:32:35.104540   27131 scheduler.go:609] "Successfully bound pod to node" pod="default/go-deployment-66878c4885-b4b7k" node="no
de1" evaluatedNodes=2 feasibleNodes=2

參考連結


  1. Scheduling Framework | Kubernetes ↩︎

  2. Scheduler Configuration | Kubernetes ↩︎

  3. 基於Prometheus的Kubernetes網路排程器 | Cylon's Collection (oomkill.com) ↩︎

相關文章