繁体   English   中英

如何使用 golang 在 kubernetes 的 DaemonSet 中运行主机命令?

[英]how to run host command in DaemonSet in kubernetes with golang?

现在,我想监控集群中节点(如docker、kubelet、cri ...)的状态。 于是我写了一个golang程序,在kubernetes中部署为DaemonSet。 但是如你所知,当 golang 程序运行 DaemonSet 中的命令以获得正确的主机结果时,它不起作用。 如何在 DaemonSet 中运行“systemctl status kubelet/docker”,却得到主机的结果?

测试代码喜欢:

package main

import (
    "fmt"
    "os/exec"
    "strings"
)

func main() {
    res,_:=ExecCommand("systemctl","status","kubelet")
    fmt.Println(res)
}

func ExecCommand(command string, args ...string) (string, error) {

    cmd := exec.Command(command, args...)
    out, err := cmd.Output()
    if err != nil {
        return "", err
    }

    return strings.TrimSuffix(string(out), "\n"), nil
}

我只想在 DaemonSet 中运行命令以获取主机的“systemctl status kubelet/docker”的结果,而不是容器。但我不知道得到它。

我还尝试将其部署为特权容器:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: cluster-monitor
  namespace: cluster-monitor
spec:
  selector:
    matchLabels:
      app: cluster-monitor
  template:
    metadata:
      labels:
        app: cluster-monitor
    spec:
      containers:
        - name: cluster-monitor
          image: monitor:v6
          imagePullPolicy: IfNotPresent
          securityContext:
            runAsUser: 0
            privileged: true
      hostIPC: true
      hostNetwork: true
      hostPID: true

此外,我还尝试在entrypoint.sh中使用“nsenter”命令设置容器的命名空间:

#!/bin/sh

## set host namespace
nsenter -t 1 -m -u -i -n /bin/sh

## run the program
/monitor -conf /config.toml

但是无论我做什么,我都无法通过在 kubernetes 中使用我的监视器 parogram 作为 DaemonSet 来获取容器中主机的状态。

那么我应该怎么做才能在一个golang程序中作为DaemonSet获取宿主的一些命令的结果。 您的回答对我来说很重要,非常感谢!

您需要使用卷的hostPath属性,如下所示: https ://kubernetes.io/docs/concepts/storage/volumes/#hostpath

这将允许您将主机中的文件/目录映射到容器中,您需要将主机中的/var/run/docker.sock映射到容器中。

apiVersion: v1
kind: Pod
metadata:
  name: test-pd
spec:
  containers:
  - image: k8s.gcr.io/test-webserver
    name: test-container
    volumeMounts:
    - mountPath:  /var/run/docker.sock
      name: docker-socket
  volumes:
  - name: docker-socket
    hostPath:
      path: /var/run/docker.sock
      type: File

您的图像还需要安装 docker

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM