-
-
Notifications
You must be signed in to change notification settings - Fork 17
/
pull.go
374 lines (341 loc) · 10.8 KB
/
pull.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
package service
import (
"context"
"fmt"
"io"
"io/ioutil"
"net/http"
"strings"
"sync"
"time"
"github.com/plgd-dev/kit/log"
pbAS "github.com/plgd-dev/cloud/authorization/pb"
"github.com/plgd-dev/cloud/cloud2cloud-connector/store"
pbCQRS "github.com/plgd-dev/cloud/resource-aggregate/pb"
pbRA "github.com/plgd-dev/cloud/resource-aggregate/pb"
"github.com/plgd-dev/kit/codec/json"
kitNetGrpc "github.com/plgd-dev/kit/net/grpc"
"github.com/plgd-dev/sdk/schema"
)
type Device struct {
Device schema.Device `json:"device"`
Status string `json:"status"`
}
type RetrieveDeviceWithLinksResponse struct {
Device
Links []schema.ResourceLink `json:"links"`
}
type pullDevicesHandler struct {
s *Store
asClient pbAS.AuthorizationServiceClient
raClient pbRA.ResourceAggregateClient
devicesSubscription *DevicesSubscription
linkedClouds map[string]store.LinkedCloud
subscriptionManager *SubscriptionManager
oauthCallback string
triggerTask func(Task)
}
func getUsersDevices(ctx context.Context, asClient pbAS.AuthorizationServiceClient) (map[string]bool, error) {
getUserDevicesClient, err := asClient.GetUserDevices(ctx, &pbAS.GetUserDevicesRequest{})
if err != nil {
return nil, fmt.Errorf("cannot get users devices: %w", err)
}
defer getUserDevicesClient.CloseSend()
userDevices := make(map[string]bool)
for {
userDevice, err := getUserDevicesClient.Recv()
if err == io.EOF {
break
}
if err != nil {
return nil, fmt.Errorf("cannot get users devices: %w", err)
}
if userDevice == nil {
continue
}
userDevices[userDevice.DeviceId] = true
}
return userDevices, nil
}
func Get(ctx context.Context, url string, linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud, v interface{}) error {
client := linkedCloud.GetHTTPClient()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", "Bearer "+string(linkedAccount.TargetCloud.AccessToken))
req.Header.Set("Accept", "application/json")
req.Header.Set("Connection", "close")
req.Close = true
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Decode(buf, v)
if err != nil {
return fmt.Errorf("cannot decode body(%v): %w", string(buf), err)
}
return nil
}
func publishDeviceResources(ctx context.Context, raClient pbRA.ResourceAggregateClient, deviceID string, linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud, subscriptionManager *SubscriptionManager, dev RetrieveDeviceWithLinksResponse, triggerTask func(Task)) error {
var errors []error
userID := linkedAccount.UserID
for _, link := range dev.Links {
link.DeviceID = deviceID
href := removeDeviceIDFromHref(link.Href)
link.Href = href
err := publishResource(ctx, raClient, userID, link, pbCQRS.CommandMetadata{
ConnectionId: linkedAccount.ID,
Sequence: uint64(time.Now().UnixNano()),
})
if err != nil {
errors = append(errors, fmt.Errorf("cannot publish respource %+v: %w", link, err))
continue
}
if linkedCloud.SupportedSubscriptionsEvents.NeedPullResources() {
continue
}
triggerTask(Task{
taskType: TaskType_SubscribeToResource,
linkedAccount: linkedAccount,
linkedCloud: linkedCloud,
deviceID: deviceID,
href: href,
})
}
if len(errors) > 0 {
return fmt.Errorf("%+v", errors)
}
return nil
}
func (p *pullDevicesHandler) getDevicesWithResourceLinks(ctx context.Context, linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud) error {
var errors []error
userID := linkedAccount.UserID
var devices []RetrieveDeviceWithLinksResponse
err := Get(ctx, linkedCloud.Endpoint.URL+"/devices", linkedAccount, linkedCloud, &devices)
if err != nil {
return err
}
ctx = kitNetGrpc.CtxWithUserID(ctx, userID)
if linkedCloud.SupportedSubscriptionsEvents.NeedPullDevices() {
registeredDevices, err := getUsersDevices(ctx, p.asClient)
if err != nil {
return err
}
for _, dev := range devices {
deviceID := dev.Device.Device.ID
ok := registeredDevices[deviceID]
err := p.devicesSubscription.Add(deviceID, linkedAccount, linkedCloud)
if err != nil {
errors = append(errors, fmt.Errorf("cannot add device %v to devicesSubscription: %w", deviceID, err))
}
if !ok {
_, err := p.asClient.AddDevice(ctx, &pbAS.AddDeviceRequest{
DeviceId: deviceID,
UserId: userID,
})
if err != nil {
errors = append(errors, fmt.Errorf("cannot addDevice %v: %w", deviceID, err))
continue
}
err = publishCloudDeviceStatus(ctx, p.raClient, userID, deviceID, pbCQRS.CommandMetadata{
ConnectionId: linkedAccount.ID,
Sequence: uint64(time.Now().UnixNano()),
})
if err != nil {
errors = append(errors, fmt.Errorf("cannot publish cloud status: %v: %w", deviceID, err))
continue
}
}
delete(registeredDevices, deviceID)
var online bool
if strings.ToLower(dev.Status) == "online" {
online = true
}
err = updateCloudStatus(ctx, p.raClient, userID, deviceID, online, pbCQRS.CommandMetadata{
ConnectionId: linkedAccount.ID,
Sequence: uint64(time.Now().UnixNano()),
})
if err != nil {
errors = append(errors, fmt.Errorf("cannot update cloud status: %v: %w", deviceID, err))
}
}
for deviceID := range registeredDevices {
err := p.devicesSubscription.Delete(userID, deviceID)
if err != nil {
errors = append(errors, fmt.Errorf("cannot delete device %v from devicesSubscription: %w", deviceID, err))
}
_, err = p.asClient.RemoveDevice(ctx, &pbAS.RemoveDeviceRequest{
DeviceId: deviceID,
})
if err != nil {
errors = append(errors, fmt.Errorf("cannot removeDevice %v: %w", deviceID, err))
}
}
}
for _, dev := range devices {
deviceID := dev.Device.Device.ID
if linkedCloud.SupportedSubscriptionsEvents.StaticDeviceEvents {
p.triggerTask(Task{
taskType: TaskType_PullDevice,
linkedAccount: linkedAccount,
linkedCloud: linkedCloud,
deviceID: deviceID,
})
} else if linkedCloud.SupportedSubscriptionsEvents.NeedPullDevice() {
err := publishDeviceResources(ctx, p.raClient, deviceID, linkedAccount, linkedCloud, p.subscriptionManager, dev, p.triggerTask)
if err != nil {
errors = append(errors, err)
continue
}
} else {
if _, ok := p.s.LoadDeviceSubscription(linkedCloud.ID, linkedAccount.ID, deviceID); ok {
continue
}
p.triggerTask(Task{
taskType: TaskType_SubscribeToDevice,
linkedAccount: linkedAccount,
linkedCloud: linkedCloud,
deviceID: deviceID,
})
}
}
if len(errors) > 0 {
return fmt.Errorf("%+v", errors)
}
return nil
}
type Representation struct {
Href string `json:"href"`
Representation interface{} `json:"rep"`
}
type RetrieveDeviceContentAllResponse struct {
Device
Links []Representation `json:"links"`
}
func removeDeviceIDFromHref(href string) string {
hrefsp := strings.Split(href, "/")
href = "/" + strings.Join(hrefsp[2:], "/")
return href
}
func (p *pullDevicesHandler) getDevicesWithResourceValues(ctx context.Context, linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud) error {
var errors []error
userID := linkedAccount.UserID
var devices []RetrieveDeviceContentAllResponse
err := Get(ctx, linkedCloud.Endpoint.URL+"/devices?content=all", linkedAccount, linkedCloud, &devices)
if err != nil {
return err
}
ctx = kitNetGrpc.CtxWithUserID(ctx, userID)
for _, dev := range devices {
deviceID := dev.Device.Device.ID
for _, link := range dev.Links {
link.Href = removeDeviceIDFromHref(link.Href)
body, err := json.Encode(link.Representation)
if err != nil {
errors = append(errors, err)
continue
}
err = notifyResourceChanged(
ctx,
p.raClient,
deviceID,
link.Href,
userID,
"application/json",
body,
pbCQRS.CommandMetadata{
ConnectionId: linkedAccount.ID,
Sequence: uint64(time.Now().UnixNano()),
},
)
log.Debugf("notifyResourceChanged %v%v: %v", deviceID, link.Href, string(body))
if err != nil {
errors = append(errors, fmt.Errorf("cannot notifyResourceChanged %+v: %w", link, err))
}
}
}
if len(errors) > 0 {
return fmt.Errorf("%+v", errors)
}
return nil
}
func RefreshToken(ctx context.Context, linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud, oauthCallback string, s *Store) (store.LinkedAccount, error) {
ctx = linkedCloud.CtxWithHTTPClient(ctx)
oauthCfg := linkedCloud.OAuth
if oauthCfg.RedirectURL == "" {
oauthCfg.RedirectURL = oauthCallback
}
token, refreshed, err := linkedAccount.TargetCloud.Refresh(ctx, linkedCloud.OAuth.ToOAuth2())
if err != nil {
return store.LinkedAccount{}, err
}
linkedAccount.TargetCloud = token
if refreshed {
err = s.UpdateLinkedAccount(ctx, linkedAccount)
if err != nil {
return store.LinkedAccount{}, fmt.Errorf("cannot store updated linked linkedAccount: %w", err)
}
}
return linkedAccount, nil
}
func (p *pullDevicesHandler) pullDevicesFromAccount(ctx context.Context, linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud) error {
linkedAccount, err := RefreshToken(ctx, linkedAccount, linkedCloud, p.oauthCallback, p.s)
if err != nil {
return err
}
var errors []error
if linkedCloud.SupportedSubscriptionsEvents.NeedPullDevices() || linkedCloud.SupportedSubscriptionsEvents.NeedPullDevice() {
err = p.getDevicesWithResourceLinks(ctx, linkedAccount, linkedCloud)
if err != nil {
errors = append(errors, err)
}
}
if linkedCloud.SupportedSubscriptionsEvents.NeedPullResources() {
err = p.getDevicesWithResourceValues(ctx, linkedAccount, linkedCloud)
if err != nil {
errors = append(errors, err)
}
}
if len(errors) > 0 {
return fmt.Errorf("%+v", errors)
}
return nil
}
func pullDevices(ctx context.Context, s *Store,
asClient pbAS.AuthorizationServiceClient,
raClient pbRA.ResourceAggregateClient,
devicesSubscription *DevicesSubscription,
subscriptionManager *SubscriptionManager,
oauthCallback string,
triggerTask func(Task)) error {
data := s.DumpLinkedAccounts()
var wg sync.WaitGroup
for _, d := range data {
log.Debugf("pulling devices for %v", d.linkedAccount)
p := pullDevicesHandler{
s: s,
asClient: asClient,
raClient: raClient,
devicesSubscription: devicesSubscription,
subscriptionManager: subscriptionManager,
oauthCallback: oauthCallback,
triggerTask: triggerTask,
}
wg.Add(1)
go func(linkedAccount store.LinkedAccount, linkedCloud store.LinkedCloud) {
defer wg.Done()
err := p.pullDevicesFromAccount(ctx, linkedAccount, linkedCloud)
if err != nil {
log.Errorf("cannot pull devices for linked linkedAccount(%v): %v", linkedAccount, err)
}
}(d.linkedAccount, d.linkedCloud)
}
wg.Wait()
return nil
}