-
Notifications
You must be signed in to change notification settings - Fork 6
/
umclient.go
381 lines (307 loc) · 9.64 KB
/
umclient.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// SPDX-License-Identifier: Apache-2.0
//
// Copyright (C) 2021 Renesas Electronics Corporation.
// Copyright (C) 2021 EPAM Systems, Inc.
//
// 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 umclient
import (
"context"
"encoding/json"
"errors"
"io"
"sync"
"time"
"github.com/aoscloud/aos_common/aoserrors"
pb "github.com/aoscloud/aos_common/api/updatemanager/v1"
"github.com/aoscloud/aos_common/utils/cryptutils"
log "github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"github.com/aoscloud/aos_updatemanager/config"
)
/***********************************************************************************************************************
* Consts
**********************************************************************************************************************/
const (
connectTimeout = 30 * time.Second
reconnectTimeout = 10 * time.Second
)
// UM states.
const (
StateIdle = iota
StatePrepared
StateUpdated
StateFailed
)
// Component statuses.
const (
StatusInstalled = iota
StatusInstalling
StatusError
)
/***********************************************************************************************************************
* Types
**********************************************************************************************************************/
// Client UM client instance.
type Client struct {
sync.Mutex
connection *grpc.ClientConn
stream pb.UMService_RegisterUMClient
messageHandler MessageHandler
umID string
closeChannel chan struct{}
}
// UMState UM state.
type UMState int32
// ComponentStatus component status.
type ComponentStatus int32
// ComponentUpdateInfo component update info.
type ComponentUpdateInfo struct {
ID string
VendorVersion string
AosVersion uint64
Annotations json.RawMessage
URL string
Sha256 []byte
Sha512 []byte
Size uint64
}
// ComponentStatusInfo component status info.
type ComponentStatusInfo struct {
ID string
VendorVersion string
AosVersion uint64
Status ComponentStatus
Error string
}
// Status update manager status.
type Status struct {
State UMState
Error string
Components []ComponentStatusInfo
}
// MessageHandler incoming messages handler.
type MessageHandler interface {
// Registered indicates the client registered on the server
Registered()
// PrepareUpdate prepares update
PrepareUpdate(components []ComponentUpdateInfo)
// StartUpdate starts update
StartUpdate()
// ApplyUpdate applies update
ApplyUpdate()
// RevertUpdate reverts update
RevertUpdate()
// StatusChannel returns status channel
StatusChannel() (channel <-chan Status)
}
// CertificateProvider interface to get certificate.
type CertificateProvider interface {
GetNodeID() (string, error)
GetCertificate(certType string) (certURL, ketURL string, err error)
}
/***********************************************************************************************************************
* Public
**********************************************************************************************************************/
// New creates new UM client.
func New(cfg *config.Config, messageHandler MessageHandler, certProvider CertificateProvider,
cryptocontext *cryptutils.CryptoContext, insecure bool,
) (client *Client, err error) {
log.Debug("Create UM client")
if messageHandler == nil {
return nil, aoserrors.New("message handler is nil")
}
client = &Client{
messageHandler: messageHandler,
closeChannel: make(chan struct{}),
}
if client.umID, err = certProvider.GetNodeID(); err != nil {
return nil, aoserrors.Wrap(err)
}
if err = client.createConnection(cfg, certProvider, cryptocontext, insecure); err != nil {
return nil, aoserrors.Wrap(err)
}
go func() {
for {
select {
case <-client.closeChannel:
return
case status := <-client.messageHandler.StatusChannel():
if err := client.sendStatus(status); err != nil {
log.Errorf("Can't send status: %s", aoserrors.Wrap(err))
}
}
}
}()
return client, nil
}
// Close closes UM client.
func (client *Client) Close() (err error) {
log.Debug("Close UM client")
if client.stream != nil {
err = aoserrors.Wrap(client.stream.CloseSend())
}
if client.connection != nil {
client.connection.Close()
}
close(client.closeChannel)
return aoserrors.Wrap(err)
}
func (state UMState) String() string {
return [...]string{
"idle", "prepared", "updated", "failed",
}[state]
}
func (status ComponentStatus) String() string {
return [...]string{
"installed", "installing", "error",
}[status]
}
/***********************************************************************************************************************
* Private
**********************************************************************************************************************/
func (client *Client) createConnection(
config *config.Config, provider CertificateProvider,
cryptocontext *cryptutils.CryptoContext, insecureConn bool,
) (err error) {
log.Debug("Connecting to CM...")
var secureOpt grpc.DialOption
if insecureConn {
secureOpt = grpc.WithTransportCredentials(insecure.NewCredentials())
} else {
certURL, keyURL, err := provider.GetCertificate(config.CertStorage)
if err != nil {
return aoserrors.Wrap(err)
}
tlsConfig, err := cryptocontext.GetClientMutualTLSConfig(certURL, keyURL)
if err != nil {
return aoserrors.Wrap(err)
}
secureOpt = grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))
}
ctx, cancel := context.WithTimeout(context.Background(), connectTimeout)
defer cancel()
if client.connection, err = grpc.DialContext(ctx, config.CMServerURL, secureOpt, grpc.WithBlock()); err != nil {
return aoserrors.Wrap(err)
}
log.Debug("Connected to CM")
go func() {
err := client.register()
for {
if err != nil && len(client.closeChannel) == 0 {
log.Errorf("Error register to CM: %s", aoserrors.Wrap(err))
} else {
client.messageHandler.Registered()
if err = client.processMessages(); err != nil {
if errors.Is(err, io.EOF) {
log.Debug("Connection is closed")
} else {
log.Errorf("Connection error: %s", aoserrors.Wrap(err))
}
}
}
log.Debugf("Reconnect to CM in %v...", reconnectTimeout)
select {
case <-client.closeChannel:
log.Debugf("Disconnected from CM")
return
case <-time.After(reconnectTimeout):
err = client.register()
}
}
}()
return nil
}
func (client *Client) register() (err error) {
client.Lock()
defer client.Unlock()
log.Debug("Registering to CM...")
if client.stream, err = pb.NewUMServiceClient(client.connection).RegisterUM(context.Background()); err != nil {
return aoserrors.Wrap(err)
}
log.Debug("Registered to CM")
return nil
}
func (client *Client) processMessages() (err error) {
for {
message, err := client.stream.Recv()
if err != nil {
if code, ok := status.FromError(err); ok {
if code.Code() == codes.Canceled {
log.Debug("UM client connection closed")
return nil
}
}
return aoserrors.Wrap(err)
}
switch data := message.GetCMMessage().(type) {
case *pb.CMMessages_PrepareUpdate:
log.Debug("Prepare update received")
components := make([]ComponentUpdateInfo, 0, len(data.PrepareUpdate.GetComponents()))
for _, component := range data.PrepareUpdate.GetComponents() {
components = append(components,
ComponentUpdateInfo{
ID: component.GetId(),
VendorVersion: component.GetVendorVersion(),
AosVersion: component.GetAosVersion(),
Annotations: json.RawMessage(component.GetAnnotations()),
URL: component.GetUrl(),
Sha256: component.GetSha256(),
Sha512: component.GetSha512(),
Size: component.GetSize(),
})
}
client.messageHandler.PrepareUpdate(components)
case *pb.CMMessages_StartUpdate:
log.Debug("Start update received")
client.messageHandler.StartUpdate()
case *pb.CMMessages_ApplyUpdate:
log.Debug("Apply update received")
client.messageHandler.ApplyUpdate()
case *pb.CMMessages_RevertUpdate:
log.Debug("Revert update received")
client.messageHandler.RevertUpdate()
}
}
}
func (client *Client) sendStatus(status Status) (err error) {
client.Lock()
defer client.Unlock()
if client.stream == nil {
return aoserrors.New("client is not connected")
}
log.WithFields(log.Fields{"umID": client, "state": status.State, "error": status.Error}).Debug("Send status")
pbComponents := make([]*pb.SystemComponent, 0, len(status.Components))
for _, component := range status.Components {
pbComponents = append(pbComponents, &pb.SystemComponent{
Id: component.ID,
VendorVersion: component.VendorVersion,
AosVersion: component.AosVersion,
Status: pb.ComponentStatus(component.Status),
Error: component.Error,
})
}
if err = client.stream.Send(&pb.UpdateStatus{
UmId: client.umID,
UmState: pb.UmState(status.State),
Error: status.Error,
Components: pbComponents,
}); err != nil {
return aoserrors.Wrap(err)
}
return nil
}