-
Notifications
You must be signed in to change notification settings - Fork 17
/
foundries.go
1809 lines (1576 loc) · 49.3 KB
/
foundries.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package client
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
tuf "github.com/theupdateframework/notary/tuf/data"
)
type Config struct {
Factory string
Token string
ClientCredentials OAuthConfig
ExtraHeaders map[string]string
InsecureSkipVerify bool
}
type Api struct {
serverUrl string
config Config
client http.Client
clientVer string
}
type ConfigFile struct {
Name string `json:"name"`
Value string `json:"value"`
Unencrypted bool `json:"unencrypted"`
OnChanged []string `json:"on-changed,omitempty"`
}
type ConfigCreateRequest struct {
Reason string `json:"reason"`
Files []ConfigFile `json:"files"`
}
type DeviceConfig struct {
CreatedAt string `json:"created-at"`
AppliedAt string `json:"applied-at"` // This is not present in factory config
CreatedBy string `json:"created-by"`
Reason string `json:"reason"`
Files []ConfigFile `json:"files"`
}
type DeviceConfigList struct {
Configs []DeviceConfig `json:"config"`
Total int `json:"total"`
Next *string `json:"next"`
}
type NetInfo struct {
Hostname string `json:"hostname"`
Ipv4 string `json:"local_ipv4"`
MAC string `json:"mac"`
}
type Update struct {
CorrelationId string `json:"correlation-id"`
Target string `json:"target"`
Version string `json:"version"`
Time string `json:"time"`
}
type UpdateList struct {
Updates []Update `json:"updates"`
Total int `json:"total"`
Next *string `json:"next"`
}
type EventType struct {
Id string `json:"id"`
}
type EventDetail struct {
Version string `json:"version"`
TargetName string `json:"targetName"`
Success *bool `json:"success,omitempty"`
Details string `json:"details"`
}
type UpdateEvent struct {
Time string `json:"deviceTime"`
Type EventType `json:"eventType"`
Detail EventDetail `json:"event"`
}
type ChangeMeta struct {
CreatedBy string `json:"created-by"`
CreatedAt string `json:"created-at"`
UpdatedBy string `json:"updated-by"`
UpdatedAt string `json:"updated-at"`
}
type DeviceGroup struct {
Id int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
ChangeMeta ChangeMeta `json:"change-meta"`
}
type AppServiceState struct {
Name string `json:"name"`
Hash string `json:"hash"`
State string `json:"state"`
Status string `json:"status"`
Health string `json:"health"`
ImageUri string `json:"image"`
Logs string `json:"logs"`
}
type AppState struct {
Services []AppServiceState `json:"services"`
State string `json:"state"`
Uri string `json:"uri"`
}
type AppsState struct {
Ostree string `json:"ostree"`
DeviceTime string `json:"deviceTime"`
Apps map[string]AppState `json:"apps,omitempty"`
}
type AppsStates struct {
States []AppsState `json:"apps-states"`
}
type Device struct {
Uuid string `json:"uuid"`
Name string `json:"name"`
Owner string `json:"owner"`
Factory string `json:"factory"`
GroupName string `json:"device-group"` // Returned in List API
Group *DeviceGroup `json:"group"` // Returned in Get API
LastSeen string `json:"last-seen"`
OstreeHash string `json:"ostree-hash"`
LmpVer string `json:"lmp-ver,omitempty"`
DockerApps []string `json:"docker-apps,omitempty"`
Tag string `json:"tag,omitempty"`
Network *NetInfo `json:"network-info,omitempty"`
Hardware *json.RawMessage `json:"hardware-info,omitempty"`
TargetName string `json:"target-name"`
Status string `json:"status"`
CurrentUpdate string `json:"current-update"`
UpToDate bool `json:"up-to-date"`
PublicKey string `json:"public-key"`
ActiveConfig *DeviceConfig `json:"active-config,omitempty"`
AktualizrToml string `json:"aktualizr-toml,omitempty"`
IsProd bool `json:"is-prod"`
IsWave bool `json:"is-wave"`
ChangeMeta ChangeMeta `json:"change-meta"`
Secondaries []struct {
Serial string `json:"serial"`
TargetName string `json:"target-name"`
HardwareId string `json:"hardware-id"`
} `json:"secondary-ecus"`
AppsState *AppsState `json:"apps-state,omitempty"`
}
type DeviceList struct {
Devices []Device `json:"devices"`
Total int `json:"total"`
Next *string `json:"next"`
}
type DockerApp struct {
FileName string `json:"filename"`
Uri string `json:"uri"`
}
type ComposeApp struct {
Uri string `json:"uri"`
}
func (a ComposeApp) Hash() string {
parts := strings.SplitN(a.Uri, "@sha256:", 2)
return parts[len(parts)-1]
}
func (a ComposeApp) Name() string {
parts := strings.SplitN(a.Uri, "@sha256:", 2)
nameStartIndx := strings.LastIndexByte(parts[0], '/')
return parts[0][nameStartIndx+1:]
}
type FactoryUser struct {
PolisId string `json:"polis-id"`
Name string `json:"name"`
Role string `json:"role"`
}
type FactoryUserAccessDetails struct {
PolisId string `json:"polis-id"`
Name string `json:"name"`
Role string `json:"role"`
Teams []FactoryTeamDetails `json:"teams-ext"`
EffectiveScopes []string `json:"effective-scopes"`
}
type FactoryTeam struct {
Name string `json:"name"`
Description string `json:"description"`
}
type FactoryTeamDetails struct {
Name string `json:"name"`
Description string `json:"description"`
Scopes []string `json:"scopes"`
Groups []string `json:"groups"`
Members []FactoryUser `json:"members"`
}
type JobservBuild struct {
ID int `json:"build_id"`
}
type JobservRun struct {
Name string `json:"name"`
Url string `json:"url"`
Artifacts []string `json:"artifacts"`
}
type TargetStatus struct {
Version int `json:"version"`
Devices int `json:"devices"`
Reinstalling int `json:"(re-)installing"`
IsOrphan bool `json:"is-orphan"`
}
type DeviceGroupStatus struct {
Name string `json:"name"`
DevicesTotal int `json:"devices-total"`
DevicesOnline int `json:"devices-online"`
DevicesOnLatest int `json:"devices-on-latest"`
DevicesOnOrphan int `json:"devices-on-orphan"`
Reinstalling int `json:"(re-)installing"`
}
type TagStatus struct {
Name string `json:"name"`
DevicesTotal int `json:"devices-total"`
DevicesOnline int `json:"devices-online"`
DevicesOnLatest int `json:"devices-on-latest"`
DevicesOnOrphan int `json:"devices-on-orphan"`
LatestTarget int `json:"latest-target"`
Targets []TargetStatus `json:"targets"`
DeviceGroups []DeviceGroupStatus `json:"device-groups"`
}
type FactoryStatus struct {
TotalDevices int `json:"total-devices"`
Tags []TagStatus `json:"tags"`
ProdTags []TagStatus `json:"prod-tags"`
ProdWaveTags []TagStatus `json:"wave-tags"`
}
type ProjectSecret struct {
Name string `json:"name"`
Value *string `json:"value"`
}
type ProjectTrigger struct {
Type string `json:"type"`
Id int `json:"id,omitempty"`
Secrets []ProjectSecret `json:"secrets"`
}
type TufCustom struct {
HardwareIds []string `json:"hardwareIds,omitempty"`
Tags []string `json:"tags,omitempty"`
TargetFormat string `json:"targetFormat,omitempty"`
Version string `json:"version,omitempty"`
ComposeApps map[string]ComposeApp `json:"docker_compose_apps,omitempty"`
Name string `json:"name,omitempty"`
ContainersSha string `json:"containers-sha,omitempty"`
LmpManifestSha string `json:"lmp-manifest-sha,omitempty"`
OverridesSha string `json:"meta-subscriber-overrides-sha,omitempty"`
Uri string `json:"uri,omitempty"`
OrigUri string `json:"origUri,omitempty"`
CreatedAt string `json:"createdAt,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
LmpVer string `json:"lmp-ver,omitempty"`
}
type Target struct {
Length int64 `json:"length"`
Hashes tuf.Hashes `json:"hashes"`
Custom *TufCustom `json:"custom,omitempty"`
}
func (t *Target) HardwareId() string {
return t.Custom.HardwareIds[0]
}
func (t *Target) Version() int {
ver, err := strconv.Atoi(t.Custom.Version)
if err != nil {
return -1
}
return ver
}
func (t *Target) Tags() []string {
return t.Custom.Tags
}
func (t *Target) HasTag(tag string) bool {
for _, ct := range t.Tags() {
if ct == tag {
return true
}
}
return false
}
func (t *Target) Name() string {
return t.Custom.Name + "-" + t.Custom.Version
}
func (t *Target) SetHash(hash string) error {
hb, err := base64.StdEncoding.DecodeString(hash)
if err != nil {
return err
}
t.Hashes["sha256"] = hb
return nil
}
type AtsTargetsMeta struct {
tuf.SignedCommon
Targets tuf.Files `json:"targets"`
// omitempty below in tuf package doesn't work, because it's not a reference type
// Delegations tuf.Delegations `json:"delegations,omitempty"` // unnecessary
}
type AtsTufTargets struct {
Signatures []tuf.Signature `json:"signatures"`
Signed AtsTargetsMeta `json:"signed"`
}
type ComposeAppContent struct {
Files []string `json:"files"`
ComposeSpec map[string]interface{} `json:"compose_spec"`
}
type ComposeAppBundle struct {
Uri string `json:"uri"`
Error string `json:"error"`
Warnings []string `json:"warnings"`
Manifest map[string]interface{} `json:"manifest"`
Content ComposeAppContent `json:"content"`
}
type TargetTestResults struct {
Name string `json:"name"`
Status string `json:"status"`
Details string `json:"details"`
}
type TargetTest struct {
Name string `json:"name"`
Id string `json:"test-id"`
DeviceUUID string `json:"device-uuid"`
DeviceName string `json:"device-name"`
Status string `json:"status"`
Details string `json:"details"`
CreatedOn float32 `json:"created-on"`
CompletedOn float32 `json:"completed-on"`
Results []TargetTestResults `json:"results"`
Artifacts []string `json:"artifacts"`
}
type TargetTestList struct {
Tests []TargetTest `json:"tests"`
Total int `json:"total"`
Next *string `json:"next"`
}
type WaveRolloutGroupRef struct {
GroupId int `json:"group-id"`
GroupName string `json:"group-name"`
CreatedAt string `json:"created-at"`
CreatedBy string `json:"created-by"`
}
type RolloutHistory struct {
GroupName string `json:"group-name"`
RolloutBy string `json:"rollout-by"`
RolloutAt string `json:"rollout-at"`
IsFullGroup bool `json:"is-full-group"`
IsFactoryWide bool `json:"is-factory-wide"`
DeviceNumber int `json:"num-devices"`
}
type Wave struct {
Name string `json:"name"`
Version string `json:"version"`
Tag string `json:"tag"`
Targets *json.RawMessage `json:"targets"`
Status string `json:"status"`
RolloutGroups map[string]WaveRolloutGroupRef `json:"rollout-groups"`
History []RolloutHistory `json:"rollout-history"`
ChangeMeta ChangeMeta `json:"change-meta"`
}
type WaveCreate struct {
Name string `json:"name"`
Version string `json:"version"`
Tag string `json:"tag"`
Targets tuf.Signed `json:"targets"`
}
type WaveList struct {
Waves []Wave `json:"waves"`
Total int `json:"total"`
Next *string `json:"next"`
}
type WaveRolloutOptions struct {
Group string `json:"group,omitempty"`
Limit int `json:"limit,omitempty"`
Percentage int `json:"percentage,omitempty"`
Uuids []string `json:"uuids,omitempty"`
DryRun bool `json:"dry-run"`
PrintUuids bool `json:"return-uuids"`
PrintNames bool `json:"return-names"`
}
type WaveRolloutResult struct {
Wave
DeviceNum int `json:"device-num"`
DeviceUuids []string `json:"device-uuids"`
DeviceNames []string `json:"device-names"`
}
type RolloutGroupStatus struct {
Name string `json:"name"`
RolloutAt string `json:"rollout-at"`
DevicesTotal int `json:"devices-total"`
DevicesOnline int `json:"devices-online"`
DevicesOnWave int `json:"devices-on-wave-version"`
DevicesOnNewer int `json:"devices-on-newer-version"`
DevicesOnOlder int `json:"devices-on-older-version"`
DevicesScheduled int `json:"devices-scheduled-for-update"`
Targets []TargetStatus `json:"targets"`
}
type WaveStatus struct {
Name string `json:"name"`
Version int `json:"version"`
Tag string `json:"tag"`
Status string `json:"status"`
CreatedAt string `json:"created-at"`
FinishedAt string `json:"finished-at"`
TotalDevices int `json:"total-devices"`
UpdatedDevices int `json:"updated-devices"`
ScheduledDevices int `json:"scheduled-devices"`
UnscheduledDevices int `json:"unscheduled-devices"`
RolloutGroups []RolloutGroupStatus `json:"rollout-groups"`
OtherGroups []RolloutGroupStatus `json:"other-groups"`
}
type WireGuardIp struct {
Name string `json:"name"`
Ip string `json:"ip"`
Enabled bool `json:"enabled"`
}
// This is an error returned in case if we've successfully received an HTTP response which contains
// an unexpected HTTP status code
type HttpError struct {
Message string
Response *http.Response
}
func (err *HttpError) Error() string {
return err.Message
}
// This is much better than err.(HttpError) as it also accounts for wrapped errors.
func AsHttpError(err error) *HttpError {
var httpError *HttpError
if errors.As(err, &httpError) {
return httpError
} else {
return nil
}
}
func (d Device) Online(inactiveHoursThreshold int) bool {
if len(d.LastSeen) == 0 {
return false
}
t, err := time.Parse(time.RFC3339, d.LastSeen)
if err == nil {
duration := time.Since(t)
if duration.Hours() > float64(inactiveHoursThreshold) {
return false
}
} else {
logrus.Error(err)
return false
}
return true
}
func NewApiClient(serverUrl string, config Config, caCertPath string, version string) *Api {
tlsCfg := &tls.Config{
InsecureSkipVerify: config.InsecureSkipVerify,
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = tlsCfg
if len(caCertPath) > 0 {
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certs, err := os.ReadFile(caCertPath)
if err != nil {
logrus.Fatalf("Failed to append %q to RootCAs: %v", caCertPath, err)
}
if ok := rootCAs.AppendCertsFromPEM(certs); !ok {
logrus.Warning("No certs appended, using system certs only")
}
tlsCfg.RootCAs = rootCAs
}
api := Api{
serverUrl: strings.TrimRight(serverUrl, "/"),
config: config,
client: *http.DefaultClient,
clientVer: version,
}
return &api
}
func httpLogger(req *http.Request) logrus.FieldLogger {
return logrus.WithFields(logrus.Fields{"url": req.URL.String(), "method": req.Method})
}
func readResponse(res *http.Response, log logrus.FieldLogger) (*[]byte, error) {
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
log.Debugf("I/O error reading response: %s", err)
return nil, err
}
// Accept all "normal" successful status codes: 200, 201, 202, 204, excluding quite inappropriate
// for RESTful web services 203, 205, and 206. There are some preferences what to return for
// each operation, but a client side normally should not fail if e.g. a POST returns 200, 202, or
// 204 instead of a usual 201. There are use cases when each of those status codes is valid and
// should be treated as a success. Though there might be some differences how that success is
// handled by a higher-level logic.
switch res.StatusCode {
case 200:
case 201:
case 202:
case 204:
break
default:
var PRINT_LIMIT, DEBUG_LIMIT int = 512, 8196
errBody := (string)(body)
if len(body) > DEBUG_LIMIT {
// too much is too much, even for a debug message
errBody = fmt.Sprintf("%s...(truncated body over %d)", body[:DEBUG_LIMIT], DEBUG_LIMIT)
}
log.Debugf("HTTP error received %s", res.Status)
log.Debugf(errBody)
// Still return a body, a caller might need it, but also return an error
msg := fmt.Sprintf("HTTP error during %s '%s': %s",
res.Request.Method, res.Request.URL.String(), res.Status)
// Some APIs return well-formatted errors, try to use them
var (
useGenericError bool
listErrors struct {
Msg string `json:"msg,omitempty"`
Message string `json:"message,omitempty"`
Errors []string `json:"errors,omitempty"`
}
dictErrors struct {
Msg string `json:"msg,omitempty"`
Message string `json:"message,omitempty"`
Errors map[string]string `json:"errors,omitempty"`
}
)
if merr := json.Unmarshal(body, &listErrors); merr == nil {
if listErrors.Msg != "" {
msg += "\n= " + listErrors.Msg
} else if listErrors.Message != "" {
msg += "\n= " + listErrors.Message
} else {
useGenericError = true
}
if !useGenericError && listErrors.Errors != nil {
for _, emsg := range listErrors.Errors {
msg += "\n * " + emsg
}
}
} else if merr = json.Unmarshal(body, &dictErrors); merr == nil {
if dictErrors.Msg != "" {
msg += "\n= " + dictErrors.Msg
} else if dictErrors.Message != "" {
msg += "\n= " + dictErrors.Message
} else {
useGenericError = true
}
if !useGenericError && dictErrors.Errors != nil {
for field, emsg := range dictErrors.Errors {
msg += fmt.Sprintf("\n * %s: %s", field, emsg)
}
}
}
if useGenericError {
logrus.Debugf("Failed to parse error data... return original error")
if len(body) < PRINT_LIMIT {
// return an error response body up to a meaningful limit - if it spans beyond a few
// lines, need to find a more appropriate message.
msg = fmt.Sprintf("%s\n= %s", msg, body)
} else {
msg += "\n= Error body too long, try to use the --verbose option"
}
}
err = &HttpError{msg, res}
}
return &body, err
}
func parseJobServResponse(resp *[]byte, err error, runName string) (string, string, error) {
if err != nil {
return "", "", err
}
type PatchResp struct {
JobServUrl string `json:"jobserv-url"`
WebUrl string `json:"web-url"`
}
pr := PatchResp{}
if err := json.Unmarshal(*resp, &pr); err != nil {
return "", "", err
}
return pr.JobServUrl + fmt.Sprintf("runs/%s/console.log", runName), pr.WebUrl, nil
}
func (a *Api) setReqHeaders(req *http.Request, jsonContent bool) {
req.Header.Set("User-Agent", "fioctl-"+a.clientVer)
if len(a.config.Token) > 0 {
logrus.Debug("Using API token for http request")
headerName := os.Getenv("TOKEN_HEADER")
if len(headerName) == 0 {
headerName = "OSF-TOKEN"
}
req.Header.Set(headerName, a.config.Token)
}
for k, v := range a.config.ExtraHeaders {
logrus.Debugf("Setting extra HTTP header %s=%s", k, v)
req.Header.Set(k, v)
}
if len(a.config.ClientCredentials.AccessToken) > 0 {
logrus.Debug("Using oauth token for http request")
tok := base64.StdEncoding.EncodeToString([]byte(a.config.ClientCredentials.AccessToken))
req.Header.Set("Authorization", "Bearer "+tok)
}
if jsonContent {
req.Header.Set("Content-Type", "application/json")
}
}
func (a *Api) GetOauthConfig() OAuthConfig {
return a.config.ClientCredentials
}
func (a *Api) RawGet(url string, headers *map[string]string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
a.setReqHeaders(req, false)
if headers != nil {
for key, val := range *headers {
req.Header.Set(key, val)
}
}
return a.client.Do(req)
}
func (a *Api) Get(url string) (*[]byte, error) {
res, err := a.RawGet(url, nil)
log := logrus.WithFields(logrus.Fields{"url": url, "method": "GET"})
if err != nil {
log.Debugf("Network Error: %s", err)
return nil, err
}
return readResponse(res, log)
}
func (a *Api) Patch(url string, data []byte) (*[]byte, error) {
req, err := http.NewRequest(http.MethodPatch, url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
a.setReqHeaders(req, true)
log := httpLogger(req)
res, err := a.client.Do(req)
if err != nil {
log.Debugf("Network Error: %s", err)
return nil, err
}
return readResponse(res, log)
}
func (a *Api) RawPost(url string, data []byte, headers *map[string]string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
a.setReqHeaders(req, true)
if headers != nil {
for k, v := range *headers {
req.Header.Set(k, v)
}
}
return a.client.Do(req)
}
func (a *Api) Post(url string, data []byte) (*[]byte, error) {
log := logrus.WithFields(logrus.Fields{"url": url, "method": "POST"})
res, err := a.RawPost(url, data, nil)
if err != nil {
log.Debugf("Network Error: %s", err)
return nil, err
}
return readResponse(res, log)
}
func (a *Api) Put(url string, data []byte) (*[]byte, error) {
req, err := http.NewRequest(http.MethodPut, url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
a.setReqHeaders(req, true)
log := httpLogger(req)
res, err := a.client.Do(req)
if err != nil {
log.Debugf("Network Error: %s", err)
return nil, err
}
return readResponse(res, log)
}
func (a *Api) Delete(url string, data []byte) (*[]byte, error) {
req, err := http.NewRequest(http.MethodDelete, url, bytes.NewBuffer(data))
if err != nil {
return nil, err
}
a.setReqHeaders(req, true)
log := httpLogger(req)
res, err := a.client.Do(req)
if err != nil {
log.Debugf("Network Error: %s", err)
return nil, err
}
return readResponse(res, log)
}
func (a *Api) DeviceGet(factory, device string) (*Device, error) {
url := a.serverUrl + "/ota/devices/" + device + "/?factory=" + factory
body, err := a.Get(url)
if err != nil {
return nil, err
}
d := Device{}
err = json.Unmarshal(*body, &d)
if err != nil {
return nil, err
}
return &d, nil
}
func (a *Api) DeviceList(
mine bool, matchTag, byFactory, byGroup, nameIlike, uuid, byTarget, sortBy string, page, limit int,
) (*DeviceList, error) {
mineInt := 0
if mine {
mineInt = 1
}
url := a.serverUrl + "/ota/devices/?"
url += fmt.Sprintf(
"mine=%d&match_tag=%s&name_ilike=%s&factory=%s&uuid=%s&group=%s&target_name=%s&sortby=%s&page=%d&limit=%d",
mineInt, matchTag, nameIlike, byFactory, uuid, byGroup, byTarget, sortBy, page, limit)
logrus.Debugf("DeviceList with url: %s", url)
return a.DeviceListCont(url)
}
func (a *Api) DeviceListCont(url string) (*DeviceList, error) {
logrus.Debugf("DeviceListCont with url: %s", url)
body, err := a.Get(url)
if err != nil {
return nil, err
}
devices := DeviceList{}
err = json.Unmarshal(*body, &devices)
if err != nil {
return nil, err
}
return &devices, nil
}
func (a *Api) DeviceListDenied(factory string, page, limit int) (*DeviceList, error) {
url := a.serverUrl + "/ota/factories/" + factory + "/denied-devices/"
url += fmt.Sprintf("?limit=%d&page=%d", limit, page)
return a.DeviceListCont(url)
}
func (a *Api) DeviceChown(factory, name, owner string) error {
body := map[string]string{"owner": owner}
data, err := json.Marshal(body)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + name + "/?factory=" + factory
_, err = a.Patch(url, data)
return err
}
func (a *Api) DeviceRename(factory, curName, newName string) error {
body := map[string]string{"name": newName}
data, err := json.Marshal(body)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + curName + "/?factory=" + factory
_, err = a.Patch(url, data)
return err
}
func (a *Api) DeviceSetGroup(factory, device, group string) error {
body := map[string]string{"group": group}
data, err := json.Marshal(body)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + device + "/?factory=" + factory
_, err = a.Patch(url, data)
return err
}
func (a *Api) DeviceDelete(factory, device string) error {
bytes := []byte{}
url := a.serverUrl + "/ota/devices/" + device + "/?factory=" + factory
_, err := a.Delete(url, bytes)
return err
}
func (a *Api) DeviceDeleteDenied(factory, uuid string) error {
bytes := []byte{}
url := a.serverUrl + "/ota/factories/" + factory + "/denied-devices/" + uuid + "/"
_, err := a.Delete(url, bytes)
return err
}
func (a *Api) DeviceListUpdates(factory, device string) (*UpdateList, error) {
url := a.serverUrl + "/ota/devices/" + device + "/updates/?factory=" + factory
return a.DeviceListUpdatesCont(url)
}
func (a *Api) DeviceListUpdatesCont(url string) (*UpdateList, error) {
body, err := a.Get(url)
if err != nil {
return nil, err
}
updates := UpdateList{}
err = json.Unmarshal(*body, &updates)
if err != nil {
return nil, err
}
return &updates, nil
}
func (a *Api) DeviceUpdateEvents(factory, device, correlationId string) ([]UpdateEvent, error) {
var events []UpdateEvent
url := a.serverUrl + "/ota/devices/" + device + "/updates/" + correlationId + "/?factory=" + factory
body, err := a.Get(url)
if err != nil {
return nil, err
}
err = json.Unmarshal(*body, &events)
if err != nil {
return events, err
}
return events, nil
}
func (a *Api) DeviceCreateConfig(factory, device string, cfg ConfigCreateRequest) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + device + "/config/?factory=" + factory
logrus.Debug("Creating new device config")
_, err = a.Post(url, data)
return err
}
func (a *Api) DevicePatchConfig(factory, device string, cfg ConfigCreateRequest, force bool) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + device + "/config/?factory=" + factory
if force {
url += "&force=1"
}
logrus.Debug("Patching device config")
_, err = a.Patch(url, data)
return err
}
func (a *Api) DeviceListConfig(factory, device string) (*DeviceConfigList, error) {
url := a.serverUrl + "/ota/devices/" + device + "/config/?factory=" + factory
logrus.Debugf("DeviceListConfig with url: %s", url)
return a.DeviceListConfigCont(url)
}
func (a *Api) DeviceListConfigCont(url string) (*DeviceConfigList, error) {
body, err := a.Get(url)
if err != nil {
return nil, err
}
config := DeviceConfigList{}
err = json.Unmarshal(*body, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func (a *Api) DeviceDeleteConfig(factory, device, filename string) error {
url := a.serverUrl + "/ota/devices/" + device + "/config/" + filename + "/?factory=" + factory
logrus.Debugf("Deleting config file: %s", url)
_, err := a.Delete(url, nil)
return err
}
func (a *Api) DeviceGetAppsStates(factory, device string) (*AppsStates, error) {
url := a.serverUrl + "/ota/devices/" + device + "/apps-states/?factory=" + factory
body, err := a.Get(url)
if err != nil {
return nil, err
}
states := AppsStates{}
err = json.Unmarshal(*body, &states)
if err != nil {
return nil, err
}
return &states, nil
}
func (a *Api) FactoryCreateConfig(factory string, cfg ConfigCreateRequest) error {
data, err := json.Marshal(cfg)