-
Notifications
You must be signed in to change notification settings - Fork 17
/
foundries.go
1550 lines (1341 loc) · 42.2 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/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
canonical "github.com/docker/go/canonical/json"
"github.com/sirupsen/logrus"
tuf "github.com/theupdateframework/notary/tuf/data"
)
type Config struct {
Factory string
Token string
ClientCredentials OAuthConfig
ExtraHeaders map[string]string
}
type Api struct {
serverUrl string
config Config
client http.Client
}
type CaCerts struct {
RootCrt string `json:"root-crt"`
CaCrt string `json:"ca-crt"`
CaCsr string `json:"ca-csr"`
TlsCrt string `json:"tls-crt"`
TlsCsr string `json:"tls-csr"`
CreateCaScript *string `json:"create_ca"`
CreateDeviceCaScript *string `json:"create_device_ca"`
SignCaScript *string `json:"sign_ca_csr"`
SignTlsScript *string `json:"sign_tls_csr"`
}
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
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 DeviceGroup struct {
Id int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
CreatedAt string `json:"created-at"`
}
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
CreatedAt string `json:"created-at"`
LastSeen string `json:"last-seen"`
OstreeHash string `json:"ostree-hash"`
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"`
}
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]
}
type FactoryUser struct {
PolisId string `json:"polis-id"`
Name string `json:"name"`
Role string `json:"role"`
}
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"`
}
// ota-tuf serializes root.json differently from Notary. The key representation
// and signing algoritms differ slightly. These Ats* structs provide an
// an implementation compatible with ota-tuf and libaktualizr.
type AtsKeyVal struct {
Public string `json:"public,omitempty"`
Private string `json:"private,omitempty"`
}
type AtsKey struct {
KeyType string `json:"keytype"`
KeyValue AtsKeyVal `json:"keyval"`
}
func (k AtsKey) KeyID() (string, error) {
bytes, err := canonical.MarshalCanonical(k)
if err != nil {
return "", nil
}
return fmt.Sprintf("%x", sha256.Sum256(bytes)), nil
}
type AtsRootMeta struct {
tuf.SignedCommon
Consistent bool `json:"consistent_snapshot"`
Keys map[string]AtsKey `json:"keys"`
Roles map[tuf.RoleName]*tuf.RootRole `json:"roles"`
}
type AtsTufRoot struct {
// A non-standard targets-signatures field allows to make an atomic key rotation
TargetsSignatures map[string][]tuf.Signature `json:"targets-signatures,omitempty"`
Signatures []tuf.Signature `json:"signatures"`
Signed AtsRootMeta `json:"signed"`
}
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"`
}
type Wave struct {
Name string `json:"name"`
Version string `json:"version"`
Tag string `json:"tag"`
Targets *json.RawMessage `json:"targets"`
CreatedAt string `json:"created-at"`
FinishedAt string `json:"finished-at"`
Status string `json:"status"`
RolloutGroups map[string]WaveRolloutGroupRef `json:"rollout-groups"`
}
type WaveCreate struct {
Name string `json:"name"`
Version string `json:"version"`
Tag string `json:"tag"`
Targets tuf.Signed `json:"targets"`
}
type WaveRolloutOptions struct {
Group string `json:"group"`
}
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"`
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("2006-01-02T15:04:05+00:00", 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) *Api {
if len(caCertPath) > 0 {
rootCAs, _ := x509.SystemCertPool()
if rootCAs == nil {
rootCAs = x509.NewCertPool()
}
certs, err := ioutil.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")
}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{
RootCAs: rootCAs,
}
}
api := Api{
serverUrl: strings.TrimRight(serverUrl, "/"),
config: config,
client: *http.DefaultClient,
}
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 := ioutil.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)
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)
}
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-2")
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) Post(url string, data []byte) (*[]byte, error) {
req, err := http.NewRequest(http.MethodPost, 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) 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(device string) (*Device, error) {
body, err := a.Get(a.serverUrl + "/ota/devices/" + device + "/")
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(shared bool, matchTag, byFactory, byGroup, nameIlike, uuid string, page, limit int) (*DeviceList, error) {
sharedInt := 0
if shared {
sharedInt = 1
}
url := a.serverUrl + "/ota/devices/?"
url += fmt.Sprintf(
"shared=%d&match_tag=%s&name_ilike=%s&factory=%s&uuid=%s&group=%s&page=%d&limit=%d",
sharedInt, matchTag, nameIlike, byFactory, uuid, byGroup, page, limit)
logrus.Debugf("DeviceList with url: %s", url)
return a.DeviceListCont(url)
}
func (a *Api) DeviceListCont(url string) (*DeviceList, error) {
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) DeviceChown(name, owner string) error {
body := map[string]string{"owner": owner}
data, err := json.Marshal(body)
if err != nil {
return err
}
_, err = a.Patch(a.serverUrl+"/ota/devices/"+name+"/", data)
return err
}
func (a *Api) DeviceRename(curName, newName string) error {
body := map[string]string{"name": newName}
data, err := json.Marshal(body)
if err != nil {
return err
}
_, err = a.Patch(a.serverUrl+"/ota/devices/"+curName+"/", data)
return err
}
func (a *Api) DeviceSetGroup(device string, group string) error {
body := map[string]string{"group": group}
data, err := json.Marshal(body)
if err != nil {
return err
}
_, err = a.Patch(a.serverUrl+"/ota/devices/"+device+"/", data)
return err
}
func (a *Api) DeviceDelete(device string) error {
bytes := []byte{}
_, err := a.Delete(a.serverUrl+"/ota/devices/"+device+"/", bytes)
return err
}
func (a *Api) DeviceListUpdates(device string) (*UpdateList, error) {
return a.DeviceListUpdatesCont(a.serverUrl + "/ota/devices/" + device + "/updates/")
}
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(device, correlationId string) ([]UpdateEvent, error) {
var events []UpdateEvent
body, err := a.Get(a.serverUrl + "/ota/devices/" + device + "/updates/" + correlationId + "/")
if err != nil {
return nil, err
}
err = json.Unmarshal(*body, &events)
if err != nil {
return events, err
}
return events, nil
}
func (a *Api) DeviceCreateConfig(device string, cfg ConfigCreateRequest) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + device + "/config/"
logrus.Debug("Creating new device config")
_, err = a.Post(url, data)
return err
}
func (a *Api) DevicePatchConfig(device string, cfg ConfigCreateRequest, force bool) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/devices/" + device + "/config/"
if force {
url += "?force=1"
}
logrus.Debug("Patching device config")
_, err = a.Patch(url, data)
return err
}
func (a *Api) DeviceListConfig(device string) (*DeviceConfigList, error) {
url := a.serverUrl + "/ota/devices/" + device + "/config/"
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(device, filename string) error {
url := a.serverUrl + "/ota/devices/" + device + "/config/" + filename + "/"
logrus.Debugf("Deleting config file: %s", url)
_, err := a.Delete(url, nil)
return err
}
func (a *Api) FactoryCreateConfig(factory string, cfg ConfigCreateRequest) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/factories/" + factory + "/config/"
logrus.Debug("Creating new factory config")
_, err = a.Post(url, data)
return err
}
func (a *Api) FactoryDeleteConfig(factory, filename string) error {
url := a.serverUrl + "/ota/factories/" + factory + "/config/" + filename + "/"
logrus.Debugf("Deleting config file: %s", url)
_, err := a.Delete(url, nil)
return err
}
func (a *Api) FactoryPatchConfig(factory string, cfg ConfigCreateRequest, force bool) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/factories/" + factory + "/config/"
if force {
url += "?force=1"
}
logrus.Debug("Creating new factory config")
_, err = a.Patch(url, data)
return err
}
func (a *Api) FactoryListConfig(factory string) (*DeviceConfigList, error) {
url := a.serverUrl + "/ota/factories/" + factory + "/config/"
logrus.Debugf("FactoryListConfig with url: %s", url)
return a.FactoryListConfigCont(url)
}
func (a *Api) FactoryListConfigCont(url string) (*DeviceConfigList, error) {
// A short cut as it behaves just the same
return a.DeviceListConfigCont(url)
}
func (a *Api) GroupCreateConfig(factory, group string, cfg ConfigCreateRequest) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/" + group + "/config/"
logrus.Debug("Creating new device group config")
_, err = a.Post(url, data)
return err
}
func (a *Api) GroupDeleteConfig(factory, group, filename string) error {
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/" + group + "/config/" + filename + "/"
logrus.Debugf("Deleting config file: %s", url)
_, err := a.Delete(url, nil)
return err
}
func (a *Api) GroupPatchConfig(factory, group string, cfg ConfigCreateRequest, force bool) error {
data, err := json.Marshal(cfg)
if err != nil {
return err
}
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/" + group + "/config/"
if force {
url += "?force=1"
}
logrus.Debug("Creating new device group config")
_, err = a.Patch(url, data)
return err
}
func (a *Api) GroupListConfig(factory, group string) (*DeviceConfigList, error) {
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/" + group + "/config/"
logrus.Debugf("GroupListConfig with url: %s", url)
return a.GroupListConfigCont(url)
}
func (a *Api) GroupListConfigCont(url string) (*DeviceConfigList, error) {
// A short cut as it behaves just the same
return a.DeviceListConfigCont(url)
}
func (a *Api) FactoryStatus(factory string, inactiveThreshold int) (*FactoryStatus, error) {
url := fmt.Sprintf("%s/ota/factories/%s/status/?offline-threshold=%d", a.serverUrl, factory, inactiveThreshold)
logrus.Debugf("FactoryStatus with url: %s", url)
body, err := a.Get(url)
if err != nil {
return nil, err
}
s := FactoryStatus{}
err = json.Unmarshal(*body, &s)
if err != nil {
return nil, err
}
return &s, nil
}
func (a *Api) FactoryCreateDeviceGroup(factory string, name string, description *string) (*DeviceGroup, error) {
body := map[string]string{"name": name}
if description != nil {
body["description"] = *description
}
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/"
logrus.Debugf("Creating new factory device group: %s", url)
resp, err := a.Post(url, data)
if err != nil {
if herr := AsHttpError(err); herr != nil && herr.Response.StatusCode == 409 {
err = fmt.Errorf("A device group with this name already exists")
}
return nil, err
}
grp := DeviceGroup{}
err = json.Unmarshal(*resp, &grp)
if err != nil {
return nil, err
}
return &grp, nil
}
func (a *Api) FactoryDeleteDeviceGroup(factory string, name string) error {
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/" + name + "/"
logrus.Debugf("Deleting factory device group: %s", url)
_, err := a.Delete(url, nil)
if herr := AsHttpError(err); herr != nil && herr.Response.StatusCode == 409 {
err = fmt.Errorf("There are devices assigned to this device group")
}
return err
}
func (a *Api) FactoryPatchDeviceGroup(factory string, name string, new_name *string, new_desc *string) error {
body := map[string]string{}
if new_name != nil {
body["name"] = *new_name
}
if new_desc != nil {
body["description"] = *new_desc
}
data, err := json.Marshal(body)
if err != nil {
return err
}
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/" + name + "/"
logrus.Debugf("Updating factory device group :%s", url)
_, err = a.Patch(url, data)
if herr := AsHttpError(err); herr != nil && herr.Response.StatusCode == 409 {
err = fmt.Errorf("A device group with this name already exists")
}
return err
}
func (a *Api) FactoryListDeviceGroup(factory string) (*[]DeviceGroup, error) {
url := a.serverUrl + "/ota/factories/" + factory + "/device-groups/"
logrus.Debugf("Fetching factory device groups: %s", url)
body, err := a.Get(url)
if err != nil {
return nil, err
}
type DeviceGroupList struct {
Groups []DeviceGroup `json:"groups"`
}
resp := DeviceGroupList{}
err = json.Unmarshal(*body, &resp)
if err != nil {
return nil, err
}
return &resp.Groups, nil
}
func (a *Api) GetFoundriesTargetsKey(factory string) (*AtsKey, error) {
url := a.serverUrl + "/ota/factories/" + factory + "/ci-targets.pub"
body, err := a.Get(url)
if err != nil {
return nil, err
}
key := AtsKey{}
err = json.Unmarshal(*body, &key)
return &key, err
}
func (a *Api) GetWireGuardIps(factory string) ([]WireGuardIp, error) {
url := a.serverUrl + "/ota/factories/" + factory + "/wireguard-ips/"
body, err := a.Get(url)
if err != nil {
return nil, err
}