我们有兴趣在启动或停止时将某些命令作为pod和服务运行.使用yml文件中的生命周期钩子对我们不起作用,因为这些命令不是可选的.我们考虑过运行一个使用watch api运行这些命令的观察器pod.但我们无法弄清楚如何使用手表api,以便它不会一次又一次地发送相同的事件.是否有办法告诉手表api仅在连接打开后才发送新事件?如果期望有状态的监视api是不合理的,是否可以通过时间戳或单调增加的id来避免已经看到的事件?
基本上我们现在正在做的是运行一个带有与api通信的守护进程的pod.我们可以将事件视为流.但是我们有兴趣在创建或删除pod时运行一些任务.
运行 kube 代理以使用 curl 无需身份验证
kubectl proxy
Run Code Online (Sandbox Code Playgroud)
用手表列出所有事件;
curl -s 127.0.0.1:8001/api/v1/watch/events
Run Code Online (Sandbox Code Playgroud)
运行 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'
Run Code Online (Sandbox Code Playgroud)
我找到了答案。万一其他人在看。
有一个更好的系统来监视资源并使用带有包的自定义任务处理事件pkg/controller/framework
我发现了这样的步骤,
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.
Run Code Online (Sandbox Code Playgroud)
如果它在集群内,你可以在 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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14700 次 |
| 最近记录: |