简体   繁体   English

Kubernetes使用api观看Pod活动

[英]Kubernetes Watch Pod Events with api

We are interested in running certain commands as pods and services, as they start or stop. 我们有兴趣在启动或停止时将某些命令作为pod和服务运行。 Using the life-cycle hooks in the yml files does not work for us, since these commands are not optional. 使用yml文件中的生命周期钩子对我们不起作用,因为这些命令不是可选的。 We have considered running a watcher pod that uses the watch api to run these commands. 我们考虑过运行一个使用watch api运行这些命令的观察器pod。 But we can't figure out how to use the watch api so that it does not keep sending the same events again and again. 但我们无法弄清楚如何使用手表api,以便它不会一次又一次地发送相同的事件。 Is there a way to tell the watch api to only send new events since connection was opened? 是否有办法告诉手表api仅在连接打开后才发送新事件? If expecting a stateful watch api is unreasonable, will it be possible to pass it a timestamp or a monotonically increasing id to avoid getting already seen events? 如果期望有状态的监视api是不合理的,是否可以通过时间戳或单调增加的id来避免已经看到的事件?

Basically what we are doing now we are running a pod with a daemon process that communicates with the api. 基本上我们现在正在做的是运行一个带有与api通信的守护进程的pod。 we can find the events as stream. 我们可以将事件视为流。 But we are interested to run some task when a pod created or deleted. 但我们有兴趣在创建或删除pod时运行一些任务。

I have found the answer. 我找到了答案。 In case anyone else is watching. 万一其他人在看。

There is a much better system to watch resource and handle events with custom tasks with pkg/controller/framework package 有一个更好的系统来监视资源并使用pkg/controller/framework 处理具有自定义任务的事件

I found the step like this, 我找到了这样的步骤,

1. initiate a framework.NewInFormer
2. Run the controller
3. the NewInFormer loads with your custom event handlers that will call when the events occured.

I'd recommend using the client from the kube repo. 我建议使用kube repo中的客户端 Why are the lifecycle hooks not working for your use case? 为什么生命周期钩子不能用于您的用例?

Run kube proxy to use curl without authentication 运行kube代理以使用curl而无需身份验证

kubectl proxy 

List all events with a watch; 列出所有带手表的活动;

curl -s 127.0.0.1:8001/api/v1/watch/events 

Run the curl to watch the events and filter it with jq for pod starts and stops. 运行curl观察事件并使用jq过滤它以便pod启动和停止。

curl -s 127.0.0.1:8001/api/v1/watch/events | jq --raw-output \ 'if .object.reason == "Started" then . elif .object.reason == "Killing" then . else empty end | [.object.firstTimestamp, .object.reason, .object.metadata.namespace, .object.metadata.name] | @csv'

More details 更多细节

In case it is in-cluster you may do it like this in golang: 如果它是集群内的,你可以在golang中这样做:

package main

import (
    "fmt"
    "time"

    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/pkg/api/v1"
    "k8s.io/client-go/tools/cache"
    "k8s.io/client-go/pkg/fields"
    "k8s.io/client-go/rest"
)

func main() {
    config, err := rest.InClusterConfig()
    if err != nil {
        panic(err.Error())
    }

    clientset, err := kubernetes.NewForConfig(config)
    if err != nil {
        panic(err.Error())
    }

    watchlist := cache.NewListWatchFromClient(clientset.Core().RESTClient(), "pods", v1.NamespaceDefault, 
       fields.Everything())
    _, controller := cache.NewInformer(
        watchlist,
        &v1.Pod{},
        time.Second * 0,
        cache.ResourceEventHandlerFuncs{
            AddFunc: func(obj interface{}) {
                fmt.Printf("add: %s \n", obj)
            },
            DeleteFunc: func(obj interface{}) {
                fmt.Printf("delete: %s \n", obj)
            },
            UpdateFunc:func(oldObj, newObj interface{}) {
                fmt.Printf("old: %s, new: %s \n", oldObj, newObj)
            },
        },
    )
    stop := make(chan struct{})
    go controller.Run(stop)
}

You say the lifecycle hooks commands are not optional, but they are indeed optional. 你说lifecycle hooks命令不是可选的,但它们确实是可选的。

Hook handler implementations
Containers can access a hook by implementing and registering a handler for that hook. There are two types of hook handlers that can be implemented for Containers:
Exec - Executes a specific command, such as pre-stop.sh, inside the cgroups and namespaces of the Container. Resources consumed by the command are counted against the Container.
HTTP - Executes an HTTP request against a specific endpoint on the Container.

From here: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/ 从这里: https//kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/

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

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