-
Notifications
You must be signed in to change notification settings - Fork 5
/
rfevent.go
1230 lines (1155 loc) · 39.8 KB
/
rfevent.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 [2019-2024] 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"
"fmt"
"strings"
"sync"
base "github.com/Cray-HPE/hms-base/v2"
"github.com/Cray-HPE/hms-xname/xnametypes"
"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"
)
var em = base.NewHMSError("sm.msgbus", "internal error")
var ErrSmMsgNoPayload = em.NewChild("empty event payload")
var ErrSmMsgBadDecode = em.NewChild("payload failed to decode")
var ErrSmMsgBadProcess = em.NewChild("event failed processing")
var ErrSmMsgNilEvent = em.NewChild("nil Event")
var ErrSmMsgNilEventRec = em.NewChild("nil EventRecord")
var ErrSmMsgNilProcRFE = em.NewChild("nil processedRFEvent")
var ErrSmMsgNoIDCtx = em.NewChild("no xname ID in any context")
var ErrSmMsgNoMsgId = em.NewChild("no MessageId found")
var ErrSmMsgBadID = em.NewChild("target xname ID is not valid")
var ErrSmMsgNoID = em.NewChild("no target xname ID found")
var ErrSmMsgNoURI = em.NewChild("no target URI found")
var ErrSmMsgNoEP = em.NewChild("no target ComponentEndpoint ID found")
var ErrSmMsgNoCreds = em.NewChild("no target component credentials found")
var ErrSmMsgRFFail = em.NewChild("redfish call failed")
var ErrSmMsgRFNoInfo = em.NewChild("no info from redfish")
var ErrSmMsgCredsStore = em.NewChild("failed to get credentials from secure store")
var ErrSmMsgCredsDB = em.NewChild("failed to get credentials from database")
var ErrSmMsgIgnState = em.NewChild("ignored state change type")
var ErrSmMsgBadCached = em.NewChild("bad decode of cached type from interface")
var ErrSmMsgNoPowerState = em.NewChild("missing power state value")
var ErrSmMsgMissedSync = em.NewChild("unexpectedly missing after sync")
var ErrSmMsgFiltered = em.NewChild("message(s) filtered due to wrong type")
type processedRFEvent struct {
MessageId string
SubLabels []string
Registry string
RegVersion string
RfEndppointID string
Origin string
Severity string
Message string
MessageArgs []string
}
// Take a string-encoded Redfish Event from the message bus and take
// the appropriate action (if any), as far as state changes or actions.
// Call once per event. Do not retry on error unless specifically told
// to do so.
func (s *SmD) doHandleRFEvent(eventRaw string) error {
if eventRaw == "" {
return ErrSmMsgNoPayload
}
// Decode Redfish Event from raw input. Should never be nil on non-error.
e, err := rf.EventDecode([]byte(eventRaw))
if err != nil {
// Don't abort. The error might be in a field we don't need.
// It will generally fill in everything it can.
s.Log(LOG_INFO, "warning: doHandleRFEvent: '%s': '%s'", err, eventRaw)
}
// Process the Redfish event into normalized form that hides the
// underlying implementation.
pes, err := s.processRFEvent(e)
if err != nil {
// Should rarely return errors unless something is really screwed up.
// We expect to get a lot of the wrong kind of error and we normally
// just ignore (and possibly log) them.
return err
}
if len(pes) > 0 {
s.Log(LOG_DEBUG, "Received event: '%s'", eventRaw)
}
for _, pe := range pes {
update, err := s.compUpdateFromRFEvent(pe)
if err != nil {
s.Log(LOG_INFO, "handleRFEvent: getting CompUpdate: '%s' ", err)
continue
} else if update == nil {
continue
}
s.Log(LOG_INFO, "CHANGING STATE: %s->%s: calling doCompUpdate(%s)",
pe.RfEndppointID, pe.MessageId, update.ComponentIDs)
err = s.doCompUpdate(update, "handleRFEvent")
if err != nil {
s.LogAlways("ERROR: %s->%s: calling doCompUpdate(%s): %s",
pe.RfEndppointID, pe.MessageId, update.ComponentIDs, err)
}
}
return nil
}
/////////////////////////////////////////////////////////////////////////////
// Normalization of raw Events into processedRFEvent structs that hide
// individual Redfish implementation details.
//
// Most of the event decoding logic goes here and there will probably
// need to be updates when new Redfish stacks are introduced.
/////////////////////////////////////////////////////////////////////////////
// Take a Redfish JSON event, decoded into a struct, and produce a
// decodedRFEvent struct or structs depending on whether multiple independent
// EventRecords require separate actions.
//
// This normalizes the implementation differences of individual events and
// processes them into a form that allows State Manager to treat all events
// the same basic way.
//
func (s *SmD) processRFEvent(e *rf.Event) ([]*processedRFEvent, error) {
pes := make([]*processedRFEvent, 0, 1) // Returned array
if e == nil {
return pes, ErrSmMsgNilEvent
}
for i, erec := range e.Events {
pe, err := s.processRFEventRecord(e, &erec)
if err != nil {
// We ignore errors, but report them unless they're things
// we don't care about.
if err == ErrSmMsgNoIDCtx {
s.Log(LOG_INFO, "Event: %s: '%s'/'%s'",
err, e.Context, erec.Context)
} else if err != ErrSmMsgFiltered {
s.Log(LOG_INFO, "EventRecord %d: %s: '%v'", i, err, e)
}
continue
}
pes = append(pes, pe)
}
return pes, nil
}
// Processes one individual EventRecord 'erec', in an event 'e'.
func (s *SmD) processRFEventRecord(
e *rf.Event,
erec *rf.EventRecord,
) (*processedRFEvent, error) {
if e == nil || erec == nil {
return nil, ErrSmMsgNilEventRec
}
// Start processing the event.
reg, ver, msgid := rf.EventRecordMsgId(erec)
if msgid == "" {
// No message id, can't identify event
return nil, ErrSmMsgNoMsgId
} else if ignoredRegistry(reg) {
return nil, ErrSmMsgFiltered
}
id, labels := GetEventIDAndLabels(e.Context, erec.Context)
if id == "" {
// No controller ID found.
return nil, ErrSmMsgNoIDCtx
}
// Enough info to process event,
pe := new(processedRFEvent)
pe.RfEndppointID = id
pe.SubLabels = labels
pe.Registry = reg
pe.RegVersion = ver
pe.MessageId = msgid
pe.Message = erec.MessageId
pe.MessageArgs = erec.MessageArgs
pe.Origin = erec.OriginOfCondition.Oid
pe.Severity = erec.Severity
return pe, nil
}
// Filter registries - Things we know we don't care about
func ignoredRegistry(reg string) bool {
switch strings.ToLower(reg) {
case "craytelemetry":
return true
}
return false
}
// This is not Redfish-driven. The context can be anything we choose, so we
// must standardize where controller xname ID in it and what the separator is.
// We capture additional tags as an array for now.
// We currently expect the xname to be first, however, we can optionally
// check (anyXName=true) every subfield, and choose the first that is a valid
// xname (for a controller)
func EventContextDecode(
context string,
anyXName bool,
) (xnameID string, subLabels []string) {
subLabels = make([]string, 0, 1)
// ":" is used after the field separator
fields := strings.Split(context, ":")
for i, field := range fields {
setID := false
if i == 0 || (xnameID == "" && anyXName == true) {
normField := xnametypes.NormalizeHMSCompID(field)
if xnametypes.IsHMSTypeController(xnametypes.GetHMSType(normField)) {
xnameID = normField
setID = true
}
}
// If not xname ID, add to generic list
if setID == false {
subLabels = append(subLabels, field)
}
}
return
}
// This is a version of EventContextDecode that looks at both potential
// context fields, the Event and an invididual EventRecord. We should
// only have one, but this hides the logic of what's what.
func GetEventIDAndLabels(eCtx, rCtx string) (id string, labels []string) {
// First time, only check for xname ID of controller in expected place.
eID, eLabels := EventContextDecode(eCtx, false)
rID, rLabels := EventContextDecode(rCtx, false)
if eID == "" && rID == "" {
// No xname IDs, be less picky about where the xname ID is
eID, eLabels = EventContextDecode(eCtx, true)
rID, rLabels = EventContextDecode(rCtx, true)
}
if eID != "" {
id = eID
labels = eLabels
} else if rID != "" {
id = rID
labels = rLabels
}
return id, labels
}
/////////////////////////////////////////////////////////////////////////////
// Generate Component state change, if needed.
/////////////////////////////////////////////////////////////////////////////
// Turn a processed RF event into a state change request that can be
// submitted
func (s *SmD) compUpdateFromRFEvent(pe *processedRFEvent) (*CompUpdate, error) {
if pe == nil {
return nil, ErrSmMsgNilProcRFE
}
action := s.GetEventActionParser(pe)
if action == nil {
return nil, nil
}
return action(s, pe)
}
/////////////////////////////////////////////////////////////////////////////
// EventActionParser - Lookup table and parsers
//
// This is where changes in logic due to new implementations and events go.
// we just
/////////////////////////////////////////////////////////////////////////////
// Handler prototype for the lookup function below
type EventActionParser func(*SmD, *processedRFEvent) (*CompUpdate, error)
// Lookups go from most general to most specific. If a more general
// lookup is ambiguous, that is the signal to keep trying with a
// more specific key. Unfortunately, we can't compare functions, except with
// nil, we can't use special function names to describe the next step. So
// calls that need disambiguation need to return nil for each ambiguous level.
//
// Level 0: Just MessageId, no version or Registry.
// Level 1: if just messageId nil, try again with MessageId:Registry
// Level 2: If messageId + reg also nil, try again with MessageId:Registry:vers
// where vers is :1 for 1.0 or 1.0.1
// Level 3: Version is still not specific enough. They again with
// MessageId:Registry:vers, but this time include maj version, i.e. 1.1
//
var eventActionParserLookup = map[string]EventActionParser{
"resourcepowerstatechanged": nil,
"resourcepowerstatechanged:resourceevent": ResourcePowerStateChangedParser,
"resourcepowerstatechanged:crayalerts": ResourcePowerStateChangedParser,
"resourcepowerstatechanged:": ResourcePowerStateChangedParser,
"systempoweron": AlertSystemPowerOnParser,
"systempoweroff": AlertSystemPowerOffParser,
"alert": AlertSystemPowerParser,
"powerstatuschange": AlertSystemPowerParser,
"serverpoweredon": AlertSystemPowerOnParser,
"serverpoweredoff": AlertSystemPowerOffParser,
}
// Gets the EventActionParser function for the processed event or returns
// noActionFound
func (s *SmD) GetEventActionParser(pe *processedRFEvent) EventActionParser {
lookup := pe.MessageId
// We may need to repeat the lookup a small number of times with
// additional info to disambiguate. This keeps the table much
// more compact.
for level := 1; level <= 3; level++ {
action, ok := eventActionParserLookup[strings.ToLower(lookup)]
if ok != true {
// No match at all, not even a nil pointer to keep trying.
// No action for event.
return nil
}
// Determine if another lookup is needed and include the requested key.
if action == nil {
switch level {
case 1:
lookup = pe.MessageId + ":" + pe.Registry
case 2:
vers, _ := rf.VersionFields(pe.RegVersion, ".", 1)
lookup = pe.MessageId + ":" + pe.Registry + ":" + vers
case 3:
vers, incl := rf.VersionFields(pe.RegVersion, ".", 2)
if incl != 2 {
// Don't have this, leave it empty
vers = ""
}
lookup = pe.MessageId + ":" + pe.Registry + ":" + vers
}
} else {
// Match - return parser
return action
}
}
// Shouldn't get here, to many levels of nil function entries. But
// assume that means we didn't find it.
return nil
}
/////////////////////////////////////////////////////////////////////////////
// ResourceEvents - Right now just for Cray hardware.
/////////////////////////////////////////////////////////////////////////////
type ResourceOp string
const (
ResourceOn ResourceOp = "on"
ResourceOff ResourceOp = "off"
ResourceUnknown ResourceOp = "unknown"
ResourceOther ResourceOp = "other"
)
// EventActionParser - ResourcePowerStateChanged - Cray addition to standard
// ResourceEvent registry. Need to look at payload to see
// new state and component type.
func ResourcePowerStateChangedParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) {
// Parse the arguments. Arg1 should be the URI for the component,
// and Arg2 the state. But take them in either order. And if there
// is no URI, use the origin.
uri := pe.Origin
op := ResourceUnknown
for _, arg := range pe.MessageArgs {
if strings.HasPrefix(arg, "/") == true {
uri = arg
} else {
switch strings.ToLower(strings.TrimSpace(arg)) {
case string(ResourceOn):
op = ResourceOn
case string(ResourceOff):
op = ResourceOff
}
}
}
// If the state is not off or on, ignore it. PoweringOn/Off is
// not used here. In HSM, it means something is actively trying to
// turn it on. But at the Redfish level, we don't care until it is
// actually on or off.
if op == ResourceUnknown {
return nil, ErrSmMsgIgnState
} else if uri == "" {
return nil, ErrSmMsgNoURI
}
xname, err := s.getIDForURI(pe.RfEndppointID, uri)
if err != nil {
return nil, err
} else if xname == "" {
s.Log(LOG_INFO, "ResourcePowerStateChangedParser(%s, %s): Not found.",
pe.RfEndppointID, uri)
return nil, ErrSmMsgNoID
}
// We already know the target, but we might need to affect other
// components if it is a power off operation, depending on the
// type of component affected, e.g. slot, etc.
switch xnametypes.GetHMSType(pe.RfEndppointID) {
case xnametypes.ChassisBMC:
return powerStateCMM(s, pe, xname, op)
case xnametypes.NodeBMC:
return powerStateNC(s, pe, xname, op)
case xnametypes.RouterBMC:
return powerStateRC(s, pe, xname, op)
case xnametypes.CabinetPDUController:
return powerStateCabPDUController(s, pe, xname, op)
default:
return nil, ErrSmMsgBadID
}
}
// Helper for ResourcePowerStateChangedParser - CMM changes
func powerStateCMM(s *SmD, pe *processedRFEvent,
xname string,
op ResourceOp,
) (*CompUpdate, error) {
u := new(CompUpdate)
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
switch op {
case ResourceOn:
u.State = base.StateOn.String()
case ResourceOff:
u.State = base.StateOff.String()
default:
// Should never happen.
return u, ErrSmMsgNoPowerState
}
switch xnametypes.GetHMSType(xname) {
case xnametypes.ComputeModule:
ids := generateNcChildIDs(s, xname, op)
u.ComponentIDs = append(u.ComponentIDs, ids...)
case xnametypes.RouterModule:
ids := generateRcChildIDs(s, xname, op)
u.ComponentIDs = append(u.ComponentIDs, ids...)
}
// Kick off rediscovery for any BMCs that are getting powered on.
// This may fail at first if the BMC isn't ready yet but the
// LastDiscoveryStatus will get changed to a failed state which will
// cause a retry later.
if u.State == base.StateOn.String() {
for _, id := range u.ComponentIDs {
if xnametypes.IsHMSTypeController(xnametypes.GetHMSType(id)) {
rep, err := s.db.GetRFEndpointByID(id)
if err != nil {
s.Log(LOG_INFO, "powerStateCMM(): Lookup failure on %s: %s", id, err)
} else if rep != nil {
go s.discoverFromEndpoint(rep, 0, false)
}
}
}
}
return u, nil
}
// Helper function for ResourcePowerStateChangedParser - nC changes
func powerStateNC(s *SmD, pe *processedRFEvent,
xname string,
op ResourceOp,
) (*CompUpdate, error) {
u := new(CompUpdate)
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
switch op {
case ResourceOn:
u.State = base.StateOn.String()
// Update hwinv for nodes
if xnametypes.GetHMSType(xname) == xnametypes.Node {
cep, ep, err := s.getCompEPInfo(xname)
if err == nil {
go s.doUpdateCompHWInv(cep, ep)
}
}
case ResourceOff:
u.State = base.StateOff.String()
}
return u, nil
}
// Helper for ResourcePowerStateChangedParser - sC/TOR changes
func powerStateRC(s *SmD, pe *processedRFEvent,
xname string,
op ResourceOp,
) (*CompUpdate, error) {
u := new(CompUpdate)
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
switch op {
case ResourceOn:
u.State = base.StateOn.String()
case ResourceOff:
u.State = base.StateOff.String()
}
return u, nil
}
// Helper for ResourcePowerStateChangedParser - PDU (RTS) changes.
func powerStateCabPDUController(s *SmD, pe *processedRFEvent,
xname string,
op ResourceOp,
) (*CompUpdate, error) {
u := new(CompUpdate)
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
switch op {
case ResourceOn:
u.State = base.StateOn.String()
case ResourceOff:
u.State = base.StateOff.String()
}
return u, nil
}
// The database will ignore any ids that don't exist, do them all.
// If ResourceOn only include up controllers/cards themselves, other
// If ResourceOff include all nodes and other subcomponents.
// This ASSUMES xname is a valid ComputeModule and Mountain slot.
func generateNcChildIDs(s *SmD, xname string, op ResourceOp) []string {
maxNCs := 4
ids := []string{}
if op != ResourceOn && op != ResourceOff {
// shouldn't happen
return ids
}
for i := 0; i < maxNCs; i++ {
// Get nth BMC for slot xname
id := fmt.Sprintf("%sb%d", xname, i) // NodeBMC
// Get children from database, syncing if necessary.
children, err := s.getChildIDsForRfEP(id)
if err != nil {
if err != ErrSmMsgBadID {
// Bad ID errors are expected here as we are talking about
// a child controller.
s.LogAlways("generateNcChildIDs(%s, %s): DB error: %s",
xname, id, err)
}
continue
}
if op == ResourceOn {
// Only turn the cards on, not the nodes, when slot comes up.
for _, childID := range children {
switch xnametypes.GetHMSType(childID) {
case xnametypes.NodeEnclosure:
fallthrough
case xnametypes.NodeBMC:
fallthrough
case xnametypes.NodeBMCNic:
ids = append(ids, childID)
}
}
} else if op == ResourceOff {
ids = append(ids, children...)
}
}
return ids
}
// Generate all subcomponents for a Mountain router slot.
// The database will ignore any ids that don't exist, do them all.
// This ASSUMES xname is a valid RouterModule and Mountain slot.
func generateRcChildIDs(s *SmD, xname string, op ResourceOp) []string {
maxControllers := 1
ids := []string{}
for i := 0; i < maxControllers; i++ {
id := fmt.Sprintf("%sb%d", xname, i) // RouterBMC
// Get children from database, syncing if necessary.
children, err := s.getChildIDsForRfEP(id)
if err != nil {
if err != ErrSmMsgBadID {
// Bad ID errors are expected here as we are talking about
// a child controller.
s.LogAlways("generateRcChildIDs(%s, %s): DB error: %s",
xname, id, err)
}
continue
}
ids = append(ids, children...)
}
return ids
}
/////////////////////////////////////////////////////////////////////////////
// Intel BMC firmware & HPE iLo
/////////////////////////////////////////////////////////////////////////////
// EventActionParser - Alert, presumably from Intel BMC, that indicates
// System (i.e. node) powered ON.
// Id in OriginOfCondition (though likely single node).
func AlertSystemPowerOnParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) {
u := new(CompUpdate)
xname, err := s.getIDForURI(pe.RfEndppointID, pe.Origin)
if err != nil {
return nil, err
} else if xname == "" {
return nil, ErrSmMsgNoID
}
// Update hwinv for nodes
if xnametypes.GetHMSType(xname) == xnametypes.Node {
cep, ep, err := s.getCompEPInfo(xname)
if err == nil {
go s.doUpdateCompHWInv(cep, ep)
}
}
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
u.State = base.StateOn.String()
return u, nil
}
// EventActionParser - Alert, presumably from Intel BMC, that indicates
// System (i.e. node) powered OFF.
// Id in OriginOfCondition (though likely single node).
func AlertSystemPowerOffParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) {
u := new(CompUpdate)
xname, err := s.getIDForURI(pe.RfEndppointID, pe.Origin)
if err != nil {
return nil, err
} else if xname == "" {
return nil, ErrSmMsgNoID
}
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
u.State = base.StateOff.String()
return u, nil
}
/////////////////////////////////////////////////////////////////////////////
// Gigabyte BMC firmware
/////////////////////////////////////////////////////////////////////////////
// AlertSystemPowerParser - Alert, presumably from Gigabyte BMC, that indicates
// System (i.e. node) powered ON or OFF.
// Id in OriginOfCondition (though likely single node).
func AlertSystemPowerParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) {
var (
cep *sm.ComponentEndpoint
ep *rf.RedfishEP
)
// Parse the arguments. Arg1 should be the URI for the component,
// and Arg2 the state. But take them in either order. And if there
// is no URI, use the origin. If there is no State reachout to the
// component via redfish to get it.
uri := pe.Origin
op := ResourceUnknown
for _, arg := range pe.MessageArgs {
if strings.HasPrefix(arg, "/") == true {
uri = arg
} else {
switch strings.ToLower(strings.TrimSpace(arg)) {
case string(ResourceOn):
op = ResourceOn
case string(ResourceOff):
op = ResourceOff
default:
op = ResourceOther
}
}
}
// If the state is not off or on, ignore it. PoweringOn/Off is
// not used here. In HSM, it means something is actively trying to
// turn it on. But at the Redfish level, we don't care until it is
// actually on or off. If there isn't a state in the msg, we'll go
// ping it.
if op == ResourceOther {
return nil, ErrSmMsgIgnState
} else if uri == "" {
return nil, ErrSmMsgNoURI
}
xname, err := s.getIDForURI(pe.RfEndppointID, uri)
if err != nil {
return nil, err
} else if xname == "" {
s.Log(LOG_INFO, "AlertSystemPowerParser(%s, %s): Not found.",
pe.RfEndppointID, uri)
return nil, ErrSmMsgNoID
}
if op == ResourceUnknown || op == ResourceOn {
cep, ep, err = s.getCompEPInfo(xname)
if err != nil {
return nil, err
}
}
// There was no state in the redfish event. We have to go get it.
if op == ResourceUnknown {
ps, err := s.getCompEPState(cep, ep)
if err != nil {
return nil, err
}
switch strings.ToLower(ps) {
case string(ResourceOn):
op = ResourceOn
case string(ResourceOff):
op = ResourceOff
default:
return nil, ErrSmMsgIgnState
}
}
u := new(CompUpdate)
u.ComponentIDs = append(u.ComponentIDs, xname)
u.UpdateType = StateDataUpdate.String()
switch op {
case ResourceOn:
u.State = base.StateOn.String()
if xnametypes.GetHMSType(xname) == xnametypes.Node {
go s.doUpdateCompHWInv(cep, ep)
}
case ResourceOff:
u.State = base.StateOff.String()
}
return u, nil
}
// getCompEPInfo - This gathers the existing ComponentEndpoint and credentials
// present in either the secure store or the database (if
// secure store is not enabled) for the xname.
//
func (s *SmD) getCompEPInfo(xname string) (*sm.ComponentEndpoint, *rf.RedfishEP, error) {
var (
user string
pw string
)
cep, err := s.getCompEPbyID(xname)
if err != nil {
return nil, nil, err
} else if cep == nil {
s.Log(LOG_INFO, "GetCompEPInfo(%s): ComponentEndpoint not found.", xname)
return nil, nil, ErrSmMsgNoEP
}
if s.readVault {
// Read component endpoint credentials from the secure store.
cred, err := s.ccs.GetCompCred(xname)
if err != nil {
if strings.Contains(err.Error(), "Code: 404") {
// Ignore if there are no credentials in vault for the component
s.Log(LOG_INFO, "GetCompEPInfo(%s): No credentials in Vault - %s",
xname, err)
return nil, nil, ErrSmMsgNoCreds
} else {
s.Log(LOG_INFO, "GetCompEPInfo(%s): Failed to get credentials from Vault - %s",
xname, err)
return nil, nil, ErrSmMsgCredsStore
}
}
user = cred.Username
pw = cred.Password
} else {
// get credentials from the database redfishendpoints
rep, err := s.db.GetRFEndpointByID(cep.RfEndpointID)
if err != nil {
s.Log(LOG_INFO, "GetCompEPInfo(%s): Lookup failure: %s", xname, err)
return nil, nil, ErrSmMsgCredsDB
}
if rep == nil {
s.Log(LOG_INFO, "GetCompEPInfo(%s): No credentials in the database for %s",
xname, cep.RfEndpointID)
return nil, nil, ErrSmMsgNoCreds
}
user = rep.User
pw = rep.Password
}
// Minimally populate a redfish description struct
rfEPType := xnametypes.GetHMSType(cep.RfEndpointID)
epDesc := rf.RedfishEPDescription{
ID: cep.RfEndpointID,
Type: rfEPType.String(),
FQDN: cep.RfEndpointFQDN,
User: user,
Password: pw,
}
// Make a RedfishEP struct to make our redfish call against.
ep, err := rf.NewRedfishEp(&epDesc)
return cep, ep, err
}
// getCompEPState - Get the redfish powerstate of a component, presumably a
// Node. This uses the existing ComponentEndpoint and
// credentials as gathered by getCompEPInfo() for the xname to
// check the power state of the component via redfish.
func (s *SmD) getCompEPState(cep *sm.ComponentEndpoint, ep *rf.RedfishEP) (string, error) {
if cep == nil || ep == nil {
return "", ErrSmMsgNoEP
}
// Make a RedfishEP struct to make our redfish call against.
url := cep.RfEndpointFQDN + cep.OdataID
rfJSON, err := ep.GETRelative(cep.OdataID)
if err != nil {
s.Log(LOG_INFO, "GetCompEPState(%s): redfish call failed: %s: %s",
cep.ID, url, err)
return "", err
}
// Parse the data that we received
rfData := new(rf.ComputerSystem)
if err := json.Unmarshal(rfJSON, &rfData); err != nil {
if rf.IsUnmarshalTypeError(err) {
s.Log(LOG_INFO, "GetCompEPState(%s): bad field(s) skipped: %s: %s",
cep.ID, url, err)
} else {
s.Log(LOG_INFO, "GetCompEPState(%s): json decode failed: %s: %s",
cep.ID, url, err)
return "", err
}
}
return rfData.PowerState, nil
}
// doUpdateCompHWInv - Update the hwinv for a component, presumably a Node.
// This uses the existing ComponentEndpoint and credentials
// as gathered by getCompEPInfo() for the xname to update
// the HW Inventory data for the Component with info
// gathered.
func (s *SmD) doUpdateCompHWInv(cep *sm.ComponentEndpoint, ep *rf.RedfishEP) error {
if cep == nil || ep == nil {
return ErrSmMsgNoEP
}
// Update the node info under the redfish endpoint
if xnametypes.GetHMSType(cep.ID) == xnametypes.Node {
// Read from redfish
status := ep.GetSystems()
if status != rf.HTTPsGetOk {
s.Log(LOG_INFO, "doUpdateCompHWInv(%s): Failed to get system info: %s",
cep.ID, status)
return ErrSmMsgRFFail
}
// Process redfish data
if err := ep.VerifySystems(); err != nil {
s.Log(LOG_INFO, "doUpdateCompHWInv(%s): Systems verification failed: %s",
cep.ID, err)
return err
}
// Discover hardware inventory from redfish data
hwlocs, err := s.DiscoverHWInvByLocArray(ep)
if err != nil {
if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported {
// Non-fatal, one or more components wasn't supported. Likely to
// recur if discovery re-run.
s.Log(LOG_INFO, "DiscoverHWInvByLocArray(%s): One or more: %s",
cep.ID, err)
} else {
s.Log(LOG_INFO, "DiscoverHWInvByLocArray(%s): Fatal error storing: %s",
cep.ID, err)
return err
}
}
// Only insert the discovered locs for the node we're concerned about.
// This will cut down on database concurrency issues.
nodehls := make([]*sm.HWInvByLoc, 0, 1)
for _, hl := range hwlocs {
if strings.Contains(hl.ID, cep.ID) {
nodehls = append(nodehls, hl)
}
}
err = s.db.InsertHWInvByLocs(nodehls)
if err != nil {
s.Log(LOG_INFO, "doUpdateCompHWInv(%s): Failed to update hwinv: %s",
cep.ID, err)
}
// Generate hardware history
err = s.GenerateHWInvHist(nodehls)
if err != nil {
s.Log(LOG_INFO, "doUpdateCompHWInv(%s): Failed to update hwinv history: %s",
cep.ID, err)
}
}
return nil
}
/////////////////////////////////////////////////////////////////////////////
//
// Cached DB lookups
//
/////////////////////////////////////////////////////////////////////////////
// Prototype function for creating a type-specific SyncMap.
type SMapBuildFunc func(*SyncMap) error
// This is a Syncronized cache with two levels. A direct lookup of
// objects by their primary key, and an indirect lookup that allows a
// primary key to be looked up via some other value that can be
// reduced to a string so we can look it up quickly via a map.
type SyncMap struct {
rwLock sync.RWMutex
valStore map[string]interface{}
syncNum int
keyLookup map[string]string
f SMapBuildFunc
}
// Creates a new SyncMap with the given function for creating the mapping,
// i.e. specific to a particular data type. This does not actually create
// the mapping. This will be done when TrySync is first called, typically
// when the first read fails and we want to make sure we try it again with
// synched data.
func NewSyncMap(f SMapBuildFunc) *SyncMap {
smap := new(SyncMap)
smap.valStore = make(map[string]interface{})
smap.syncNum = 0
smap.keyLookup = make(map[string]string)
smap.f = f
return smap
}
// Read the current update number after making sure we are ordered
// before or after a sync.
func (smap *SyncMap) GetSyncNum() int {
smap.rwLock.RLock()
defer smap.rwLock.RUnlock()
return smap.syncNum
}
// Based on last read, try to update the mapping if it has not already
// been updated since that read completed (returning syncNum).
// Should return now-current syncNum (>= input value) or the original
// number plus an error.
//
// TODO: Call this periodically so missing entries are purged. This is
// less critical since state changes will be ignored if component is
// empty. This also leads to fewer syncs.
func (smap *SyncMap) TrySync(syncNum int) (bool, int, error) {
smap.rwLock.Lock()
defer smap.rwLock.Unlock()
if smap.syncNum != syncNum {
return false, smap.syncNum, nil
}
err := smap.f(smap)
if err != nil {
return false, smap.syncNum, err
}
smap.syncNum += 1
return true, smap.syncNum, nil
}
// Get the primary key for a stored object based on a lookup string
func (smap *SyncMap) LookupKey(queryKey string) (string, int) {
smap.rwLock.RLock()
defer smap.rwLock.RUnlock()
value, ok := smap.keyLookup[queryKey]
if !ok {
return "", smap.syncNum
}
return value, smap.syncNum
}
// Get the stored data type by it's primary key
func (smap *SyncMap) LookupValue(key string) (interface{}, int) {
smap.rwLock.RLock()
defer smap.rwLock.RUnlock()
value, ok := smap.valStore[key]
if !ok {
return nil, smap.syncNum
}
return value, smap.syncNum
}
/////////////////////////////////////////////////////////////////////////////
// Cached DB lookups - ComponentEndpoints
/////////////////////////////////////////////////////////////////////////////
const CompEPQueryKeyChildren = "children"
const CompEPSyncRetries = 3
// This creates a ComponentEndpoint mapping, with keys that can be
// looked up by the parent RedfishEndpoint plus the Redfish URI.
// It is used for reverse lookups in events, at least where the
// events contain the proper origin information as the OriginOfCondition
// or as one of the MessageArgs.
//
// Other mappings are possible where needed, but we really want to avoid
// assuming the xname, as we don't necessarily want to depend on the
// index starting at zero or one. This is even more important for
// things like (Redfish) Chassis, where the name is often ambiguous
// across different implementations.
func ComponentEndpointSMap(s *SmD) SMapBuildFunc {
return func(smap *SyncMap) error {
ceps, err := s.db.GetCompEndpointsAll()
if err != nil {
return err
}
smap.valStore = make(map[string]interface{})
smap.keyLookup = make(map[string]string)
for _, cep := range ceps {
// Add to ComponentEndpoint array, keyed on each member's xname ID
smap.valStore[cep.ID] = cep