钩子函数
- 这里主要参考了ClusterAPI里的machine_collection选择器,使用了钩子函数,支持自定义过滤条件(Hook)
// Filter returns a Machines containing only the Machines that match all of the given MachineFilters.
func (s Machines) Filter(filters ...Func) Machines {
return newFilteredMachineCollection(And(filters...), s.UnsortedList()...)
}
// AnyFilter returns a Machines containing only the Machines that match any of the given MachineFilters.
func (s Machines) AnyFilter(filters ...Func) Machines {
return newFilteredMachineCollection(Or(filters...), s.UnsortedList()...)
}
先看下Func的定义:
// Func is the functon definition for a filter.
type Func func(machine *clusterv1.Machine) bool
以及两个自定义Hook
// ActiveMachines returns a filter to find all active machines.
// Usage: GetFilteredMachinesForCluster(ctx, client, cluster, ActiveMachines).
func ActiveMachines(machine *clusterv1.Machine) bool {
if machine == nil {
return false
}
return machine.DeletionTimestamp.IsZero()
}
// HasDeletionTimestamp returns a filter to find all machines that have a deletion timestamp.
func HasDeletionTimestamp(machine *clusterv1.Machine) bool {
if machine == nil {
return false
}
return !machine.DeletionTimestamp.IsZero()
}
同时想支持And或Or(Hook)对过滤条件进行再筛选
// And returns a filter that returns true if all of the given filters returns true.
func And(filters ...Func) Func {
return func(machine *clusterv1.Machine) bool {
for _, f := range filters {
if !f(machine) {
return false
}
}
return true
}
}
// Or returns a filter that returns true if any of the given filters returns true.
func Or(filters ...Func) Func {
return func(machine *clusterv1.Machine) bool {
for _, f := range filters {
if f(machine) {
return true
}
}
return false
}
}
// Not returns a filter that returns the opposite of the given filter.
func Not(mf Func) Func {
return func(machine *clusterv1.Machine) bool {
return !mf(machine)
}
}
通过钩子函数,使用的方式可以多种多样,如下:
machines := c.Machines.Filter(collections.Not(collections.HasDeletionTimestamp))