-
Notifications
You must be signed in to change notification settings - Fork 7
/
c8yfetcher.go
1093 lines (920 loc) · 37.6 KB
/
c8yfetcher.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 c8yfetcher
import (
"context"
"fmt"
"io"
"reflect"
"strconv"
"strings"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/cmderrors"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/cmdutil"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/flags"
"github.com/reubenmiller/go-c8y-cli/v2/pkg/iterator"
"github.com/reubenmiller/go-c8y/pkg/c8y"
"github.com/spf13/cobra"
"github.com/tidwall/gjson"
)
type DefaultFetcher struct{}
func (f *DefaultFetcher) IsID(v string) bool {
return IsID(v)
}
type IDNameFetcher struct{}
func (f *IDNameFetcher) IsID(v string) bool {
return !strings.ContainsAny(v, "*")
}
func ParseValues(values []string) (ids []string) {
for _, value := range values {
parts := strings.Split(value, ",")
for _, part := range parts {
// Only add uint looking values, and filter out custom pipeline mapped flags
if part != "" && part != flags.FlagReadFromPipeText && !strings.HasPrefix(part, flags.FlagReadFromPipeJSON) {
ids = append(ids, strings.TrimSpace(part))
}
}
}
return
}
type entityReference struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Data fetcherResultSet `json:"data,omitempty"`
}
type fetcherResultSet struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Self string `json:"self,omitempty"`
Value interface{} `json:"value,omitempty"`
}
type idValue struct {
raw string
}
// NewIDValue returns a new id formatter
// Example: NewIDValue("12345|deviceName")
func NewIDValue(raw string) *idValue {
return &idValue{
raw: raw,
}
}
func (i *idValue) GetID() string {
parts := strings.Split(i.raw, "|")
return parts[0]
}
func (i *idValue) GetName() string {
parts := strings.Split(i.raw, "|")
if len(parts) > 1 {
return parts[1]
}
return ""
}
func applyFormatter(value string, format string) string {
if format != "" {
value = fmt.Sprintf(format, value)
}
return value
}
type EntityFetcher interface {
getByID(string) ([]fetcherResultSet, error)
getByName(string) ([]fetcherResultSet, error)
IsID(string) bool
}
func lookupIDByName(fetch EntityFetcher, name string, getID bool, format string) ([]entityReference, error) {
results, err := lookupEntity(fetch, []string{name}, getID, format)
filteredResults := make([]entityReference, 0)
for _, item := range results {
if item.ID != "" {
filteredResults = append(filteredResults, item)
}
}
return filteredResults, err
}
func lookupEntity(fetch EntityFetcher, values []string, getID bool, format string) ([]entityReference, error) {
ids, names := parseAndSanitizeIDs(fetch.IsID, values)
entities := make([]entityReference, 0)
// Lookup by id
for _, id := range ids {
if getID {
if v, err := fetch.getByID(id); err == nil {
for _, resultSet := range v {
// Try to retrieve self link
if data, ok := resultSet.Value.(gjson.Result); ok {
if value := data.Get("self"); value.Exists() {
resultSet.Self = value.Str
}
}
entities = append(entities, entityReference{
ID: applyFormatter(id, format),
Name: resultSet.Name,
Data: resultSet,
})
}
}
// TODO: Handle error
} else {
entities = append(entities, entityReference{
ID: applyFormatter(id, format),
})
}
}
// Lookup via a name
for _, name := range names {
if v, err := fetch.getByName(name); err == nil {
for _, resultSet := range v {
entities = append(entities, entityReference{
ID: applyFormatter(resultSet.ID, format),
Name: resultSet.Name,
Data: resultSet,
})
}
}
// TODO: Handle error
}
return entities, nil
}
func IsID(v string) bool {
if _, err := strconv.ParseUint(v, 10, 64); v != "" && err == nil {
return true
}
return false
}
func parseAndSanitizeIDs(isID func(string) bool, values []string) (ids []string, names []string) {
for _, value := range values {
parts := strings.Split(strings.ReplaceAll(value, ", ", ","), ",")
for _, part := range parts {
// Only add uint looking values
if isID(part) {
ids = append(ids, part)
} else {
names = append(names, part)
}
}
}
return
}
func GetFetchedResultsAsString(refs []entityReference) (results []string, invalidLookups []string) {
for _, item := range refs {
if item.ID != "" {
if item.Name != "" {
results = append(results, fmt.Sprintf("%s|%s", item.ID, item.Name))
} else {
results = append(results, item.ID)
}
} else {
if item.Name != "" {
invalidLookups = append(invalidLookups, item.Name)
}
}
}
return
}
type EntityIterator struct {
Fetcher EntityFetcher
Factory *cmdutil.Factory
valueIterator iterator.Iterator
GetID bool
UseSelfLink bool
MinimumMatches int
OverrideValue iterator.Iterator
Format string
}
// NewReferenceByNameIterator create a new iterator which can look up values by their id or names
func NewReferenceByNameIterator(fetcher EntityFetcher, factory *cmdutil.Factory, valueIterator iterator.Iterator, minimumMatches int, overrideValue iterator.Iterator, format string) *EntityIterator {
return &EntityIterator{
Fetcher: fetcher,
Factory: factory,
valueIterator: valueIterator,
GetID: false,
MinimumMatches: minimumMatches,
OverrideValue: overrideValue,
Format: format,
}
}
// MarshalJSON return the value in a json compatible value
func (i *EntityIterator) MarshalJSON() (line []byte, err error) {
return iterator.MarshalJSON(i)
}
// IsBound return true if the iterator is bound
func (i *EntityIterator) IsBound() bool {
return true
}
func (i *EntityIterator) GetNext() (value []byte, input interface{}, err error) {
if i.valueIterator == nil {
return nil, nil, io.EOF
}
value, rawValue, err := i.valueIterator.GetNext()
if err == io.EOF && len(value) > 0 {
// ignore EOF if the value is not empty
err = nil
}
// override the value if it is not nil
if i.OverrideValue != nil && !reflect.ValueOf(i.OverrideValue).IsNil() {
overrideValue, _, overrideErr := i.OverrideValue.GetNext()
if overrideErr != nil {
if i.valueIterator.IsBound() && overrideErr == io.EOF {
// ignore as the other iterator is bound, so let it control the loop
} else {
return overrideValue, rawValue, overrideErr
}
}
if len(overrideValue) > 0 {
value = overrideValue
}
}
if err != nil {
return value, rawValue, err
}
refs := []entityReference{}
if len(value) != 0 {
// only lookup if value is not empty. Formatting is done later
refs, err = lookupIDByName(i.Fetcher, string(value), i.GetID, "")
if err != nil {
return nil, rawValue, err
}
// Return an error if no matches are found regardless of minimum
// matches, as the user is using lookup by name
if len(refs) == 0 {
return nil, rawValue, cmderrors.NewNoMatchesFoundError(string(value))
}
}
if len(refs) == 0 {
if len(refs) < i.MinimumMatches {
return nil, rawValue, cmderrors.NewNoMatchesFoundError(string(value))
}
return nil, rawValue, nil
}
if len(refs) < i.MinimumMatches {
return nil, rawValue, cmderrors.NewNoMatchesFoundError(string(value))
}
// use self rather than id if not empty
returnValue := refs[0].ID
if i.UseSelfLink && refs[0].Data.Self != "" {
returnValue = refs[0].Data.Self
}
if i.Format != "" {
returnValue = fmt.Sprintf(i.Format, returnValue)
}
return []byte(returnValue), rawValue, nil
}
// WithIDSlice adds an id slice from cli arguments
func WithIDSlice(args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
src, dst, _ := flags.UnpackGetterOptions("", opts...)
// check for arguments which could override the value
values, err := cmd.Flags().GetStringSlice(src)
if err != nil {
singleValue, singleErr := cmd.Flags().GetString(src)
if singleErr != nil {
return "", "", singleErr
}
err = nil
values = []string{singleValue}
}
values = ParseValues(append(values, args...))
var overrideValue iterator.Iterator
if len(values) > 0 {
overrideValue = iterator.NewSliceIterator(values)
}
if inputIterators != nil && inputIterators.PipeOptions.Name == src {
hasPipeSupport := inputIterators.PipeOptions.Name == src
pipeIter, err := flags.NewFlagWithPipeIterator(cmd, inputIterators.PipeOptions, hasPipeSupport)
if err == iterator.ErrEmptyPipeInput && !inputIterators.PipeOptions.EmptyPipe {
return inputIterators.PipeOptions.Property, nil, err
}
if err != nil || pipeIter == nil {
return "", nil, err
}
if pipeIter.IsBound() {
// Use infinite slice iterator so that the stdin can drive the iteration
// but only if the other pipe iterator is bound, otherwise it would create an infinite loop!
overrideValue = iterator.NewInfiniteSliceIterator(values)
}
iter := iterator.NewOverrideIterator(pipeIter, overrideValue)
return inputIterators.PipeOptions.Property, iter, nil
}
if len(values) == 0 {
return "", values, nil
}
return dst, values, err
}
}
// WithReferenceByName adds support for looking up values by name via cli args
func WithReferenceByName(factory *cmdutil.Factory, fetcher EntityFetcher, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
src, dst, format := flags.UnpackGetterOptions("", opts...)
// check for arguments which could override the value
values, err := cmd.Flags().GetStringSlice(src)
if err != nil {
singleValue, singleErr := cmd.Flags().GetString(src)
if singleErr != nil {
return "", "", singleErr
}
err = nil
values = []string{singleValue}
}
values = ParseValues(append(values, args...))
var overrideValue iterator.Iterator
if len(values) > 0 {
overrideValue = iterator.NewSliceIterator(values, format)
}
if inputIterators != nil && inputIterators.PipeOptions.Name == src {
hasPipeSupport := inputIterators.PipeOptions.Name == src
pipeIter, err := flags.NewFlagWithPipeIterator(cmd, inputIterators.PipeOptions, hasPipeSupport)
if err == iterator.ErrEmptyPipeInput && !inputIterators.PipeOptions.EmptyPipe {
return inputIterators.PipeOptions.Property, nil, err
}
if err != nil || pipeIter == nil {
return "", nil, err
}
if pipeIter.IsBound() {
// Use infinite slice iterator so that the stdin can drive the iteration
// but only if the other pipe iterator is bound, otherwise it would create an infinite loop!
overrideValue = iterator.NewInfiniteSliceIterator(values)
}
minMatches := 0
if inputIterators.PipeOptions.Required {
minMatches = 1
}
iter := NewReferenceByNameIterator(fetcher, factory, pipeIter, minMatches, overrideValue, format)
return inputIterators.PipeOptions.Property, iter, nil
}
if len(values) == 0 {
return "", values, nil
}
formattedValues, err := lookupEntity(fetcher, values, false, format)
if err != nil {
return dst, values, fmt.Errorf("failed to lookup by name. %w", err)
}
results := []string{}
invalidLookups := []string{}
for _, item := range formattedValues {
if item.ID != "" {
if item.Name != "" {
results = append(results, fmt.Sprintf("%s|%s", item.ID, item.Name))
} else {
results = append(results, item.ID)
}
} else {
if item.Name != "" {
invalidLookups = append(invalidLookups, item.Name)
}
}
}
var errs error
if len(invalidLookups) > 0 {
errs = fmt.Errorf("no results %v", invalidLookups)
}
return dst, results, errs
}
}
// WithSelfReferenceByName adds support for looking up values by name via cli args
func WithSelfReferenceByName(factory *cmdutil.Factory, fetcher EntityFetcher, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
src, dst, format := flags.UnpackGetterOptions("", opts...)
// check for arguments which could override the value
values, err := cmd.Flags().GetStringSlice(src)
if err != nil {
singleValue, singleErr := cmd.Flags().GetString(src)
if singleErr != nil {
return "", "", singleErr
}
err = nil
values = []string{singleValue}
}
values = ParseValues(append(values, args...))
var overrideValue iterator.Iterator
if len(values) > 0 {
overrideValue = iterator.NewSliceIterator(values, format)
}
if inputIterators != nil && inputIterators.PipeOptions.Name == src {
hasPipeSupport := inputIterators.PipeOptions.Name == src
pipeIter, err := flags.NewFlagWithPipeIterator(cmd, inputIterators.PipeOptions, hasPipeSupport)
if err == iterator.ErrEmptyPipeInput && !inputIterators.PipeOptions.EmptyPipe {
return inputIterators.PipeOptions.Property, nil, err
}
if err != nil || pipeIter == nil {
return "", nil, err
}
minMatches := 0
if inputIterators.PipeOptions.Required {
minMatches = 1
}
iter := NewReferenceByNameIterator(fetcher, factory, pipeIter, minMatches, overrideValue, format)
iter.UseSelfLink = true
iter.GetID = true
return inputIterators.PipeOptions.Property, iter, nil
}
if len(values) == 0 {
return "", values, nil
}
formattedValues, err := lookupEntity(fetcher, values, true, format)
if err != nil {
return dst, values, fmt.Errorf("failed to lookup by name. %w", err)
}
results := []string{}
invalidLookups := []string{}
for _, item := range formattedValues {
var selfLink string
// Try to retrieve self link
if data, ok := item.Data.Value.(gjson.Result); ok {
if value := data.Get("self"); value.Exists() {
selfLink = value.Str
}
}
if selfLink != "" {
if item.Name != "" {
results = append(results, fmt.Sprintf("%s|%s", selfLink, item.Name))
} else {
results = append(results, selfLink)
}
} else {
if item.Name != "" {
invalidLookups = append(invalidLookups, item.Name)
}
}
}
var errors error
if len(invalidLookups) > 0 {
errors = fmt.Errorf("no results %v", invalidLookups)
}
return dst, results, errors
}
}
// WithManagedObjectPropertyFirstMatch add reference by name matching using a fetcher via cli args. Only the first match will be used
func WithManagedObjectPropertyFirstMatch(factory *cmdutil.Factory, fetcher EntityFetcher, args []string, property string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
client, err := factory.Client()
if err != nil {
return "", nil, err
}
opt := WithReferenceByName(factory, fetcher, args, opts...)
name, values, err := opt(cmd, inputIterators)
if name == "" {
return "", "", nil
}
switch v := values.(type) {
case []string:
if len(v) == 0 {
return name, nil, fmt.Errorf("reference by name: no matches found")
}
moID := NewIDValue(v[0]).GetID()
mo, _, err := client.Inventory.GetManagedObject(c8y.WithDisabledDryRunContext(context.Background()), moID, nil)
value := mo.Item.Get(property)
if !value.Exists() {
return name, "", nil
}
return name, value.Str, err
case iterator.Iterator:
// value will be evalulated later
return name, v, nil
default:
if err == nil {
err = fmt.Errorf("reference by name: invalid name lookup type. only strings are supported")
}
return "", "", err
}
}
}
func ignoreArgsAfterDash(cmd *cobra.Command, args []string) []string {
if i := cmd.ArgsLenAtDash(); i > -1 {
return args[0:i]
}
return args[:]
}
// WithReferenceByNameFirstMatch add reference by name matching using a fetcher via cli args. Only the first match will be used
func WithReferenceByNameFirstMatch(factory *cmdutil.Factory, fetcher EntityFetcher, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByName(factory, fetcher, ignoreArgsAfterDash(cmd, args), opts...)
name, values, err := opt(cmd, inputIterators)
if name == "" {
return "", "", nil
}
switch v := values.(type) {
case []string:
if len(v) == 0 {
return name, nil, fmt.Errorf("reference by name: no matches found")
}
return name, NewIDValue(v[0]).GetID(), err
case iterator.Iterator:
// value will be evalulated later
return name, v, nil
default:
if err == nil {
err = fmt.Errorf("reference by name: invalid name lookup type. only strings are supported")
}
return "", "", err
}
}
}
// WithSelfReferenceByNameFirstMatch add reference by name matching using a fetcher via cli args. Only the first match will be used
func WithSelfReferenceByNameFirstMatch(factory *cmdutil.Factory, fetcher EntityFetcher, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithSelfReferenceByName(factory, fetcher, ignoreArgsAfterDash(cmd, args), opts...)
name, values, err := opt(cmd, inputIterators)
if name == "" {
return "", "", nil
}
switch v := values.(type) {
case []string:
if len(v) == 0 {
return name, nil, fmt.Errorf("reference by name: no matches found")
}
return name, NewIDValue(v[0]).GetID(), err
case iterator.Iterator:
// value will be evalulated later
return name, v, nil
default:
if err == nil {
err = fmt.Errorf("reference by name: invalid name lookup type. only strings are supported")
}
return "", "", err
}
}
}
// WithDeviceByNameFirstMatch add reference by name matching for devices via cli args. Only the first match will be used
func WithDeviceByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewDeviceFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithApplicationByNameFirstMatch add reference by name matching for applications via cli args. Only the first match will be used
func WithApplicationByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewApplicationFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithHostedApplicationByNameFirstMatch add reference by name matching for hosted (web) applications via cli args. Only the first match will be used
func WithHostedApplicationByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewHostedApplicationFetcher(factory, false), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithMicroserviceByNameFirstMatch add reference by name matching for microservices via cli args. Only the first match will be used
func WithMicroserviceByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewMicroserviceFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithUIPluginByNameFirstMatch add reference by name matching for UI extensions via cli args. Only the first match will be used
func WithUIPluginByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
fetch := NewUIPluginFetcher(factory)
fetch.EnableSharedPlugins = true
opt := WithReferenceByNameFirstMatch(factory, fetch, args, opts...)
return opt(cmd, inputIterators)
}
}
// WithAgentByNameFirstMatch add reference by name matching for agents via cli args. Only the first match will be used
func WithAgentByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewAgentFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithDeviceGroupByNameFirstMatch add reference by name matching for device groups via cli args. Only the first match will be used
func WithDeviceGroupByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewDeviceGroupFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithSmartGroupByNameFirstMatch add reference by name matching for smart groups via cli args. Only the first match will be used
func WithSmartGroupByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewSmartGroupFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithSoftwareByNameFirstMatch add reference by name matching for software via cli args. Only the first match will be used
func WithSoftwareByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewSoftwareFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithSoftwareVersionData adds software information (name, version and url)
func WithSoftwareVersionData(factory *cmdutil.Factory, flagSoftware, flagVersion, flagURL string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
client, err := factory.Client()
if err != nil {
return "", nil, err
}
software := ""
if v, err := flags.GetFlagStringValues(cmd, flagSoftware); err == nil && len(v) > 0 {
software = v[0]
}
version := ""
if v, err := flags.GetFlagStringValues(cmd, flagVersion); err == nil && len(v) > 0 {
version = v[0]
}
url := ""
if v, err := flags.GetFlagStringValues(cmd, flagURL); err == nil && len(v) > 0 {
url = v[0]
}
_, dst, _ := flags.UnpackGetterOptions("", opts...)
output := map[string]string{}
// If version is empty, then pass the values as is
if version == "" || (software != "" && version != "" && url != "") {
output["name"] = software
output["version"] = version
output["url"] = url
return dst, output, nil
}
// Check for explicit managed object id
if IsID(version) {
mo, _, err := client.Inventory.GetManagedObject(c8y.WithDisabledDryRunContext(context.Background()), version, &c8y.ManagedObjectOptions{
WithParents: true,
})
if err != nil {
return "", "", err
}
output["name"] = mo.Item.Get("additionParents.references.0.managedObject.name").String()
output["version"] = mo.Item.Get("c8y_Software.version").String()
output["url"] = mo.Item.Get("c8y_Software.url").String()
return dst, output, nil
}
// Lookup version (and software if not already resolved)
versionCol, _, err := client.Software.GetSoftwareVersionsByName(c8y.WithDisabledDryRunContext(context.Background()), software, version, true, c8y.NewPaginationOptions(5))
if err != nil {
return "", "", err
}
if len(versionCol.ManagedObjects) == 0 {
return "", "", cmderrors.NewNoMatchesFoundError(flagVersion)
}
output["version"] = versionCol.Items[0].Get("c8y_Software.version").String()
output["url"] = versionCol.Items[0].Get("c8y_Software.url").String()
output["name"] = versionCol.Items[0].Get("additionParents.references.0.managedObject.name").String()
return dst, output, err
}
}
// WithSoftwareVersionUrl add software version url
func WithSoftwareVersionUrlByNameFirstMatch(factory *cmdutil.Factory, softwareFlag string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
software := ""
if v, err := flags.GetFlagStringValues(cmd, softwareFlag); err == nil && len(v) > 0 {
software = v[0]
}
opt := WithManagedObjectPropertyFirstMatch(factory, NewSoftwareVersionFetcher(factory, software), args, "c8y_Software.url", opts...)
return opt(cmd, inputIterators)
}
}
// WithSoftwareVersionByNameFirstMatch add reference by name matching for software version via cli args. Only the first match will be used
func WithSoftwareVersionByNameFirstMatch(factory *cmdutil.Factory, softwareFlag string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
software := ""
if v, err := cmd.Flags().GetStringSlice(softwareFlag); err == nil && len(v) > 0 {
software = v[0]
}
opt := WithReferenceByNameFirstMatch(factory, NewSoftwareVersionFetcher(factory, software), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithSoftwareVersionByNameFirstMatch add reference by name matching for software version via cli args. Only the first match will be used
func WithDeviceServiceByNameFirstMatch(factory *cmdutil.Factory, flagDevice string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
device := ""
if v, err := cmd.Flags().GetStringSlice(flagDevice); err == nil && len(v) > 0 {
device = v[0]
}
opt := WithReferenceByNameFirstMatch(factory, NewDeviceServiceFetcher(factory, device), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithFirmwareByNameFirstMatch add reference by name matching for firmware via cli args. Only the first match will be used
func WithFirmwareByNameFirstMatch(factory *cmdutil.Factory, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
opt := WithReferenceByNameFirstMatch(factory, NewFirmwareFetcher(factory), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithFirmwareVersionByNameFirstMatch add reference by name matching for firmware version via cli args. Only the first match will be used
func WithFirmwareVersionByNameFirstMatch(factory *cmdutil.Factory, flagFirmware string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
firmware := ""
// Note: Lookup of firmware does not work if "firmware" is piped input
if v, err := cmd.Flags().GetStringSlice(flagFirmware); err == nil && len(v) > 0 {
firmware = v[0]
}
opt := WithReferenceByNameFirstMatch(factory, NewFirmwareVersionFetcher(factory, firmware, false), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithFirmwareVersionData adds firmware information (name, version and url)
func WithFirmwareVersionData(factory *cmdutil.Factory, flagFirmware, flagVersion, flagURL string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
client, err := factory.Client()
if err != nil {
return "", nil, err
}
firmware := ""
if v, err := flags.GetFlagStringValues(cmd, flagFirmware); err == nil && len(v) > 0 {
firmware = v[0]
}
version := ""
if v, err := flags.GetFlagStringValues(cmd, flagVersion); err == nil && len(v) > 0 {
version = v[0]
}
url := ""
if v, err := flags.GetFlagStringValues(cmd, flagURL); err == nil && len(v) > 0 {
url = v[0]
}
_, dst, _ := flags.UnpackGetterOptions("", opts...)
output := map[string]string{}
// If version is empty, or all values are provided, then pass the values as is
if version == "" || (firmware != "" && version != "" && url != "") {
output["name"] = firmware
output["version"] = version
output["url"] = url
return dst, output, nil
}
// Check for explicit managed object id
if IsID(version) {
mo, _, err := client.Inventory.GetManagedObject(c8y.WithDisabledDryRunContext(context.Background()), version, &c8y.ManagedObjectOptions{
WithParents: true,
})
if err != nil {
return "", "", err
}
output["name"] = mo.Item.Get("additionParents.references.0.managedObject.name").String()
output["version"] = mo.Item.Get("c8y_Firmware.version").String()
output["url"] = mo.Item.Get("c8y_Firmware.url").String()
return dst, output, nil
}
// Lookup version (and software if not already resolved)
versionCol, _, err := client.Firmware.GetFirmwareVersionsByName(c8y.WithDisabledDryRunContext(context.Background()), firmware, version, true, c8y.NewPaginationOptions(5))
if err != nil {
return "", "", err
}
if len(versionCol.ManagedObjects) == 0 {
return "", "", cmderrors.NewNoMatchesFoundError(flagVersion)
}
output["version"] = versionCol.Items[0].Get("c8y_Firmware.version").String()
output["url"] = versionCol.Items[0].Get("c8y_Firmware.url").String()
output["name"] = versionCol.Items[0].Get("additionParents.references.0.managedObject.name").String()
return dst, output, err
}
}
// WithFirmwarePatchByNameFirstMatch add reference by name matching for firmware version via cli args. Only the first match will be used
func WithFirmwarePatchByNameFirstMatch(factory *cmdutil.Factory, firmwareFlag string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
firmware := ""
// Note: Lookup of firmware does not work if "firmware" is piped input
if v, err := cmd.Flags().GetStringSlice(firmwareFlag); err == nil && len(v) > 0 {
firmware = v[0]
}
opt := WithReferenceByNameFirstMatch(factory, NewFirmwareVersionFetcher(factory, firmware, true), args, opts...)
return opt(cmd, inputIterators)
}
}
// WithConfigurationFileData adds configuration information (type, url etc.)
func WithConfigurationFileData(factory *cmdutil.Factory, flagConfiguration, flagConfigurationType, flagURL string, args []string, opts ...string) flags.GetOption {
return func(cmd *cobra.Command, inputIterators *flags.RequestInputIterators) (string, interface{}, error) {
client, err := factory.Client()
if err != nil {
return "", nil, err
}
configuration := ""
if v, err := flags.GetFlagStringValues(cmd, flagConfiguration); err == nil && len(v) > 0 {
configuration = v[0]
}
configurationType := ""
if v, err := flags.GetFlagStringValues(cmd, flagConfigurationType); err == nil && len(v) > 0 {
configurationType = v[0]
}
url := ""
if v, err := flags.GetFlagStringValues(cmd, flagURL); err == nil && len(v) > 0 {
url = v[0]
}
_, dst, _ := flags.UnpackGetterOptions("", opts...)
output := map[string]string{}
// If version is empty, or all values are provided, then pass the values as is
if configuration == "" && configurationType != "" && url != "" {
output["type"] = configurationType
output["url"] = url
output["name"] = configuration
return dst, output, nil
}
// Check for explicit managed object id
if IsID(configuration) {
mo, _, err := client.Inventory.GetManagedObject(c8y.WithDisabledDryRunContext(context.Background()), configuration, &c8y.ManagedObjectOptions{
WithParents: true,
})
if err != nil {
return "", "", err
}
output["type"] = mo.Item.Get("configurationType").String()
output["url"] = mo.Item.Get("url").String()
output["name"] = mo.Item.Get("name").String()
return dst, output, nil
}
// Lookup version (and software if not already resolved)
query := fmt.Sprintf("type eq 'c8y_ConfigurationDump' and name eq '%s'", configuration)
if configurationType != "" {
query += fmt.Sprintf(" and configurationType eq '%s'", configurationType)
}
col, _, err := client.Inventory.GetManagedObjects(
c8y.WithDisabledDryRunContext(context.Background()),
&c8y.ManagedObjectOptions{
Query: query,
WithParents: false,
PaginationOptions: *c8y.NewPaginationOptions(5),
},
)
if err != nil {
return "", "", err
}
if len(col.ManagedObjects) == 0 {
return "", "", cmderrors.NewNoMatchesFoundError(flagConfiguration)
}
output["type"] = col.Items[0].Get("configurationType").String()
output["url"] = col.Items[0].Get("url").String()
output["name"] = col.Items[0].Get("name").String()
return dst, output, err
}
}
// WithConfigurationByNameFirstMatch add reference by name matching for configuration via cli args. Only the first match will be used