-
Notifications
You must be signed in to change notification settings - Fork 3
/
rfendpoints.go
2026 lines (1883 loc) · 69.8 KB
/
rfendpoints.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-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 rf
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"path"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode"
base "github.com/Cray-HPE/hms-base"
"github.com/Cray-HPE/hms-certs/pkg/hms_certs"
)
const PKG_VERSION = "0.2"
// Error codes for problems obtaining data from remote RF endpoints.
const (
DiscoveryStarted = "DiscoveryStarted"
EndpointInvalid = "EndpointInvalid"
EPResponseFailedDecode = "EPResponseFailedDecode"
HTTPsGetFailed = "HTTPsGetFailed"
HTTPsGetOk = "HTTPsGetOk"
NoEthIfacesFound = "NoEthIfacesFound"
NotYetQueried = "NotYetQueried"
VerifyingData = "VerifyingData"
VerificationFailed = "VerificationFailed"
ChildVerificationFailed = "ChildVerificationFailed"
RedfishSubtypeNoSupport = "RedfishSubtypeNoSupport"
EndpointTypeNotSupported = "EndpointTypeNotSupported"
EndpointNotEnabled = "EndpointNotEnabled"
DiscoverOK = "DiscoverOK"
StoreFailed = "StoreFailed"
UnexpectedErrorPreStore = "UnexpectedErrorPreStore"
)
// These are types of structures in rfendpoints that are built upon
// the underlying Redfish type of the same name.
const (
ServiceRootType = "ServiceRoot"
ChassisType = "Chassis"
ComputerSystemType = "ComputerSystem"
EthernetInterfaceType = "EthernetInterface"
ManagerType = "Manager"
MemoryType = "Memory"
ProcessorType = "Processor"
DriveType = "Drive"
StorageGroupType = "StorageGroup"
PowerSupplyType = "PowerSupply"
PowerType = "Power"
NodeAccelRiserType = "GPUSubsystem"
AssemblyType = "Assembly"
HpeDeviceType = "HpeDevice"
OutletType = "Outlet"
PDUType = "PowerDistribution"
NetworkAdapterType = "NetworkAdapter"
AccountServiceType = "AccountService"
EventServiceType = "EventService"
LogServiceType = "LogService"
SessionServiceType = "SessionService"
TaskServiceType = "TaskService"
UpdateServiceType = "UpdateService"
)
// Redfish object subtypes, i.e. {type-name}Type,
// For example, ChassisType, ManagerType, etc.
const (
RFSubtypeRack = "Rack"
RFSubtypeBlade = "Blade"
RFSubtypeEnclosure = "Enclosure"
RFSubtypeStandAlone = "StandAlone"
RFSubtypeRackMount = "RackMount"
RFSubtypeCard = "Card"
RFSubtypeCartridge = "Cartridge"
RFSubtypeRow = "Row"
RFSubtypePod = "Pod"
RFSubtypeExpansion = "Expansion"
RFSubtypeSidecar = "Sidecar"
RFSubtypeZone = "Zone"
RFSubtypeSled = "Sled"
RFSubtypeShelf = "Shelf"
RFSubtypeDrawer = "Drawer"
RFSubtypeModule = "Module"
RFSubtypeComponent = "Component"
RFSubtypeOther = "Other"
RFSubtypePhysical = "Physical"
RFSubtypeVirtual = "Virtual"
RFSubtypeOS = "OS"
RFSubtypePhysicallyPartitioned = "PhysicallyPartitioned"
RFSubtypeVirtuallyPartitioned = "VirtuallyPartitioned"
RFSubtypeManagementController = "ManagementController"
RFSubtypeEnclosureManager = "EnclosureManager"
RFSubtypeBMC = "BMC"
RFSubtypeRackManager = "RackManager"
RFSubtypeAuxiliaryController = "AuxiliaryController"
// PDU Types
RFSubtypeRackPDU = "RackPDU"
RFSubtypeFloorPDU = "FloorPDU"
RFSubtypeManualTransferSwitch = "ManualTransferSwitch"
RFSubtypeAutomaticTransferSwitch = "AutomaticTransferSwitch"
// Outlet types
RFSubtypeOutNEMA_5_15R = "NEMA_5_15R"
RFSubtypeOutNEMA_5_20R = "NEMA_5_20R"
RFSubtypeOutNEMA_L5_20R = "NEMA_L5_20R"
RFSubtypeOutNEMA_L5_30R = "NEMA_L5_30R"
RFSubtypeOutNEMA_L6_20R = "NEMA_L6_20R"
RFSubtypeOutNEMA_L6_30R = "NEMA_L6_30R"
RFSubtypeOutC13 = "C13"
RFSubtypeOutC15 = "C15"
RFSubtypeOutC19 = "C19"
RFSubtypeOutCEE_7_Type_E = "CEE_7_Type_E"
RFSubtypeOutCEE_7_Type_F = "CEE_7_Type_F"
RFSubtypeOutSEV_1011_TYPE_12 = "SEV_1011_TYPE_12"
RFSubtypeOutSEV_1011_TYPE_23 = "SEV_1011_TYPE_23"
RFSubtypeOutBS_1363_Type_G = "BS_1363_Type_G"
RFSubtypeUnknown = "Unknown" // Not found/error
)
const MaxFanout int = 1000
var ErrRFDiscFQDNMissing = errors.New("FQDN unexpectedly empty string")
var ErrRFDiscURLNotFound = errors.New("URL request returned 404: Not Found")
var ErrRFDiscILOLicenseReq = errors.New("iLO License Required")
/////////////////////////////////////////////////////////////////////////////
//
// RedfishEndpoint creation
//
/////////////////////////////////////////////////////////////////////////////
//
// This is a scan-friendly version of RedfishEndpoint that can be used to
// create or update an entry (or at least the writable fields set by the user).
// The redfish endpoint addresses can be given variously as hostname + domain,
// FQDN, or IP addresses. They are "preferred" in this order. If the hostname
// and domain are not provided, they will be obtained from the FQDN, however
// if the hostname is provided, the FQDN must match. If both hostname and
// domain are provided, they override any FQDN values or an error occurs.
//
// TODO: In the future there will be some process to autmatically add these
// for endpoints that advertise their presence, e.g. via SSDP, but we
// will likely always need the ability to add manual endpoints that do
// not. Those that do advertise will likely just need a generic
// identifier, e.g. a domain with no specific host info, or perhaps a
// subnet.
type RawRedfishEP struct {
ID string `json:"ID"`
Type string `json:"Type"`
Name string `json:"Name"` // user supplied descriptive name
Hostname string `json:"Hostname"`
Domain string `json:"Domain"`
FQDN string `json:"FQDN"`
Enabled *bool `json:"Enabled"`
UUID string `json:"UUID"`
User string `json:"User"`
Password string `json:"Password"`
UseSSDP *bool `json:"UseSSDP"`
MACRequired *bool `json:"MACRequired"`
MACAddr string `json:"MACAddr"`
IPAddr string `json:"IPAddress"`
RediscOnUpdate *bool `json:"RediscoverOnUpdate"`
TemplateID string `json:"TemplateID"`
}
// String function to redact passwords from any kind of output
func (rrep RawRedfishEP) String() string {
// NOTE: the value form is slightly less efficient since it involves a
// copy, but it will work for both pass by value and pass by pointer.
buf := bytes.NewBufferString("{")
fmt.Fprintf(buf, "ID: %s, ", rrep.ID)
fmt.Fprintf(buf, "Type: %s, ", rrep.Type)
fmt.Fprintf(buf, "Name: %s, ", rrep.Name)
fmt.Fprintf(buf, "Hostname: %s, ", rrep.Hostname)
fmt.Fprintf(buf, "Domain: %s, ", rrep.Domain)
fmt.Fprintf(buf, "FQDN: %s, ", rrep.FQDN)
if rrep.Enabled == nil {
fmt.Fprintf(buf, "Enabled: nil, ")
} else {
fmt.Fprintf(buf, "Enabled: %t, ", *rrep.Enabled)
}
fmt.Fprintf(buf, "UUID: %s, ", rrep.UUID)
fmt.Fprintf(buf, "User: %s, ", rrep.User)
fmt.Fprintf(buf, "Password: <REDACTED>, ")
if rrep.UseSSDP == nil {
fmt.Fprintf(buf, "UseSSDP: nil, ")
} else {
fmt.Fprintf(buf, "UseSSDP: %t, ", *rrep.UseSSDP)
}
if rrep.MACRequired == nil {
fmt.Fprintf(buf, "MACRequired: nil, ")
} else {
fmt.Fprintf(buf, "MACRequired: %t, ", *rrep.MACRequired)
}
fmt.Fprintf(buf, "MACAddr: %s, ", rrep.MACAddr)
fmt.Fprintf(buf, "IPAddress: %s, ", rrep.IPAddr)
if rrep.RediscOnUpdate == nil {
fmt.Fprintf(buf, "RediscOnUpdate: nil, ")
} else {
fmt.Fprintf(buf, "RediscOnUpdate: %t, ", *rrep.RediscOnUpdate)
}
fmt.Fprintf(buf, "TemplateID: %s, ", rrep.TemplateID)
fmt.Fprintf(buf, "}")
return buf.String()
}
// Defaults for RedfishEndpoint properties
const (
EnabledDefault = true
UseSSDPDefault = false
MACRequiredDefault = false
RediscOnUpdateDefault = false
)
// JSON-friendly array of RawRedfishEP entries
type RawRedfishEPs struct {
RedfishEndpoints []RawRedfishEP `json:"RedfishEndpoints"`
}
// Create RedfishEPDescription from unvalidated input, e.g. provided by
// the user. Fields that were omitted can be populated with default values.
func NewRedfishEPDescription(rep *RawRedfishEP) (*RedfishEPDescription, error) {
if rep == nil {
err := fmt.Errorf("got nil pointer")
return nil, err
}
ep := new(RedfishEPDescription)
//
// Figure out the FQDN to contact the endpoint at.
// Use Hostname and Domain fields first.
//
if rep.Domain != "" {
ep.Domain = strings.Trim(rep.Domain, "./ ")
}
hostIsIP := false
if rep.Hostname != "" {
ep.Hostname = strings.Trim(rep.Hostname, "./ ")
ipHost := GetIPAddressString(ep.Hostname)
if ipHost != "" {
hostIsIP = true
ep.Hostname = ipHost
} else {
splitHost := strings.SplitN(ep.Hostname, ".", 2)
if len(splitHost) > 1 {
err := fmt.Errorf("Hostname is not a basename or IP address.")
return nil, err
}
}
}
// If a FQDN was given instead, use those to fill in the hostname
// or domain if either was missing. But we must not have a mismatch.
if rep.FQDN != "" {
// If the FQDN is an IP address, don't treat it as host.domain.
// Just treat it as a single hostname. We don't really want to
// use IP addresses, but if that's all we have, it will work as
// long as ID is set to an xname.
fqdnIP := GetIPAddressString(rep.FQDN)
if fqdnIP != "" && ep.Hostname == "" {
// Just use the IP as the Hostname/FQDN with no domain.
ep.Hostname = fqdnIP
hostIsIP = true
}
// Assume FQDN is in normal host.domain1.domain2.etc format.
fqdnHost := ""
fqdnDomain := ""
splitFQDN := strings.SplitN(rep.FQDN, ".", 2)
fqdnHost = strings.Trim(splitFQDN[0], "./ ")
if len(splitFQDN) > 1 {
fqdnDomain = strings.Trim(splitFQDN[1], "./ ")
}
if ep.Hostname == "" {
ep.Hostname = fqdnHost
}
if ep.Domain == "" {
if ep.Hostname == fqdnHost {
ep.Domain = fqdnDomain
}
}
}
//
// Set fields in RedfishEndpointDescription from its raw equivalent.
//
// ID must be given, or the Hostname will be used instead.
// The difference is the ID must be an xname, the hostname
// need not be (unless the ID is not given and the hostname is used).
// Generally the hostname should always match, unless we are stuck
// with a hostname that is not an xname but still need to contact the
// endpoint.
if rep.ID == "" {
ep.ID = ep.Hostname
} else {
ep.ID = strings.Trim(rep.ID, "./ ")
}
// ID should be set by now unless we got no ID, hostname or FQDN.
if ep.ID == "" {
err := fmt.Errorf("No xname ID found")
return nil, err
}
ep.ID = base.NormalizeHMSCompID(ep.ID)
// Get type from ID (or hostname if ID not given). It should be a
// valid controller type.
hmsType := base.GetHMSType(ep.ID)
if base.IsHMSTypeController(hmsType) ||
hmsType == base.MgmtSwitch ||
hmsType == base.MgmtHLSwitch ||
hmsType == base.CDUMgmtSwitch {
ep.Type = hmsType.String()
} else if hmsType == base.HMSTypeInvalid {
// No type found. Not a valid xname
err := fmt.Errorf("%s is not a valid locational xname ID", ep.ID)
return nil, err
} else {
// Found a type but it is not a controller. Other component
// types should not be Redfish endpoints.
err := fmt.Errorf("xname ID %s has wrong type for RF endpoint: %s",
ep.ID, hmsType.String())
return nil, err
}
ep.Name = rep.Name
// Hostname may not be set if just the ID field is given. This is
// used for the FQDN instead.
hostname := ep.Hostname
if hostname == "" {
hostname = ep.ID
}
// Set FQDN. This is not actually a stored field, as these must match
// the hostname + domain at this point, either because both were given,
// or because we got them from the rep.FQDN.
if ep.Domain != "" {
if hostIsIP {
ep.FQDN = ep.Hostname
} else {
ep.FQDN = hostname + "." + ep.Domain
}
} else {
ep.FQDN = hostname
}
// If these don't match, host/id + domain given but it doesn't agree
// with non-empty FQDN
repFQDN := GetIPAddressString(rep.FQDN)
if repFQDN == "" {
repFQDN = rep.FQDN
}
if rep.FQDN != "" && ep.FQDN != repFQDN {
err := fmt.Errorf("host/domain conflicts with FQDN: '%s' != '%s'",
ep.FQDN, repFQDN)
return nil, err
}
// Validate given IP address that is not in the 'Hostname' or 'FQDN' fields
if rep.IPAddr != "" {
repIP := GetIPAddressString(rep.IPAddr)
if repIP == "" {
err := fmt.Errorf("IPAddress is not a valid IP address: '%s'", rep.IPAddr)
return nil, err
}
// If the hostname is an IP address, the given IP address should match
if hostIsIP && repIP != ep.Hostname {
err := fmt.Errorf("hostname IP address conflicts with given IP address: '%s' != '%s'",
ep.Hostname, repIP)
return nil, err
}
ep.IPAddr = repIP
} else if hostIsIP {
// Use the IP address hostname as the IP address.
ep.IPAddr = ep.Hostname
}
if rep.Enabled != nil {
ep.Enabled = *rep.Enabled
} else {
ep.Enabled = EnabledDefault
}
ep.UUID = rep.UUID
ep.User = rep.User
ep.Password = rep.Password
if rep.UseSSDP != nil {
ep.UseSSDP = *rep.UseSSDP
} else {
ep.UseSSDP = UseSSDPDefault
}
if rep.MACRequired != nil {
ep.MACRequired = *rep.MACRequired
} else {
ep.MACRequired = MACRequiredDefault
}
ep.MACAddr = rep.MACAddr
if rep.RediscOnUpdate != nil {
ep.RediscOnUpdate = *rep.RediscOnUpdate
} else {
ep.RediscOnUpdate = RediscOnUpdateDefault
}
ep.DiscInfo.LastStatus = NotYetQueried
return ep, nil
}
/////////////////////////////////////////////////////////////////////////////
//
// RedfishEndpoint discovery
//
/////////////////////////////////////////////////////////////////////////////
type RedfishEPDescription struct {
ID string `json:"ID"`
Type string `json:"Type"`
Name string `json:"Name,omitempty"` // user supplied descriptive name
Hostname string `json:"Hostname"`
Domain string `json:"Domain"`
FQDN string `json:"FQDN"`
Enabled bool `json:"Enabled"`
UUID string `json:"UUID,omitempty"`
User string `json:"User"`
Password string `json:"Password"` // Temporary until more secure method
UseSSDP bool `json:"UseSSDP,omitempty"`
MACRequired bool `json:"MACRequired,omitempty"`
MACAddr string `json:"MACAddr,omitempty"`
IPAddr string `json:"IPAddress,omitempty"`
RediscOnUpdate bool `json:"RediscoverOnUpdate"`
TemplateID string `json:"TemplateID,omitempty"`
DiscInfo DiscoveryInfo `json:"DiscoveryInfo"`
}
// String function to redact passwords from any kind of output
func (red RedfishEPDescription) String() string {
// NOTE: the value form is slightly less efficient since it involves a
// copy, but it will work for both pass by value and pass by pointer.
buf := bytes.NewBufferString("{")
fmt.Fprintf(buf, "ID: %s, ", red.ID)
fmt.Fprintf(buf, "Type: %s, ", red.Type)
fmt.Fprintf(buf, "Name: %s, ", red.Name)
fmt.Fprintf(buf, "Hostname: %s, ", red.Hostname)
fmt.Fprintf(buf, "Domain: %s, ", red.Domain)
fmt.Fprintf(buf, "FQDN: %s, ", red.FQDN)
fmt.Fprintf(buf, "Enabled: %t, ", red.Enabled)
fmt.Fprintf(buf, "UUID: %s, ", red.UUID)
fmt.Fprintf(buf, "User: %s, ", red.User)
fmt.Fprintf(buf, "Password: <REDACTED>, ")
fmt.Fprintf(buf, "UseSSDP: %t, ", red.UseSSDP)
fmt.Fprintf(buf, "MACRequired: %t, ", red.MACRequired)
fmt.Fprintf(buf, "MACAddr: %s, ", red.MACAddr)
fmt.Fprintf(buf, "IPAddress: %s, ", red.IPAddr)
fmt.Fprintf(buf, "RediscOnUpdate: %t, ", red.RediscOnUpdate)
fmt.Fprintf(buf, "TemplateID: %s, ", red.TemplateID)
fmt.Fprintf(buf, "DiscInfo: %+v", red.DiscInfo)
fmt.Fprintf(buf, "}")
return buf.String()
}
type DiscoveryInfo struct {
LastAttempt string `json:"LastDiscoveryAttempt,omitempty"`
LastStatus string `json:"LastDiscoveryStatus"`
RedfishVersion string `json:"RedfishVersion,omitempty"`
}
// Update Status and set timestamp to now.
func (d *DiscoveryInfo) UpdateLastStatusWithTS(status string) {
d.LastAttempt = time.Now().UTC().Format("2006-01-02T15:04:05.000000Z07:00")
d.LastStatus = status
}
// Set timestamp to now.
func (d *DiscoveryInfo) TSNow() {
d.LastAttempt = time.Now().UTC().Format("2006-01-02T15:04:05.000000Z07:00")
}
type RedfishEPDescriptions struct {
RfEPDescriptions []RedfishEPDescription
}
// Create RedfishEPDescriptions struct from raw input from decoded RawEndpoints
// struct, e.g. from a JSON file or POST body.
func NewRedfishEPDescriptions(reps *RawRedfishEPs) (*RedfishEPDescriptions, error) {
// We create one endpoint per desc
epds := new(RedfishEPDescriptions)
if reps == nil {
err := fmt.Errorf("got nil pointer")
return epds, err
}
var savedError error
for _, rep := range reps.RedfishEndpoints {
epd, err := NewRedfishEPDescription(&rep)
if err == nil {
epds.RfEPDescriptions = append(epds.RfEPDescriptions, *epd)
} else {
errlog.Printf("NewRedfishEPDescriptions: %s", err)
savedError = err
}
}
return epds, savedError
}
// This is the endpoint structure generated from a base RedfishEPDescription.
// It is used to facilitate connections to the endpoints and is
// is used to discover top-level resources (e.g. systems) so that
// they can be discovered in more details with routines appropriate
// to each type.
type RedfishEP struct {
// Embedded struct
RedfishEPDescription
ServiceRootURL string `json:"serviceRootURL"` // URL of root service
RedfishType string `json:"redfishType"` // i.e. ServiceRoot
IPaddr string `json:"ipaddr"`
OdataID string `json:"odataID"` // i.e. /redfish/v1
ServiceRootRF ServiceRoot `json:"serviceRootRF"`
NumChassis int `json:"numChassis"`
NumManagers int `json:"numManagers"`
NumSystems int `json:"numSystems"`
NumRackPDUs int `json:"numRackPDUs"`
AccountService *EpAccountService `json:"accountService"`
SessionService *EpSessionService `json:"sessionService"`
EventService *EpEventService `json:"eventService"`
TaskService *EpTaskService `json:"taskService"`
UpdateService *EpUpdateService `json:"updateService"`
Chassis EpChassisSet `json:"chassis"`
Managers EpManagers `json:"managers"`
Systems EpSystems `json:"systems"`
RackPDUs EpPDUs `json:"rackpdus"`
rootSvcRaw *json.RawMessage //`json:"rootSvcRaw"`
chassisRaw *json.RawMessage //`json:"chassisRaw"`
managersRaw *json.RawMessage //`json:"managersRaw"`
systemsRaw *json.RawMessage //`json:"systemsRaw"`
// Contains various PowerEquipment links; we only care about PDUs for now
powerEquipment *PowerEquipment
client *hms_certs.HTTPClientPair
}
// Create RedfishEP struct from a validated RedfishEndpointDescription.
// The description would be generated from user-supplied RawEndpoints and/or
// retrieved from the database.
// The RedfishEP struct is set up based on the description to conduct queries
// of the remote endpoint and to store the raw data retrieved from it.
func NewRedfishEp(rep *RedfishEPDescription) (*RedfishEP, error) {
ep := new(RedfishEP)
if rep == nil {
err := fmt.Errorf("got nil pointer!")
ep.DiscInfo.UpdateLastStatusWithTS(EndpointInvalid)
return ep, err
}
ep.RedfishEPDescription = *rep
ep.ServiceRootURL = ep.FQDN + "/redfish/v1"
ep.OdataID = "/redfish/v1"
ep.NumSystems = 0
// Add client handle. Allow for proxy if configured.
/*
if httpClientProxyURL != "" {
ep.client = RfProxyClient(httpClientProxyURL)
} else {
ep.client = RfDefaultClient()
}
*/
ep.client = RfDefaultClient()
err := ep.CheckPrePhase1()
if err != nil {
errlog.Printf("NewRedfishEp failed: %s", err)
ep.DiscInfo.UpdateLastStatusWithTS(EndpointInvalid)
return ep, err
}
return ep, nil
}
// Set of RedfishEP, struct representing a root-level RF endpoint in system.
type RedfishEPs struct {
Num int `json:"num"`
IDs map[string]*RedfishEP `json:"ids"`
waitGroup sync.WaitGroup // For synchronizing threads
}
// Create RedfishEPs structs from a set of validated RedfishEndpointDescriptions.
func NewRedfishEps(epds *RedfishEPDescriptions) (*RedfishEPs, error) {
// We create one endpoint per raw entry under a RedfishEPs struct.
eps := new(RedfishEPs)
eps.IDs = make(map[string]*RedfishEP)
eps.Num = 0
if epds == nil {
err := fmt.Errorf("got nil pointer")
return eps, err
}
var savedError error
for i, epd := range epds.RfEPDescriptions {
ep, err := NewRedfishEp(&epd)
if err != nil {
errlog.Println("Endpoint ", i, " was invalid: ")
savedError = err
} else {
eps.IDs[ep.ID] = ep
eps.Num = eps.Num + 1
}
}
return eps, savedError
}
// GET the page at the given rpath relative to the redfish hostname of
// the given endpoint, e.g. /redfish/v1/Systems/System.Embedded.1. Keeping
// with Redfish style there should always be a leading slash and the
// "/redfish/v1" part should presumably always be present in the rpath (as the
// odata.id always includes this).
//
// If no error results, result should be the raw body (i.e. Redfish JSON).
// returned.
// This is the starting point for decoding the JSON into a particular
// structure (i.e. given the resource's schema, or into a generic
// interface{} map.
func (ep *RedfishEP) GETRelative(rpath string) (json.RawMessage, error) {
var rsp *http.Response
var path string = "https://" + ep.FQDN + strings.Replace(rpath, "#", "%23", -1)
var body []byte
// In case we don't catch this...
if ep.FQDN == "" {
errlog.Printf("Can't HTTP GET (%s): FQDN is empty", path)
return nil, ErrRFDiscFQDNMissing
}
req, err := http.NewRequest("GET", path, nil)
if err != nil {
errlog.Printf("Error forming new request for (%s) %s", path, err)
return nil, err
}
req.SetBasicAuth(ep.User, ep.Password)
req.Header.Set("Accept", "*/*")
req.Close = true
//TODO: Future enhancement for unsupported River BMCs to reduce RF failovers
//and log clutter:
//
// Check the ID (xname) and:
// o If ep.client.SecureClient != nil && != InsecureClient:
// o If ID shows 'c0', then scrutinize:
// o If there have been > 1 failovers with successful Do() calls, then set
// ep.client.SecureClient = InsecureClient
// Do retries on errors. They could be temporary interuptions in service.
retryCount := 3
sleepTime := 1
for retry := 0; retry <= retryCount; retry++ {
rsp, err = ep.client.Do(req)
if err != nil {
if retry == retryCount {
errlog.Printf("GETRelative (%s) ERROR: %s", path, err)
return nil, err
} else {
errlog.Printf("GETRelative (%s) ERROR: %s, Retrying...", path, err)
time.Sleep(time.Duration(sleepTime) * time.Second)
sleepTime += (retry + 1) * 10
continue
}
}
break
}
if rsp.Body != nil {
body, _ = ioutil.ReadAll(rsp.Body)
rsp.Body.Close()
}
if rsp.StatusCode != http.StatusOK {
rerr := fmt.Errorf("%s", http.StatusText(rsp.StatusCode))
errlog.Printf("GETRelative (%s) Bad rsp: %s", path, rerr)
if rsp.StatusCode == http.StatusNotFound {
// Return a named error so we can take special action
return nil, ErrRFDiscURLNotFound
} else {
var compErr RedfishError
if err := json.Unmarshal(json.RawMessage(body), &compErr); err != nil {
if IsUnmarshalTypeError(err) {
errlog.Printf("bad field(s) skipped: %s: %s\n", path, err)
} else {
errlog.Printf("ERROR: json decode failed: %s: %s\n", path, err)
return nil, rerr
}
}
if len(compErr.Error.ExtendedInfo) > 0 && strings.Contains(compErr.Error.ExtendedInfo[0].MessageId, "LicenseKeyRequired") {
return nil, ErrRFDiscILOLicenseReq
}
}
return nil, rerr
}
// We want to return the raw JSON output. It unmarshals just as
// well if it's indented, so we do that here to verify that it is
// valid JSON. This lets us defer to the caller how to unmarshall it,
// and puts it in a more (human) readable format.
var out bytes.Buffer
err = json.Indent(&out, body, "", "\t")
if err != nil {
errlog.Printf("Error decoding %s: %s", path, err)
return nil, err
}
// Dump response and path in a unit-test friendly format for regression
// test auto-generation.
if genTestingPayloadsTitle != "" {
if genTestingPayloadsDumpEpID == ep.ID {
GenTestingPayloads(genTestingPayloadsOutfile,
genTestingPayloadsTitle,
rpath,
out.Bytes())
}
}
jsonBody := json.RawMessage(out.Bytes())
return jsonBody, nil
}
// Loop through all endpoints to get top-level information, i.e.
// how many systems, etc. and initalize these structures so they
// can be discovered in more detail.
//
// Note this is done in parallel, each RedfishEP in a separate thread.
// Each RedfishEP structure should not share any data with the others so
// little synchronization is needed. We could conceivably speed things up
// more by parallelizing the individual page gets, but that would have to
// be done a bit more carefully and for now this should be fast enough.
func (eps *RedfishEPs) GetAllRootInfo() {
var numWait int = 0
// for _, ep := range eps.Endpoints {
for _, ep := range eps.IDs {
// Wait for this go routine to finish
eps.waitGroup.Add(1)
// Start each endpoint as a separate thread
go func(e *RedfishEP) {
defer eps.waitGroup.Done()
e.GetRootInfo()
}(ep)
numWait++
if numWait > MaxFanout {
errlog.Printf("GetAllRootInfo() Max fanout of %d reached. "+
"Wait for completion.", MaxFanout)
eps.waitGroup.Wait()
numWait = 0
}
}
// Wait for all goroutines to finish
eps.waitGroup.Wait()
}
// For a given Redfish endpoint, get top-level information, i.e.
// how many systems, chassis, managers, etc. and initalize these structures
// so can be discovered in more detail.
func (ep *RedfishEP) GetRootInfo() {
ep.DiscInfo.TSNow()
err := ep.CheckPrePhase1()
if err != nil {
errlog.Printf("Discover failed: %s", err)
ep.DiscInfo.UpdateLastStatusWithTS(EndpointInvalid)
return
}
// Skip inventory discovery if not enabled.
if ep.Enabled == false {
errlog.Printf("Discover skipped for %s: '%s'",
ep.ID, EndpointNotEnabled)
ep.DiscInfo.UpdateLastStatusWithTS(EndpointNotEnabled)
return
}
// Get ServiceRoot for endpoint
path := ep.OdataID
rootSvcJSON, err := ep.GETRelative(path)
if err != nil || rootSvcJSON == nil {
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetFailed)
return
}
if rfDebug > 0 {
errlog.Printf("%s: %s\n", ep.FQDN+path, rootSvcJSON)
}
ep.rootSvcRaw = &rootSvcJSON
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetOk)
// Decode ServiceRoot JSON into matching Go struct
err = json.Unmarshal(rootSvcJSON, &ep.ServiceRootRF)
if err != nil {
errlog.Printf("Failed to decode %s: %s\n", path, err)
ep.DiscInfo.UpdateLastStatusWithTS(EPResponseFailedDecode)
}
ep.RedfishType = ServiceRootType
ep.DiscInfo.RedfishVersion = ep.ServiceRootRF.RedfishVersion
ep.UUID = ep.ServiceRootRF.UUID
//
// Now create structs for each of the services in the
// SystemRoot, then discover them, so that we can interact
// with the services they provide.
//
if ep.ServiceRootRF.AccountService.Oid != "" {
oid := ep.ServiceRootRF.AccountService.Oid
ep.AccountService = NewEpAccountService(ep, oid)
ep.AccountService.discoverRemotePhase1()
} else {
errlog.Printf("%s: No AccountService entry found!\n", ep.FQDN)
}
if ep.ServiceRootRF.SessionService.Oid != "" {
oid := ep.ServiceRootRF.SessionService.Oid
ep.SessionService = NewEpSessionService(ep, oid)
ep.SessionService.discoverRemotePhase1()
} else {
errlog.Printf("%s: No SessionService entry found!\n", ep.FQDN)
}
if ep.ServiceRootRF.EventService.Oid != "" {
oid := ep.ServiceRootRF.EventService.Oid
ep.EventService = NewEpEventService(ep, oid)
ep.EventService.discoverRemotePhase1()
} else {
errlog.Printf("%s: No EventService entry found!\n", ep.FQDN)
}
// Note: The service root property is called "Tasks" but should point to
// /redfish/v1/TaskService. We use the latter for consistency
// in the structs created here.
if ep.ServiceRootRF.Tasks.Oid != "" {
oid := ep.ServiceRootRF.Tasks.Oid
ep.TaskService = NewEpTaskService(ep, oid)
ep.TaskService.discoverRemotePhase1()
} else {
errlog.Printf("%s: No TaskService entry found!\n", ep.FQDN)
}
if ep.ServiceRootRF.UpdateService.Oid != "" {
oid := ep.ServiceRootRF.UpdateService.Oid
ep.UpdateService = NewEpUpdateService(ep, oid)
ep.UpdateService.discoverRemotePhase1()
} else {
errlog.Printf("%s: No UpdateService entry found!\n", ep.FQDN)
}
//
// We now take each set of root level Redfish component objects in
// turn so we can dive deeper and collect info on those we need for
// futher system discovery.
//
// First, the set of Redfish Chassis objects for the endpoint.
// Start by fetching the Chassis/ set from the root.
//
if ep.ServiceRootRF.Chassis.Oid != "" {
path = ep.ServiceRootRF.Chassis.Oid
} else {
path = ep.OdataID + "/Chassis"
}
chassisJSON, err := ep.GETRelative(path)
if err != nil && !base.ControllerHasChassisStr(ep.Type) {
// Don't expect any Chassis here, so if no collection, no problem.
// Just create an empty collection so we don't choke later.
ep.NumChassis = 0
ep.Chassis.OIDs = make(map[string]*EpChassis)
} else if err != nil || chassisJSON == nil {
// Expected Chassis collection but didn't get one or it was corrupt.
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetFailed)
return
} else {
// Found Chassis collection
if rfDebug > 0 {
errlog.Printf("%s: %s\n", ep.FQDN+path, chassisJSON)
}
ep.chassisRaw = &chassisJSON
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetOk)
// Decode chassis list for endpoint, create an EpChassis for each
// for subsequent discovery.
var chInfo ChassisCollection
err = json.Unmarshal(chassisJSON, &chInfo)
if err != nil {
errlog.Printf("Failed to decode %s: %s\n", path, err)
ep.DiscInfo.UpdateLastStatusWithTS(EPResponseFailedDecode)
return
}
// The count is typically given as "Members@odata.count", but
// older versions drop the "Members" identifier
ep.NumChassis = len(chInfo.Members)
if chInfo.MembersOCount > 0 && chInfo.MembersOCount != ep.NumChassis {
errlog.Printf("%s: Member@odata.count != Member array len\n", ep.FQDN+path)
} else if chInfo.OCount > 0 && chInfo.OCount != ep.NumChassis {
errlog.Printf("%s: odata.count != Member array len\n", ep.FQDN+path)
}
ep.Chassis.OIDs = make(map[string]*EpChassis)
ep.Chassis.Num = ep.NumChassis
sort.Sort(ResourceIDSlice(chInfo.Members))
for i, chOID := range chInfo.Members {
chID := chOID.Basename()
ep.Chassis.OIDs[chID] = NewEpChassis(ep, chOID, i)
}
// Fetch info for each chassis in list and populate new structs.
ep.Chassis.discoverRemotePhase1()
}
//
// Next, the set of Managers for the endpoint.
// Get Managers/ root listing of all Managers (BMCs, etc.) under endpoint.
//
if ep.ServiceRootRF.Managers.Oid != "" {
path = ep.ServiceRootRF.Managers.Oid
} else {
path = ep.OdataID + "/Managers"
}
managersJSON, err := ep.GETRelative(path)
if err != nil || managersJSON == nil {
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetFailed)
return
}
if rfDebug > 0 {
errlog.Printf("%s: %s\n", ep.FQDN+path, managersJSON)
}
ep.managersRaw = &managersJSON
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetOk)
// Decode Managers list for endpoint, create an EpManager for each
// for subsequent discovery.
var manInfo ManagerCollection
err = json.Unmarshal(managersJSON, &manInfo)
if err != nil {
errlog.Printf("Failed to decode %s: %s\n", path, err)
ep.DiscInfo.UpdateLastStatusWithTS(EPResponseFailedDecode)
return
}
ep.NumManagers = len(manInfo.Members)
if manInfo.MembersOCount > 0 && manInfo.MembersOCount != ep.NumManagers {
errlog.Printf("%s: Member@odata.count != Member array len\n", ep.FQDN+path)
} else if manInfo.OCount > 0 && manInfo.OCount != ep.NumManagers {
errlog.Printf("%s: odata.count != Member array len\n", ep.FQDN+path)
}
ep.Managers.OIDs = make(map[string]*EpManager)
ep.Managers.Num = ep.NumManagers
sort.Sort(ResourceIDSlice(manInfo.Members))
for i, mOID := range manInfo.Members {
mID := mOID.Basename()
ep.Managers.OIDs[mID] = NewEpManager(ep, mOID, i)
}
ep.Managers.discoverRemotePhase1()
//
// Next, the set of ComputerSystems for the endpoint.
// Get Systems/ root listing of all Systems under endpoint.
//
status := ep.GetSystems()
if status != HTTPsGetOk {
return
}
//
// Next, the PowerEquipment for the endpoint, if it exits. For now,
// we just get the RackPDUs collection under it.
//
// HPE PDUs use PowerDistribution, so setup PowerEquipment path
if ep.ServiceRootRF.PowerDistribution.Oid != "" {
ep.ServiceRootRF.PowerEquipment.Oid = "/redfish/v1/PowerEquipment"
}
if ep.ServiceRootRF.PowerEquipment.Oid != "" {
path = ep.ServiceRootRF.PowerEquipment.Oid
powerJSON, err := ep.GETRelative(path)
if err != nil || powerJSON == nil {
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetFailed)
return
}
if rfDebug > 0 {
errlog.Printf("%s: %s\n", ep.FQDN+path, powerJSON)
}
ep.DiscInfo.UpdateLastStatusWithTS(HTTPsGetOk)
// Decode PowerEquipment object
var powerInfo PowerEquipment
err = json.Unmarshal(powerJSON, &powerInfo)