GoLang -如何获得Kubernetes修改

inkz8wg9  于 2022-11-28  发布在  Kubernetes
关注(0)|答案(1)|浏览(114)

我是golang的新手,我有以下要求:
1.我有一个使用映像nginx:latest运行的部署
1.然后手动将此映像更新为其他映像(例如:nginx:1.22
1.我需要获取旧图像版本和新图像版本
所以,我研究了Go Lang中的“共享告密者”。我写道:

func main() {

. . . 

    // create shared informers for resources in all known API group versions with a reSync period and namespace
    factory := informers.NewSharedInformerFactoryWithOptions(clientSet, 1*time.Hour, informers.WithNamespace(namespace_to_watch))
    podInformer := factory.Core().V1().Pods().Informer()

    defer runtime.HandleCrash()

    // start informer ->
    go factory.Start(stopper)

    // start to sync and call list
    if !cache.WaitForCacheSync(stopper, podInformer.HasSynced) {
        runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))
        return
    }

    podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
        AddFunc:    onAdd, // register add eventhandler
        UpdateFunc: onUpdate,
        DeleteFunc: onDelete,
    })
}

func onUpdate(oldObj interface{}, newObj interface{}) {
    oldPod := oldObj.(*corev1.Pod)
    newPod := newObj.(*corev1.Pod)

    for container_old := range oldPod.Spec.Containers {
       fmt.Printf("Container Old :%s", container_old.Image )
    }

    for container_new := range newPod.Spec.Containers {
       fmt.Printf("Container New :%s", container_new.Image )
    }
  
}

如上所述,根据onUpdate函数,我应该得到这两个值,而不是每次更新时得到相同的值,如下所示:
旧容器:nginx:最新的
新容器:nginx:最新的
旧容器:nginx:1.22
新容器:nginx:1.22
旧容器:nginx:1.22
新容器:nginx:1.22
上面的输出是因为onUpdate函数被触发了三次,但是正如你所看到的,每次的值都是一样的(对于每个输出)。
旧容器:nginx:最新的
新容器:nginx:1.22
有人能帮我吗?

uqjltbpv

uqjltbpv1#

当在部署中更新映像时,pod将使用新的映像容器重新启动,并且不会保留旧pod规范的任何痕迹。您应该观察部署而不是pod,并检查旧部署和新部署对象之间的映像。以下是如何修改onUpdate方法的示例。

func onUpdate(oldObj interface{}, newObj interface{}) {
    oldDepl := oldObj.(*v1.Deployment)
    newDepl := newObj.(*v1.Deployment)

    for oldContainerID := range oldDepl.Spec.Template.Spec.Containers {
        for newContainerID := range newDepl.Spec.Template.Spec.Containers {
            if oldDepl.Spec.Template.Spec.Containers[oldContainerID].Name == newDepl.Spec.Template.Spec.Containers[newContainerID].Name {
                if oldDepl.Spec.Template.Spec.Containers[oldContainerID].Image != newDepl.Spec.Template.Spec.Containers[newContainerID].Image {
                    fmt.Printf("CONTAINER IMAGE UPDATED FROM %s to %s",
                        oldDepl.Spec.Template.Spec.Containers[oldContainerID].Image, newDepl.Spec.Template.Spec.Containers[newContainerID].Image)
                }
            }
        }
    }
}

相关问题