/
listwatch.go
96 lines (80 loc) · 2.35 KB
/
listwatch.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
Copyright 2019 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package sharding
import (
"hash/fnv"
jump "github.com/dgryski/go-jump"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/tools/cache"
)
type shardedListWatch struct {
sharding *sharding
lw cache.ListerWatcher
}
func NewShardedListWatch(shard int32, totalShards int, lw cache.ListerWatcher) cache.ListerWatcher {
// This is an "optimization" as this configuration means no sharding is to
// be performed.
if shard == 0 && totalShards == 1 {
return lw
}
return &shardedListWatch{sharding: &sharding{shard: shard, totalShards: totalShards}, lw: lw}
}
func (s *shardedListWatch) List(options metav1.ListOptions) (runtime.Object, error) {
list, err := s.lw.List(options)
if err != nil {
return nil, err
}
items, err := meta.ExtractList(list)
if err != nil {
return nil, err
}
res := &metav1.List{
Items: []runtime.RawExtension{},
}
for _, item := range items {
a, err := meta.Accessor(item)
if err != nil {
return nil, err
}
if s.sharding.keep(a) {
res.Items = append(res.Items, runtime.RawExtension{Object: item})
}
}
return res, nil
}
func (s *shardedListWatch) Watch(options metav1.ListOptions) (watch.Interface, error) {
w, err := s.lw.Watch(options)
if err != nil {
return nil, err
}
return watch.Filter(w, func(in watch.Event) (out watch.Event, keep bool) {
a, err := meta.Accessor(in.Object)
if err != nil {
// TODO(brancz): needs logging
return in, true
}
return in, s.sharding.keep(a)
}), nil
}
type sharding struct {
shard int32
totalShards int
}
func (s *sharding) keep(o metav1.Object) bool {
h := fnv.New64a()
h.Write([]byte(o.GetUID()))
return jump.Hash(h.Sum64(), s.totalShards) == s.shard
}