-
Notifications
You must be signed in to change notification settings - Fork 5
/
smd-api.go
5352 lines (4981 loc) · 167 KB
/
smd-api.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
// MIT License
//
// (C) Copyright [2018-2023] Hewlett Packard Enterprise Development LP
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"strconv"
"strings"
base "github.com/Cray-HPE/hms-base/v2"
"github.com/Cray-HPE/hms-xname/xnametypes"
compcreds "github.com/Cray-HPE/hms-compcredentials"
"github.com/Cray-HPE/hms-smd/v2/internal/hmsds"
rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish"
"github.com/Cray-HPE/hms-smd/v2/pkg/sm"
"github.com/gorilla/mux"
)
type componentIn struct {
base.Component
ExtendedInfo json.RawMessage `json:"ExtendedInfo,omitempty"`
}
type componentArrayIn struct {
Components []base.Component `json:"Components"`
ExtendedInfo json.RawMessage `json:"ExtendedInfo,omitempty"`
}
type CompQueryIn struct {
ComponentIDs []string `json:"ComponentIDs"`
}
type NIDQueryIn struct {
NIDRanges []string `json:"NIDRanges"`
}
type FieldFltrIn struct {
StateOnly bool `json:"stateonly"`
FlagOnly bool `json:"flagonly"`
RoleOnly bool `json:"roleonly"`
NIDOnly bool `json:"nidonly"`
}
type FieldFltrInForm struct {
StateOnly []string `json:"stateonly"`
FlagOnly []string `json:"flagonly"`
RoleOnly []string `json:"roleonly"`
NIDOnly []string `json:"nidonly"`
}
type HwInvIn struct {
Hardware []sm.HWInvByLoc `json:"Hardware"`
}
type HwInvQueryIn struct {
ID []string `json:"id"`
Type []string `json:"type"`
Manufacturer []string `json:"manufacturer"`
PartNumber []string `json:"partnumber"`
SerialNumber []string `json:"serialnumber"`
FruId []string `json:"fruid"`
Children []string `json:"children"`
Parents []string `json:"parents"`
Partition []string `json:"partition"`
Format []string `json:"format"`
}
type HwInvHistIn struct {
ID []string `json:"id"`
FruId []string `json:"fruid"`
EventType []string `json:"eventtype"`
StartTime []string `json:"starttime"`
EndTime []string `json:"endtime"`
}
type GrpPartFltr struct {
Group []string `json:"group"`
Tag []string `json:"tag"`
Partition []string `json:"partition"`
}
type CompLockFltr struct {
ID []string `json:"id"`
Owner []string `json:"owner"`
Xname []string `json:"xname"`
}
type CompGetLockFltr struct {
Type []string `json:"Type"`
State []string `json:"State"`
Role []string `json:"Role"`
SubRole []string `json:"Subrole"`
Locked []string `json:"Locked"`
Reserved []string `json:"Reserved"`
ReservationDisabled []string `json:"ReservationDisabled"`
}
type CompEthInterfaceFltr struct {
ID []string `json:"id"`
MACAddr []string `json:"macaddress"`
IPAddr []string `json:"ipaddress"`
Network []string `json:"network"`
OlderThan []string `json:"olderthan"`
NewerThan []string `json:"newerthan"`
CompID []string `json:"componentid"`
Type []string `json:"type"`
}
const (
compUpdateState = "State"
compUpdateFlagOnly = "FlagOnly"
compUpdateEnabled = "Enabled"
compUpdateSwStatus = "SoftwareStatus"
compUpdateRole = "Role"
compUpdateNID = "NID"
)
type HMSValueSelect int
const (
HMSValAll HMSValueSelect = iota
HMSValArch
HMSValClass
HMSValFlag
HMSValNetType
HMSValRole
HMSValSubRole
HMSValState
HMSValType
)
type HMSValues struct {
Arch []string `json:"Arch,omitempty"`
Class []string `json:"Class,omitempty"`
Flag []string `json:"Flag,omitempty"`
NetType []string `json:"NetType,omitempty"`
Role []string `json:"Role,omitempty"`
SubRole []string `json:"SubRole,omitempty"`
State []string `json:"State,omitempty"`
Type []string `json:"Type,omitempty"`
}
/////////////////////////////////////////////////////////////////////////////
// Helper Fuctions
/////////////////////////////////////////////////////////////////////////////
// Translate form input into a FieldFilter
func getFieldFilterForm(f *FieldFltrInForm) hmsds.FieldFilter {
/* Deal with the component field filters (i.e. "stateonly"). Due to the way that
* the query parameter parsing works, these values will be coming to us as strings.
* Convert them to bool. Take the first one that is true.
*/
if f == nil {
return hmsds.FLTR_DEFAULT
}
if len(f.StateOnly) > 0 {
compFltr, _ := strconv.ParseBool(f.StateOnly[0])
if compFltr {
return hmsds.FLTR_STATEONLY
}
}
if len(f.FlagOnly) > 0 {
compFltr, _ := strconv.ParseBool(f.FlagOnly[0])
if compFltr {
return hmsds.FLTR_FLAGONLY
}
}
if len(f.RoleOnly) > 0 {
compFltr, _ := strconv.ParseBool(f.RoleOnly[0])
if compFltr {
return hmsds.FLTR_ROLEONLY
}
}
if len(f.NIDOnly) > 0 {
compFltr, _ := strconv.ParseBool(f.NIDOnly[0])
if compFltr {
return hmsds.FLTR_NIDONLY
}
}
return hmsds.FLTR_DEFAULT
}
// Translate POST input into a FieldFilter
func getFieldFilter(f *FieldFltrIn) hmsds.FieldFilter {
/* Deal with the component field filters (i.e. "stateonly"). Due to the way that
* the query parameter parsing works, these values will be coming to us as strings.
* Convert them to bool. Take the first one that is true.
*/
if f == nil {
return hmsds.FLTR_DEFAULT
}
if f.StateOnly {
return hmsds.FLTR_STATEONLY
}
if f.FlagOnly {
return hmsds.FLTR_FLAGONLY
}
if f.RoleOnly {
return hmsds.FLTR_ROLEONLY
}
if f.NIDOnly {
return hmsds.FLTR_NIDONLY
}
return hmsds.FLTR_DEFAULT
}
// Parse an array of NIDs and NID ranges into the NIDStart, NIDEnd, NID fields
// of a ComponentFilter. This function will prepend the parsed values to the
// NID, NIDStart, and NIDEnd arrays in the given ComponentFilter. This way
// pre-existing values in NIDStart and NIDEnd do not affect the reletive index
// of parsed NIDStart-NIDEnd pairs. A ComponentFilter will be created if one
// is not specified.
func nidRangeToCompFilter(nidRanges []string, f *hmsds.ComponentFilter) (*hmsds.ComponentFilter, error) {
NIDStart := make([]string, 0, 1)
NIDEnd := make([]string, 0, 1)
NID := make([]string, 0, 1)
// Create a ComponentFilter if one was not provided
if f == nil {
f = new(hmsds.ComponentFilter)
}
// Parse the NID ranges
for _, nid := range nidRanges {
nidRange := strings.Split(nid, "-")
if len(nidRange) > 1 {
// NID Range
if len(nidRange[0]) == 0 || len(nidRange[len(nidRange)-1]) == 0 {
return f, errors.New("Argument was not a valid NID Range")
}
NIDStart = append(NIDStart, nidRange[0])
NIDEnd = append(NIDEnd, nidRange[len(nidRange)-1])
} else {
// Single NID
if len(nid) > 0 {
NID = append(NID, nid)
}
}
}
// Append any values from the given ComponentFilter effectively prepending the parsed values.
if len(f.NIDStart) > 0 {
NIDStart = append(NIDStart, f.NIDStart...)
}
if len(f.NIDEnd) > 0 {
NIDEnd = append(NIDEnd, f.NIDEnd...)
}
if len(f.NID) > 0 {
NID = append(NID, f.NID...)
}
f.NIDStart = NIDStart
f.NIDEnd = NIDEnd
f.NID = NID
return f, nil
}
func compGetLockFltrToCompLockV2Filter(cglf CompGetLockFltr) (clf sm.CompLockV2Filter) {
clf.Type = cglf.Type
clf.State = cglf.State
clf.Role = cglf.Role
clf.SubRole = cglf.SubRole
clf.Locked = cglf.Locked
clf.Reserved = cglf.Reserved
clf.ReservationDisabled = cglf.ReservationDisabled
return clf
}
/////////////////////////////////////////////////////////////////////////////
// HSM Service Info
/////////////////////////////////////////////////////////////////////////////
// Get the readiness state of HSM
func (s *SmD) doReadyGet(w http.ResponseWriter, r *http.Request) {
// If we got here then the initial database connection was successful
// Check that the DB connection is still available
err := s.db.TestConnection()
if err != nil {
s.LogAlways("doReadyGet(): Database failed health check: %s", err)
sendJsonError(w, http.StatusServiceUnavailable, "HSM's database is unhealthy: "+err.Error())
return
}
// Tell them we are up and healthy
sendJsonError(w, http.StatusOK, "HSM is healthy")
}
// Get the liveness state of HSM
func (s *SmD) doLivenessGet(w http.ResponseWriter, r *http.Request) {
// Let the caller know we are accepting HTTP requests.
w.WriteHeader(http.StatusNoContent)
}
// Get all HMS base enum values
func (s *SmD) doValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValAll, w, r)
}
// Get HMS base enum values for arch
func (s *SmD) doArchValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValArch, w, r)
}
// Get HMS base enum values for class
func (s *SmD) doClassValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValClass, w, r)
}
// Get HMS base enum values for flag
func (s *SmD) doFlagValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValFlag, w, r)
}
// Get HMS base enum values for nettype
func (s *SmD) doNetTypeValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValNetType, w, r)
}
// Get HMS base enum values for role
func (s *SmD) doRoleValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValRole, w, r)
}
// Get HMS base enum values for subrole
func (s *SmD) doSubRoleValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValSubRole, w, r)
}
// Get HMS base enum values for state
func (s *SmD) doStateValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValState, w, r)
}
// Get HMS base enum values for type
func (s *SmD) doTypeValuesGet(w http.ResponseWriter, r *http.Request) {
s.getHMSValues(HMSValType, w, r)
}
func (s *SmD) getHMSValues(valSelect HMSValueSelect, w http.ResponseWriter, r *http.Request) {
values := new(HMSValues)
switch valSelect {
case HMSValArch:
values.Arch = base.GetHMSArchList()
case HMSValClass:
values.Class = base.GetHMSClassList()
case HMSValFlag:
values.Flag = base.GetHMSFlagList()
case HMSValNetType:
values.NetType = base.GetHMSNetTypeList()
case HMSValRole:
values.Role = base.GetHMSRoleList()
case HMSValSubRole:
values.SubRole = base.GetHMSSubRoleList()
case HMSValState:
values.State = base.GetHMSStateList()
case HMSValType:
values.Type = xnametypes.GetHMSTypeList()
case HMSValAll:
values.Arch = base.GetHMSArchList()
values.Class = base.GetHMSClassList()
values.Flag = base.GetHMSFlagList()
values.NetType = base.GetHMSNetTypeList()
values.Role = base.GetHMSRoleList()
values.SubRole = base.GetHMSSubRoleList()
values.State = base.GetHMSStateList()
values.Type = xnametypes.GetHMSTypeList()
}
sendJsonValueRsp(w, values)
}
/////////////////////////////////////////////////////////////////////////////
// Component Status
/////////////////////////////////////////////////////////////////////////////
// Get single HMS component by xname ID
func (s *SmD) doComponentGet(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
xname := xnametypes.NormalizeHMSCompID(vars["xname"])
cmp, err := s.db.GetComponentByID(xname)
if err != nil {
s.LogAlways("doComponentGet(): Lookup failure: (%s) %s", xname, err)
sendJsonDBError(w, "", "", err)
return
}
if cmp == nil {
sendJsonError(w, http.StatusNotFound, "no such xname.")
return
}
// Over all summary error code needs to be computed...
sendJsonCompRsp(w, cmp)
}
// Delete single ComponentEndpoint, by its xname ID.
func (s *SmD) doComponentDelete(w http.ResponseWriter, r *http.Request) {
s.lg.Printf("doComponentDelete(): trying...")
vars := mux.Vars(r)
xname := xnametypes.NormalizeHMSCompID(vars["xname"])
if !xnametypes.IsHMSCompIDValid(xname) {
sendJsonError(w, http.StatusBadRequest, "invalid xname")
return
}
didDelete, err := s.db.DeleteComponentByID(xname)
if err != nil {
s.LogAlways("doComponentDelete(): delete failure: (%s) %s", xname, err)
sendJsonDBError(w, "", "", err)
return
}
if didDelete == false {
sendJsonError(w, http.StatusNotFound, "no such xname.")
return
}
sendJsonError(w, http.StatusOK, "deleted 1 entry")
}
// Get all HMS Components as named array
func (s *SmD) doComponentsGet(w http.ResponseWriter, r *http.Request) {
comps := new(base.ComponentArray)
var err error
// Parse arguments
if err := r.ParseForm(); err != nil {
s.lg.Printf("doComponentsGet(): ParseForm: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
formJSON, err := json.Marshal(r.Form)
if err != nil {
s.lg.Printf("doComponentsGet(): Marshall form: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
compFilter := new(hmsds.ComponentFilter)
if err = json.Unmarshal(formJSON, compFilter); err != nil {
s.lg.Printf("doComponentsGet(): Unmarshall form: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
// Get the component field filter options (i.e. stateonly)
fieldFltrIn := new(FieldFltrInForm)
if err = json.Unmarshal(formJSON, fieldFltrIn); err != nil {
s.lg.Printf("doComponentsGet(): Unmarshall form: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
fieldFltr := getFieldFilterForm(fieldFltrIn)
comps.Components, err = s.db.GetComponentsFilter(compFilter, fieldFltr)
if err != nil {
s.LogAlways("doComponentsGet(): Lookup failure: %s", err)
sendJsonDBError(w, "bad query param: ", "", err)
return
}
sendJsonCompArrayRsp(w, comps)
}
// CREATE/Update components. If the component already exists it will not be
// overwritten unless force=true in which case State, Flag, Subtype, NetType,
// Arch, and Class will get overwritten.
func (s *SmD) doComponentsPost(w http.ResponseWriter, r *http.Request) {
var err error
var compsIn sm.ComponentsPost
body, err := ioutil.ReadAll(r.Body)
err = json.Unmarshal(body, &compsIn)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
if len(compsIn.Components) < 1 || len(compsIn.Components[0].ID) == 0 {
sendJsonError(w, http.StatusBadRequest, "Missing Components")
return
}
err = compsIn.VerifyNormalize()
if err != nil {
s.lg.Printf("doComponentsPost(): Couldn't validate components: %s", err)
sendJsonError(w, http.StatusBadRequest,
"couldn't validate components: "+err.Error())
return
}
// Get the nid and role defaults for all node types
for _, comp := range compsIn.Components {
if comp.Type == xnametypes.Node.String() {
if len(comp.Role) == 0 || len(comp.NID) == 0 || len(comp.Class) == 0 {
newNID, defRole, defSubRole, defClass := s.GetCompDefaults(comp.ID, base.RoleCompute.String(), "", "")
if len(comp.Role) == 0 {
comp.Role = defRole
}
if len(comp.SubRole) == 0 {
comp.SubRole = defSubRole
}
if len(comp.NID) == 0 {
comp.NID = json.Number(strconv.FormatUint(newNID, 10))
}
if len(comp.Class) == 0 {
comp.Class = defClass
}
}
}
}
changeMap, err := s.db.UpsertComponents(compsIn.Components, compsIn.Force)
if err != nil {
sendJsonDBError(w, "operation 'Post Components' failed: ", "", err)
s.LogAlways("failed: %s %s, Err: %s", r.RemoteAddr, string(body), err)
return
}
scnIds := make(map[string]map[string][]string, 0)
// Group component ids by change type and new value for generating SCNs
for _, comp := range compsIn.Components {
changes, ok := changeMap[comp.ID]
if !ok {
continue
}
for change, value := range changes {
// Skip if the type of change didn't happen.
if !value {
continue
}
switch change {
case "state":
if _, ok := scnIds[change]; !ok {
scnIds[change] = make(map[string][]string, 0)
}
scnIds[change][comp.State] = append(scnIds[change][comp.State], comp.ID)
case "enabled":
if _, ok := scnIds[change]; !ok {
scnIds[change] = make(map[string][]string, 0)
}
if comp.Enabled == nil {
enabled := true
comp.Enabled = &enabled
}
str := strconv.FormatBool(*comp.Enabled)
scnIds[change][str] = append(scnIds[change][str], comp.ID)
case "swStatus":
if _, ok := scnIds[change]; !ok {
scnIds[change] = make(map[string][]string, 0)
}
scnIds[change][comp.SwStatus] = append(scnIds[change][comp.SwStatus], comp.ID)
case "role":
if _, ok := scnIds[change]; !ok {
scnIds[change] = make(map[string][]string, 0)
}
changeVal := comp.Role + "." + comp.SubRole
scnIds[change][changeVal] = append(scnIds[change][changeVal], comp.ID)
}
}
}
// Send out a SCN for each unique combination of change type and new value
for change, valMap := range scnIds {
for val, list := range valMap {
switch change {
case "state":
scn := NewJobSCN(list, base.Component{State: val}, s)
s.wp.Queue(scn)
case "enabled":
enabled, _ := strconv.ParseBool(val)
scn := NewJobSCN(list, base.Component{Enabled: &enabled}, s)
s.wp.Queue(scn)
case "swStatus":
scn := NewJobSCN(list, base.Component{SwStatus: val}, s)
s.wp.Queue(scn)
case "role":
roles := strings.Split(val, ".")
scn := NewJobSCN(list, base.Component{Role: roles[0], SubRole: roles[1]}, s)
s.wp.Queue(scn)
}
}
}
// Send 204 status (success, no content in response)
sendJsonError(w, http.StatusNoContent, "operation completed")
return
}
// Get all HMS Components under multiple parent components as named array
func (s *SmD) doComponentsQueryPost(w http.ResponseWriter, r *http.Request) {
comps := new(base.ComponentArray)
var err error
body, err := ioutil.ReadAll(r.Body)
// Get the component list
compQuery := new(CompQueryIn)
err = json.Unmarshal(body, compQuery)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
if len(compQuery.ComponentIDs) < 1 {
sendJsonError(w, http.StatusBadRequest, "Missing IDs")
return
}
// Get the query parameters
compFilter := new(hmsds.ComponentFilter)
err = json.Unmarshal(body, compFilter)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
// Get the component field filter options (i.e. stateonly)
fieldFltrIn := new(FieldFltrIn)
err = json.Unmarshal(body, fieldFltrIn)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
fieldFltr := getFieldFilter(fieldFltrIn)
comps.Components, err = s.db.GetComponentsQuery(compFilter, fieldFltr, compQuery.ComponentIDs)
if err != nil {
s.LogAlways("doComponentsQueryPost(): Lookup failure: %s", err)
sendJsonDBError(w, "bad query param: ", "", err)
return
}
sendJsonCompArrayRsp(w, comps)
}
// Get all HMS Components under a single parent component as named array
func (s *SmD) doComponentsQueryGet(w http.ResponseWriter, r *http.Request) {
comps := new(base.ComponentArray)
ids := make([]string, 0, 1)
var err error
vars := mux.Vars(r)
xname := xnametypes.NormalizeHMSCompID(vars["xname"])
// Parse arguments
if err := r.ParseForm(); err != nil {
s.lg.Printf("doComponentsQueryGet(): ParseForm: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
formJSON, err := json.Marshal(r.Form)
if err != nil {
s.lg.Printf("doComponentsQueryGet(): Marshall form: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
// Get the query parameters
compFilter := new(hmsds.ComponentFilter)
if err = json.Unmarshal(formJSON, compFilter); err != nil {
s.lg.Printf("doComponentsQueryGet(): Unmarshall form: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
// Get the component field filter options (i.e. stateonly)
fieldFltrIn := new(FieldFltrInForm)
if err = json.Unmarshal(formJSON, fieldFltrIn); err != nil {
s.lg.Printf("doComponentsQueryGet(): Unmarshall form: %s", err)
sendJsonError(w, http.StatusInternalServerError,
"failed to decode query parameters.")
return
}
fieldFltr := getFieldFilterForm(fieldFltrIn)
ids = append(ids, xname)
comps.Components, err = s.db.GetComponentsQuery(compFilter, fieldFltr, ids)
if err != nil {
s.LogAlways("doComponentsQueryGet(): Lookup failure: %s", err)
sendJsonDBError(w, "bad query param: ", "", err)
return
}
sendJsonCompArrayRsp(w, comps)
}
// Delete entire collection of ComponentEndpoints, undoing discovery.
func (s *SmD) doComponentsDeleteAll(w http.ResponseWriter, r *http.Request) {
var err error
numDeleted, err := s.db.DeleteComponentsAll()
if err != nil {
s.lg.Printf("doCompEndpointsDelete(): Delete failure: %s", err)
sendJsonError(w, http.StatusInternalServerError, "DB query failed.")
return
}
if numDeleted == 0 {
sendJsonError(w, http.StatusNotFound, "no entries to delete")
return
}
numStr := strconv.FormatInt(numDeleted, 10)
sendJsonError(w, http.StatusOK, "deleted "+numStr+" entries")
}
// Get single HMS component by NID, if it exists and is a type that has a
// NID (i.e. a node)
func (s *SmD) doComponentByNIDGet(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
xname := vars["nid"]
cmp, err := s.db.GetComponentByNID(xname)
if err != nil {
s.LogAlways("doStateComponent(): Lookup failure: (%s) %s", xname, err)
sendJsonDBError(w, "", "", err)
return
}
if cmp == nil {
sendJsonError(w, http.StatusNotFound, "no such NID.")
return
}
// Over all summary error code needs to be computed...
sendJsonCompRsp(w, cmp)
}
// Get an array of HMS component by NID, if it exists and is a type that has a
// NID (i.e. a node)
func (s *SmD) doComponentByNIDQueryPost(w http.ResponseWriter, r *http.Request) {
comps := new(base.ComponentArray)
var err error
body, err := ioutil.ReadAll(r.Body)
// Get the component list
nidQuery := new(NIDQueryIn)
err = json.Unmarshal(body, nidQuery)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
if len(nidQuery.NIDRanges) < 1 {
sendJsonError(w, http.StatusBadRequest, "Missing NID ranges")
return
}
// Get the query parameters. This is mostly
// just to pick up a partition if specified.
compFilter := new(hmsds.ComponentFilter)
err = json.Unmarshal(body, compFilter)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
// Get the component field filter options (i.e. stateonly)
fieldFltrIn := new(FieldFltrIn)
err = json.Unmarshal(body, fieldFltrIn)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
fieldFltr := getFieldFilter(fieldFltrIn)
// Reset the NID query arrays in the component filter just in case something weird happened
compFilter.NID = compFilter.NID[:0]
compFilter.NIDStart = compFilter.NIDStart[:0]
compFilter.NIDEnd = compFilter.NIDEnd[:0]
// Parse the NID ranges and add them to the compFilter
compFilter, err = nidRangeToCompFilter(nidQuery.NIDRanges, compFilter)
if err != nil {
sendJsonError(w, http.StatusBadRequest, "bad query param: "+err.Error())
return
}
comps.Components, err = s.db.GetComponentsFilter(compFilter, fieldFltr)
if err != nil {
s.LogAlways("doComponentsQueryGet(): Lookup failure: %s", err)
sendJsonDBError(w, "bad query param: ", "", err)
return
}
sendJsonCompArrayRsp(w, comps)
}
// Bulk NID patch. Unlike other patch methods, there needs to be a
// NID for each ID given, so the handling has to be a little different.
func (s *SmD) doCompBulkNIDPatch(w http.ResponseWriter, r *http.Request) {
var err error
var compsIn componentArrayIn
body, err := ioutil.ReadAll(r.Body)
err = json.Unmarshal(body, &compsIn)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
components := &compsIn.Components
if len(*components) < 1 || len((*components)[0].ID) < 1 {
sendJsonError(w, http.StatusBadRequest, "Missing Components")
return
}
err = s.db.BulkUpdateCompNID(components)
if err != nil {
sendJsonDBError(w, "operation 'Bulk Update NID' failed: ",
"", err)
s.LogAlways("failed: %s %s, Err: %s", r.RemoteAddr, string(body), err)
return
}
s.lg.Printf("succeeded: %s %s", r.RemoteAddr, string(body))
// Send 204 status (success, no content in response)
sendJsonError(w, http.StatusNoContent, "")
return
}
// Update component state and flag for a list of components
func (s *SmD) doCompBulkStateDataPatch(w http.ResponseWriter, r *http.Request) {
s.compBulkPatch(w, r, StateDataUpdate, "doCompBulkStateDataPatch")
return
}
// Update component state and flag for a list of components
func (s *SmD) doCompBulkFlagOnlyPatch(w http.ResponseWriter, r *http.Request) {
s.compBulkPatch(w, r, FlagOnlyUpdate, "doCompBulkFlagOnlyPatch")
return
}
// Update component 'Enabled' boolean for a list of components
func (s *SmD) doCompBulkEnabledPatch(w http.ResponseWriter, r *http.Request) {
s.compBulkPatch(w, r, EnabledUpdate, "doCompBulkEnabledPatch")
return
}
// Update component SoftwareStatus field for a list of components
func (s *SmD) doCompBulkSwStatusPatch(w http.ResponseWriter, r *http.Request) {
s.compBulkPatch(w, r, SwStatusUpdate, "doCompBulkSwStatusPatch")
return
}
// Update component state and flag for a list of components
func (s *SmD) doCompBulkRolePatch(w http.ResponseWriter, r *http.Request) {
s.compBulkPatch(w, r, RoleUpdate, "doCompBulkRolePatch")
return
}
// Helper function for doing a bulk patch via http. CompUpdateInvalid
// is equivalent to no default. We don't really want a default unless
// it's for backwards compatibility, or the API specifies a specific
// operation type.
func (s *SmD) compBulkPatch(
w http.ResponseWriter,
r *http.Request,
t CompUpdateType,
name string,
) {
var err error
body, err := ioutil.ReadAll(r.Body)
bulkUpdate := new(CompUpdate)
err = json.Unmarshal(body, bulkUpdate)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
return
}
s.compPatchHelper(w, r, t, name, bulkUpdate, true, body)
}
// Backend for all patch operations
func (s *SmD) compPatchHelper(
w http.ResponseWriter,
r *http.Request,
t CompUpdateType,
name string,
update *CompUpdate,
isBulk bool,
body []byte,
) {
if t != CompUpdateInvalid {
update.UpdateType = t.String()
} else {
sendJsonError(w, http.StatusBadRequest, ErrSMDNoUpType.Error())
return
}
//
// Update Database
//
err := s.doCompUpdate(update, name)
if err != nil {
op := VerifyNormalizeCompUpdateType(update.UpdateType)
if base.IsHMSError(err) {
// HMS error, ok to send directly
sendJsonError(w, http.StatusBadRequest, err.Error())
} else {
// Non-HMS error, print generic error message.
if isBulk == true {
// print generic message for bulk error
sendJsonError(w, http.StatusBadRequest, "operation 'Bulk "+
op+" Update' failed")
} else {
// Print generic error for non-bulk operations.
id := "nil"
if len(update.ComponentIDs) > 0 {
id = update.ComponentIDs[0]
}
sendJsonError(w, http.StatusBadRequest,
"operation '"+op+"' failed for "+id)
}
}
// Either way we log the real error, we just don't want to leak
// internals via user reported errors.
s.Log(LOG_INFO, "%s(%s) failed: %s %s, Err: %s",
name, op, r.RemoteAddr, string(body), err)
return
} else {
s.Log(LOG_DEBUG, "%s() succeeded: %s %s",
name, r.RemoteAddr, string(body))
}
// Send 204 status (success, no content in response)
sendJsonError(w, http.StatusNoContent, "")
return
}
// Patch the State and Flag field (latter defaults to OK) for a single
// component.
func (s *SmD) doCompStateDataPatch(w http.ResponseWriter, r *http.Request) {
s.componentPatch(w, r, StateDataUpdate, "doCompStateDataPatch")
return
}
// Patch the Flag field only (state does not change) for a single component.
func (s *SmD) doCompFlagOnlyPatch(w http.ResponseWriter, r *http.Request) {
s.componentPatch(w, r, FlagOnlyUpdate, "doCompFlagOnlyPatch")
return
}
// Patch the Enabled boolean for a single component, leaving other fields
// in place.
func (s *SmD) doCompEnabledPatch(w http.ResponseWriter, r *http.Request) {
s.componentPatch(w, r, EnabledUpdate, "doCompEnabledPatch")
return
}
// Patch the SoftwareStatus field for a single component, leaving other
// fields in place.
func (s *SmD) doCompSwStatusPatch(w http.ResponseWriter, r *http.Request) {
s.componentPatch(w, r, SwStatusUpdate, "doCompSwStatusPatch")
return
}
// Patch the Role field for a single component, leaving other fields in place.
func (s *SmD) doCompRolePatch(w http.ResponseWriter, r *http.Request) {
s.componentPatch(w, r, RoleUpdate, "doCompRolePatch")
return
}
// Update the NID (Node ID) for a single component, leaving other fields
// in place.
func (s *SmD) doCompNIDPatch(w http.ResponseWriter, r *http.Request) {
s.componentPatch(w, r, SingleNIDUpdate, "doCompNIDPatch")
return
}
// Scan function to keep compatibility with API, though we don't really
// need the ID field as it is filled in by the URL for single component
// patch operations.
type compPatchIn struct {
ID string `json:"ID"`
CompUpdate // embedded struct
}
// Helper function to swap the state-change API in HTTP for single
// component updates.
func (s *SmD) componentPatch(
w http.ResponseWriter,
r *http.Request, t CompUpdateType,
name string,
) {
vars := mux.Vars(r)
xname := vars["xname"]
var update compPatchIn
body, err := ioutil.ReadAll(r.Body)
err = json.Unmarshal(body, &update)
if err != nil {
sendJsonError(w, http.StatusInternalServerError,
"error decoding JSON "+err.Error())
s.Log(LOG_INFO, "%s() Got json error: '%s'", name, err)
return
}
// Get the ID from the path. It should never be empty.
if update.ID == "" {
if xname == "" {
sendJsonError(w, http.StatusBadRequest, ErrSMDNoID.Error())
return