forked from crossplane-contrib/provider-ansible
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshardutil.go
More file actions
44 lines (39 loc) · 1.39 KB
/
shardutil.go
File metadata and controls
44 lines (39 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package shardutil
import (
"hash/fnv"
"sigs.k8s.io/controller-runtime/pkg/client"
event "sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)
// Define a predicate function to filter resources based on consistent hashing
func IsResourceForShard(targetShard, totalShards int) predicate.Predicate {
return predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
return isResourceForShardHelper(e.Object, targetShard, totalShards)
},
UpdateFunc: func(e event.UpdateEvent) bool {
return isResourceForShardHelper(e.ObjectNew, targetShard, totalShards)
},
DeleteFunc: func(e event.DeleteEvent) bool {
return isResourceForShardHelper(e.Object, targetShard, totalShards)
},
GenericFunc: func(e event.GenericEvent) bool {
return isResourceForShardHelper(e.Object, targetShard, totalShards)
},
}
}
// Helper function to check if the resource belongs to the current shard
func isResourceForShardHelper(obj client.Object, targetShard, totalShards int) bool {
// Calculate a hash of the resource name
hash := hashString(obj.GetName())
// Perform modulo operation to determine the shard
shard := hash % uint32(totalShards)
// Check if the shard matches the target shard
return int(shard) == targetShard
}
// Helper function to hash a string using FNV-1a
func hashString(s string) uint32 {
h := fnv.New32a()
h.Write([]byte(s))
return h.Sum32()
}