-
Notifications
You must be signed in to change notification settings - Fork 41
/
sync_server.go
302 lines (238 loc) · 8.27 KB
/
sync_server.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
// Copyright 2019 The Kubernetes Authors.
//
// 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 kubernetes
import (
"fmt"
"sync"
"time"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/rest"
"k8s.io/klog"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
"github.com/open-cluster-management/multicloud-operators-subscription/pkg/utils"
)
const (
syncWorkNum = 5
)
// TemplateUnit defines the basic unit of Template and whether it should be updated or not
type TemplateUnit struct {
*unstructured.Unstructured
Source string
ResourceUpdated bool
StatusUpdated bool
}
// ResourceMap is a registry for all resources
type ResourceMap struct {
GroupVersionResource schema.GroupVersionResource
Namespaced bool
ServerUpdated bool
TemplateMap map[string]*TemplateUnit
}
// KubeSynchronizer handles resources to a kube endpoint
type KubeSynchronizer struct {
Interval int
LocalClient client.Client
RemoteClient client.Client
localConfig *rest.Config
DynamicClient dynamic.Interface
kmtx sync.Mutex // lock the kubeResource
KubeResources map[schema.GroupVersionKind]*ResourceMap
SynchronizerID *types.NamespacedName
Extension Extension
eventrecorder *utils.EventRecorder
tplCh chan resourceOrder
dmtx sync.Mutex //this lock protect the dynamicFactory and stopCh
stopCh chan struct{}
dynamicFactory dynamicinformer.DynamicSharedInformerFactory
}
var (
crdRetryMultiplier = 3
)
var defaultSynchronizer *KubeSynchronizer
// Add creates the default syncrhonizer and add the start function as runnable into manager
func Add(mgr manager.Manager, hubconfig *rest.Config, syncid *types.NamespacedName, interval int) error {
var err error
defaultSynchronizer, err = CreateSynchronizer(mgr.GetConfig(), hubconfig, mgr.GetScheme(), syncid, interval, defaultExtension)
if err != nil {
klog.Error("Failed to create synchronizer with error: ", err)
return err
}
return mgr.Add(defaultSynchronizer)
}
// GetDefaultSynchronizer - return the default kubernetse synchronizer
func GetDefaultSynchronizer() *KubeSynchronizer {
return defaultSynchronizer
}
// CreateSynchronizer createa an instance of synchrizer with give api-server config
func CreateSynchronizer(config, remoteConfig *rest.Config, scheme *runtime.Scheme, syncid *types.NamespacedName,
interval int, ext Extension) (*KubeSynchronizer, error) {
if klog.V(utils.QuiteLogLel) {
fnName := utils.GetFnName()
klog.Infof("Entering: %v()", fnName)
defer klog.Infof("Exiting: %v()", fnName)
}
var err error
dynamicClient := dynamic.NewForConfigOrDie(config)
s := &KubeSynchronizer{
Interval: interval,
SynchronizerID: syncid,
DynamicClient: dynamicClient,
localConfig: config,
kmtx: sync.Mutex{},
KubeResources: make(map[schema.GroupVersionKind]*ResourceMap),
Extension: ext,
tplCh: make(chan resourceOrder, syncWorkNum),
dmtx: sync.Mutex{},
stopCh: make(chan struct{}),
}
s.LocalClient, err = client.New(config, client.Options{})
if err != nil {
klog.Error("Failed to initialize client to update local status. err: ", err)
return nil, err
}
s.RemoteClient = s.LocalClient
if remoteConfig != nil {
s.RemoteClient, err = client.New(remoteConfig, client.Options{})
if err != nil {
klog.Error("Failed to initialize client to update remote status. err: ", err)
return nil, err
}
}
defaultExtension.localClient = s.LocalClient
defaultExtension.remoteClient = s.RemoteClient
if ext == nil {
s.Extension = defaultExtension
}
s.eventrecorder, err = utils.NewEventRecorder(config, scheme)
if err != nil {
klog.Error("Failed to create event recorder. err: ", err)
return nil, err
}
s.discoverResourcesOnce()
return s, nil
}
// Start the discovery and start caches, this will be triggered by the manager
func (sync *KubeSynchronizer) Start(s <-chan struct{}) error {
klog.Info("start synchronizer")
defer klog.Info("stop synchronizer")
sync.rediscoverResource()
go sync.processTplChan(s)
return nil
}
func (sync *KubeSynchronizer) processTplChan(stopCh <-chan struct{}) {
crdTicker := time.NewTicker(time.Duration(sync.Interval*crdRetryMultiplier) * time.Second)
defer klog.Info("stop synchronizer channel")
for {
select {
case order, ok := <-sync.tplCh:
if !ok {
sync.tplCh = nil
}
klog.Infof("order processor: received order %v", order.hostSub.String())
st := time.Now()
err := sync.processOrder(order)
order.err <- err
close(order.err)
klog.Infof("order processor: done order %v, took: %v", order.hostSub.String(), time.Since(st))
case <-crdTicker.C: //discovery CRD resource applied by user
sync.rediscoverResource()
case <-stopCh: //this channel is from controller manager
close(sync.tplCh)
crdTicker.Stop()
return
}
}
}
func (sync *KubeSynchronizer) purgeSubscribedResource(subType string, hostSub types.NamespacedName) error {
var err error
sync.kmtx.Lock()
defer sync.kmtx.Unlock()
for _, resmap := range sync.KubeResources {
for _, tplunit := range resmap.TemplateMap {
tplhost := sync.Extension.GetHostFromObject(tplunit)
tpldpl := utils.GetHostDeployableFromObject(tplunit)
if tplhost != nil && tplhost.String() == hostSub.String() {
klog.V(10).Infof("Start DeRegister, with host: %s, dpl: %s", tplhost, tpldpl)
err = sync.DeRegisterTemplate(*tplhost, *tpldpl, subType)
if err != nil {
klog.Error("Failed to deregister template for cleanup by host with error: ", err)
}
}
}
}
return err
}
func (sync *KubeSynchronizer) processOrder(order resourceOrder) error {
// meaning clean up all the resource from a source:host
if len(order.dpls) == 0 {
return sync.purgeSubscribedResource(order.subType, order.hostSub)
}
keySet := make(map[string]bool)
resSet := make(map[string]map[schema.GroupVersionKind]bool)
crdFlag := false
var err error
//adding update,new resource to cache and create them at cluster
for _, dplUn := range order.dpls {
err = sync.RegisterTemplate(order.hostSub, dplUn.Dpl, order.subType)
if err != nil {
klog.Error(fmt.Sprintf("failed to register template of %v/%v, error: %v",
dplUn.Dpl.GetNamespace(), dplUn.Dpl.GetName(), err))
continue
}
dplKey := types.NamespacedName{Name: dplUn.Dpl.GetName(), Namespace: dplUn.Dpl.GetNamespace()}
rKey := sync.generateResourceMapKey(order.hostSub, dplKey)
keySet[rKey] = true
if _, ok := resSet[rKey][dplUn.Gvk]; !ok {
resSet[rKey] = map[schema.GroupVersionKind]bool{dplUn.Gvk: true}
}
if dplUn.Gvk.Kind == crdKind {
crdFlag = true
}
}
// handle orphan resource
sync.kmtx.Lock()
for resgvk, resmap := range sync.KubeResources {
for reskey, tplunit := range resmap.TemplateMap {
//if resource's key don't belong to the current key set, then do
//nothing
if _, ok := keySet[reskey]; ok {
continue
}
//if the resource map have a key belong to this resource order, then
//check if the order required the resgvk, if not, delete the resgvk
if _, ok := resSet[reskey][resgvk]; !ok {
// will ignore non-syncsource templates
tplhost := sync.Extension.GetHostFromObject(tplunit)
tpldpl := utils.GetHostDeployableFromObject(tplunit)
klog.V(10).Infof("Start DeRegister, with resgvk: %v, reskey: %s", resgvk, reskey)
err = sync.DeRegisterTemplate(*tplhost, *tpldpl, order.subType)
if err != nil {
klog.Error("Failed to deregister template for applying validator with error: ", err)
}
}
}
sync.applyKindTemplates(resmap)
}
sync.kmtx.Unlock()
if crdFlag {
sync.rediscoverResource()
}
return err
}