-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathmain.go
1221 lines (1136 loc) · 37.5 KB
/
main.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 main
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"time"
"github.com/amenzhinsky/iothub/cmd/internal"
"github.com/amenzhinsky/iothub/eventhub"
"github.com/amenzhinsky/iothub/iotservice"
"github.com/amenzhinsky/iothub/logger"
)
// globally accessible by command handlers, is it a good idea?
var (
// common
formatFlag string
logLevelFlag = logger.LevelWarn
// send
uidFlag string
midFlag string
cidFlag string
expFlag time.Duration
ackFlag iotservice.AckType
connectTimeoutFlag uint
responseTimeoutFlag uint
// create/update device
sasPrimaryFlag string
sasSecondaryFlag string
x509PrimaryFlag string
x509SecondaryFlag string
caFlag bool
statusFlag iotservice.DeviceStatus
statusReasonFlag string
capabilitiesFlag map[string]interface{}
forceFlag bool
edgeFlag bool
// send
propsFlag map[string]string
// sas and connection string
secondaryFlag bool
// sas
uriFlag string
durationFlag time.Duration
// watch events
ehcsFlag string
ehcgFlag string
// twins
tagsFlag map[string]interface{}
twinPropsFlag map[string]interface{}
// modules
managedByFlag string
// configuration
schemaVersionFlag string
priorityFlag uint
labelsFlag map[string]string
targetConditionFlag string
modulesContentFlag map[string]interface{}
devicesContentFlag map[string]interface{}
metricsFlag map[string]string
// export
excludeKeysFlag bool
// schedule jobs
jobIDFlag string
queryFlag string
startTimeFlag time.Time
maxExecTimeFlag uint
timeoutFlag uint
jobTypeFlag iotservice.JobV2Type
jobStatusFlag iotservice.JobV2Status
// deployments
envFlag map[string]interface{}
// https://docs.docker.com/engine/api/v1.30/#operation/ContainerCreate
createOptionsFlag map[string]interface{}
)
func main() {
if err := run(); err != nil {
if err != internal.ErrInvalidUsage {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
}
os.Exit(1)
}
}
const help = `Helps with interacting and managing your iothub devices.
The $IOTHUB_SERVICE_CONNECTION_STRING environment variable is required for authentication.`
func run() error {
ctx := context.Background()
return internal.New(help, func(f *flag.FlagSet) {
f.StringVar(&formatFlag, "format", "json-pretty", "data output format <json|json-pretty>")
f.Var((*internal.LogLevelFlag)(&logLevelFlag), "log-level", "log `level` <error|warn|info|debug>")
}, []*internal.Command{
{
Name: "send",
Args: []string{"DEVICE", "PAYLOAD"},
Desc: "send cloud-to-device message",
Handler: wrap(ctx, send),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar((*string)(&ackFlag), "ack", "", "type of ack feedback <none|positive|negative|full>")
f.StringVar(&uidFlag, "uid", "golang-iothub", "origin of the message")
f.StringVar(&midFlag, "mid", "", "identifier for the message")
f.StringVar(&cidFlag, "cid", "", "message identifier in a request-reply")
f.DurationVar(&expFlag, "exp", 0, "message lifetime")
f.Var((*internal.StringsMapFlag)(&propsFlag), "prop", "custom property, key=value")
},
},
{
Name: "watch-events",
Desc: "subscribe to cloud-to-device messages",
Handler: wrap(ctx, watchEvents),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&ehcsFlag, "ehcs", "", "custom eventhub connection string")
f.StringVar(&ehcgFlag, "ehcg", "$Default", "eventhub consumer group")
},
},
{
Name: "watch-feedback",
Desc: "subscribe to message delivery feedback",
Handler: wrap(ctx, watchFeedback),
},
{
Name: "watch-file-notifications",
Desc: "subscribe to file upload notifications",
Handler: wrap(ctx, watchFileNotifications),
},
{
Name: "call",
Args: []string{"DEVICE", "METHOD", "PAYLOAD"},
Desc: "call a direct method on the named device",
Handler: wrap(ctx, callDevice),
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&connectTimeoutFlag, "connect-timeout", 0, "connect timeout in seconds")
f.UintVar(&responseTimeoutFlag, "response-timeout", 30, "response timeout in seconds")
},
},
{
Name: "device",
Args: []string{"DEVICE"},
Desc: "get device information",
Handler: wrap(ctx, getDevice),
},
{
Name: "devices",
Desc: "list all available devices",
Handler: wrap(ctx, listDevices),
},
{
Name: "create-device",
Args: []string{"DEVICE"},
Desc: "request an existing device identity",
Handler: wrap(ctx, createDevice),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&sasPrimaryFlag, "primary-key", "", "primary key (base64)")
f.StringVar(&sasSecondaryFlag, "secondary-key", "", "secondary key (base64)")
f.StringVar(&x509PrimaryFlag, "primary-thumbprint", "", "x509 primary thumbprint")
f.StringVar(&x509SecondaryFlag, "secondary-thumbprint", "", "x509 secondary thumbprint")
f.BoolVar(&caFlag, "ca", false, "use certificate authority authentication")
f.StringVar((*string)(&statusFlag), "status", "", "device status")
f.StringVar(&statusReasonFlag, "status-reason", "", "disabled device status reason")
f.Var((*internal.JSONMapFlag)(&capabilitiesFlag), "capability", "device capability, key=value")
f.BoolVar(&edgeFlag, "edge", false, "create an IoT Edge device (same as -capability=iotEdge=true)")
},
},
{
Name: "update-device",
Args: []string{"DEVICE"},
Desc: "update the named device",
Handler: wrap(ctx, updateDevice),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&sasPrimaryFlag, "sas-primary", "", "SAS primary key (base64)")
f.StringVar(&sasSecondaryFlag, "sas-secondary-key", "", "SAS secondary key (base64)")
f.StringVar(&x509PrimaryFlag, "x509-primary", "", "x509 primary thumbprint")
f.StringVar(&x509SecondaryFlag, "x509-secondary", "", "x509 secondary thumbprint")
f.BoolVar(&caFlag, "ca", false, "use certificate authority authentication")
f.StringVar((*string)(&statusFlag), "status", "", "device status")
f.StringVar(&statusReasonFlag, "status-reason", "", "disabled device status reason")
f.Var((*internal.JSONMapFlag)(&capabilitiesFlag), "capability", "device capability, key=value")
f.BoolVar(&forceFlag, "force", false, "force update")
},
},
{
Name: "delete-device",
Args: []string{"DEVICE"},
Desc: "delete the named device from the registry",
Handler: wrap(ctx, deleteDevice),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&forceFlag, "force", false, "force update")
},
},
{
Name: "call-module",
Args: []string{"DEVICE", "MODULE", "METHOD", "PAYLOAD"},
Desc: "call a direct method on the named module",
Handler: wrap(ctx, callModule),
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&connectTimeoutFlag, "connect-timeout", 0, "connect timeout in seconds")
f.UintVar(&responseTimeoutFlag, "response-timeout", 30, "response timeout in seconds")
},
},
{
Name: "modules",
Args: []string{"DEVICE"},
Desc: "list the named device's modules",
Handler: wrap(ctx, listModules),
},
{
Name: "create-module",
Args: []string{"DEVICE", "MODULE"},
Desc: "add the given module to the registry",
Handler: wrap(ctx, createModule),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&sasPrimaryFlag, "sas-primary", "", "SAS primary key (base64)")
f.StringVar(&sasSecondaryFlag, "sas-secondary-key", "", "SAS secondary key (base64)")
f.StringVar(&x509PrimaryFlag, "x509-primary", "", "x509 primary thumbprint")
f.StringVar(&x509SecondaryFlag, "x509-secondary", "", "x509 secondary thumbprint")
f.BoolVar(&caFlag, "ca", false, "use certificate authority authentication")
f.StringVar(&managedByFlag, "managed-by", "", "module's owner")
},
},
{
Name: "module",
Args: []string{"DEVICE", "MODULE"},
Desc: "get info of the named module",
Handler: wrap(ctx, getModule),
},
{
Name: "update-module",
Args: []string{"DEVICE", "MODULE"},
Desc: "update the named module",
Handler: wrap(ctx, updateModule),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&sasPrimaryFlag, "sas-primary", "", "SAS primary key (base64)")
f.StringVar(&sasSecondaryFlag, "sas-secondary-key", "", "SAS secondary key (base64)")
f.StringVar(&x509PrimaryFlag, "x509-primary", "", "x509 primary thumbprint")
f.StringVar(&x509SecondaryFlag, "x509-secondary", "", "x509 secondary thumbprint")
f.BoolVar(&caFlag, "ca", false, "use certificate authority authentication")
f.BoolVar(&forceFlag, "force", false, "force update")
f.StringVar(&managedByFlag, "managed-by", "", "module's owner")
},
},
{
Name: "delete-module",
Args: []string{"DEVICE", "MODULE"},
Desc: "remove the named module from the registry",
Handler: wrap(ctx, deleteModule),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&forceFlag, "force", false, "force update")
},
},
{
Name: "twin",
Args: []string{"DEVICE"},
Desc: "inspect the named twin device",
Handler: wrap(ctx, getDeviceTwin),
},
{
Name: "module-twin",
Args: []string{"DEVICE", "MODULE"},
Desc: "get the named module twin",
Handler: wrap(ctx, getModuleTwin),
},
{
Name: "update-twin",
Args: []string{"DEVICE"},
Desc: "update the named twin device",
Handler: wrap(ctx, updateDeviceTwin),
ParseFunc: func(f *flag.FlagSet) {
f.Var((*internal.JSONMapFlag)(&twinPropsFlag), "prop", "property to update, key=value")
f.Var((*internal.JSONMapFlag)(&tagsFlag), "tag", "custom tag, key=value")
},
},
{
Name: "update-module-twin",
Args: []string{"DEVICE", "MODULE"},
Desc: "update the named module twin",
Handler: wrap(ctx, updateModuleTwin),
ParseFunc: func(f *flag.FlagSet) {
f.Var((*internal.JSONMapFlag)(&twinPropsFlag), "prop", "property to update, key=value")
f.BoolVar(&forceFlag, "force", false, "force update")
},
},
{
Name: "digital-twin",
Args: []string{"DEVICE"},
Desc: "inspect the named digital twin",
Handler: wrap(ctx, getDigitalTwin),
},
{
Name: "update-digital-twin",
Args: []string{"DEVICE", "PATCH"},
Desc: "update the named digital twin",
Handler: wrap(ctx, updateDigitalTwin),
},
{
Name: "call-digital-twin",
Args: []string{"DEVICE", "COMMAND", "PAYLOAD"},
Desc: "invoke the named digital twin command",
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&connectTimeoutFlag, "connect-timeout", 0, "connect timeout in seconds")
f.UintVar(&responseTimeoutFlag, "response-timeout", 30, "response timeout in seconds")
},
Handler: wrap(ctx, callDigitalTwin),
},
{
Name: "call-digital-twin-component",
Args: []string{"DEVICE", "COMPONENT", "COMMAND", "PAYLOAD"},
Desc: "invoke the named digital twin component command",
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&connectTimeoutFlag, "connect-timeout", 0, "connect timeout in seconds")
f.UintVar(&responseTimeoutFlag, "response-timeout", 30, "response timeout in seconds")
},
Handler: wrap(ctx, callDigitalTwinComponent),
},
{
Name: "configurations",
Desc: "list all configurations",
Handler: wrap(ctx, listConfigurations),
},
{
Name: "create-configuration",
Args: []string{"CONFIGURATION"},
Desc: "add a configuration to the registry",
Handler: wrap(ctx, createConfiguration),
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&priorityFlag, "priority", 10, "priority to resolve configuration conflicts")
f.StringVar(&schemaVersionFlag, "schema-version", "1.0", "configuration schema version")
f.Var((*internal.StringsMapFlag)(&labelsFlag), "label", "specific label, key=value")
f.StringVar(&targetConditionFlag, "target-condition", "*", "target condition")
f.Var((*internal.StringsMapFlag)(&metricsFlag), "metric", "metric name and query, key=value")
f.Var((*internal.JSONMapFlag)(&devicesContentFlag), "device-prop", "device property, key=value")
},
},
{
Name: "configuration",
Args: []string{"CONFIGURATION"},
Desc: "retrieve the named configuration",
Handler: wrap(ctx, getConfiguration),
},
{
Name: "update-configuration",
Args: []string{"CONFIGURATION"},
Desc: "update the named configuration",
Handler: wrap(ctx, updateConfiguration),
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&priorityFlag, "priority", 0, "priority to resolve configuration conflicts")
f.StringVar(&schemaVersionFlag, "schema-version", "", "configuration schema version")
f.Var((*internal.StringsMapFlag)(&labelsFlag), "label", "specific labels in key=value format")
f.StringVar(&targetConditionFlag, "target-condition", "*", "target condition")
f.Var((*internal.StringsMapFlag)(&metricsFlag), "metric", "metric name and query, key=value")
f.Var((*internal.JSONMapFlag)(&devicesContentFlag), "device-prop", "device property, key=value")
f.BoolVar(&forceFlag, "force", false, "force update")
},
},
{
Name: "delete-configuration",
Args: []string{"CONFIGURATION"},
Desc: "delete the named configuration by id",
Handler: wrap(ctx, deleteConfiguration),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&forceFlag, "force", false, "force update")
},
},
{
Name: "apply-configuration",
Args: []string{"DEVICE"},
Desc: "applies configuration on the named device",
Handler: wrap(ctx, applyConfiguration),
ParseFunc: func(f *flag.FlagSet) {
f.Var((*internal.JSONMapFlag)(&devicesContentFlag), "device-prop", "device property, key=value")
f.Var((*internal.JSONMapFlag)(&modulesContentFlag), "module-prop", "module property, key=value")
},
},
{
Name: "deployments",
Args: []string{},
Desc: "list all IoT Edge deployments (configurations)",
Handler: wrap(ctx, listDeployments),
},
{
Name: "create-deployment",
Args: []string{"DEPLOYMENT", "MODULE", "IMAGE"},
Desc: "create an IoT Edge deployment",
Handler: wrap(ctx, createDeployment),
ParseFunc: func(f *flag.FlagSet) {
f.UintVar(&priorityFlag, "priority", 10, "priority to resolve configuration conflicts")
f.StringVar(&schemaVersionFlag, "schema-version", "1.0", "configuration schema version")
f.Var((*internal.StringsMapFlag)(&labelsFlag), "label", "specific label, key=value")
f.StringVar(&targetConditionFlag, "target-condition", "*", "target condition")
f.Var((*internal.StringsMapFlag)(&metricsFlag), "metric", "metric name and query, key=value")
f.Var((*internal.JSONMapFlag)(&modulesContentFlag), "module-prop", "module property, key=value")
f.Var((*internal.JSONMapFlag)(&envFlag), "env", "container environment, key=value")
f.Var((*internal.JSONMapFlag)(&createOptionsFlag), "create-options", "container create options, key=value")
},
},
{
Name: "query",
Args: []string{"SQL"},
Desc: "execute sql query on devices",
Handler: wrap(ctx, query),
},
{
Name: "device-statistics",
Desc: "get device statistics of the identity registry",
Handler: wrap(ctx, deviceStats),
},
{
Name: "service-statistics",
Desc: "get service statistics of the identity registry",
Handler: wrap(ctx, serviceStats),
},
{
Name: "import",
Desc: "import devices from a blob",
Args: []string{"INPUT", "OUTPUT"},
Handler: wrap(ctx, importFromBlob),
},
{
Name: "export",
Desc: "export devices to a blob",
Args: []string{"OUTPUT"},
Handler: wrap(ctx, exportToBlob),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&excludeKeysFlag, "exclude-keys", false, "exclude keys in the export blob file")
},
},
{
Name: "jobs",
Desc: "list the last import/export jobs",
Handler: wrap(ctx, listJobs),
},
{
Name: "job",
Args: []string{"JOB"},
Desc: "get the status of a import/export job",
Handler: wrap(ctx, getJob),
},
{
Name: "cancel-job",
Desc: "cancel a import/export job",
Handler: wrap(ctx, cancelJob),
},
{
Name: "schedule-jobs",
Desc: "list all scheduled jobs",
Handler: wrap(ctx, listScheduleJobs),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar((*string)(&jobTypeFlag), "type", "",
"job type <scheduleUpdateTwin|scheduleDeviceMethod>")
f.StringVar((*string)(&jobStatusFlag), "status", "",
"job status <queued|scheduled|running|cancelled|completed>")
},
},
{
Name: "get-schedule-job",
Args: []string{"JOB"},
Desc: "retrieve the named job information from the registry",
Handler: wrap(ctx, getScheduleJob),
},
{
Name: "cancel-schedule-job",
Args: []string{"JOB"},
Desc: "cancel the named job",
Handler: wrap(ctx, cancelScheduleJob),
},
{
Name: "schedule-method-call",
Args: []string{"METHOD", "PAYLOAD"},
Handler: wrap(ctx, scheduleMethodCall),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&jobIDFlag, "job-id", "", "unique job id")
f.StringVar(&queryFlag, "query", "*", "query condition")
f.Var((*internal.TimeFlag)(&startTimeFlag), "start-time", "start time in RFC3339")
f.UintVar(&timeoutFlag, "connect-timeout", 0, "connection timeout in seconds")
f.UintVar(&maxExecTimeFlag, "exec-timeout", 30, "maximal execution time in seconds")
},
},
{
Name: "schedule-twin-update",
Args: []string{}, // TODO
Handler: wrap(ctx, scheduleTwinUpdate),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&jobIDFlag, "job-id", "", "unique job id")
f.StringVar(&queryFlag, "query", "*", "query condition")
f.Var((*internal.TimeFlag)(&startTimeFlag), "start-time", "start time in RFC3339")
f.UintVar(&maxExecTimeFlag, "exec-timeout", 30, "maximal execution time in seconds")
},
},
{
Name: "device-connection-string",
Args: []string{"DEVICE"},
Desc: "get a device's connection string",
Handler: wrap(ctx, deviceConnectionString),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&secondaryFlag, "secondary", false, "use the secondary key instead")
},
},
{
Name: "module-connection-string",
Args: []string{"DEVICE", "MODULE"},
Desc: "get a module's connection string",
Handler: wrap(ctx, moduleConnectionString),
ParseFunc: func(f *flag.FlagSet) {
f.BoolVar(&secondaryFlag, "secondary", false, "use the secondary key instead")
},
},
{
Name: "access-signature",
Args: []string{"DEVICE"},
Desc: "generate a SAS token",
Handler: wrap(ctx, sas),
ParseFunc: func(f *flag.FlagSet) {
f.StringVar(&uriFlag, "uri", "", "storage resource uri")
f.DurationVar(&durationFlag, "duration", time.Hour, "token validity time")
f.BoolVar(&secondaryFlag, "secondary", false, "use the secondary key instead")
},
},
}).Run(os.Args)
}
func wrap(
ctx context.Context,
fn func(context.Context, *iotservice.Client, []string) error,
) internal.HandlerFunc {
return func(args []string) error {
c, err := iotservice.NewFromConnectionString(
os.Getenv("IOTHUB_SERVICE_CONNECTION_STRING"),
iotservice.WithLogger(
logger.New(logLevelFlag, nil),
),
)
if err != nil {
return err
}
defer c.Close()
// handle first SIGINT and try to exit gracefully
ctx, cancel := context.WithCancel(ctx)
defer cancel()
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt)
go func() {
<-sigc
signal.Reset(os.Interrupt)
close(sigc)
cancel()
}()
if err := fn(ctx, c, args); err != nil {
select {
case <-sigc:
if err == context.Canceled {
return nil
}
default:
}
return err
}
return nil
}
}
func getDevice(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.GetDevice(ctx, args[0]))
}
func listDevices(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.ListDevices(ctx))
}
func createDevice(ctx context.Context, c *iotservice.Client, args []string) error {
if edgeFlag {
if capabilitiesFlag == nil {
capabilitiesFlag = map[string]interface{}{}
}
capabilitiesFlag["iotEdge"] = true
}
device := &iotservice.Device{
DeviceID: args[0],
Authentication: &iotservice.Authentication{},
Status: statusFlag,
StatusReason: statusReasonFlag,
Capabilities: capabilitiesFlag,
}
if err := updateAuth(device.Authentication); err != nil {
return err
}
return output(c.CreateDevice(ctx, device))
}
func updateDevice(ctx context.Context, c *iotservice.Client, args []string) error {
device, err := c.GetDevice(ctx, args[0])
if err != nil {
return err
}
if forceFlag {
device.ETag = ""
}
if statusFlag != "" {
device.Status = statusFlag
}
if statusReasonFlag != "" {
device.StatusReason = statusReasonFlag
}
mergeMapJSON(capabilitiesFlag, device.Capabilities)
if err := updateAuth(device.Authentication); err != nil {
return err
}
return output(c.UpdateDevice(ctx, device))
}
func updateAuth(auth *iotservice.Authentication) error {
switch {
case sasPrimaryFlag != "" || sasSecondaryFlag != "":
if x509PrimaryFlag != "" || x509SecondaryFlag != "" {
return errors.New("-x509-* options cannot be used along with sas authentication")
} else if caFlag {
return errors.New("-ca option cannot be used along with sas authentication")
}
auth.Type = iotservice.AuthSAS
auth.X509Thumbprint = nil
auth.SymmetricKey = &iotservice.SymmetricKey{
PrimaryKey: sasPrimaryFlag,
SecondaryKey: sasSecondaryFlag,
}
case x509PrimaryFlag != "" || x509SecondaryFlag != "":
if caFlag {
return errors.New("-ca option cannot be used along with x509 authentication")
}
auth.Type = iotservice.AuthSelfSigned
auth.SymmetricKey = nil
auth.X509Thumbprint = &iotservice.X509Thumbprint{
PrimaryThumbprint: x509PrimaryFlag,
SecondaryThumbprint: x509SecondaryFlag,
}
case caFlag:
auth.Type = iotservice.AuthCA
auth.SymmetricKey = nil
auth.X509Thumbprint = nil
}
return nil
}
func deleteDevice(ctx context.Context, c *iotservice.Client, args []string) error {
device, err := c.GetDevice(ctx, args[0])
if err != nil {
return err
}
if forceFlag {
device.ETag = ""
}
return c.DeleteDevice(ctx, device)
}
func listModules(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.ListModules(ctx, args[0]))
}
func getModule(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.GetModule(ctx, args[0], args[1]))
}
func createModule(ctx context.Context, c *iotservice.Client, args []string) error {
module := &iotservice.Module{
DeviceID: args[0],
ModuleID: args[1],
Authentication: &iotservice.Authentication{},
ManagedBy: managedByFlag,
}
if err := updateAuth(module.Authentication); err != nil {
return err
}
return output(c.CreateModule(ctx, module))
}
func updateModule(ctx context.Context, c *iotservice.Client, args []string) error {
module, err := c.GetModule(ctx, args[0], args[1])
if err != nil {
return err
}
if forceFlag {
module.ETag = ""
}
if managedByFlag != "" {
module.ManagedBy = managedByFlag
}
if err := updateAuth(module.Authentication); err != nil {
return err
}
return output(c.UpdateModule(ctx, module))
}
func deleteModule(ctx context.Context, c *iotservice.Client, args []string) error {
module, err := c.GetModule(ctx, args[0], args[1])
if err != nil {
return err
}
if forceFlag {
module.ETag = ""
}
return c.DeleteModule(ctx, module)
}
func listConfigurations(ctx context.Context, c *iotservice.Client, args []string) error {
return listConfigurationsFiltered(ctx, c, func(cfg *iotservice.Configuration) bool {
return cfg.Content.DeviceContent != nil
})
}
func listDeployments(ctx context.Context, c *iotservice.Client, args []string) error {
return listConfigurationsFiltered(ctx, c, func(cfg *iotservice.Configuration) bool {
return cfg.Content.ModulesContent != nil
})
}
func listConfigurationsFiltered(
ctx context.Context,
c *iotservice.Client,
matches func(configuration *iotservice.Configuration) bool,
) error {
configurations, err := c.ListConfigurations(ctx)
if err != nil {
return err
}
filtered := make([]*iotservice.Configuration, 0, len(configurations))
for _, configuration := range configurations {
if matches(configuration) {
filtered = append(filtered, configuration)
}
}
return output(filtered, nil)
}
func getConfiguration(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.GetConfiguration(ctx, args[0]))
}
func createConfiguration(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.CreateConfiguration(ctx, &iotservice.Configuration{
ID: args[0],
SchemaVersion: schemaVersionFlag,
Priority: priorityFlag,
Labels: labelsFlag,
TargetCondition: targetConditionFlag,
Content: &iotservice.ConfigurationContent{
DeviceContent: devicesContentFlag,
},
Metrics: &iotservice.ConfigurationMetrics{
Queries: metricsFlag,
},
}))
}
// https://github.com/Azure/azure-iot-cli-extension/blob/v0.8.7/azext_iot/assets/edge-deploy-2.0.schema.json
func createDeployment(ctx context.Context, c *iotservice.Client, args []string) error {
env := make(map[string]interface{}, len(envFlag))
for k, v := range envFlag {
env[k] = map[string]interface{}{
"value": v,
}
}
createOptions, err := json.Marshal(createOptionsFlag)
if err != nil {
return err
}
return output(c.CreateConfiguration(ctx, &iotservice.Configuration{
ID: args[0],
SchemaVersion: schemaVersionFlag,
Priority: priorityFlag,
Labels: labelsFlag,
TargetCondition: targetConditionFlag,
Content: &iotservice.ConfigurationContent{
ModulesContent: map[string]interface{}{
"$edgeAgent": map[string]interface{}{
"properties.desired": map[string]interface{}{
"modules": map[string]interface{}{
args[1]: map[string]interface{}{
"type": "docker",
"settings": map[string]interface{}{
"image": args[2],
"createOptions": string(createOptions),
},
"env": env,
"status": "running",
"restartPolicy": "always",
"version": "1.0",
},
},
"runtime": map[string]interface{}{
"type": "docker",
"settings": map[string]interface{}{
"minDockerVersion": "v1.25",
"registryCredentials": map[string]interface{}{
// TODO: "REGISTRYNAME": map[string]interface{}{
// TODO: "address": "docker.com",
// TODO: "password": "pwd",
// TODO: "username": "test",
// TODO: },
},
},
},
"schemaVersion": "1.0",
"systemModules": map[string]interface{}{
"edgeAgent": map[string]interface{}{
"settings": map[string]interface{}{
"image": "mcr.microsoft.com/azureiotedge-agent:1.0",
"createOptions": "",
},
"type": "docker",
},
"edgeHub": map[string]interface{}{
"settings": map[string]interface{}{
"image": "mcr.microsoft.com/azureiotedge-hub:1.0",
"createOptions": "{\"HostConfig\":{\"PortBindings\":{\"8883/tcp\":[{\"HostPort\":\"8883\"}],\"5671/tcp\":[{\"HostPort\":\"5671\"}],\"443/tcp\":[{\"HostPort\":\"443\"}]}}}",
},
"type": "docker",
"status": "running",
"restartPolicy": "always",
},
},
},
},
"$edgeHub": map[string]interface{}{
"properties.desired": map[string]interface{}{
"routes": map[string]interface{}{},
"schemaVersion": "1.0",
"storeAndForwardConfiguration": map[string]interface{}{
"timeToLiveSecs": 7200,
},
},
},
// TODO: "testmodulename": map[string]interface{}{
// TODO: "properties.desired.test": map[string]interface{}{
// TODO: "foo": "bar",
// TODO: },
// TODO: },
},
},
Metrics: &iotservice.ConfigurationMetrics{
Queries: metricsFlag,
},
}))
}
func updateConfiguration(ctx context.Context, c *iotservice.Client, args []string) error {
config, err := c.GetConfiguration(ctx, args[0])
if err != nil {
return err
}
if forceFlag {
config.ETag = ""
}
if schemaVersionFlag != "" {
config.SchemaVersion = schemaVersionFlag
}
if priorityFlag != 0 {
config.Priority = priorityFlag
}
mergeMapStrings(config.Labels, labelsFlag)
mergeMapJSON(config.Content.ModulesContent, modulesContentFlag)
mergeMapJSON(config.Content.DeviceContent, devicesContentFlag)
mergeMapStrings(config.Metrics.Queries, metricsFlag)
if targetConditionFlag != "" {
config.TargetCondition = targetConditionFlag
}
return output(c.UpdateConfiguration(ctx, config))
}
func deleteConfiguration(ctx context.Context, c *iotservice.Client, args []string) error {
config, err := c.GetConfiguration(ctx, args[0])
if err != nil {
return err
}
if forceFlag {
config.ETag = ""
}
return c.DeleteConfiguration(ctx, config)
}
func applyConfiguration(ctx context.Context, c *iotservice.Client, args []string) error {
return c.ApplyConfigurationContentOnDevice(
ctx,
args[0],
&iotservice.ConfigurationContent{
ModulesContent: modulesContentFlag,
DeviceContent: devicesContentFlag,
},
)
}
func query(ctx context.Context, c *iotservice.Client, args []string) error {
return c.QueryDevices(ctx, args[0], func(v map[string]interface{}) error {
return output(v, nil)
})
}
func deviceStats(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.DeviceStats(ctx))
}
func serviceStats(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.ServiceStats(ctx))
}
func importFromBlob(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.CreateJob(ctx, &iotservice.Job{
Type: iotservice.JobImport,
InputBlobContainerURI: args[0],
OutputBlobContainerURI: args[1],
}))
}
func exportToBlob(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.CreateJob(ctx, &iotservice.Job{
Type: iotservice.JobExport,
OutputBlobContainerURI: args[0],
ExcludeKeysInExport: excludeKeysFlag,
}))
}
func getDeviceTwin(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.GetDeviceTwin(ctx, args[0]))
}
func getModuleTwin(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.GetModuleTwin(ctx, args[0], args[1]))
}
func updateDeviceTwin(ctx context.Context, c *iotservice.Client, args []string) error {
twin, err := c.GetDeviceTwin(ctx, args[0])
if err != nil {
return err
}
if forceFlag {
twin.ETag = ""
}
mergeMapJSON(twin.Tags, tagsFlag)
mergeMapJSON(twin.Properties.Desired, twinPropsFlag)
return output(c.UpdateDeviceTwin(ctx, twin))
}
func updateModuleTwin(ctx context.Context, c *iotservice.Client, args []string) error {
twin, err := c.GetModuleTwin(ctx, args[0], args[1])
if err != nil {
return err
}
if forceFlag {
twin.ETag = ""
}
mergeMapJSON(twin.Properties.Desired, twinPropsFlag)
return output(c.UpdateModuleTwin(ctx, twin))
}
func getDigitalTwin(ctx context.Context, c *iotservice.Client, args []string) error {
return output(c.GetDigitalTwin(ctx, args[0]))
}
func updateDigitalTwin(ctx context.Context, c *iotservice.Client, args []string) error {
var patch []map[string]interface{}
if err := json.Unmarshal([]byte(args[1]), &patch); err != nil {
return err
}
return output(c.UpdateDigitalTwin(ctx, args[0], patch))
}
func callDigitalTwin(ctx context.Context, c *iotservice.Client, args []string) error {
_, v, err := c.CallDigitalTwin(ctx, args[0], args[1], []byte(args[2]),
iotservice.WithCallDigitalTwinConnectTimeout(int(connectTimeoutFlag)),
iotservice.WithCallDigitalTwinResponseTimeout(int(responseTimeoutFlag)),
)
if err != nil {
return err
}