-
Notifications
You must be signed in to change notification settings - Fork 492
/
statussynccontroller.go
321 lines (265 loc) · 8.6 KB
/
statussynccontroller.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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/* * Copyright (c) 2017, The Easegress 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 statussynccontroller implements the StatusSyncController.
package statussynccontroller
import (
"runtime/debug"
"strings"
"sync"
"github.com/megaease/easegress/v2/pkg/api"
"github.com/megaease/easegress/v2/pkg/cluster"
"github.com/megaease/easegress/v2/pkg/logger"
"github.com/megaease/easegress/v2/pkg/supervisor"
"github.com/megaease/easegress/v2/pkg/util/codectool"
"github.com/megaease/easegress/v2/pkg/util/timetool"
"github.com/megaease/easegress/v2/pkg/object/trafficcontroller"
)
const (
// Category is the category of StatusSyncController.
Category = supervisor.CategorySystemController
// Kind is the kind of StatusSyncController.
Kind = "StatusSyncController"
maxStatusesRecordCount = 10
)
type (
// StatusSyncController is a system controller to synchronize
// status of every object to remote storage.
StatusSyncController struct {
superSpec *supervisor.Spec
spec *Spec
timer *timetool.DistributedTimer
lastSyncStatusUnits map[string]*statusUnit
// sorted by timestamp in ascending order
statusSnapshots []*StatusesSnapshot
statusSnapshotsMutex sync.RWMutex
// statusUpdateMaxBatchSize is maximum statuses to update in one cluster transaction
statusUpdateMaxBatchSize int
done chan struct{}
}
// Spec describes StatusSyncController.
Spec struct{}
// StatusesSnapshot is the history record for status of every running object.
StatusesSnapshot struct {
Statuses map[string]*supervisor.Status
UnixTimestamp int64
}
statusUnit struct {
namespace string
objectName string
timestamp int64
status interface{}
}
)
func newStatusUnit(namespace, objectName string, timestamp int64, status interface{}) *statusUnit {
return &statusUnit{
namespace: namespace,
objectName: objectName,
timestamp: timestamp,
status: status,
}
}
func (s *statusUnit) clusterKey(layout *cluster.Layout) string {
return layout.StatusObjectKey(s.namespace, s.objectName)
}
func (s *statusUnit) id() string {
return s.namespace + "/" + s.objectName
}
func (s *statusUnit) marshal() ([]byte, error) {
buff, err := codectool.MarshalJSON(s.status)
if err != nil {
return nil, err
}
m := map[string]interface{}{}
err = codectool.Unmarshal(buff, &m)
if err != nil {
return nil, err
}
if m == nil {
m = map[string]interface{}{}
}
m["timestamp"] = s.timestamp
buff, err = codectool.MarshalJSON(m)
if err != nil {
return nil, err
}
return buff, nil
}
func init() {
supervisor.Register(&StatusSyncController{})
api.RegisterObject(&api.APIResource{
Category: Category,
Kind: Kind,
Name: strings.ToLower(Kind),
Aliases: []string{"statussynccontroller", "ssc"},
})
}
// Category returns the category of StatusSyncController.
func (ssc *StatusSyncController) Category() supervisor.ObjectCategory {
return Category
}
// Kind return the kind of StatusSyncController.
func (ssc *StatusSyncController) Kind() string {
return Kind
}
// DefaultSpec returns the default spec of StatusSyncController.
func (ssc *StatusSyncController) DefaultSpec() interface{} {
return &Spec{}
}
// Init initializes StatusSyncController.
func (ssc *StatusSyncController) Init(superSpec *supervisor.Spec) {
ssc.superSpec, ssc.spec = superSpec, superSpec.ObjectSpec().(*Spec)
ssc.reload()
}
// Inherit inherits previous generation of StatusSyncController.
func (ssc *StatusSyncController) Inherit(spec *supervisor.Spec, previousGeneration supervisor.Object) {
previousGeneration.Close()
ssc.Init(spec)
}
func (ssc *StatusSyncController) reload() {
ssc.timer = timetool.NewDistributedTimer(nextSyncStatusDuration)
ssc.done = make(chan struct{})
opts := ssc.superSpec.Super().Options()
ssc.statusUpdateMaxBatchSize = opts.StatusUpdateMaxBatchSize
if ssc.statusUpdateMaxBatchSize < 1 {
ssc.statusUpdateMaxBatchSize = 20
}
logger.Infof("StatusUpdateMaxBatchSize is %d", ssc.statusUpdateMaxBatchSize)
go ssc.run()
}
func (ssc *StatusSyncController) run() {
for {
select {
case t := <-ssc.timer.C:
ssc.handleStatus(t.Unix())
case <-ssc.done:
return
}
}
}
// Status returns the status of StatusSyncController.
func (ssc *StatusSyncController) Status() *supervisor.Status {
return &supervisor.Status{
ObjectStatus: struct{}{},
}
}
// Close closes StatusSyncController.
func (ssc *StatusSyncController) Close() {
close(ssc.done)
ssc.timer.Close()
}
func (ssc *StatusSyncController) handleStatus(unixTimestamp int64) {
statusUnits := make(map[string]*statusUnit)
walkFn := func(entity *supervisor.ObjectEntity) bool {
defer func() {
if err := recover(); err != nil {
logger.Errorf("recover from syncStatus, err: %v, stack trace:\n%s\n",
err, debug.Stack())
}
}()
namespace := cluster.NamespaceDefault
objectName := entity.Spec().Name()
status := entity.Instance().Status()
status.Timestamp = unixTimestamp
switch objectStatus := status.ObjectStatus.(type) {
case *trafficcontroller.Status:
for _, namespaceStatus := range objectStatus.Namespaces {
namespace := namespaceStatus.TrafficNamespace()
for _, trafficObject := range namespaceStatus.TrafficObjects {
su := newStatusUnit(namespace, trafficObject.Name,
unixTimestamp, trafficObject.TrafficObjectStatus)
statusUnits[su.id()] = su
}
}
default:
su := newStatusUnit(namespace, objectName, unixTimestamp, status.ObjectStatus)
statusUnits[su.id()] = su
}
return true
}
ssc.superSpec.Super().WalkControllers(walkFn)
ssc.takeSnapshot(statusUnits, unixTimestamp)
ssc.syncStatusToCluster(statusUnits)
}
func (ssc *StatusSyncController) syncStatusToCluster(statusUnits map[string]*statusUnit) {
// Delete statuses which disappeared in current status.
if ssc.lastSyncStatusUnits != nil {
kvs := make(map[string]*string)
for k, su := range ssc.lastSyncStatusUnits {
if _, exists := statusUnits[k]; !exists {
key := su.clusterKey(ssc.superSpec.Super().Cluster().Layout())
kvs[key] = nil
}
}
err := ssc.superSpec.Super().Cluster().PutAndDeleteUnderLease(kvs)
if err != nil {
logger.Errorf("sync status failed. If the message size is too large, "+
"please increase the value of cluster.MaxCallSendMsgSize in configuration: %v", err)
}
}
ssc.lastSyncStatusUnits = statusUnits
kvs := make(map[string]*string)
for _, su := range statusUnits {
key := su.clusterKey(ssc.superSpec.Super().Cluster().Layout())
buff, err := su.marshal()
if err != nil {
logger.Errorf("BUG: marshal %#v failed: %v", su, err)
continue
}
value := string(buff)
kvs[key] = &value
if len(kvs) >= ssc.statusUpdateMaxBatchSize {
err := ssc.superSpec.Super().Cluster().PutAndDeleteUnderLease(kvs)
if err != nil {
logger.Errorf("sync status failed. If the message size is too large, "+
"please increase the value of cluster.MaxCallSendMsgSize in configuration: %v", err)
}
kvs = make(map[string]*string)
}
}
if len(kvs) > 0 {
err := ssc.superSpec.Super().Cluster().PutAndDeleteUnderLease(kvs)
if err != nil {
logger.Errorf("sync status failed. If the message size is too large, "+
"please increase the value of cluster.MaxCallSendMsgSize in configuration: %v", err)
}
}
}
func (ssc *StatusSyncController) takeSnapshot(statusUnits map[string]*statusUnit, timestamp int64) {
snapshot := &StatusesSnapshot{
Statuses: make(map[string]*supervisor.Status),
UnixTimestamp: timestamp,
}
for _, su := range statusUnits {
snapshot.Statuses[su.id()] = &supervisor.Status{
ObjectStatus: su.status,
Timestamp: timestamp,
}
}
ssc.statusSnapshotsMutex.Lock()
defer ssc.statusSnapshotsMutex.Unlock()
ssc.statusSnapshots = append(ssc.statusSnapshots, snapshot)
if len(ssc.statusSnapshots) > maxStatusesRecordCount {
ssc.statusSnapshots = ssc.statusSnapshots[1:]
}
}
// GetStatusSnapshots return the latest status snapshots.
func (ssc *StatusSyncController) GetStatusSnapshots() []*StatusesSnapshot {
ssc.statusSnapshotsMutex.RLock()
defer ssc.statusSnapshotsMutex.RUnlock()
records := make([]*StatusesSnapshot, len(ssc.statusSnapshots))
copy(records, ssc.statusSnapshots)
return records
}