如何根据创建时间对Pod进行排序

huangapple go评论77阅读模式
英文:

How to sort pods based on creation time

问题

我想按照创建时间对 Kubernetes Pod 进行排序。我尝试添加了以下逻辑。这里的'result'是 Pod 数组(类型为 k8s.io/api/core/v1/Pod):

sort.Slice(result, func(i, j int) bool { 
    fmt.Printf("%T \n", result[j].CreationTimestamp)
    fmt.Printf("time  %t", result[i].CreationTimestamp.Before(result[j].CreationTimestamp))
    return result[i].CreationTimestamp.Before(result[j].CreationTimestamp) 
})

使用上述逻辑,我得到了错误信息:
cannot use t2 (type "k8s.io/apimachinery/pkg/apis/meta/v1".Time) as type *"k8s.io/apimachinery/pkg/apis/meta/v1".Time in argument to t1.Before

我尝试打印'result[j].CreationTimestamp'的类型,结果是 v1.Time。我不确定还缺少了什么。请问有人可以指导我吗?

解决方法是创建另一个对象,并将其字段设置为 Pod 的名称和创建时间,然后对其进行排序,但这会影响性能。

英文:

I want to sort Kubernetes pod's on creation time. I tried adding logic like this. Here 'result' is array of Pod ( of type k8s.io/api/core/v1/Pod)

 sort.Slice(result, func(i, j int) bool { 
	fmt.Printf("%T \n", result[j].CreationTimestamp)
	fmt.Printf("time  %t" , result[i].CreationTimestamp.Before(result[j].CreationTimestamp))
	return result[i].CreationTimestamp.Before(result[j].CreationTimestamp) 
})

With above logic , i get error
cannot use t2 (type "k8s.io/apimachinery/pkg/apis/meta/v1".Time) as type *"k8s.io/apimachinery/pkg/apis/meta/v1".Time in argument to t1.Before

I tried printing type of "result[j].CreationTimestamp" which comes to v1.Time. I am not sure what else I am missing. Can anyone please guide me.

Workaround would be to create a another object and set its fields to name and creationTime of Pod and sort it but that would hit performance.

答案1

得分: 2

根据文档Before函数接受一个*Time参数,因此我认为你需要像下面这样引用第二个时间戳:

return result[i].CreationTimestamp.Before(&result[j].CreationTimestamp)
英文:

According to the docs Before takes a *Time therefore I think you have to reference the second timestamp like so:

return result[i].CreationTimestamp.Before(&result[j].CreationTimestamp)

huangapple
  • 本文由 发表于 2021年7月26日 15:48:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/68526210.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定