forked from open-cluster-management-io/sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagentclient.go
More file actions
339 lines (282 loc) · 10.7 KB
/
Copy pathagentclient.go
File metadata and controls
339 lines (282 loc) · 10.7 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
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package generic
import (
"context"
"fmt"
"strconv"
"time"
cloudevents "github.com/cloudevents/sdk-go/v2"
cloudeventstypes "github.com/cloudevents/sdk-go/v2/types"
"k8s.io/klog/v2"
"open-cluster-management.io/sdk-go/pkg/cloudevents/generic/options"
"open-cluster-management.io/sdk-go/pkg/cloudevents/generic/payload"
"open-cluster-management.io/sdk-go/pkg/cloudevents/generic/types"
)
// CloudEventAgentClient is a client for an agent to resync/send/receive its resources with cloud events.
//
// An agent is a component that handles the deployment of requested resources on the managed cluster and status report
// to the source.
type CloudEventAgentClient[T ResourceObject] struct {
*baseClient
lister Lister[T]
codec Codec[T]
statusHashGetter StatusHashGetter[T]
agentID string
clusterName string
}
// NewCloudEventAgentClient returns an instance for CloudEventAgentClient. The following arguments are required to
// create a client.
// - agentOptions provides the clusterName and agentID and the cloudevents clients that are based on different event
// protocols for sending/receiving the cloudevents.
// - lister gets the resources from a cache/store of an agent.
// - statusHashGetter calculates the resource status hash.
// - codec is used to encode/decode a resource objet/cloudevent to/from a cloudevent/resource objet.
func NewCloudEventAgentClient[T ResourceObject](
ctx context.Context,
agentOptions *options.CloudEventsAgentOptions,
lister Lister[T],
statusHashGetter StatusHashGetter[T],
codec Codec[T],
) (*CloudEventAgentClient[T], error) {
baseClient := &baseClient{
clientID: agentOptions.AgentID,
cloudEventsOptions: agentOptions.CloudEventsOptions,
cloudEventsRateLimiter: NewRateLimiter(agentOptions.EventRateLimit),
reconnectedChan: make(chan struct{}),
dataType: codec.EventDataType(),
}
if err := baseClient.connect(ctx); err != nil {
return nil, err
}
return &CloudEventAgentClient[T]{
baseClient: baseClient,
lister: lister,
codec: codec,
statusHashGetter: statusHashGetter,
agentID: agentOptions.AgentID,
clusterName: agentOptions.ClusterName,
}, nil
}
// ReconnectedChan returns a chan which indicates the source/agent client is reconnected.
// The source/agent client callers should consider sending a resync request when receiving this signal.
func (c *CloudEventAgentClient[T]) ReconnectedChan() <-chan struct{} {
return c.reconnectedChan
}
// Resync the resources spec by sending a spec resync request from the current to the given source.
func (c *CloudEventAgentClient[T]) Resync(ctx context.Context, source string) error {
// list the resource objects that are maintained by the current agent with the given source
options := types.ListOptions{Source: source, ClusterName: c.clusterName, CloudEventsDataType: c.codec.EventDataType()}
objs, err := c.lister.List(options)
if err != nil {
return err
}
resources := &payload.ResourceVersionList{Versions: make([]payload.ResourceVersion, len(objs))}
for i, obj := range objs {
resourceVersion, err := strconv.ParseInt(obj.GetResourceVersion(), 10, 64)
if err != nil {
return err
}
resources.Versions[i] = payload.ResourceVersion{
ResourceID: string(obj.GetUID()),
ResourceVersion: resourceVersion,
}
}
eventType := types.CloudEventsType{
CloudEventsDataType: c.codec.EventDataType(),
SubResource: types.SubResourceSpec,
Action: types.ResyncRequestAction,
}
evt := types.NewEventBuilder(c.agentID, eventType).
WithOriginalSource(source).
WithClusterName(c.clusterName).
NewEvent()
if err := evt.SetData(cloudevents.ApplicationJSON, resources); err != nil {
return fmt.Errorf("failed to set data to cloud event: %v", err)
}
if err := c.publish(ctx, evt); err != nil {
return err
}
increaseCloudEventsSentFromAgentCounter(evt.Source(), source, c.codec.EventDataType().String(), string(eventType.SubResource), string(eventType.Action))
return nil
}
// Publish a resource status from an agent to a source.
func (c *CloudEventAgentClient[T]) Publish(ctx context.Context, eventType types.CloudEventsType, obj T) error {
if eventType.CloudEventsDataType != c.codec.EventDataType() {
return fmt.Errorf("unsupported cloudevent data type %s", eventType.CloudEventsDataType)
}
evt, err := c.codec.Encode(c.agentID, eventType, obj)
if err != nil {
return err
}
if err := c.publish(ctx, *evt); err != nil {
return err
}
originalSource, _ := cloudeventstypes.ToString(evt.Context.GetExtensions()[types.ExtensionOriginalSource])
increaseCloudEventsSentFromAgentCounter(evt.Source(), originalSource, eventType.CloudEventsDataType.String(), string(eventType.SubResource), string(eventType.Action))
return nil
}
// Subscribe the events that are from the source status resync request or source resource spec request.
// For status resync request, agent publish the current resources status back as response.
// For resource spec request, agent receives resource spec and handles the spec with resource handlers.
func (c *CloudEventAgentClient[T]) Subscribe(ctx context.Context, handlers ...ResourceHandler[T]) {
c.subscribe(ctx, func(ctx context.Context, evt cloudevents.Event) {
c.receive(ctx, evt, handlers...)
})
}
func (c *CloudEventAgentClient[T]) receive(ctx context.Context, evt cloudevents.Event, handlers ...ResourceHandler[T]) {
eventType, err := types.ParseCloudEventsType(evt.Type())
if err != nil {
klog.Errorf("failed to parse cloud event type %s, %v", evt.Type(), err)
return
}
increaseCloudEventsReceivedByAgentCounter(evt.Source(), eventType.CloudEventsDataType.String(), string(eventType.SubResource), string(eventType.Action))
if eventType.Action == types.ResyncRequestAction {
if eventType.SubResource != types.SubResourceStatus {
klog.Warningf("unsupported resync event type %s, ignore", eventType)
return
}
startTime := time.Now()
if err := c.respondResyncStatusRequest(ctx, eventType.CloudEventsDataType, evt); err != nil {
klog.Errorf("failed to resync manifestsstatus, %v", err)
}
updateResourceStatusResyncDurationMetric(evt.Source(), c.clusterName, eventType.CloudEventsDataType.String(), startTime)
return
}
if eventType.SubResource != types.SubResourceSpec {
klog.Warningf("unsupported event type %s, ignore", eventType)
return
}
evtExtensions := evt.Context.GetExtensions()
clusterName, err := cloudeventstypes.ToString(evtExtensions[types.ExtensionClusterName])
if err != nil {
klog.Errorf("failed to get clustername extension: %v", err)
return
}
if clusterName != c.clusterName {
klog.V(4).Infof("event clustername %s and agent clustername %s do not match, ignore", clusterName, c.clusterName)
return
}
if eventType.CloudEventsDataType != c.codec.EventDataType() {
klog.Warningf("unsupported event data type %s, ignore", eventType.CloudEventsDataType)
return
}
obj, err := c.codec.Decode(&evt)
if err != nil {
klog.Errorf("failed to decode spec, %v", err)
return
}
action, err := c.specAction(evt.Source(), eventType.CloudEventsDataType, obj)
if err != nil {
klog.Errorf("failed to generate spec action %s, %v", evt, err)
return
}
if len(action) == 0 {
// no action is required, ignore
return
}
for _, handler := range handlers {
if err := handler(action, obj); err != nil {
klog.Errorf("failed to handle spec event %s, %v", evt, err)
}
}
}
// Upon receiving the status resync event, the agent responds by sending resource status events to the broker as
// follows:
// - If the event payload is empty, the agent returns the status of all resources it maintains.
// - If the event payload is not empty, the agent retrieves the resource with the specified ID and compares the
// received resource status hash with the current resource status hash. If they are not equal, the agent sends the
// resource status message.
func (c *CloudEventAgentClient[T]) respondResyncStatusRequest(
ctx context.Context, eventDataType types.CloudEventsDataType, evt cloudevents.Event,
) error {
options := types.ListOptions{ClusterName: c.clusterName, Source: evt.Source(), CloudEventsDataType: eventDataType}
objs, err := c.lister.List(options)
if err != nil {
return err
}
statusHashes, err := payload.DecodeStatusResyncRequest(evt)
if err != nil {
return err
}
eventType := types.CloudEventsType{
CloudEventsDataType: eventDataType,
SubResource: types.SubResourceStatus,
Action: types.ResyncResponseAction,
}
if len(statusHashes.Hashes) == 0 {
// publish all resources status
for _, obj := range objs {
if err := c.Publish(ctx, eventType, obj); err != nil {
return err
}
}
return nil
}
for _, obj := range objs {
lastHash, ok := findStatusHash(string(obj.GetUID()), statusHashes.Hashes)
if !ok {
// ignore the resource that is not on the source, but exists on the agent, wait for the source deleting it
klog.Infof("The resource %s is not found from the source, ignore", obj.GetUID())
continue
}
currentHash, err := c.statusHashGetter(obj)
if err != nil {
continue
}
if currentHash == lastHash {
// the status is not changed, do nothing
continue
}
if err := c.Publish(ctx, eventType, obj); err != nil {
return err
}
}
return nil
}
func (c *CloudEventAgentClient[T]) specAction(
source string, eventDataType types.CloudEventsDataType, obj T) (evt types.ResourceAction, err error) {
options := types.ListOptions{ClusterName: c.clusterName, Source: source, CloudEventsDataType: eventDataType}
objs, err := c.lister.List(options)
if err != nil {
return evt, err
}
lastObj, exists := getObj(string(obj.GetUID()), objs)
if !exists {
return types.Added, nil
}
if !obj.GetDeletionTimestamp().IsZero() {
return types.Deleted, nil
}
// if both the current and the last object have the resource version "0", then object
// is considered as modified, the message broker guarantees the order of the messages
if obj.GetResourceVersion() == "0" && lastObj.GetResourceVersion() == "0" {
return types.Modified, nil
}
resourceVersion, err := strconv.ParseInt(obj.GetResourceVersion(), 10, 64)
if err != nil {
return evt, err
}
lastResourceVersion, err := strconv.ParseInt(lastObj.GetResourceVersion(), 10, 64)
if err != nil {
return evt, err
}
if resourceVersion <= lastResourceVersion {
return evt, nil
}
return types.Modified, nil
}
func getObj[T ResourceObject](resourceID string, objs []T) (obj T, exists bool) {
for _, obj := range objs {
if string(obj.GetUID()) == resourceID {
return obj, true
}
}
return obj, false
}
func findStatusHash(id string, hashes []payload.ResourceStatusHash) (string, bool) {
for _, hash := range hashes {
if id == hash.ResourceID {
return hash.StatusHash, true
}
}
return "", false
}