From b3ae2b245c9304d5bef1fe4b0dc20f682fbfb24e Mon Sep 17 00:00:00 2001 From: Ryan Sjostrand Date: Tue, 29 Aug 2023 15:25:45 -0500 Subject: [PATCH 1/3] Add hms-xname --- go.mod | 1 + go.sum | 2 ++ vendor/modules.txt | 2 ++ 3 files changed, 5 insertions(+) diff --git a/go.mod b/go.mod index 8d1b581..43d3f5c 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/Cray-HPE/hms-go-http-lib v1.5.3 github.com/Cray-HPE/hms-msgbus v1.11.0 github.com/Cray-HPE/hms-securestorage v1.12.2 + github.com/Cray-HPE/hms-xname v1.2.0 // indirect github.com/DATA-DOG/go-sqlmock v1.3.3 github.com/Masterminds/squirrel v1.4.0 github.com/frankban/quicktest v1.7.3 // indirect diff --git a/go.sum b/go.sum index 989a860..76c229a 100644 --- a/go.sum +++ b/go.sum @@ -36,6 +36,8 @@ github.com/Cray-HPE/hms-msgbus v1.11.0 h1:w5ThMJ8D5pmuvXhc817rJDG4TTixEfvtcDi3tR github.com/Cray-HPE/hms-msgbus v1.11.0/go.mod h1:cxn+lUOq3tpY3+KdFml6L56ZQo8sqN2VoZ6gGxds6o8= github.com/Cray-HPE/hms-securestorage v1.12.2 h1:H5n0i6ldzewd5p7PI2Hktr/+9cYfSCui+0367p2L6n8= github.com/Cray-HPE/hms-securestorage v1.12.2/go.mod h1:P4CMKqQVlx/lv+AdyEjNQubZw2FKNyo/IAtFNgQ3VuI= +github.com/Cray-HPE/hms-xname v1.2.0 h1:boZ8QlTQr/FxXbH+sloqr7qCGkKatJ6QNyIGbdOVmdw= +github.com/Cray-HPE/hms-xname v1.2.0/go.mod h1:XKdjQSzoTps5KDOE8yWojBTAWASGaS6LfRrVDxwTQO8= github.com/DATA-DOG/go-sqlmock v1.3.3 h1:CWUqKXe0s8A2z6qCgkP4Kru7wC11YoAnoupUKFDnH08= github.com/DATA-DOG/go-sqlmock v1.3.3/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM= github.com/Masterminds/squirrel v1.4.0 h1:he5i/EXixZxrBUWcxzDYMiju9WZ3ld/l7QBNuo/eN3w= diff --git a/vendor/modules.txt b/vendor/modules.txt index 6a5c1c8..095d671 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -16,6 +16,8 @@ github.com/Cray-HPE/hms-msgbus # github.com/Cray-HPE/hms-securestorage v1.12.2 ## explicit github.com/Cray-HPE/hms-securestorage +# github.com/Cray-HPE/hms-xname v1.2.0 +## explicit # github.com/DATA-DOG/go-sqlmock v1.3.3 ## explicit github.com/DATA-DOG/go-sqlmock From c6a72425a0cd52f8a07d116a10dccebd1b67ca31 Mon Sep 17 00:00:00 2001 From: Ryan Sjostrand Date: Wed, 30 Aug 2023 09:31:33 -0500 Subject: [PATCH 2/3] Initial conversion to hms-xname --- cmd/smd-loader/smd-loader.go | 11 +- cmd/smd/components.go | 27 +- cmd/smd/discover.go | 130 +-- cmd/smd/hmsdsmock_test.go | 54 +- cmd/smd/job-types.go | 73 +- cmd/smd/msgbus.go | 5 +- cmd/smd/response.go | 4 +- cmd/smd/rfevent.go | 92 +- cmd/smd/smd-api.go | 125 +-- cmd/smd/smd-api_test.go | 987 +++++++++--------- cmd/smd/smd.go | 62 +- cmd/smd/state-change.go | 16 +- go.mod | 4 +- go.sum | 2 + internal/hbtdapi/hbtdapi.go | 7 +- internal/hbtdapi/hbtdapi_test.go | 16 +- internal/hmsds/hmsds-api-filters.go | 69 +- internal/hmsds/hmsds-api.go | 34 +- internal/hmsds/hmsds-postgres.go | 77 +- internal/hmsds/hmsds-postgres_test.go | 621 +++++------ internal/hmsds/hmsds-tx-postgres.go | 241 ++--- internal/hmsds/query-postgres.go | 6 +- internal/hmsds/query-shared-sq.go | 54 +- internal/hmsds/query-shared.go | 22 +- internal/slsapi/slsapi.go | 28 +- internal/slsapi/slsapi_test.go | 46 +- pkg/redfish/redfish.go | 45 +- pkg/redfish/rfcomponents-assembly.go | 5 +- pkg/redfish/rfcomponents-hpe.go | 37 +- pkg/redfish/rfcomponents-network.go | 5 +- pkg/redfish/rfcomponents-power.go | 43 +- pkg/redfish/rfcomponents-storage.go | 13 +- pkg/redfish/rfcomponents.go | 73 +- pkg/redfish/rfcomponents_test.go | 34 +- pkg/redfish/rfendpoints.go | 171 +-- pkg/redfish/rfservices.go | 2 +- pkg/service-reservations/interface.go | 152 ++- pkg/sharedtest/util.go | 4 +- pkg/sm/compethinterfaces.go | 11 +- pkg/sm/compethinterfaces_test.go | 10 +- pkg/sm/complocks.go | 7 +- pkg/sm/complocks_test.go | 2 +- pkg/sm/comps.go | 20 +- pkg/sm/comps_test.go | 24 +- pkg/sm/endpoints.go | 6 +- pkg/sm/events.go | 4 +- pkg/sm/groups.go | 14 +- pkg/sm/groups_test.go | 3 +- pkg/sm/hwinv.go | 387 +++---- pkg/sm/hwinvhist.go | 7 +- pkg/sm/misc.go | 5 +- pkg/sm/nodemap.go | 8 +- pkg/sm/powermap.go | 7 +- .../Cray-HPE/hms-base/v2/.gitignore | 1 + .../github.com/Cray-HPE/hms-base/v2/.version | 1 + .../Cray-HPE/hms-base/v2/CHANGELOG.md | 269 +++++ .../github.com/Cray-HPE/hms-base/v2/LICENSE | 21 + .../github.com/Cray-HPE/hms-base/v2/Makefile | 29 + .../Cray-HPE/hms-base/v2/configWatch.go | 151 +++ vendor/github.com/Cray-HPE/hms-base/v2/doc.go | 37 + vendor/github.com/Cray-HPE/hms-base/v2/go.mod | 9 + vendor/github.com/Cray-HPE/hms-base/v2/go.sum | 9 + .../github.com/Cray-HPE/hms-base/v2/hmserr.go | 481 +++++++++ .../Cray-HPE/hms-base/v2/hmstypes.go | 518 +++++++++ .../github.com/Cray-HPE/hms-base/v2/http.go | 223 ++++ .../github.com/Cray-HPE/hms-base/v2/util.go | 93 ++ .../Cray-HPE/hms-base/v2/worker-pool.go | 196 ++++ vendor/github.com/Cray-HPE/hms-xname/LICENSE | 21 + .../Cray-HPE/hms-xname/xnametypes/hmstypes.go | 871 ++++++++++++++++ vendor/modules.txt | 5 +- 70 files changed, 4931 insertions(+), 1916 deletions(-) create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/.gitignore create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/.version create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/CHANGELOG.md create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/LICENSE create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/Makefile create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/configWatch.go create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/doc.go create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/go.mod create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/go.sum create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/hmserr.go create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/hmstypes.go create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/http.go create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/util.go create mode 100644 vendor/github.com/Cray-HPE/hms-base/v2/worker-pool.go create mode 100644 vendor/github.com/Cray-HPE/hms-xname/LICENSE create mode 100644 vendor/github.com/Cray-HPE/hms-xname/xnametypes/hmstypes.go diff --git a/cmd/smd-loader/smd-loader.go b/cmd/smd-loader/smd-loader.go index 85fce13..19cbfbd 100644 --- a/cmd/smd-loader/smd-loader.go +++ b/cmd/smd-loader/smd-loader.go @@ -25,15 +25,16 @@ package main import ( "context" "fmt" - "github.com/hashicorp/go-retryablehttp" "io/ioutil" "net/http" "os" "os/signal" - "github.com/Cray-HPE/hms-base" - hmshttp "github.com/Cray-HPE/hms-go-http-lib" "syscall" "time" + + base "github.com/Cray-HPE/hms-base/v2" + hmshttp "github.com/Cray-HPE/hms-go-http-lib" + "github.com/hashicorp/go-retryablehttp" ) var ctx context.Context @@ -127,8 +128,8 @@ func main() { CustomHeaders: make(map[string]string), } - svcName,serr := base.GetServiceInstanceName() - if (serr != nil) { + svcName, serr := base.GetServiceInstanceName() + if serr != nil { svcName = "SMD-LOADER" } diff --git a/cmd/smd/components.go b/cmd/smd/components.go index bb2a408..ef9aa43 100644 --- a/cmd/smd/components.go +++ b/cmd/smd/components.go @@ -27,9 +27,10 @@ import ( "fmt" "strconv" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/internal/hmsds" rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" + "github.com/Cray-HPE/hms-xname/xnametypes" ) //////////////////////////////////////////////////////////////////////////// @@ -99,16 +100,16 @@ func (s *SmD) DiscoverComponentChassis(chEP *rf.EpChassis) *base.Component { comp.Class = chEP.DefaultClass if comp.Class == "" { - if comp.Type == base.Chassis.String() { + if comp.Type == xnametypes.Chassis.String() { comp.Class = base.ClassMountain.String() // Just incase our redfish endpoint didn't exist when our child // components were discovered, update them to be Mountain too. f := hmsds.ComponentFilter{ Type: []string{ - base.NodeBMC.String(), - base.NodeEnclosure.String(), - base.Node.String(), - base.RouterBMC.String(), + xnametypes.NodeBMC.String(), + xnametypes.NodeEnclosure.String(), + xnametypes.Node.String(), + xnametypes.RouterBMC.String(), }, } children, err := s.db.GetComponentsQuery(&f, hmsds.FLTR_ID_ONLY, []string{comp.ID}) @@ -131,12 +132,12 @@ func (s *SmD) DiscoverComponentChassis(chEP *rf.EpChassis) *base.Component { // Chassis first then go down a level to the chassisBMC p := comp.ID for { - p = base.GetHMSCompParent(p) + p = xnametypes.GetHMSCompParent(p) if p == "" { s.LogAlways("DiscoverComponentChassis: Could not determine ChassisBMC ID for %s", comp.ID) break } - if base.GetHMSType(p) != base.Chassis { + if xnametypes.GetHMSType(p) != xnametypes.Chassis { continue } chassisBmc := p + "b0" @@ -194,12 +195,12 @@ func (s *SmD) DiscoverComponentSystem(sysEP *rf.EpSystem) *base.Component { // Chassis first then go down a level to the chassisBMC p := comp.ID for { - p = base.GetHMSCompParent(p) + p = xnametypes.GetHMSCompParent(p) if p == "" { s.LogAlways("DiscoverComponentChassis: Could not determine ChassisBMC ID for %s", comp.ID) break } - if base.GetHMSType(p) != base.Chassis { + if xnametypes.GetHMSType(p) != xnametypes.Chassis { continue } chassisBmc := p + "b0" @@ -246,19 +247,19 @@ func (s *SmD) DiscoverComponentManager(mEP *rf.EpManager) *base.Component { comp.Class = mEP.DefaultClass if comp.Class == "" { - if comp.Type == base.ChassisBMC.String() { + if comp.Type == xnametypes.ChassisBMC.String() { comp.Class = base.ClassMountain.String() } else { // Get the ID for the parent Chassis BMC. Need to find the // Chassis first then go down a level to the chassisBMC p := comp.ID for { - p = base.GetHMSCompParent(p) + p = xnametypes.GetHMSCompParent(p) if p == "" { s.LogAlways("DiscoverComponentChassis: Could not determine ChassisBMC ID for %s", comp.ID) break } - if base.GetHMSType(p) != base.Chassis { + if xnametypes.GetHMSType(p) != xnametypes.Chassis { continue } chassisBmc := p + "b0" diff --git a/cmd/smd/discover.go b/cmd/smd/discover.go index 4a03d0a..33ed04a 100644 --- a/cmd/smd/discover.go +++ b/cmd/smd/discover.go @@ -28,21 +28,23 @@ import ( "strings" "sync" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" compcreds "github.com/Cray-HPE/hms-compcredentials" rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // When we discover a Redfish Endpoint, the data retrieved is processed // in the rf package to associate it with basic data needed to place it // within the system and extra HMS-level metadata. // We do this discovery and then use the resulting data to create HMS-level -// structures and place them in the database. +// structures and place them in the dataxnametypes. // // Args: -// eps is a set of RedfishEndpoints retrieved from the database. -// id is the id of the DiscoveryStatus object to write status to. +// +// eps is a set of RedfishEndpoints retrieved from the dataxnametypes. +// id is the id of the DiscoveryStatus object to write status to. func (s *SmD) discoverFromEndpoints(eps []*sm.RedfishEndpoint, id uint, update, force bool) { idsFiltered := make([]string, 0, len(eps)) for _, ep := range eps { @@ -56,7 +58,7 @@ func (s *SmD) discoverFromEndpoints(eps []*sm.RedfishEndpoint, id uint, update, ep.ID) continue } - idsFiltered = append(idsFiltered, base.VerifyNormalizeCompID(ep.ID)) + idsFiltered = append(idsFiltered, xnametypes.VerifyNormalizeCompID(ep.ID)) } // This should not fail in practice unless eps have not been inserted yet // This will "lock" the LastStatus to in-progress so it can't be started @@ -125,8 +127,9 @@ func (s *SmD) discoverFromEndpoints(eps []*sm.RedfishEndpoint, id uint, update, // Single-endpoint version of the above. // // Args: -// ep is a single RedfishEndpoint retrieved from the database. -// id is the id of the DiscoveryStatus object to write status to. +// +// ep is a single RedfishEndpoint retrieved from the dataxnametypes. +// id is the id of the DiscoveryStatus object to write status to. func (s *SmD) discoverFromEndpoint(ep *sm.RedfishEndpoint, id uint, force bool) { if ep.RediscOnUpdate != true { s.LogAlways("Skipping discovery for %s: !RediscoverOnUpdate", ep.ID) @@ -195,7 +198,7 @@ func (s *SmD) doDiscovery(rfEP *rf.RedfishEP) { rfEP.GetRootInfo() // Create/update HMS-level components from the retrieved discovery data - // from Redfish. This also inserts the data into the database. + // from Redfish. This also inserts the data into the dataxnametypes. s.updateFromRfEndpoint(rfEP) } @@ -204,8 +207,9 @@ func (s *SmD) doDiscovery(rfEP *rf.RedfishEP) { // RedfishEndpoint. // // Args: -// rfEP - A discovered rf.RedfishEP, created from a RedfishEndpoint -// and then queried via gets to the specified destination. +// +// rfEP - A discovered rf.RedfishEP, created from a RedfishEndpoint +// and then queried via gets to the specified destination. func (s *SmD) updateFromRfEndpoint(rfEP *rf.RedfishEP) error { ep := sm.NewRedfishEndpoint(&rfEP.RedfishEPDescription) var savedErr error = nil @@ -305,7 +309,7 @@ func (s *SmD) updateFromRfEndpoint(rfEP *rf.RedfishEP) error { savedPw = ep.Password savedUn = ep.User if s.readVault { - // Empty the password so it doesn't get stored in the database. + // Empty the password so it doesn't get stored in the dataxnametypes. ep.Password = "" } } @@ -316,7 +320,7 @@ func (s *SmD) updateFromRfEndpoint(rfEP *rf.RedfishEP) error { compMap := make(map[string]*base.Component) compList := make([]string, 0, 1) for _, comp := range comps.Components { - if comp.Type == base.Node.String() && comp.State == base.StateOn.String() { + if comp.Type == xnametypes.Node.String() && comp.State == base.StateOn.String() { compMap[comp.ID] = comp compList = append(compList, comp.ID) } @@ -385,7 +389,7 @@ func (s *SmD) updateFromRfEndpoint(rfEP *rf.RedfishEP) error { if err != nil { // If we fail to store credentials in vault, we'll lose the // credentials and the component endpoints associated with - // them will still be successfully in the database. + // them will still be successfully in the dataxnametypes. s.LogAlways("Failed to store credentials for %s in Vault - %s", cep.ID, err) savedErr = err } @@ -640,7 +644,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err } hwlocs = append(hwlocs, hwloc) for _, powerSupplyEP := range chEP.PowerSupplies.OIDs { - if powerSupplyEP.Type == base.CMMRectifier.String() { + if powerSupplyEP.Type == xnametypes.CMMRectifier.String() { hwloc, err := s.DiscoverHWInvByLocCMMRectifier(powerSupplyEP) if err != nil { if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported { @@ -652,7 +656,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err return nil, err } hwlocs = append(hwlocs, hwloc) - } else if powerSupplyEP.Type == base.NodeEnclosurePowerSupply.String() { + } else if powerSupplyEP.Type == xnametypes.NodeEnclosurePowerSupply.String() { hwloc, err := s.DiscoverHWInvByLocNodeEnclosurePowerSupply(powerSupplyEP) if err != nil { if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported { @@ -711,7 +715,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err } hwlocs = append(hwlocs, hwloc) } - + for _, procEP := range sysEP.Processors.OIDs { hwloc, err := s.DiscoverHWInvByLocProcessor(procEP) if err != nil { @@ -752,7 +756,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err hwlocs = append(hwlocs, hwloc) } for _, nodeAccelRiserEP := range sysEP.NodeAccelRisers.OIDs { - if nodeAccelRiserEP.Type == base.NodeAccelRiser.String() { + if nodeAccelRiserEP.Type == xnametypes.NodeAccelRiser.String() { hwloc, err := s.DiscoverHWInvByLocNodeAccelRiser(nodeAccelRiserEP) if err != nil { if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported { @@ -767,7 +771,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err } } for _, networkAdapterEP := range sysEP.NetworkAdapters.OIDs { - if networkAdapterEP.Type == base.NodeHsnNic.String() { + if networkAdapterEP.Type == xnametypes.NodeHsnNic.String() { hwloc, err := s.DiscoverHWInvByLocNodeHsnNic(networkAdapterEP) if err != nil { if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported { @@ -813,7 +817,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err // Managers from Redfish "Manager" objects for _, managerEP := range rfEP.Managers.OIDs { - if managerEP.Type == base.NodeBMC.String() { + if managerEP.Type == xnametypes.NodeBMC.String() { hwloc, err := s.DiscoverHWInvByLocNodeBMC(managerEP) if err != nil { if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported { @@ -826,7 +830,7 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err } hwlocs = append(hwlocs, hwloc) } - if managerEP.Type == base.RouterBMC.String() { + if managerEP.Type == xnametypes.RouterBMC.String() { hwloc, err := s.DiscoverHWInvByLocRouterBMC(managerEP) if err != nil { if err == base.ErrHMSTypeInvalid || err == base.ErrHMSTypeUnsupported { @@ -850,11 +854,12 @@ func (s *SmD) DiscoverHWInvByLocArray(rfEP *rf.RedfishEP) ([]*sm.HWInvByLoc, err // Generate HWInv history entries. This determines the historical event type // based on the most recent entry for that FRU. -// - No history means we are adding. -// - Previously removed means we are adding. -// - Same location means we are scanning. -// - Different location mean we are removing from the previous location and -// adding to the new location. (Removal event wasn't generated) +// - No history means we are adding. +// - Previously removed means we are adding. +// - Same location means we are scanning. +// - Different location mean we are removing from the previous location and +// adding to the new location. (Removal event wasn't generated) +// // If a eventType is specified, all generated entries will be forced to that // event type. func (s *SmD) GenerateHWInvHist(hwlocs []*sm.HWInvByLoc) error { @@ -926,35 +931,35 @@ func (s *SmD) DiscoverHWInvByLocChassis(chEP *rf.EpChassis) (*sm.HWInvByLoc, err hwloc.PopulatedFRU = hwfru } //rfChassisLocationInfo := &chEP.ChassisRF.ChassisLocationInfoRF - switch base.ToHMSType(hwloc.Type) { - case base.Cabinet: + switch xnametypes.ToHMSType(hwloc.Type) { + case xnametypes.Cabinet: hwloc.HMSCabinetLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocCabinet - case base.Chassis: + case xnametypes.Chassis: hwloc.HMSChassisLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocChassis - case base.ComputeModule: + case xnametypes.ComputeModule: hwloc.HMSComputeModuleLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocComputeModule - case base.RouterModule: + case xnametypes.RouterModule: hwloc.HMSRouterModuleLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocRouterModule - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: hwloc.HMSNodeEnclosureLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocNodeEnclosure - case base.HSNBoard: + case xnametypes.HSNBoard: hwloc.HMSHSNBoardLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocHSNBoard - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: hwloc.HMSMgmtSwitchLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocMgmtSwitch - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: hwloc.HMSMgmtHLSwitchLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocMgmtHLSwitch - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: hwloc.HMSCDUMgmtSwitchLocationInfo = &chEP.ChassisRF.ChassisLocationInfoRF hwloc.HWInventoryByLocationType = sm.HWInvByLocCDUMgmtSwitch - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err := base.ErrHMSTypeInvalid return nil, err default: @@ -1015,8 +1020,8 @@ func (s *SmD) DiscoverHWInvByLocHpeDevice(hpeDeviceEP *rf.EpHpeDevice) (*sm.HWIn } hwloc.PopulatedFRU = hwfru } - switch base.ToHMSType(hwloc.Type) { - case base.NodeAccel: + switch xnametypes.ToHMSType(hwloc.Type) { + case xnametypes.NodeAccel: accelInfo := rf.ProcessorLocationInfoRF{ Id: hpeDeviceEP.DeviceRF.Id, Name: hpeDeviceEP.DeviceRF.Name, @@ -1024,7 +1029,7 @@ func (s *SmD) DiscoverHWInvByLocHpeDevice(hpeDeviceEP *rf.EpHpeDevice) (*sm.HWIn } hwloc.HMSNodeAccelLocationInfo = &accelInfo hwloc.HWInventoryByLocationType = sm.HWInvByLocNodeAccel - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: nicInfo := rf.NALocationInfoRF{ Id: hpeDeviceEP.DeviceRF.Id, Name: hpeDeviceEP.DeviceRF.Name, @@ -1032,7 +1037,7 @@ func (s *SmD) DiscoverHWInvByLocHpeDevice(hpeDeviceEP *rf.EpHpeDevice) (*sm.HWIn } hwloc.HMSHSNNICLocationInfo = &nicInfo hwloc.HWInventoryByLocationType = sm.HWInvByLocHSNNIC - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err := base.ErrHMSTypeInvalid return nil, err default: @@ -1380,35 +1385,35 @@ func (s *SmD) DiscoverHWInvByFRUChassis(chEP *rf.EpChassis) (*sm.HWInvByFRU, err hwfru.Subtype = chEP.Subtype rfChassisFRUInfo := &chEP.ChassisRF.ChassisFRUInfoRF - switch base.ToHMSType(hwfru.Type) { - case base.Cabinet: + switch xnametypes.ToHMSType(hwfru.Type) { + case xnametypes.Cabinet: hwfru.HMSCabinetFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUCabinet - case base.Chassis: + case xnametypes.Chassis: hwfru.HMSChassisFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUChassis - case base.ComputeModule: + case xnametypes.ComputeModule: hwfru.HMSComputeModuleFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUComputeModule - case base.RouterModule: + case xnametypes.RouterModule: hwfru.HMSRouterModuleFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRURouterModule - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: hwfru.HMSNodeEnclosureFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUNodeEnclosure - case base.HSNBoard: + case xnametypes.HSNBoard: hwfru.HMSHSNBoardFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUHSNBoard - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: hwfru.HMSMgmtSwitchFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUMgmtSwitch - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: hwfru.HMSMgmtHLSwitchFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUMgmtHLSwitch - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: hwfru.HMSCDUMgmtSwitchFRUInfo = rfChassisFRUInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUCDUMgmtSwitch - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err := base.ErrHMSTypeInvalid return nil, err default: @@ -1464,27 +1469,27 @@ func (s *SmD) DiscoverHWInvByFRUHpeDevice(hpeDeviceEP *rf.EpHpeDevice) (*sm.HWIn hwfru.Type = hpeDeviceEP.Type hwfru.Subtype = hpeDeviceEP.Subtype - switch base.ToHMSType(hwfru.Type) { - case base.NodeAccel: + switch xnametypes.ToHMSType(hwfru.Type) { + case xnametypes.NodeAccel: accelInfo := rf.ProcessorFRUInfoRF{ - Manufacturer: hpeDeviceEP.DeviceRF.Manufacturer, - Model: hpeDeviceEP.DeviceRF.Model, - SerialNumber: hpeDeviceEP.DeviceRF.SerialNumber, - PartNumber: hpeDeviceEP.DeviceRF.PartNumber, + Manufacturer: hpeDeviceEP.DeviceRF.Manufacturer, + Model: hpeDeviceEP.DeviceRF.Model, + SerialNumber: hpeDeviceEP.DeviceRF.SerialNumber, + PartNumber: hpeDeviceEP.DeviceRF.PartNumber, ProcessorType: hpeDeviceEP.DeviceRF.DeviceType, } hwfru.HMSNodeAccelFRUInfo = &accelInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUNodeAccel - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: nicInfo := rf.NAFRUInfoRF{ Manufacturer: hpeDeviceEP.DeviceRF.Manufacturer, - Model: hpeDeviceEP.DeviceRF.Model, + Model: hpeDeviceEP.DeviceRF.Model, SerialNumber: hpeDeviceEP.DeviceRF.SerialNumber, - PartNumber: hpeDeviceEP.DeviceRF.PartNumber, + PartNumber: hpeDeviceEP.DeviceRF.PartNumber, } hwfru.HMSHSNNICFRUInfo = &nicInfo hwfru.HWInventoryByFRUType = sm.HWInvByFRUHSNNIC - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err := base.ErrHMSTypeInvalid return nil, err default: @@ -1515,7 +1520,7 @@ func (s *SmD) DiscoverHWInvByFRUProcessor(procEP *rf.EpProcessor) (*sm.HWInvByFR hwfru.Type = procEP.Type hwfru.Subtype = procEP.Subtype - if procEP.Type == base.NodeAccel.String() { + if procEP.Type == xnametypes.NodeAccel.String() { hwfru.HMSNodeAccelFRUInfo = &procEP.ProcessorRF.ProcessorFRUInfoRF hwfru.HWInventoryByFRUType = sm.HWInvByFRUNodeAccel } else { @@ -1523,7 +1528,6 @@ func (s *SmD) DiscoverHWInvByFRUProcessor(procEP *rf.EpProcessor) (*sm.HWInvByFR hwfru.HWInventoryByFRUType = sm.HWInvByFRUProcessor } - return hwfru, nil } diff --git a/cmd/smd/hmsdsmock_test.go b/cmd/smd/hmsdsmock_test.go index 93d876b..4b12a13 100644 --- a/cmd/smd/hmsdsmock_test.go +++ b/cmd/smd/hmsdsmock_test.go @@ -25,7 +25,7 @@ package main import ( "log" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/internal/hmsds" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" ) @@ -1460,7 +1460,8 @@ func (d *hmsdbtest) UpsertComponents(comps []*base.Component, force bool) (map[s // // If force = true ignores any starting state restrictions and will // always set ids to 'state', unless it is already set. -// Note: If flag is not set, it will be set to OK (i.e. no flag) +// +// Note: If flag is not set, it will be set to OK (i.e. no flag) func (d *hmsdbtest) UpdateCompStates(ids []string, state string, flag string, force bool, pi *hmsds.PartInfo) ([]string, error) { d.t.UpdateCompStates.Input.ids = ids d.t.UpdateCompStates.Input.state = state @@ -1610,7 +1611,7 @@ func (d *hmsdbtest) DeleteNodeMapByID(id string) (bool, error) { return d.t.DeleteNodeMapByID.Return.changed, d.t.DeleteNodeMapByID.Return.err } -// Delete all Node NID Mapping entries from database. +// Delete all Node NID Mapping entries from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteNodeMapsAll() (int64, error) { return d.t.DeleteNodeMapsAll.Return.numRows, d.t.DeleteNodeMapsAll.Return.err @@ -1654,7 +1655,7 @@ func (d *hmsdbtest) DeletePowerMapByID(id string) (bool, error) { return d.t.DeletePowerMapByID.Return.changed, d.t.DeletePowerMapByID.Return.err } -// Delete all Power Mapping entries from database. +// Delete all Power Mapping entries from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeletePowerMapsAll() (int64, error) { return d.t.DeletePowerMapsAll.Return.numRows, d.t.DeletePowerMapsAll.Return.err @@ -1891,7 +1892,7 @@ func (d *hmsdbtest) GetRFEndpointsFilter(f *hmsds.RedfishEPFilter) ([]*sm.Redfis return d.t.GetRFEndpointsFilter.Return.entries, d.t.GetRFEndpointsFilter.Return.err } -// Insert new RedfishEndpoint into database. +// Insert new RedfishEndpoint into dataxnametypes. // Does not update any ComponentEndpoint children. // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -1910,7 +1911,7 @@ func (d *hmsdbtest) InsertRFEndpoints(eps *sm.RedfishEndpointArray) error { return d.t.InsertRFEndpoints.Return.err } -// Update existing RedfishEndpointArray entry in database. +// Update existing RedfishEndpointArray entry in dataxnametypes. // Does not update any ComponentEndpoint children. // Returns updated entry or nil/nil if not found. If an error occurred, // nil/error will be returned. @@ -1972,7 +1973,7 @@ func (d *hmsdbtest) DeleteRFEndpointByID(id string) (bool, error) { return d.t.DeleteRFEndpointByID.Return.changed, d.t.DeleteRFEndpointByID.Return.err } -// Delete all RedfishEndpoints from database. +// Delete all RedfishEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteRFEndpointsAll() (int64, error) { return d.t.DeleteRFEndpointsAll.Return.numRows, d.t.DeleteRFEndpointsAll.Return.err @@ -1989,7 +1990,7 @@ func (d *hmsdbtest) DeleteRFEndpointByIDSetEmpty(id string) (bool, []string, err d.t.DeleteRFEndpointByIDSetEmpty.Return.err } -// Delete all RedfishEndpoints from database. +// Delete all RedfishEndpoints from dataxnametypes. // This also deletes all child ComponentEndpoints, and in addition, // sets the State/Components entries for those ComponentEndpoints to Empty/OK // Also returns number of deleted rows, if error is nil. @@ -2048,7 +2049,7 @@ func (d *hmsdbtest) DeleteCompEndpointByID(id string) (bool, error) { return d.t.DeleteCompEndpointByID.Return.changed, d.t.DeleteCompEndpointByID.Return.err } -// Delete all ComponentEndpoints from database. +// Delete all ComponentEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteCompEndpointsAll() (int64, error) { return d.t.DeleteCompEndpointsAll.Return.numRows, d.t.DeleteCompEndpointsAll.Return.err @@ -2066,7 +2067,7 @@ func (d *hmsdbtest) DeleteCompEndpointByIDSetEmpty(id string) (bool, []string, e d.t.DeleteCompEndpointByIDSetEmpty.Return.err } -// Delete all ComponentEndpoints from database. In addition, +// Delete all ComponentEndpoints from dataxnametypes. In addition, // sets the State/Components entry for each ComponentEndpoint to Empty/OK // Also returns number of deleted rows, if error is nil, and also string array // of those xname IDs that were set to Empty/OK (i.e. not already Empty/OK) @@ -2127,7 +2128,7 @@ func (d *hmsdbtest) DeleteServiceEndpointByID(svc, id string) (bool, error) { return d.t.DeleteServiceEndpointByID.Return.changed, d.t.DeleteServiceEndpointByID.Return.err } -// Delete all ServiceEndpoints from database. +// Delete all ServiceEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteServiceEndpointsAll() (int64, error) { return d.t.DeleteServiceEndpointsAll.Return.numRows, d.t.DeleteServiceEndpointsAll.Return.err @@ -2154,7 +2155,7 @@ func (d *hmsdbtest) GetCompEthInterfaceFilter(f_opts ...hmsds.CompEthInterfaceFi return d.t.GetCompEthInterfaceFilter.Return.ceis, d.t.GetCompEthInterfaceFilter.Return.err } -// Insert a new CompEthInterface into the database. +// Insert a new CompEthInterface into the dataxnametypes. // If ID or MAC address already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil func (d *hmsdbtest) InsertCompEthInterface(cei *sm.CompEthInterfaceV2) error { @@ -2171,7 +2172,7 @@ func (d *hmsdbtest) InsertCompEthInterfaces(ceis []*sm.CompEthInterfaceV2) error return d.t.InsertCompEthInterfaces.Return.err } -// Insert/update a CompEthInterface in the database. +// Insert/update a CompEthInterface in the dataxnametypes. // If ID or MAC address already exists, only overwrite ComponentID // and Type fields. // No insertion done on err != nil @@ -2222,7 +2223,7 @@ func (d *hmsdbtest) DeleteCompEthInterfaceByID(id string) (bool, error) { return d.t.DeleteCompEthInterfaceByID.Return.didDelete, d.t.DeleteCompEthInterfaceByID.Return.err } -// Delete all CompEthInterfaces from the database. +// Delete all CompEthInterfaces from the dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteCompEthInterfacesAll() (int64, error) { return d.t.DeleteCompEthInterfacesAll.Return.numRows, d.t.DeleteCompEthInterfacesAll.Return.err @@ -2230,9 +2231,9 @@ func (d *hmsdbtest) DeleteCompEthInterfacesAll() (int64, error) { // Add IP Address mapping to the existing component ethernet interface. // returns: -// - ErrHMSDSNoCompEthInterface if the parent component ethernet interface -// - ErrHMSDSDuplicateKey if the parent component ethernet interface already -// has that IP address +// - ErrHMSDSNoCompEthInterface if the parent component ethernet interface +// - ErrHMSDSDuplicateKey if the parent component ethernet interface already +// has that IP address // // Returns key of new IP Address Mapping id, should be the IP address func (d *hmsdbtest) AddCompEthInterfaceIPAddress(id string, ipm *sm.IPAddressMapping) (string, error) { @@ -2295,16 +2296,15 @@ func (d *hmsdbtest) UpsertDiscoveryStatus(stat *sm.DiscoveryStatus) error { // Atomically: // -// 1. Update discovery-writable fields for RedfishEndpoint -// 2. Upsert ComponentEndpointArray into database within the -// same transaction. -// 3. Insert or update array of HWInventoryByLocation structs. -// If PopulatedFRU is present, these is also added to the DB If -// it is not, this effectively "depopulates" the given locations. -// The actual HWInventoryByFRU is stored using within the same -// transaction. -// 4. Inserts or updates HMS Components entries in ComponentArray -// +// 1. Update discovery-writable fields for RedfishEndpoint +// 2. Upsert ComponentEndpointArray into database within the +// same transaction. +// 3. Insert or update array of HWInventoryByLocation structs. +// If PopulatedFRU is present, these is also added to the DB If +// it is not, this effectively "depopulates" the given locations. +// The actual HWInventoryByFRU is stored using within the same +// transaction. +// 4. Inserts or updates HMS Components entries in ComponentArray func (d *hmsdbtest) UpdateAllForRFEndpoint( ep *sm.RedfishEndpoint, ceps *sm.ComponentEndpointArray, diff --git a/cmd/smd/job-types.go b/cmd/smd/job-types.go index 20dc81e..2a7210a 100644 --- a/cmd/smd/job-types.go +++ b/cmd/smd/job-types.go @@ -27,7 +27,6 @@ import ( "encoding/json" "errors" "fmt" - "github.com/hashicorp/go-retryablehttp" "io/ioutil" "log" "net/http" @@ -35,7 +34,9 @@ import ( "sync" "time" - base "github.com/Cray-HPE/hms-base" + "github.com/hashicorp/go-retryablehttp" + + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" ) @@ -57,9 +58,9 @@ var JTypeString = map[base.JobType]string{ JTYPE_MAX: "JTYPE_MAX", } -/////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////// // Job: JTYPE_SCN -/////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////// type JobSCN struct { Status base.JobStatus IDs []string @@ -69,14 +70,14 @@ type JobSCN struct { Logger *log.Logger } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Create a JTYPE_SCN job data structure. // // ids(in): List of XNames to be sent in the SCN // state(in): The state of the components in 'ids'. // s(in): SmD instance we are working on behalf of. // Return: Job data structure to be used by work Q. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func NewJobSCN(ids []string, data base.Component, s *SmD) base.Job { j := new(JobSCN) j.Status = base.JSTAT_DEFAULT @@ -88,36 +89,36 @@ func NewJobSCN(ids []string, data base.Component, s *SmD) base.Job { return j } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Log function for SCN job. Note that for now this is just a simple // log call, but may be expanded in the future. // // format(in): Printf-like format string. // a(in): Printf-like argument list. // Return: None. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobSCN) Log(format string, a ...interface{}) { // Use caller's line number (depth=2) j.Logger.Output(2, fmt.Sprintf(format, a...)) } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Return current job type. // // Args: None // Return: Job type. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobSCN) Type() base.JobType { return JTYPE_SCN } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Run a job. This is done by the worker pool when popping a job off of the // work Q/chan. // // Args: None. // Return: None. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobSCN) Run() { var trigger string var triggerType int @@ -178,14 +179,14 @@ func (j *JobSCN) Run() { for retry := 0; retry < 3; retry++ { var strbody []byte req, rerr := http.NewRequest("POST", urlStr, bytes.NewReader(payload)) - if (err != nil) { + if err != nil { j.s.LogAlways("WARNING: can't create an HTTP request: %v", rerr) time.Sleep(5 * time.Second) continue } base.SetHTTPUserAgent(req, serviceName) - req.Header.Add("Content-Type","application/json") + req.Header.Add("Content-Type", "application/json") newRequest, rerr := retryablehttp.FromRequest(req) if err != nil { j.s.LogAlways("WARNING: can't create an HTTP request: %v", @@ -214,12 +215,12 @@ func (j *JobSCN) Run() { waitGroup.Wait() } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Return the current job status and error info. // // Args: None // Return: Current job status, and any error info (if any). -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobSCN) GetStatus() (base.JobStatus, error) { if j.Status == base.JSTAT_ERROR { return j.Status, j.Err @@ -227,13 +228,13 @@ func (j *JobSCN) GetStatus() (base.JobStatus, error) { return j.Status, nil } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Set job status. // // newStatus(in): Status to set job to. // err(in): Error info to associate with the job. // Return: Previous job status; nil on success, error string on error. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobSCN) SetStatus(newStatus base.JobStatus, err error) (base.JobStatus, error) { if newStatus >= base.JSTAT_MAX { return j.Status, errors.New("Error: Invalid Status") @@ -245,13 +246,13 @@ func (j *JobSCN) SetStatus(newStatus base.JobStatus, err error) (base.JobStatus, } } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Cancel a job. Note that this JobType does not support cancelling the // job while it is being processed // // Args: None // Return: Current job status before cancelling. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobSCN) Cancel() base.JobStatus { if j.Status == base.JSTAT_QUEUED || j.Status == base.JSTAT_DEFAULT { j.Status = base.JSTAT_CANCELLED @@ -259,9 +260,9 @@ func (j *JobSCN) Cancel() base.JobStatus { return j.Status } -/////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////// // Job: JTYPE_RFEVENT -/////////////////////////////////////////////////////////////////////////////// +// ///////////////////////////////////////////////////////////////////////////// type JobRFEvent struct { Status base.JobStatus Payload string @@ -270,13 +271,13 @@ type JobRFEvent struct { Logger *log.Logger } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Create a JTYPE_RFEVENT job data structure. // // payload(in): The raw redfish event to process // s(in): SmD instance we are working on behalf of. // Return: Job data structure to be used by work Q. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func NewJobRFEvent(payload string, s *SmD) base.Job { j := new(JobRFEvent) j.Status = base.JSTAT_DEFAULT @@ -287,36 +288,36 @@ func NewJobRFEvent(payload string, s *SmD) base.Job { return j } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Log function for SCN job. Note that for now this is just a simple // log call, but may be expanded in the future. // // format(in): Printf-like format string. // a(in): Printf-like argument list. // Return: None. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobRFEvent) Log(format string, a ...interface{}) { // Use caller's line number (depth=2) j.Logger.Output(2, fmt.Sprintf(format, a...)) } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Return current job type. // // Args: None // Return: Job type. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobRFEvent) Type() base.JobType { return JTYPE_RFEVENT } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Run a job. This is done by the worker pool when popping a job off of the // work Q/chan. // // Args: None. // Return: None. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobRFEvent) Run() { err := j.s.doHandleRFEvent(j.Payload) if err != nil { @@ -324,12 +325,12 @@ func (j *JobRFEvent) Run() { } } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Return the current job status and error info. // // Args: None // Return: Current job status, and any error info (if any). -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobRFEvent) GetStatus() (base.JobStatus, error) { if j.Status == base.JSTAT_ERROR { return j.Status, j.Err @@ -337,13 +338,13 @@ func (j *JobRFEvent) GetStatus() (base.JobStatus, error) { return j.Status, nil } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Set job status. // // newStatus(in): Status to set job to. // err(in): Error info to associate with the job. // Return: Previous job status; nil on success, error string on error. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobRFEvent) SetStatus(newStatus base.JobStatus, err error) (base.JobStatus, error) { if newStatus >= base.JSTAT_MAX { return j.Status, errors.New("Error: Invalid Status") @@ -355,13 +356,13 @@ func (j *JobRFEvent) SetStatus(newStatus base.JobStatus, err error) (base.JobSta } } -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// // Cancel a job. Note that this JobType does not support cancelling the // job while it is being processed // // Args: None // Return: Current job status before cancelling. -///////////////////////////////////////////////////////////////////////////// +// /////////////////////////////////////////////////////////////////////////// func (j *JobRFEvent) Cancel() base.JobStatus { if j.Status == base.JSTAT_QUEUED || j.Status == base.JSTAT_DEFAULT { j.Status = base.JSTAT_CANCELLED diff --git a/cmd/smd/msgbus.go b/cmd/smd/msgbus.go index add29b7..48a114c 100644 --- a/cmd/smd/msgbus.go +++ b/cmd/smd/msgbus.go @@ -23,10 +23,11 @@ package main import ( - base "github.com/Cray-HPE/hms-base" - msgbus "github.com/Cray-HPE/hms-msgbus" "strconv" "strings" + + base "github.com/Cray-HPE/hms-base/v2" + msgbus "github.com/Cray-HPE/hms-msgbus" ) var MsgBusAlreadyConnected = base.NewHMSError("sm_msg", diff --git a/cmd/smd/response.go b/cmd/smd/response.go index f3188fe..69093a3 100644 --- a/cmd/smd/response.go +++ b/cmd/smd/response.go @@ -27,7 +27,7 @@ import ( "fmt" "net/http" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" ) @@ -48,7 +48,7 @@ func sendJsonError(w http.ResponseWriter, ecode int, message string) { if ecode < 400 { sendJsonResponse(w, ecode, message) } else { - // Use library function in HMS base. Problem will be + // Use library function in HMS xnametypes. Problem will be // a generic one with title matching the HTTP Status code text // with message as the details field. For this type of problem // title can just be set to "about:blank" so we need no diff --git a/cmd/smd/rfevent.go b/cmd/smd/rfevent.go index 289faa0..6d50900 100644 --- a/cmd/smd/rfevent.go +++ b/cmd/smd/rfevent.go @@ -28,10 +28,11 @@ import ( "strings" "sync" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "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/Cray-HPE/hms-xname/xnametypes" ) var em = base.NewHMSError("sm.msgbus", "internal error") @@ -132,7 +133,6 @@ func (s *SmD) doHandleRFEvent(eventRaw string) error { // 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 { @@ -218,8 +218,8 @@ func EventContextDecode( for i, field := range fields { setID := false if i == 0 || (xnameID == "" && anyXName == true) { - normField := base.NormalizeHMSCompID(field) - if base.IsHMSTypeController(base.GetHMSType(normField)) { + normField := xnametypes.NormalizeHMSCompID(field) + if xnametypes.IsHMSTypeController(xnametypes.GetHMSType(normField)) { xnameID = normField setID = true } @@ -290,10 +290,12 @@ type EventActionParser func(*SmD, *processedRFEvent) (*CompUpdate, error) // 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 +// +// 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 // +// MessageId:Registry:vers, but this time include maj version, i.e. 1.1 var eventActionParserLookup = map[string]EventActionParser{ "resourcepowerstatechanged": nil, "resourcepowerstatechanged:resourceevent": ResourcePowerStateChangedParser, @@ -362,8 +364,9 @@ const ( ) // EventActionParser - ResourcePowerStateChanged - Cray addition to standard -// ResourceEvent registry. Need to look at payload to see -// new state and component type. +// +// 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 @@ -402,14 +405,14 @@ func ResourcePowerStateChangedParser(s *SmD, pe *processedRFEvent) (*CompUpdate, // 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 base.GetHMSType(pe.RfEndppointID) { - case base.ChassisBMC: + switch xnametypes.GetHMSType(pe.RfEndppointID) { + case xnametypes.ChassisBMC: return powerStateCMM(s, pe, xname, op) - case base.NodeBMC: + case xnametypes.NodeBMC: return powerStateNC(s, pe, xname, op) - case base.RouterBMC: + case xnametypes.RouterBMC: return powerStateRC(s, pe, xname, op) - case base.CabinetPDUController: + case xnametypes.CabinetPDUController: return powerStateCabPDUController(s, pe, xname, op) default: return nil, ErrSmMsgBadID @@ -433,11 +436,11 @@ func powerStateCMM(s *SmD, pe *processedRFEvent, // Should never happen. return u, ErrSmMsgNoPowerState } - switch base.GetHMSType(xname) { - case base.ComputeModule: + switch xnametypes.GetHMSType(xname) { + case xnametypes.ComputeModule: ids := generateNcChildIDs(s, xname, op) u.ComponentIDs = append(u.ComponentIDs, ids...) - case base.RouterModule: + case xnametypes.RouterModule: ids := generateRcChildIDs(s, xname, op) u.ComponentIDs = append(u.ComponentIDs, ids...) } @@ -448,7 +451,7 @@ func powerStateCMM(s *SmD, pe *processedRFEvent, // cause a retry later. if u.State == base.StateOn.String() { for _, id := range u.ComponentIDs { - if base.IsHMSTypeController(base.GetHMSType(id)) { + 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) @@ -474,7 +477,7 @@ func powerStateNC(s *SmD, pe *processedRFEvent, case ResourceOn: u.State = base.StateOn.String() // Update hwinv for nodes - if base.GetHMSType(xname) == base.Node { + if xnametypes.GetHMSType(xname) == xnametypes.Node { cep, ep, err := s.getCompEPInfo(xname) if err == nil { go s.doUpdateCompHWInv(cep, ep) @@ -549,12 +552,12 @@ func generateNcChildIDs(s *SmD, xname string, op ResourceOp) []string { if op == ResourceOn { // Only turn the cards on, not the nodes, when slot comes up. for _, childID := range children { - switch base.GetHMSType(childID) { - case base.NodeEnclosure: + switch xnametypes.GetHMSType(childID) { + case xnametypes.NodeEnclosure: fallthrough - case base.NodeBMC: + case xnametypes.NodeBMC: fallthrough - case base.NodeBMCNic: + case xnametypes.NodeBMCNic: ids = append(ids, childID) } } @@ -594,8 +597,9 @@ func generateRcChildIDs(s *SmD, xname string, op ResourceOp) []string { ///////////////////////////////////////////////////////////////////////////// // EventActionParser - Alert, presumably from Intel BMC, that indicates -// System (i.e. node) powered ON. -// Id in OriginOfCondition (though likely single node). +// +// 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) @@ -605,7 +609,7 @@ func AlertSystemPowerOnParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) return nil, ErrSmMsgNoID } // Update hwinv for nodes - if base.GetHMSType(xname) == base.Node { + if xnametypes.GetHMSType(xname) == xnametypes.Node { cep, ep, err := s.getCompEPInfo(xname) if err == nil { go s.doUpdateCompHWInv(cep, ep) @@ -618,8 +622,9 @@ func AlertSystemPowerOnParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) } // EventActionParser - Alert, presumably from Intel BMC, that indicates -// System (i.e. node) powered OFF. -// Id in OriginOfCondition (though likely single node). +// +// 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) @@ -639,8 +644,9 @@ func AlertSystemPowerOffParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error ///////////////////////////////////////////////////////////////////////////// // AlertSystemPowerParser - Alert, presumably from Gigabyte BMC, that indicates -// System (i.e. node) powered ON or OFF. -// Id in OriginOfCondition (though likely single node). +// +// 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 @@ -714,7 +720,7 @@ func AlertSystemPowerParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) { switch op { case ResourceOn: u.State = base.StateOn.String() - if base.GetHMSType(xname) == base.Node { + if xnametypes.GetHMSType(xname) == xnametypes.Node { go s.doUpdateCompHWInv(cep, ep) } case ResourceOff: @@ -724,9 +730,9 @@ func AlertSystemPowerParser(s *SmD, pe *processedRFEvent) (*CompUpdate, error) { } // 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. // +// 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 @@ -772,7 +778,7 @@ func (s *SmD) getCompEPInfo(xname string) (*sm.ComponentEndpoint, *rf.RedfishEP, pw = rep.Password } // Minimally populate a redfish description struct - rfEPType := base.GetHMSType(cep.RfEndpointID) + rfEPType := xnametypes.GetHMSType(cep.RfEndpointID) epDesc := rf.RedfishEPDescription{ ID: cep.RfEndpointID, Type: rfEPType.String(), @@ -786,9 +792,10 @@ func (s *SmD) getCompEPInfo(xname string) (*sm.ComponentEndpoint, *rf.RedfishEP, } // 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. +// +// 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 @@ -818,16 +825,17 @@ func (s *SmD) getCompEPState(cep *sm.ComponentEndpoint, ep *rf.RedfishEP) (strin } // 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. +// +// 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 base.GetHMSType(cep.ID) == base.Node { + if xnametypes.GetHMSType(cep.ID) == xnametypes.Node { // Read from redfish status := ep.GetSystems() if status != rf.HTTPsGetOk { @@ -1186,7 +1194,7 @@ func (s *SmD) checkSyncCompEP(xname string, snum int) (found, didUpdate bool, er ids := []string{} for i := 0; i < CompEPSyncRetries; i++ { - if base.GetHMSType(xname) == base.CabinetPDUController { + if xnametypes.GetHMSType(xname) == xnametypes.CabinetPDUController { // CabinentPDUControllers (xXmM) don't have ComponentEndpoint // entries. See if we've discovered any children. ids, err = s.db.GetCompEndpointIDs(hmsds.CE_RfEPs([]string{xname})) diff --git a/cmd/smd/smd-api.go b/cmd/smd/smd-api.go index e987170..5242c70 100644 --- a/cmd/smd/smd-api.go +++ b/cmd/smd/smd-api.go @@ -30,11 +30,12 @@ import ( "strconv" "strings" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" 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/Cray-HPE/hms-xname/xnametypes" "github.com/gorilla/mux" ) @@ -373,7 +374,7 @@ func (s *SmD) getHMSValues(valSelect HMSValueSelect, w http.ResponseWriter, r *h case HMSValState: values.State = base.GetHMSStateList() case HMSValType: - values.Type = base.GetHMSTypeList() + values.Type = xnametypes.GetHMSTypeList() case HMSValAll: values.Arch = base.GetHMSArchList() values.Class = base.GetHMSClassList() @@ -382,7 +383,7 @@ func (s *SmD) getHMSValues(valSelect HMSValueSelect, w http.ResponseWriter, r *h values.Role = base.GetHMSRoleList() values.SubRole = base.GetHMSSubRoleList() values.State = base.GetHMSStateList() - values.Type = base.GetHMSTypeList() + values.Type = xnametypes.GetHMSTypeList() } sendJsonValueRsp(w, values) } @@ -394,7 +395,7 @@ func (s *SmD) getHMSValues(valSelect HMSValueSelect, w http.ResponseWriter, r *h // Get single HMS component by xname ID func (s *SmD) doComponentGet(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) cmp, err := s.db.GetComponentByID(xname) if err != nil { @@ -414,9 +415,9 @@ func (s *SmD) doComponentGet(w http.ResponseWriter, r *http.Request) { func (s *SmD) doComponentDelete(w http.ResponseWriter, r *http.Request) { s.lg.Printf("doComponentDelete(): trying...") vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) - if !base.IsHMSCompIDValid(xname) { + if !xnametypes.IsHMSCompIDValid(xname) { sendJsonError(w, http.StatusBadRequest, "invalid xname") return } @@ -505,7 +506,7 @@ func (s *SmD) doComponentsPost(w http.ResponseWriter, r *http.Request) { } // Get the nid and role defaults for all node types for _, comp := range compsIn.Components { - if comp.Type == base.Node.String() { + 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 { @@ -649,7 +650,7 @@ func (s *SmD) doComponentsQueryGet(w http.ResponseWriter, r *http.Request) { ids := make([]string, 0, 1) var err error vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) // Parse arguments if err := r.ParseForm(); err != nil { @@ -1019,7 +1020,7 @@ func (s *SmD) componentPatch( // otherwise be write-only fields. func (s *SmD) doComponentPut(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) var compIn sm.ComponentPut body, err := ioutil.ReadAll(r.Body) @@ -1037,7 +1038,7 @@ func (s *SmD) doComponentPut(w http.ResponseWriter, r *http.Request) { } else { component.ID = xname } - } else if base.NormalizeHMSCompID(component.ID) != xname { + } else if xnametypes.NormalizeHMSCompID(component.ID) != xname { sendJsonError(w, http.StatusBadRequest, "ID in URL and POST body do not match") return @@ -1050,7 +1051,7 @@ func (s *SmD) doComponentPut(w http.ResponseWriter, r *http.Request) { return } // Get the nid and role defaults for all node types - if component.Type == base.Node.String() { + if component.Type == xnametypes.Node.String() { if len(component.Role) == 0 || len(component.NID) == 0 || len(component.Class) == 0 { newNID, defRole, defSubRole, defClass := s.GetCompDefaults(component.ID, base.RoleCompute.String(), "", "") if len(component.Role) == 0 { @@ -1215,7 +1216,7 @@ func (s *SmD) doNodeMapsPost(w http.ResponseWriter, r *http.Request) { // UPDATE EXISTING Node->NID mapping by it's xname URI. func (s *SmD) doNodeMapPut(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) var m sm.NodeMap body, err := ioutil.ReadAll(r.Body) @@ -1229,7 +1230,7 @@ func (s *SmD) doNodeMapPut(w http.ResponseWriter, r *http.Request) { if xname != "" { m.ID = xname } - } else if base.NormalizeHMSCompID(m.ID) != xname { + } else if xnametypes.NormalizeHMSCompID(m.ID) != xname { sendJsonError(w, http.StatusBadRequest, "xname in URL and PUT body do not match") return @@ -1268,9 +1269,9 @@ func (s *SmD) doNodeMapPut(w http.ResponseWriter, r *http.Request) { func (s *SmD) doNodeMapDelete(w http.ResponseWriter, r *http.Request) { s.lg.Printf("doNodeMapDelete(): trying...") vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) - if !base.IsHMSCompIDValid(xname) { + if !xnametypes.IsHMSCompIDValid(xname) { sendJsonError(w, http.StatusBadRequest, "invalid xname") return } @@ -1354,7 +1355,7 @@ func (s *SmD) doHWInvByLocationGetAll(w http.ResponseWriter, r *http.Request) { if len(hwInvIn.ID) > 0 { for i, id := range hwInvIn.ID { - normId := base.VerifyNormalizeCompID(id) + normId := xnametypes.VerifyNormalizeCompID(id) if normId == "" { s.lg.Printf("doHWInvByLocationGetAll(): Invalid xname: %s", id) sendJsonError(w, http.StatusBadRequest, "Invalid xname") @@ -1368,7 +1369,7 @@ func (s *SmD) doHWInvByLocationGetAll(w http.ResponseWriter, r *http.Request) { // Validate types if len(hwInvIn.Type) > 0 { for i, cType := range hwInvIn.Type { - normType := base.VerifyNormalizeType(cType) + normType := xnametypes.VerifyNormalizeType(cType) if normType == "" { s.lg.Printf("doHWInvByLocationGetAll(): Invalid HMS type: %s", cType) sendJsonError(w, http.StatusBadRequest, "Invalid HMS type") @@ -1499,7 +1500,7 @@ func (s *SmD) doHWInvByFRUGetAll(w http.ResponseWriter, r *http.Request) { // Validate types if len(hwInvIn.Type) > 0 { for i, cType := range hwInvIn.Type { - normType := base.VerifyNormalizeType(cType) + normType := xnametypes.VerifyNormalizeType(cType) if normType == "" { s.lg.Printf("doHWInvByFRUGetAll(): Invalid HMS type: %s", cType) sendJsonError(w, http.StatusBadRequest, "Invalid HMS type") @@ -1543,7 +1544,7 @@ func (s *SmD) doHWInvByFRUGetAll(w http.ResponseWriter, r *http.Request) { // and optionally nested (fully, or node subcomponents only). func (s *SmD) doHWInvByLocationQueryGet(w http.ResponseWriter, r *http.Request) { var ( - compType base.HMSType + compType xnametypes.HMSType parentQuery bool ) vars := mux.Vars(r) @@ -1576,28 +1577,28 @@ func (s *SmD) doHWInvByLocationQueryGet(w http.ResponseWriter, r *http.Request) // Treat blanks as s0 if xname == "" { - compType = base.System + compType = xnametypes.System } else { - compType = base.GetHMSType(xname) + compType = xnametypes.GetHMSType(xname) } // Validate xnames - if compType == base.HMSTypeInvalid { + if compType == xnametypes.HMSTypeInvalid { s.lg.Printf("doHWInvByLocationQueryGet(): Invalid xname: %s", xname) sendJsonError(w, http.StatusBadRequest, "Invalid xname") return - } else if compType == base.Partition { + } else if compType == xnametypes.Partition { hwInvIn.Partition = append(hwInvIn.Partition, xname) - } else if !(compType == base.System || compType == base.HMSTypeAll) { + } else if !(compType == xnametypes.System || compType == xnametypes.HMSTypeAll) { // Add anything other than s0 or "all". If it is s0 or "all" we // leave ID empty so it will cause the filter to query everything. - hwInvLocFilter = append(hwInvLocFilter, hmsds.HWInvLoc_ID(base.NormalizeHMSCompID(xname))) + hwInvLocFilter = append(hwInvLocFilter, hmsds.HWInvLoc_ID(xnametypes.NormalizeHMSCompID(xname))) } // Validate types if len(hwInvIn.Type) > 0 { for i, cType := range hwInvIn.Type { - normType := base.VerifyNormalizeType(cType) + normType := xnametypes.VerifyNormalizeType(cType) if normType == "" { s.lg.Printf("doHWInvByLocationQueryGet(): Invalid HMS type: %s", cType) sendJsonError(w, http.StatusBadRequest, "Invalid HMS type") @@ -1820,7 +1821,7 @@ func (s *SmD) hwInvHistGet(w http.ResponseWriter, r *http.Request, format sm.HWI switch format { case sm.HWInvHistFmtByLoc: - normId := base.VerifyNormalizeCompID(id) + normId := xnametypes.VerifyNormalizeCompID(id) if normId == "" { s.lg.Printf("hwInvHistGet(%s): Invalid xname: %s", id, id) sendJsonError(w, http.StatusBadRequest, "Invalid xname") @@ -1928,7 +1929,7 @@ func (s *SmD) hwInvHistGetAll(w http.ResponseWriter, r *http.Request, format sm. if len(hwInvHistIn.ID) > 0 { for i, id := range hwInvHistIn.ID { - normId := base.VerifyNormalizeCompID(id) + normId := xnametypes.VerifyNormalizeCompID(id) if normId == "" { s.lg.Printf("hwInvHistGetAll(%s): Invalid xname: %s", fmtStr, id) sendJsonError(w, http.StatusBadRequest, "Invalid xname") @@ -1987,7 +1988,7 @@ func (s *SmD) hwInvHistGetAll(w http.ResponseWriter, r *http.Request, format sm. func (s *SmD) doHWInvHistByLocationDelete(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) xname := vars["xname"] - normId := base.VerifyNormalizeCompID(xname) + normId := xnametypes.VerifyNormalizeCompID(xname) if normId == "" { s.lg.Printf("doHWInvHistByLocationDelete(%s): Invalid xname: %s", xname, xname) sendJsonError(w, http.StatusBadRequest, "Invalid xname") @@ -2181,7 +2182,7 @@ func (s *SmD) doRedfishEndpointsDeleteAll(w http.ResponseWriter, r *http.Request // user-writable portions). func (s *SmD) doRedfishEndpointPut(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) var rep rf.RawRedfishEP var cred compcreds.CompCredentials @@ -2196,7 +2197,7 @@ func (s *SmD) doRedfishEndpointPut(w http.ResponseWriter, r *http.Request) { if xname != "" { rep.ID = xname } - } else if base.NormalizeHMSCompID(rep.ID) != xname { + } else if xnametypes.NormalizeHMSCompID(rep.ID) != xname { sendJsonError(w, http.StatusBadRequest, "xname in URL and PUT body do not match") return @@ -2250,7 +2251,7 @@ func (s *SmD) doRedfishEndpointPut(w http.ResponseWriter, r *http.Request) { // redfish endpoint changes we just made in the database? If we // fail to store credentials in vault, we'll lose the credentials // and the redfish endpoints associated with them will still be - // successfully in the database. I think this is ok for now + // successfully in the dataxnametypes. I think this is ok for now // since the future plan is for HSM to only read credentials // from Vault. Other services like REDS should be writing the // credentials to Vault. @@ -2285,7 +2286,7 @@ func (s *SmD) doRedfishEndpointPut(w http.ResponseWriter, r *http.Request) { // PATCH existing RedfishEndpoint entry but only the fields specified. func (s *SmD) doRedfishEndpointPatch(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - xname := base.VerifyNormalizeCompID(vars["xname"]) + xname := xnametypes.VerifyNormalizeCompID(vars["xname"]) var rep sm.RedfishEndpointPatch var epUser string @@ -2354,7 +2355,7 @@ func (s *SmD) doRedfishEndpointPatch(w http.ResponseWriter, r *http.Request) { // redfish endpoint changes we just made in the database? If we // fail to store credentials in vault, we'll lose the credentials // and the redfish endpoints associated with them will still be - // successfully in the database. I think this is ok for now + // successfully in the dataxnametypes. I think this is ok for now // since the future plan is for HSM to only read credentials // from Vault. Other services like REDS should be writing the // credentials to Vault. @@ -2478,7 +2479,7 @@ func (s *SmD) doRedfishEndpointsPost(w http.ResponseWriter, r *http.Request) { // endpoints we just inserted into the database? If we fail to // store credentials in vault, we'll lose the credentials and // the redfish endpoints associated with them will still be - // successfully in the database. I think this is ok for now + // successfully in the dataxnametypes. I think this is ok for now // since the future plan is for HSM to only read credentials // from Vault. Other services like REDS should be writing the // credentials to Vault. @@ -2884,7 +2885,7 @@ func (s *SmD) doCompEthInterfacesGetV2(w http.ResponseWriter, r *http.Request) { } if len(filter.CompID) > 0 { for i, xname := range filter.CompID { - xnameNorm := base.VerifyNormalizeCompID(xname) + xnameNorm := xnametypes.VerifyNormalizeCompID(xname) if len(xnameNorm) == 0 && len(xname) != 0 { s.lg.Printf("doCompEthInterfacesGetV2(): Invalid CompID.") sendJsonError(w, http.StatusBadRequest, "Invalid CompID.") @@ -2897,7 +2898,7 @@ func (s *SmD) doCompEthInterfacesGetV2(w http.ResponseWriter, r *http.Request) { if len(filter.Type) > 0 { for i, compType := range filter.Type { - compTypeNorm := base.VerifyNormalizeType(compType) + compTypeNorm := xnametypes.VerifyNormalizeType(compType) if len(compTypeNorm) == 0 { s.lg.Printf("doCompEthInterfacesGetV2(): Invalid HMS type.") sendJsonError(w, http.StatusBadRequest, "Invalid HMS type.") @@ -3383,7 +3384,7 @@ func (s *SmD) doPostSCNSubscription(w http.ResponseWriter, r *http.Request) { } s.scnSubLock.Lock() - // Insert the subscription into the database. + // Insert the subscription into the dataxnametypes. // Existing subscriptions will be updated. id, err := s.db.InsertSCNSubscription(*subIn) if err != nil { @@ -3555,7 +3556,7 @@ func (s *SmD) doPutSCNSubscription(w http.ResponseWriter, r *http.Request) { } s.scnSubLock.Lock() - // Update the subscription in the database. + // Update the subscription in the dataxnametypes. didUpdate, err := s.db.UpdateSCNSubscription(id, *subIn) if err != nil { s.scnSubLock.Unlock() @@ -3676,7 +3677,7 @@ func (s *SmD) doPatchSCNSubscription(w http.ResponseWriter, r *http.Request) { } s.scnSubLock.Lock() - // Patch the subscription in the database. + // Patch the subscription in the dataxnametypes. didPatch, err := s.db.PatchSCNSubscription(id, patchIn.Op, *patchIn) if err != nil { s.scnSubLock.Unlock() @@ -3691,7 +3692,7 @@ func (s *SmD) doPatchSCNSubscription(w http.ResponseWriter, r *http.Request) { // Patch the cached subscription table. // Look for an existing subscription. Patch it. // Note: There is a possibility that the cached subscription table is out - // of sync with the database. Patch what we have anyway. We'll get + // of sync with the dataxnametypes. Patch what we have anyway. We'll get // corrected by the SCNSubscriptionRefresh() thread. for i, sub := range s.scnSubs.SubscriptionList { if sub.ID == id { @@ -4144,8 +4145,9 @@ func (s *SmD) doGroupDelete(w http.ResponseWriter, r *http.Request) { // To update the tags array and/or description, a PATCH operation can be used. // Omitted fields are not updated. // NOTE: This cannot be used to completely replace the members list. Rather, -// individual members can be removed or added with the -// POST/DELETE {group_label}/members API. +// +// individual members can be removed or added with the +// POST/DELETE {group_label}/members API. func (s *SmD) doGroupPatch(w http.ResponseWriter, r *http.Request) { var groupPatch sm.GroupPatch vars := mux.Vars(r) @@ -4293,8 +4295,8 @@ func (s *SmD) doGroupMembersPost(w http.ResponseWriter, r *http.Request) { "error decoding JSON "+err.Error()) return } - normID := base.NormalizeHMSCompID(memberIn.ID) - if !base.IsHMSCompIDValid(normID) { + normID := xnametypes.NormalizeHMSCompID(memberIn.ID) + if !xnametypes.IsHMSCompIDValid(normID) { s.lg.Printf("doGroupMemberPost(): Invalid xname ID.") sendJsonError(w, http.StatusBadRequest, "invalid xname ID") return @@ -4327,7 +4329,7 @@ func (s *SmD) doGroupMembersPost(w http.ResponseWriter, r *http.Request) { func (s *SmD) doGroupMemberDelete(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) label := sm.NormalizeGroupField(vars["group_label"]) - id := base.NormalizeHMSCompID(vars["xname_id"]) + id := xnametypes.NormalizeHMSCompID(vars["xname_id"]) if sm.VerifyGroupField(label) != nil { s.lg.Printf("doGroupMemberDelete(): Invalid group label.") @@ -4335,7 +4337,7 @@ func (s *SmD) doGroupMemberDelete(w http.ResponseWriter, r *http.Request) { "Invalid group label.") return } - if !base.IsHMSCompIDValid(id) { + if !xnametypes.IsHMSCompIDValid(id) { s.lg.Printf("doGroupMemberDelete(): Invalid xname ID.") sendJsonError(w, http.StatusBadRequest, "invalid xname ID") return @@ -4569,8 +4571,9 @@ func (s *SmD) doPartitionDelete(w http.ResponseWriter, r *http.Request) { // To update the tags array and/or description, a PATCH operation can be used. // Omitted fields are not updated. // NOTE: This cannot be used to completely replace the members list. Rather, -// individual members can be removed or added with the POST/DELETE -// {partition_name}/members API. +// +// individual members can be removed or added with the POST/DELETE +// {partition_name}/members API. func (s *SmD) doPartitionPatch(w http.ResponseWriter, r *http.Request) { var partPatch sm.PartitionPatch vars := mux.Vars(r) @@ -4693,8 +4696,8 @@ func (s *SmD) doPartitionMembersPost(w http.ResponseWriter, r *http.Request) { "error decoding JSON "+err.Error()) return } - normID := base.NormalizeHMSCompID(memberIn.ID) - if !base.IsHMSCompIDValid(normID) { + normID := xnametypes.NormalizeHMSCompID(memberIn.ID) + if !xnametypes.IsHMSCompIDValid(normID) { s.lg.Printf("doPartitionMembersPost(): Invalid xname ID.") sendJsonError(w, http.StatusBadRequest, "invalid xname ID") return @@ -4728,7 +4731,7 @@ func (s *SmD) doPartitionMembersPost(w http.ResponseWriter, r *http.Request) { func (s *SmD) doPartitionMemberDelete(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := sm.NormalizeGroupField(vars["partition_name"]) - id := base.NormalizeHMSCompID(vars["xname_id"]) + id := xnametypes.NormalizeHMSCompID(vars["xname_id"]) if sm.VerifyGroupField(name) != nil { s.lg.Printf("doPartitionMemberDelete(): Invalid partition name.") @@ -4736,7 +4739,7 @@ func (s *SmD) doPartitionMemberDelete(w http.ResponseWriter, r *http.Request) { "Invalid partition name.") return } - if !base.IsHMSCompIDValid(id) { + if !xnametypes.IsHMSCompIDValid(id) { s.lg.Printf("doPartitionMemberDelete(): Invalid xname ID.") sendJsonError(w, http.StatusBadRequest, "invalid xname ID") return @@ -4800,9 +4803,9 @@ func (s *SmD) doMembershipsGet(w http.ResponseWriter, r *http.Request) { func (s *SmD) doMembershipGet(w http.ResponseWriter, r *http.Request) { var err error vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) - if !base.IsHMSCompIDValid(xname) { + if !xnametypes.IsHMSCompIDValid(xname) { s.lg.Printf("doMembershipGet(): Invalid xname.") sendJsonError(w, http.StatusBadRequest, "invalid xname") return @@ -5184,8 +5187,8 @@ func (s *SmD) doCompLocksDisable(w http.ResponseWriter, r *http.Request) { func (s *SmD) doPowerMapGet(w http.ResponseWriter, r *http.Request) { s.lg.Printf("doPowerMapGet(): trying...") vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) - if !base.IsHMSCompIDValid(xname) { + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) + if !xnametypes.IsHMSCompIDValid(xname) { s.lg.Printf("doPowerMapGet(): Invalid xname.") sendJsonError(w, http.StatusBadRequest, "invalid xname") return @@ -5264,7 +5267,7 @@ func (s *SmD) doPowerMapsPost(w http.ResponseWriter, r *http.Request) { // UPDATE EXISTING Power mapping by it's xname URI. func (s *SmD) doPowerMapPut(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) var mIn sm.PowerMap body, err := ioutil.ReadAll(r.Body) @@ -5278,7 +5281,7 @@ func (s *SmD) doPowerMapPut(w http.ResponseWriter, r *http.Request) { if xname != "" { mIn.ID = xname } - } else if base.NormalizeHMSCompID(mIn.ID) != xname { + } else if xnametypes.NormalizeHMSCompID(mIn.ID) != xname { sendJsonError(w, http.StatusBadRequest, "xname in URL and PUT body do not match") return @@ -5313,9 +5316,9 @@ func (s *SmD) doPowerMapPut(w http.ResponseWriter, r *http.Request) { func (s *SmD) doPowerMapDelete(w http.ResponseWriter, r *http.Request) { s.lg.Printf("doPowerMapDelete(): trying...") vars := mux.Vars(r) - xname := base.NormalizeHMSCompID(vars["xname"]) + xname := xnametypes.NormalizeHMSCompID(vars["xname"]) - if !base.IsHMSCompIDValid(xname) { + if !xnametypes.IsHMSCompIDValid(xname) { sendJsonError(w, http.StatusBadRequest, "invalid xname") return } diff --git a/cmd/smd/smd-api_test.go b/cmd/smd/smd-api_test.go index 9614d07..affa76e 100644 --- a/cmd/smd/smd-api_test.go +++ b/cmd/smd/smd-api_test.go @@ -35,13 +35,14 @@ import ( "strings" "testing" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" compcreds "github.com/Cray-HPE/hms-compcredentials" sstorage "github.com/Cray-HPE/hms-securestorage" "github.com/Cray-HPE/hms-smd/v2/internal/hmsds" + rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" stest "github.com/Cray-HPE/hms-smd/v2/pkg/sharedtest" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" - rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" + "github.com/Cray-HPE/hms-xname/xnametypes" "github.com/gorilla/mux" ) @@ -4350,54 +4351,54 @@ func TestDoHWInvByLocationPost(t *testing.T) { payload2, _ := json.Marshal(hwIn2) tests := []struct { - reqType string - reqURI string - reqBody []byte - expectedHWInvByLocs []*sm.HWInvByLoc - hmsdsRespErr error - expectedResp []byte + reqType string + reqURI string + reqBody []byte + expectedHWInvByLocs []*sm.HWInvByLoc + hmsdsRespErr error + expectedResp []byte }{{ - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/Hardware", - reqBody: payload1, - expectedHWInvByLocs: hwLocs1, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"Created 1 entries"}` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/Hardware", - reqBody: payload2, - expectedHWInvByLocs: hwLocs2, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"Created 5 entries"}` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/Hardware", - reqBody: json.RawMessage(`{}`), - expectedHWInvByLocs: hwLocs2, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"Created 0 entries"}` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/Hardware", - reqBody: payload2, - expectedHWInvByLocs: hwLocs2, - hmsdsRespErr: errors.New("Unknown Error"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'POST' failed during store.","status":500}` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/Hardware", - reqBody: payload2, - expectedHWInvByLocs: hwLocs2, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/Hardware", - reqBody: payload2, - expectedHWInvByLocs: hwLocs2, - hmsdsRespErr: hmsds.ErrHMSDSDuplicateKey, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Would create a duplicate key or non-unique field","status":400}` + "\n"), + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/Hardware", + reqBody: payload1, + expectedHWInvByLocs: hwLocs1, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"Created 1 entries"}` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/Hardware", + reqBody: payload2, + expectedHWInvByLocs: hwLocs2, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"Created 5 entries"}` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/Hardware", + reqBody: json.RawMessage(`{}`), + expectedHWInvByLocs: hwLocs2, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"Created 0 entries"}` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/Hardware", + reqBody: payload2, + expectedHWInvByLocs: hwLocs2, + hmsdsRespErr: errors.New("Unknown Error"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'POST' failed during store.","status":500}` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/Hardware", + reqBody: payload2, + expectedHWInvByLocs: hwLocs2, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/Hardware", + reqBody: payload2, + expectedHWInvByLocs: hwLocs2, + hmsdsRespErr: hmsds.ErrHMSDSDuplicateKey, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Would create a duplicate key or non-unique field","status":400}` + "\n"), }} for i, test := range tests { @@ -4730,7 +4731,7 @@ func TestDoHWInvByLocationQueryGet(t *testing.T) { hmsdsRespErr: nil, expectedFilter: &hmsds.HWInvLocFilter{ ID: []string{"x0c0s0b0n0"}, - Type: []string{base.Processor.String()}, + Type: []string{xnametypes.Processor.String()}, Children: true, }, expectedResp: payload3, @@ -5416,40 +5417,40 @@ func TestDoRedfishEndpointGet(t *testing.T) { payload, _ := json.Marshal(&stest.TestRedfishEndpointNodeBMC1) tests := []struct { - reqType string - reqURI string - hmsdsRespEP *sm.RedfishEndpoint - hmsdsRespErr error - expectedID string - expectedResp []byte + reqType string + reqURI string + hmsdsRespEP *sm.RedfishEndpoint + hmsdsRespErr error + expectedID string + expectedResp []byte }{{ - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, - hmsdsRespEP: &stest.TestRedfishEndpointNodeBMC1, - hmsdsRespErr: nil, - expectedID: xname, - expectedResp: payload, - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, - hmsdsRespEP: nil, - hmsdsRespErr: nil, - expectedID: xname, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, - hmsdsRespEP: nil, - hmsdsRespErr: hmsds.ErrHMSDSArgMissing, - expectedID: xname, - expectedResp: jsonErrHMSDSArgMissing, - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, - hmsdsRespEP: nil, - hmsdsRespErr: errors.New("unexpected DB error"), - expectedID: xname, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, + hmsdsRespEP: &stest.TestRedfishEndpointNodeBMC1, + hmsdsRespErr: nil, + expectedID: xname, + expectedResp: payload, + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, + hmsdsRespEP: nil, + hmsdsRespErr: nil, + expectedID: xname, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, + hmsdsRespEP: nil, + hmsdsRespErr: hmsds.ErrHMSDSArgMissing, + expectedID: xname, + expectedResp: jsonErrHMSDSArgMissing, + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/" + xname, + hmsdsRespEP: nil, + hmsdsRespErr: errors.New("unexpected DB error"), + expectedID: xname, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), }} for i, test := range tests { @@ -5708,41 +5709,41 @@ func TestDoRedfishEndpointQueryGet(t *testing.T) { payload, _ := json.Marshal(redfishEndpointArr) tests := []struct { - reqType string - reqURI string - hmsdsRespEPs []*sm.RedfishEndpoint - hmsdsRespErr error - expectedResp []byte - }{{ - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", - hmsdsRespEPs: []*sm.RedfishEndpoint{&stest.TestRedfishEndpointNodeBMC1,}, - hmsdsRespErr: nil, - expectedResp: payload, - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/all", - hmsdsRespEPs: []*sm.RedfishEndpoint{&stest.TestRedfishEndpointNodeBMC1,}, - hmsdsRespErr: nil, - expectedResp: payload, - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", - hmsdsRespEPs: nil, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"RedfishEndpoints":null}` + "\n"), - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", - hmsdsRespEPs: nil, - hmsdsRespErr: hmsds.ErrHMSDSArgMissing, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", - hmsdsRespEPs: nil, - hmsdsRespErr: errors.New("Argument was not a valid xname"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), + reqType string + reqURI string + hmsdsRespEPs []*sm.RedfishEndpoint + hmsdsRespErr error + expectedResp []byte + }{{ + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", + hmsdsRespEPs: []*sm.RedfishEndpoint{&stest.TestRedfishEndpointNodeBMC1}, + hmsdsRespErr: nil, + expectedResp: payload, + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/all", + hmsdsRespEPs: []*sm.RedfishEndpoint{&stest.TestRedfishEndpointNodeBMC1}, + hmsdsRespErr: nil, + expectedResp: payload, + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", + hmsdsRespEPs: nil, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"RedfishEndpoints":null}` + "\n"), + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", + hmsdsRespEPs: nil, + hmsdsRespErr: hmsds.ErrHMSDSArgMissing, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/Query/s0", + hmsdsRespEPs: nil, + hmsdsRespErr: errors.New("Argument was not a valid xname"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), }} for i, test := range tests { @@ -5772,47 +5773,47 @@ func TestDoRedfishEndpointQueryGet(t *testing.T) { func TestDoRedfishEndpointDelete(t *testing.T) { tests := []struct { - reqType string - reqURI string - hmsdsDidDelete bool - hmsdsExpectedId []string - hmsdsRespErr error - expectedResp []byte + reqType string + reqURI string + hmsdsDidDelete bool + hmsdsExpectedId []string + hmsdsRespErr error + expectedResp []byte }{{ - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - hmsdsDidDelete: true, - hmsdsExpectedId: []string{"x0c0s14b0"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entry"}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{"x0c0s14b0"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/ ", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{" "}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{"x0c0s14b0"}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{"x0c0s14b0"}, - hmsdsRespErr: errors.New("Unknown error"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + hmsdsDidDelete: true, + hmsdsExpectedId: []string{"x0c0s14b0"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entry"}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{"x0c0s14b0"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/ ", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{" "}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{"x0c0s14b0"}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{"x0c0s14b0"}, + hmsdsRespErr: errors.New("Unknown error"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), }} for i, test := range tests { @@ -5832,7 +5833,7 @@ func TestDoRedfishEndpointDelete(t *testing.T) { t.Errorf("Response code was %v; expected an error", w.Code) } - if strings.Join(test.hmsdsExpectedId,"") != results.DeleteRFEndpointByIDSetEmpty.Input.id { + if strings.Join(test.hmsdsExpectedId, "") != results.DeleteRFEndpointByIDSetEmpty.Input.id { t.Errorf("Test %v Failed: Expected endpoint ID is '%v'; Received endpoint ID '%v'", i, test.hmsdsExpectedId, results.DeleteRFEndpointByIDSetEmpty.Input.id) } @@ -5844,47 +5845,47 @@ func TestDoRedfishEndpointDelete(t *testing.T) { func TestDoRedfishEndpointsDeleteAll(t *testing.T) { tests := []struct { - reqType string - reqURI string - hmsdsRespCount int64 - hmsdsExpectedIds []string - hmsdsRespErr error - expectedResp []byte + reqType string + reqURI string + hmsdsRespCount int64 + hmsdsExpectedIds []string + hmsdsRespErr error + expectedResp []byte }{{ - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - hmsdsRespCount: 1, - hmsdsExpectedIds: []string{"x0c0s14b0"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entries"}`), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - hmsdsRespCount: 4, - hmsdsExpectedIds: []string{"x0c0s14b0","x0c0s15b0","x0c0s16b0","x0c0s17b0"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"deleted 4 entries"}`), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - hmsdsRespCount: 0, - hmsdsExpectedIds: []string{""}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no entries to delete","status":404}`), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - hmsdsRespCount: 0, - hmsdsExpectedIds: []string{""}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - hmsdsRespCount: 0, - hmsdsExpectedIds: []string{""}, - hmsdsRespErr: errors.New("DB Error"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + hmsdsRespCount: 1, + hmsdsExpectedIds: []string{"x0c0s14b0"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entries"}`), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + hmsdsRespCount: 4, + hmsdsExpectedIds: []string{"x0c0s14b0", "x0c0s15b0", "x0c0s16b0", "x0c0s17b0"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"deleted 4 entries"}`), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + hmsdsRespCount: 0, + hmsdsExpectedIds: []string{""}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no entries to delete","status":404}`), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + hmsdsRespCount: 0, + hmsdsExpectedIds: []string{""}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + hmsdsRespCount: 0, + hmsdsExpectedIds: []string{""}, + hmsdsRespErr: errors.New("DB Error"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), }} for i, test := range tests { @@ -5929,50 +5930,50 @@ func TestDoRedfishEndpointPut(t *testing.T) { redfishEndpointPtr := sm.NewRedfishEndpoint(redfishEndpointDescPtr) tests := []struct { - reqType string - reqURI string - reqBody []byte - expectedRedfishEP *sm.RedfishEndpoint - hmsdsRespEntry *sm.RedfishEndpoint - hmsdsRespAffectedIds []string - hmsdsRespErr error - expectedResp []byte + reqType string + reqURI string + reqBody []byte + expectedRedfishEP *sm.RedfishEndpoint + hmsdsRespEntry *sm.RedfishEndpoint + hmsdsRespAffectedIds []string + hmsdsRespErr error + expectedResp []byte }{{ - reqType: "PUT", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - reqBody: json.RawMessage(`{"Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), - expectedRedfishEP: redfishEndpointPtr, - hmsdsRespEntry: redfishEndpointPtr, - hmsdsRespAffectedIds: []string{"x0c0s14b0"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"ID":"x0c0s14b0","Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}` + "\n"), - }, { - reqType: "PUT", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - reqBody: json.RawMessage(`{"Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), - expectedRedfishEP: &sm.RedfishEndpoint{}, - hmsdsRespEntry: redfishEndpointPtr, - hmsdsRespAffectedIds: []string{"x0c0s14b0"}, - hmsdsRespErr: hmsds.ErrHMSDSArgNoMatch, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'PUT' failed during store","status":500}` + "\n"), - }, { - reqType: "PUT", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - reqBody: json.RawMessage(`{"Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), - expectedRedfishEP: &sm.RedfishEndpoint{}, - hmsdsRespEntry: redfishEndpointPtr, - hmsdsRespAffectedIds: []string{"x0c0s14b0"}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'PUT' failed during store","status":500}` + "\n"), - }, { - reqType: "PUT", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", - reqBody: json.RawMessage(`{"ID":"x0c0s16b1","Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), - expectedRedfishEP: &sm.RedfishEndpoint{}, - hmsdsRespEntry: redfishEndpointPtr, - hmsdsRespAffectedIds: []string{"x0c0s14b0"}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"xname in URL and PUT body do not match","status":400}` + "\n"), + reqType: "PUT", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + reqBody: json.RawMessage(`{"Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), + expectedRedfishEP: redfishEndpointPtr, + hmsdsRespEntry: redfishEndpointPtr, + hmsdsRespAffectedIds: []string{"x0c0s14b0"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"ID":"x0c0s14b0","Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}` + "\n"), + }, { + reqType: "PUT", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + reqBody: json.RawMessage(`{"Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), + expectedRedfishEP: &sm.RedfishEndpoint{}, + hmsdsRespEntry: redfishEndpointPtr, + hmsdsRespAffectedIds: []string{"x0c0s14b0"}, + hmsdsRespErr: hmsds.ErrHMSDSArgNoMatch, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'PUT' failed during store","status":500}` + "\n"), + }, { + reqType: "PUT", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + reqBody: json.RawMessage(`{"Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), + expectedRedfishEP: &sm.RedfishEndpoint{}, + hmsdsRespEntry: redfishEndpointPtr, + hmsdsRespAffectedIds: []string{"x0c0s14b0"}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'PUT' failed during store","status":500}` + "\n"), + }, { + reqType: "PUT", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0", + reqBody: json.RawMessage(`{"ID":"x0c0s16b1","Type":"NodeBMC","Hostname":"10.10.255.11","Domain":"local","FQDN":"10.10.255.11","Enabled":true,"UUID":"d4c6d22f-6983-42d8-8e6e-e1fd6d675c17","User":"root","Password":"********","IPAddress":"10.10.255.11","RediscoverOnUpdate":true,"DiscoveryInfo":{"LastDiscoveryStatus":"NotYetQueried"}}`), + expectedRedfishEP: &sm.RedfishEndpoint{}, + hmsdsRespEntry: redfishEndpointPtr, + hmsdsRespAffectedIds: []string{"x0c0s14b0"}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"xname in URL and PUT body do not match","status":400}` + "\n"), }} for i, test := range tests { @@ -6006,48 +6007,48 @@ func TestDoRedfishEndpointsPost(t *testing.T) { }() s.writeVault = false - redfishEndpointArr1 := &stest.TestRedfishEndpointArrayNodeBMC1 - payload1, _ := json.Marshal(redfishEndpointArr1) - - redfishEndpointArr2 := &stest.TestRedfishEndpointArray - payload2, _ := json.Marshal(redfishEndpointArr2) - - tests := []struct { - reqType string - reqURI string - reqBody []byte - expectedRedfishEPs *sm.RedfishEndpointArray - hmsdsRespErr error - expectedResp []byte - }{{ - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - reqBody: payload1, - expectedRedfishEPs: redfishEndpointArr1, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`[{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0"}]` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - reqBody: payload2, - expectedRedfishEPs: redfishEndpointArr2, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`[{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0"},{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x11c0s1b0"},{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x11c0r1b0"},{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x6c1b0"}]` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - reqBody: payload2, - expectedRedfishEPs: redfishEndpointArr2, - hmsdsRespErr: errors.New("Unknown Error"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'POST' failed during store. ","status":500}` + "\n"), - }, { - reqType: "POST", - reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", - reqBody: payload2, - expectedRedfishEPs: redfishEndpointArr2, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'POST' failed during store. ","status":500}` + "\n"), - }} + redfishEndpointArr1 := &stest.TestRedfishEndpointArrayNodeBMC1 + payload1, _ := json.Marshal(redfishEndpointArr1) + + redfishEndpointArr2 := &stest.TestRedfishEndpointArray + payload2, _ := json.Marshal(redfishEndpointArr2) + + tests := []struct { + reqType string + reqURI string + reqBody []byte + expectedRedfishEPs *sm.RedfishEndpointArray + hmsdsRespErr error + expectedResp []byte + }{{ + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + reqBody: payload1, + expectedRedfishEPs: redfishEndpointArr1, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`[{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0"}]` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + reqBody: payload2, + expectedRedfishEPs: redfishEndpointArr2, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`[{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x0c0s14b0"},{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x11c0s1b0"},{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x11c0r1b0"},{"URI":"/hsm/v2/Inventory/RedfishEndpoints/x6c1b0"}]` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + reqBody: payload2, + expectedRedfishEPs: redfishEndpointArr2, + hmsdsRespErr: errors.New("Unknown Error"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'POST' failed during store. ","status":500}` + "\n"), + }, { + reqType: "POST", + reqURI: "https://localhost/hsm/v2/Inventory/RedfishEndpoints", + reqBody: payload2, + expectedRedfishEPs: redfishEndpointArr2, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"operation 'POST' failed during store. ","status":500}` + "\n"), + }} for i, test := range tests { if i == 0 { @@ -6084,40 +6085,40 @@ func TestDoComponentEndpointGet(t *testing.T) { payload, _ := json.Marshal(&stest.TestCompEndpointNodeBMC) tests := []struct { - reqType string - reqURI string - hmsdsRespEP *sm.ComponentEndpoint - hmsdsRespErr error - expectedID string - expectedResp []byte + reqType string + reqURI string + hmsdsRespEP *sm.ComponentEndpoint + hmsdsRespErr error + expectedID string + expectedResp []byte }{{ - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, - hmsdsRespEP: &stest.TestCompEndpointNodeBMC, - hmsdsRespErr: nil, - expectedID: xname, - expectedResp: payload, - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, - hmsdsRespEP: nil, - hmsdsRespErr: nil, - expectedID: xname, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, - hmsdsRespEP: nil, - hmsdsRespErr: hmsds.ErrHMSDSArgMissing, - expectedID: xname, - expectedResp: jsonErrHMSDSArgMissing, - }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, - hmsdsRespEP: nil, - hmsdsRespErr: errors.New("unexpected DB error"), - expectedID: xname, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, + hmsdsRespEP: &stest.TestCompEndpointNodeBMC, + hmsdsRespErr: nil, + expectedID: xname, + expectedResp: payload, + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, + hmsdsRespEP: nil, + hmsdsRespErr: nil, + expectedID: xname, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, + hmsdsRespEP: nil, + hmsdsRespErr: hmsds.ErrHMSDSArgMissing, + expectedID: xname, + expectedResp: jsonErrHMSDSArgMissing, + }, { + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/" + xname, + hmsdsRespEP: nil, + hmsdsRespErr: errors.New("unexpected DB error"), + expectedID: xname, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), }} for i, test := range tests { @@ -6151,92 +6152,92 @@ func TestDoComponentEndpointsGet(t *testing.T) { payload, _ := json.Marshal(componentEndpointArray) tests := []struct { - reqType string - reqURI string - hmsdsRespEPs []*sm.ComponentEndpoint - hmsdsRespErr error - expectedFilter *hmsds.CompEPFilter - expectedResp []byte - expectError bool + reqType string + reqURI string + hmsdsRespEPs []*sm.ComponentEndpoint + hmsdsRespErr error + expectedFilter *hmsds.CompEPFilter + expectedResp []byte + expectError bool }{{ reqType: "GET", reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", hmsdsRespEPs: stest.SampleCompEndpoints, hmsdsRespErr: nil, - expectedFilter: &hmsds.CompEPFilter{}, + expectedFilter: &hmsds.CompEPFilter{}, expectedResp: payload, - expectError: false, + expectError: false, }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?id=x1c4", - hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: nil, - expectedFilter: &hmsds.CompEPFilter{ + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?id=x1c4", + hmsdsRespEPs: stest.SampleCompEndpoints, + hmsdsRespErr: nil, + expectedFilter: &hmsds.CompEPFilter{ ID: []string{"x1c4"}, }, - expectedResp: payload, - expectError: false, + expectedResp: payload, + expectError: false, }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?redfish_ep=x1c4b0", - hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: nil, - expectedFilter: &hmsds.CompEPFilter{ + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?redfish_ep=x1c4b0", + hmsdsRespEPs: stest.SampleCompEndpoints, + hmsdsRespErr: nil, + expectedFilter: &hmsds.CompEPFilter{ RfEndpointID: []string{"x1c4b0"}, }, - expectedResp: payload, - expectError: false, + expectedResp: payload, + expectError: false, }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?type=NodeBMC", - hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: nil, - expectedFilter: &hmsds.CompEPFilter{ + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?type=NodeBMC", + hmsdsRespEPs: stest.SampleCompEndpoints, + hmsdsRespErr: nil, + expectedFilter: &hmsds.CompEPFilter{ Type: []string{"NodeBMC"}, }, - expectedResp: payload, - expectError: false, + expectedResp: payload, + expectError: false, }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?redfish_type=Chassis", - hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: nil, - expectedFilter: &hmsds.CompEPFilter{ + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?redfish_type=Chassis", + hmsdsRespEPs: stest.SampleCompEndpoints, + hmsdsRespErr: nil, + expectedFilter: &hmsds.CompEPFilter{ RedfishType: []string{"Chassis"}, }, - expectedResp: payload, - expectError: false, + expectedResp: payload, + expectError: false, }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?id=x1c4&redfish_ep=x1c4b0&type=Chassis&redfish_type=Chassis", - hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: nil, - expectedFilter: &hmsds.CompEPFilter{ - ID: []string{"x1c4"}, + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?id=x1c4&redfish_ep=x1c4b0&type=Chassis&redfish_type=Chassis", + hmsdsRespEPs: stest.SampleCompEndpoints, + hmsdsRespErr: nil, + expectedFilter: &hmsds.CompEPFilter{ + ID: []string{"x1c4"}, RfEndpointID: []string{"x1c4b0"}, - Type: []string{"Chassis"}, - RedfishType: []string{"Chassis"}, + Type: []string{"Chassis"}, + RedfishType: []string{"Chassis"}, }, - expectedResp: payload, - expectError: false, + expectedResp: payload, + expectError: false, }, { - reqType: "GET", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?type=fake", - hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: hmsds.ErrHMSDSArgBadType, - expectedFilter: &hmsds.CompEPFilter{ + reqType: "GET", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints?type=fake", + hmsdsRespEPs: stest.SampleCompEndpoints, + hmsdsRespErr: hmsds.ErrHMSDSArgBadType, + expectedFilter: &hmsds.CompEPFilter{ Type: []string{"fake"}, }, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"bad query param: Argument was not a valid HMS Type","status":400}` + "\n"), - expectError: true, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"bad query param: Argument was not a valid HMS Type","status":400}` + "\n"), + expectError: true, }, { reqType: "GET", reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", hmsdsRespEPs: stest.SampleCompEndpoints, - hmsdsRespErr: errors.New("Unknown error"), - expectedFilter: &hmsds.CompEPFilter{}, + hmsdsRespErr: errors.New("Unknown error"), + expectedFilter: &hmsds.CompEPFilter{}, expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), - expectError: true, + expectError: true, }} for i, test := range tests { @@ -6269,47 +6270,47 @@ func TestDoComponentEndpointsGet(t *testing.T) { func TestDoComponentEndpointDelete(t *testing.T) { tests := []struct { - reqType string - reqURI string - hmsdsDidDelete bool - hmsdsExpectedId []string - hmsdsRespErr error - expectedResp []byte + reqType string + reqURI string + hmsdsDidDelete bool + hmsdsExpectedId []string + hmsdsRespErr error + expectedResp []byte }{{ - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", - hmsdsDidDelete: true, - hmsdsExpectedId: []string{"x1c4"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entry"}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{"x1c4"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/ ", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{" "}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{"x1c4"}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", - hmsdsDidDelete: false, - hmsdsExpectedId: []string{"x1c4"}, - hmsdsRespErr: errors.New("Unknown error"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", + hmsdsDidDelete: true, + hmsdsExpectedId: []string{"x1c4"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entry"}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{"x1c4"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no such xname.","status":404}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/ ", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{" "}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{"x1c4"}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid xname ID","status":400}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints/x1c4", + hmsdsDidDelete: false, + hmsdsExpectedId: []string{"x1c4"}, + hmsdsRespErr: errors.New("Unknown error"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"failed to query DB.","status":500}` + "\n"), }} for i, test := range tests { @@ -6329,7 +6330,7 @@ func TestDoComponentEndpointDelete(t *testing.T) { t.Errorf("Response code was %v; expected an error", w.Code) } - if strings.Join(test.hmsdsExpectedId,"") != results.DeleteCompEndpointByIDSetEmpty.Input.id { + if strings.Join(test.hmsdsExpectedId, "") != results.DeleteCompEndpointByIDSetEmpty.Input.id { t.Errorf("Test %v Failed: Expected endpoint ID is '%v'; Received endpoint ID '%v'", i, test.hmsdsExpectedId, results.DeleteCompEndpointByIDSetEmpty.Input.id) } @@ -6341,47 +6342,47 @@ func TestDoComponentEndpointDelete(t *testing.T) { func TestDoComponentEndpointsDeleteAll(t *testing.T) { tests := []struct { - reqType string - reqURI string - hmsdsRespCount int64 - hmsdsExpectedIds []string - hmsdsRespErr error - expectedResp []byte + reqType string + reqURI string + hmsdsRespCount int64 + hmsdsExpectedIds []string + hmsdsRespErr error + expectedResp []byte }{{ - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", - hmsdsRespCount: 1, - hmsdsExpectedIds: []string{"x0c0s14b0"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entries"}`), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", - hmsdsRespCount: 4, - hmsdsExpectedIds: []string{"x1c4","x1c5","x1c6","x1c7"}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"code":0,"message":"deleted 4 entries"}`), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", - hmsdsRespCount: 0, - hmsdsExpectedIds: []string{""}, - hmsdsRespErr: nil, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no entries to delete","status":404}`), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", - hmsdsRespCount: 0, - hmsdsExpectedIds: []string{""}, - hmsdsRespErr: hmsds.ErrHMSDSArgBadID, - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), - }, { - reqType: "DELETE", - reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", - hmsdsRespCount: 0, - hmsdsExpectedIds: []string{""}, - hmsdsRespErr: errors.New("DB Error"), - expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", + hmsdsRespCount: 1, + hmsdsExpectedIds: []string{"x0c0s14b0"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"deleted 1 entries"}`), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", + hmsdsRespCount: 4, + hmsdsExpectedIds: []string{"x1c4", "x1c5", "x1c6", "x1c7"}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"code":0,"message":"deleted 4 entries"}`), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", + hmsdsRespCount: 0, + hmsdsExpectedIds: []string{""}, + hmsdsRespErr: nil, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Not Found","detail":"no entries to delete","status":404}`), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", + hmsdsRespCount: 0, + hmsdsExpectedIds: []string{""}, + hmsdsRespErr: hmsds.ErrHMSDSArgBadID, + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), + }, { + reqType: "DELETE", + reqURI: "https://localhost/hsm/v2/Inventory/ComponentEndpoints", + hmsdsRespCount: 0, + hmsdsExpectedIds: []string{""}, + hmsdsRespErr: errors.New("DB Error"), + expectedResp: json.RawMessage(`{"type":"about:blank","title":"Internal Server Error","detail":"DB query failed.","status":500}` + "\n"), }} for i, test := range tests { @@ -10420,78 +10421,78 @@ func TestDoCompLocksStatusGet(t *testing.T) { expectedResp []byte expectError bool }{{ - reqURI: "https://localhost/hsm/v2/locks/status", + reqURI: "https://localhost/hsm/v2/locks/status", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - ProcessingModel: sm.CLProcessingModelRigid, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?type=Node", + reqURI: "https://localhost/hsm/v2/locks/status?type=Node", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - Type: []string{"Node"}, - ProcessingModel: sm.CLProcessingModelRigid, + Type: []string{"Node"}, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?state=Ready", + reqURI: "https://localhost/hsm/v2/locks/status?state=Ready", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - State: []string{"Ready"}, - ProcessingModel: sm.CLProcessingModelRigid, + State: []string{"Ready"}, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?role=Management", + reqURI: "https://localhost/hsm/v2/locks/status?role=Management", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - Role: []string{"Management"}, - ProcessingModel: sm.CLProcessingModelRigid, + Role: []string{"Management"}, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?subrole=Master", + reqURI: "https://localhost/hsm/v2/locks/status?subrole=Master", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - SubRole: []string{"Master"}, - ProcessingModel: sm.CLProcessingModelRigid, + SubRole: []string{"Master"}, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?locked=True", + reqURI: "https://localhost/hsm/v2/locks/status?locked=True", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - ProcessingModel: sm.CLProcessingModelRigid, - Locked: []string{"True"}, + ProcessingModel: sm.CLProcessingModelRigid, + Locked: []string{"True"}, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?reserved=False", + reqURI: "https://localhost/hsm/v2/locks/status?reserved=False", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ - ProcessingModel: sm.CLProcessingModelRigid, - Reserved: []string{"False"}, + ProcessingModel: sm.CLProcessingModelRigid, + Reserved: []string{"False"}, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?reservationDisabled=False", + reqURI: "https://localhost/hsm/v2/locks/status?reservationDisabled=False", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ ProcessingModel: sm.CLProcessingModelRigid, ReservationDisabled: []string{"False"}, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status?type=Node&state=Ready&role=Management&subrole=Master&locked=True&reserved=False&reservationDisabled=False", + reqURI: "https://localhost/hsm/v2/locks/status?type=Node&state=Ready&role=Management&subrole=Master&locked=True&reserved=False&reservationDisabled=False", hmsdsRespErr: nil, expectedFilter: sm.CompLockV2Filter{ Type: []string{"Node"}, @@ -10504,24 +10505,24 @@ func TestDoCompLocksStatusGet(t *testing.T) { ReservationDisabled: []string{"False"}, }, expectedResp: expectedRespGood, - expectError: false, + expectError: false, }, { - reqURI: "https://localhost/hsm/v2/locks/status", + reqURI: "https://localhost/hsm/v2/locks/status", hmsdsRespErr: sm.ErrCompLockV2NotFound, expectedFilter: sm.CompLockV2Filter{ - ProcessingModel: sm.CLProcessingModelRigid, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Component not found","status":400}` + "\n"), - expectError: true, + expectError: true, }, { - reqURI: "https://localhost/hsm/v2/locks/status?type=Fake", + reqURI: "https://localhost/hsm/v2/locks/status?type=Fake", hmsdsRespErr: hmsds.ErrHMSDSArgBadType, expectedFilter: sm.CompLockV2Filter{ - Type: []string{"Fake"}, - ProcessingModel: sm.CLProcessingModelRigid, + Type: []string{"Fake"}, + ProcessingModel: sm.CLProcessingModelRigid, }, expectedResp: json.RawMessage(`{"type":"about:blank","title":"Bad Request","detail":"Argument was not a valid HMS Type","status":400}` + "\n"), - expectError: true, + expectError: true, }} for i, test := range tests { diff --git a/cmd/smd/smd.go b/cmd/smd/smd.go index 4a17c79..c2345ca 100644 --- a/cmd/smd/smd.go +++ b/cmd/smd/smd.go @@ -27,27 +27,28 @@ import ( "errors" "flag" "fmt" - "github.com/gorilla/mux" - "github.com/hashicorp/go-retryablehttp" - "github.com/sirupsen/logrus" "log" "net/http" "os" "runtime" - base "github.com/Cray-HPE/hms-base" + "strconv" + "strings" + "sync" + "time" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-certs/pkg/hms_certs" compcreds "github.com/Cray-HPE/hms-compcredentials" msgbus "github.com/Cray-HPE/hms-msgbus" sstorage "github.com/Cray-HPE/hms-securestorage" "github.com/Cray-HPE/hms-smd/v2/internal/hbtdapi" "github.com/Cray-HPE/hms-smd/v2/internal/hmsds" "github.com/Cray-HPE/hms-smd/v2/internal/slsapi" - "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" + rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" - "github.com/Cray-HPE/hms-certs/pkg/hms_certs" - "strconv" - "strings" - "sync" - "time" + "github.com/gorilla/mux" + "github.com/hashicorp/go-retryablehttp" + "github.com/sirupsen/logrus" ) const ( @@ -405,9 +406,10 @@ func (s *SmD) JobSync() { // instance of HSM dies. This spins off a goroutine to periodically check for // orphaned discovery jobs and picks them up. // TODO: Close potential race condition between GetRFEndpointsFilter() and when -// discoverFromEndpoint() updates the DiscInfo.LastAttempt where another HSM -// instance could run GetRFEndpointsFilter() to get the same list of orphaned -// EPs. For now, this should be rare. +// +// discoverFromEndpoint() updates the DiscInfo.LastAttempt where another HSM +// instance could run GetRFEndpointsFilter() to get the same list of orphaned +// EPs. For now, this should be rare. func (s *SmD) DiscoverySync() { go func() { for { @@ -752,8 +754,8 @@ func main() { os.Exit(1) } - serviceName,err = base.GetServiceInstanceName() - if (err != nil) { + serviceName, err = base.GetServiceInstanceName() + if err != nil { serviceName = "SMD" s.LogAlways("WARNING, can't get service/instance name, using '%s'", serviceName) @@ -784,11 +786,11 @@ func main() { } // Use socks, etc. proxy when interrogating Redfish endpoints -// if s.proxyURL != "" { -// s.LogAlways("Using '%s' as proxy when interrogating Redfish.", -// s.proxyURL) -// rf.SetHTTPClientProxyURL(s.proxyURL) -// } + // if s.proxyURL != "" { + // s.LogAlways("Using '%s' as proxy when interrogating Redfish.", + // s.proxyURL) + // rf.SetHTTPClientProxyURL(s.proxyURL) + // } // Generate unit test output during Redfish inventory discovery if s.genTestPayloads != "" { if err := rf.EnableGenTestingPayloads(s.genTestPayloads); err != nil { @@ -852,30 +854,30 @@ func main() { //Cert mgmt support - hms_certs.InitInstance(nil,serviceName) + hms_certs.InitInstance(nil, serviceName) vurl := os.Getenv("SMD_VAULT_CA_URL") - if (vurl != "") { - s.LogAlways("Replacing default Vault CA URL with: '%s'",vurl) + if vurl != "" { + s.LogAlways("Replacing default Vault CA URL with: '%s'", vurl) hms_certs.ConfigParams.VaultCAUrl = vurl } vurl = os.Getenv("SMD_VAULT_PKI_URL") - if (vurl != "") { - s.LogAlways("Replacing default Vault PKI URL with: '%s'",vurl) + if vurl != "" { + s.LogAlways("Replacing default Vault PKI URL with: '%s'", vurl) hms_certs.ConfigParams.VaultPKIUrl = vurl } vurl = os.Getenv("SMD_LOG_INSECURE_FAILOVER") - if (vurl != "") { - yn,_ := strconv.ParseBool(vurl) - if (yn == false) { + if vurl != "" { + yn, _ := strconv.ParseBool(vurl) + if yn == false { //Defaults to true hms_certs.ConfigParams.LogInsecureFailover = false } } vurl = os.Getenv("SMD_CA_URI") - if (vurl == "") { + if vurl == "" { s.LogAlways("CA_URI: Not specified.") } else { - s.LogAlways("CA_URI: '%s'.",vurl) + s.LogAlways("CA_URI: '%s'.", vurl) } //Initialize the SCN subscription list and map diff --git a/cmd/smd/state-change.go b/cmd/smd/state-change.go index eb772c8..d173379 100644 --- a/cmd/smd/state-change.go +++ b/cmd/smd/state-change.go @@ -24,13 +24,15 @@ package main import ( "encoding/json" - base "github.com/Cray-HPE/hms-base" - "github.com/Cray-HPE/hms-smd/v2/internal/hmsds" - "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" - "github.com/Cray-HPE/hms-smd/v2/pkg/sm" "strconv" "strings" "time" + + base "github.com/Cray-HPE/hms-base/v2" + "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/Cray-HPE/hms-xname/xnametypes" ) var e = base.NewHMSError("sm", "server error") @@ -145,7 +147,7 @@ func (s *SmD) doCompUpdate(u *CompUpdate, name string) error { return ErrSMDNoIDs } else { for _, id := range u.ComponentIDs { - normID := base.VerifyNormalizeCompID(id) + normID := xnametypes.VerifyNormalizeCompID(id) if normID == "" { return ErrSMDBadID } @@ -176,7 +178,7 @@ func (s *SmD) doCompUpdate(u *CompUpdate, name string) error { // Start State Redfish Polling jobs for any nodes // transitioning to standby. for _, id := range scnIDs { - if base.GetHMSTypeString(id) == base.Node.String() { + if xnametypes.GetHMSTypeString(id) == xnametypes.Node.String() { s.doStateRFPoll(id, 30) } } @@ -487,7 +489,7 @@ func (s *SmD) doPollRFState(job *Job) { pw = rep.Password } // Minimally populate a redfish description struct - rfEPType := base.GetHMSType(cep.RfEndpointID) + rfEPType := xnametypes.GetHMSType(cep.RfEndpointID) epDesc := rf.RedfishEPDescription{ ID: cep.RfEndpointID, Type: rfEPType.String(), diff --git a/go.mod b/go.mod index 43d3f5c..d4b8cb9 100644 --- a/go.mod +++ b/go.mod @@ -3,13 +3,13 @@ module github.com/Cray-HPE/hms-smd/v2 go 1.16 require ( - github.com/Cray-HPE/hms-base v1.15.0 + github.com/Cray-HPE/hms-base/v2 v2.0.1 github.com/Cray-HPE/hms-certs v1.3.2 github.com/Cray-HPE/hms-compcredentials v1.11.2 github.com/Cray-HPE/hms-go-http-lib v1.5.3 github.com/Cray-HPE/hms-msgbus v1.11.0 github.com/Cray-HPE/hms-securestorage v1.12.2 - github.com/Cray-HPE/hms-xname v1.2.0 // indirect + github.com/Cray-HPE/hms-xname v1.2.0 github.com/DATA-DOG/go-sqlmock v1.3.3 github.com/Masterminds/squirrel v1.4.0 github.com/frankban/quicktest v1.7.3 // indirect diff --git a/go.sum b/go.sum index 76c229a..39c1548 100644 --- a/go.sum +++ b/go.sum @@ -26,6 +26,8 @@ github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym github.com/ClickHouse/clickhouse-go v1.3.12/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI= github.com/Cray-HPE/hms-base v1.15.0 h1:VaQj6cY9OAs6rcD1miE133eqQnRTkEcX1lnwJA/SUuU= github.com/Cray-HPE/hms-base v1.15.0/go.mod h1:+G8KFLPtanLC5lQ602hrf3MDfLTmIXedTavVCOdz5XA= +github.com/Cray-HPE/hms-base/v2 v2.0.1 h1:xHQWmoOlmA/UU0zDWjHxCK/qOF9WMLr7MrSpFAxLXWY= +github.com/Cray-HPE/hms-base/v2 v2.0.1/go.mod h1:Mq+Ao3q4YtNZJZ1ly9wnEIKyvc3+QaA1B/xpiUpyhzQ= github.com/Cray-HPE/hms-certs v1.3.2 h1:Prd7PTwiSMULYuL8bhsvw7LSICx+pSvpWlA9fQKvW9s= github.com/Cray-HPE/hms-certs v1.3.2/go.mod h1:6DymilWScLtbQkaQRMuf55K1MzEi0kYCoXfT212yLjY= github.com/Cray-HPE/hms-compcredentials v1.11.2 h1:Ug7e7vMSx1STHKkniWY27ddD1X49pQAEljQmTcVkng4= diff --git a/internal/hbtdapi/hbtdapi.go b/internal/hbtdapi/hbtdapi.go index d68d079..ff31b0f 100644 --- a/internal/hbtdapi/hbtdapi.go +++ b/internal/hbtdapi/hbtdapi.go @@ -27,13 +27,14 @@ import ( "crypto/tls" "encoding/json" "fmt" - "github.com/hashicorp/go-retryablehttp" - "github.com/sirupsen/logrus" "io/ioutil" "net/http" "net/url" "time" - "github.com/Cray-HPE/hms-base" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/hashicorp/go-retryablehttp" + "github.com/sirupsen/logrus" ) const DefaultHbtdUrl string = "http://cray-hbtd/hmi/v1" diff --git a/internal/hbtdapi/hbtdapi_test.go b/internal/hbtdapi/hbtdapi_test.go index 4087cab..6b8896c 100644 --- a/internal/hbtdapi/hbtdapi_test.go +++ b/internal/hbtdapi/hbtdapi_test.go @@ -28,13 +28,13 @@ package hbtdapi import ( "bytes" - "github.com/hashicorp/go-retryablehttp" "io/ioutil" "net/http" "net/url" "os" "testing" - "github.com/Cray-HPE/hms-base" + + "github.com/hashicorp/go-retryablehttp" ) var client *retryablehttp.Client @@ -203,18 +203,18 @@ const testPayloadHBTDAPI_goodNoHB = ` func NewRTFuncSLSAPI() RTFunc { return func(req *http.Request) *http.Response { bad := true - if (len(req.Header) > 0) { - vals,ok := req.Header[base.USERAGENT] - if (ok) { - for _,v := range(vals) { - if (v == testSvcName) { + if len(req.Header) > 0 { + vals, ok := req.Header[xnametypes.USERAGENT] + if ok { + for _, v := range vals { + if v == testSvcName { bad = false break } } } } - if (bad) { + if bad { return &http.Response{ StatusCode: http.StatusInternalServerError, // Send mock response for rpath diff --git a/internal/hmsds/hmsds-api-filters.go b/internal/hmsds/hmsds-api-filters.go index d529bfa..19b100a 100644 --- a/internal/hmsds/hmsds-api-filters.go +++ b/internal/hmsds/hmsds-api-filters.go @@ -25,7 +25,8 @@ package hmsds import ( "strings" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) type FieldFilter int @@ -50,23 +51,23 @@ type PCondition struct { type ComponentFilter struct { // User-writable options - ID []string `json:"id"` - NID []string `json:"nid"` - NIDStart []string `json:"nid_start"` - NIDEnd []string `json:"nid_end"` - Type []string `json:"type"` - State []string `json:"state"` - Flag []string `json:"flag"` - Enabled []string `json:"enabled"` - SwStatus []string `json:"softwarestatus"` - Role []string `json:"role"` - SubRole []string `json:"subrole"` - Subtype []string `json:"subtype"` - Arch []string `json:"arch"` - Class []string `json:"class"` - Group []string `json:"group"` // Arbitrary Groups have UUID ids as well as globally unique names - Partition []string `json:"partition"` - Locked []string `json:"locked"` + ID []string `json:"id"` + NID []string `json:"nid"` + NIDStart []string `json:"nid_start"` + NIDEnd []string `json:"nid_end"` + Type []string `json:"type"` + State []string `json:"state"` + Flag []string `json:"flag"` + Enabled []string `json:"enabled"` + SwStatus []string `json:"softwarestatus"` + Role []string `json:"role"` + SubRole []string `json:"subrole"` + Subtype []string `json:"subtype"` + Arch []string `json:"arch"` + Class []string `json:"class"` + Group []string `json:"group"` // Arbitrary Groups have UUID ids as well as globally unique names + Partition []string `json:"partition"` + Locked []string `json:"locked"` ReservationDisabled []string `json:"reservation_disabled"` // private options @@ -209,8 +210,9 @@ type CompFiltFunc func(*ComponentFilter) // negated with "!" and all such ids will be excluded. // // NOTE: will add the empty string if ids is zero length to select no ids. -// The assumption is that this isn't being used to select any ID as -// this option would be unneccessary otherwise. +// +// The assumption is that this isn't being used to select any ID as +// this option would be unneccessary otherwise. func IDs(ids []string) CompFiltFunc { return func(f *ComponentFilter) { if f != nil { @@ -448,7 +450,7 @@ func (f *ComponentFilter) VerifyNormalize() error { if err != nil { return ErrHMSDSArgBadID } - err = checkFilterField(f.Type, base.VerifyNormalizeType, true) + err = checkFilterField(f.Type, xnametypes.VerifyNormalizeType, true) if err != nil { return ErrHMSDSArgBadType } @@ -574,8 +576,9 @@ type CompEPFiltFunc func(*CompEPFilter) // negated with "!" and all such ids will be excluded. // // NOTE: will add the empty string if ids is zero length to select no ids. -// The assumption is that this isn't being used to select any ID as -// this option would be unneccessary otherwise. +// +// The assumption is that this isn't being used to select any ID as +// this option would be unneccessary otherwise. func CE_IDs(ids []string) CompEPFiltFunc { return func(f *CompEPFilter) { if f != nil { @@ -664,8 +667,9 @@ type RedfishEPFiltFunc func(*RedfishEPFilter) // negated with "!" and all such ids will be excluded. // // NOTE: will add the empty string if ids is zero length to select no ids. -// The assumption is that this isn't being used to select any ID as -// this option would be unneccessary otherwise. +// +// The assumption is that this isn't being used to select any ID as +// this option would be unneccessary otherwise. func RFE_IDs(ids []string) RedfishEPFiltFunc { return func(f *RedfishEPFilter) { if f != nil { @@ -945,8 +949,9 @@ type HWInvLocFiltFunc func(*HWInvLocFilter) // negated with "!" and all such ids will be excluded. // // NOTE: will add the empty string if ids is zero length to select no ids. -// The assumption is that this isn't being used to select any ID as -// this option would be unneccessary otherwise. +// +// The assumption is that this isn't being used to select any ID as +// this option would be unneccessary otherwise. func HWInvLoc_IDs(ids []string) HWInvLocFiltFunc { return func(f *HWInvLocFilter) { if f != nil { @@ -1090,8 +1095,9 @@ type HWInvHistFiltFunc func(*HWInvHistFilter) // negated with "!" and all such ids will be excluded. // // NOTE: will add the empty string if ids is zero length to select no ids. -// The assumption is that this isn't being used to select any ID as -// this option would be unneccessary otherwise. +// +// The assumption is that this isn't being used to select any ID as +// this option would be unneccessary otherwise. func HWInvHist_IDs(ids []string) HWInvHistFiltFunc { return func(f *HWInvHistFilter) { if f != nil { @@ -1183,8 +1189,9 @@ type CompEthInterfaceFiltFunc func(*CompEthInterfaceFilter) // negated with "!" and all such ids will be excluded. // // NOTE: will add the empty string if ids is zero length to select no ids. -// The assumption is that this isn't being used to select any ID as -// this option would be unneccessary otherwise. +// +// The assumption is that this isn't being used to select any ID as +// this option would be unneccessary otherwise. func CEI_IDs(ids []string) CompEthInterfaceFiltFunc { return func(f *CompEthInterfaceFilter) { if f != nil { diff --git a/internal/hmsds/hmsds-api.go b/internal/hmsds/hmsds-api.go index 9d0380b..d49273a 100644 --- a/internal/hmsds/hmsds-api.go +++ b/internal/hmsds/hmsds-api.go @@ -23,7 +23,7 @@ package hmsds import ( - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" ) @@ -299,7 +299,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteNodeMapByID(id string) (bool, error) - // Delete all Node NID Mapping entries from database. + // Delete all Node NID Mapping entries from dataxnametypes. // Also returns number of deleted rows, if error is nil. DeleteNodeMapsAll() (int64, error) @@ -325,7 +325,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeletePowerMapByID(id string) (bool, error) - // Delete all Power Mapping entries from database. + // Delete all Power Mapping entries from dataxnametypes. // Also returns number of deleted rows, if error is nil. DeletePowerMapsAll() (int64, error) @@ -467,7 +467,7 @@ type HMSDB interface { // do not match ALL of the non-empty strings in the filter struct GetRFEndpointsFilter(f *RedfishEPFilter) ([]*sm.RedfishEndpoint, error) - // Insert new RedfishEndpoint into database. + // Insert new RedfishEndpoint into dataxnametypes. // Does not insert any ComponentEndpoint children. // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -480,7 +480,7 @@ type HMSDB interface { // No insertions are done on err != nil InsertRFEndpoints(eps *sm.RedfishEndpointArray) error - // Update existing RedfishEndpointArray entry in database. + // Update existing RedfishEndpointArray entry in dataxnametypes. // Does not update any ComponentEndpoint children. // Returns updated entry or nil/nul if not found. If an error occurred, // nil/error will be returned. @@ -519,7 +519,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteRFEndpointByID(id string) (bool, error) - // Delete all RedfishEndpoints from database. + // Delete all RedfishEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. DeleteRFEndpointsAll() (int64, error) @@ -529,7 +529,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteRFEndpointByIDSetEmpty(id string) (bool, []string, error) - // Delete all RedfishEndpoints from database. + // Delete all RedfishEndpoints from dataxnametypes. // This also deletes all child ComponentEndpoints, and in addition, // sets the State/Components entries for those ComponentEndpoints to Empty/OK // Also returns number of deleted rows, if error is nil. @@ -566,7 +566,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteCompEndpointByID(id string) (bool, error) - // Delete all ComponentEndpoints from database. + // Delete all ComponentEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. DeleteCompEndpointsAll() (int64, error) @@ -577,7 +577,7 @@ type HMSDB interface { // string array returns the single xname ID that changed state or is empty. DeleteCompEndpointByIDSetEmpty(id string) (bool, []string, error) - // Delete all ComponentEndpoints from database. In addition, + // Delete all ComponentEndpoints from dataxnametypes. In addition, // sets the State/Components entry for each ComponentEndpoint to Empty/OK // Also returns number of deleted rows, if error is nil, and also string array // of those xname IDs that were set to Empty/OK (i.e. not already Empty/OK) @@ -614,7 +614,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteServiceEndpointByID(svc, id string) (bool, error) - // Delete all ServiceEndpoints from database. + // Delete all ServiceEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. DeleteServiceEndpointsAll() (int64, error) @@ -630,7 +630,7 @@ type HMSDB interface { // do not match ALL of the non-empty strings in the filter struct GetCompEthInterfaceFilter(f_opts ...CompEthInterfaceFiltFunc) ([]*sm.CompEthInterfaceV2, error) - // Insert a new CompEthInterface into the database. + // Insert a new CompEthInterface into the dataxnametypes. // If ID or MAC address already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil InsertCompEthInterface(cei *sm.CompEthInterfaceV2) error @@ -641,7 +641,7 @@ type HMSDB interface { // No insertions are done on err != nil InsertCompEthInterfaces(ceis []*sm.CompEthInterfaceV2) error - // Insert/update a CompEthInterface in the database. + // Insert/update a CompEthInterface in the dataxnametypes. // If ID or MAC address already exists, only overwrite ComponentID // and Type fields. // No insertion done on err != nil @@ -675,7 +675,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteCompEthInterfaceByID(id string) (bool, error) - // Delete all CompEthInterfaces from the database. + // Delete all CompEthInterfaces from the dataxnametypes. // Also returns number of deleted rows, if error is nil. DeleteCompEthInterfacesAll() (int64, error) @@ -1083,7 +1083,7 @@ type HMSDBTx interface { // Update NID. If NID is not set or negative, it is set to -1 which // effectively unsets it and suppresses its output. UpdateCompNIDTx(c *base.Component) error - + // Update NID. If NID is not set or negative, it is set to -1 which // effectively unsets it and suppresses its output. BulkUpdateCompNIDTx(comps []base.Component) error @@ -1161,7 +1161,7 @@ type HMSDBTx interface { GetHWInvByFRUAllTx() ([]*sm.HWInvByFRU, error) // Insert or update HWInventoryByLocation struct (in transaction) - // If PopulatedFRU is present, only the FRUID is added to the database. If + // If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction), as @@ -1169,7 +1169,7 @@ type HMSDBTx interface { InsertHWInvByLocTx(hl *sm.HWInvByLoc) error // Insert or update HWInventoryByLocation structs (in transaction) - // If PopulatedFRU is present, only the FRUID is added to the database. If + // If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction), as @@ -1543,7 +1543,7 @@ type HMSDBTx interface { // Component Lock Management // // // - // Insert component reservations into the database. + // Insert component reservations into the dataxnametypes. // To Insert reservations without a duration, the component must be locked. // To Insert reservations with a duration, the component must be unlocked. InsertCompReservationsTx(ids []string, duration int) ([]sm.CompLockV2Success, string, error) diff --git a/internal/hmsds/hmsds-postgres.go b/internal/hmsds/hmsds-postgres.go index 5593b15..acf5225 100644 --- a/internal/hmsds/hmsds-postgres.go +++ b/internal/hmsds/hmsds-postgres.go @@ -34,9 +34,10 @@ import ( "strings" "time" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" + "github.com/Cray-HPE/hms-xname/xnametypes" sq "github.com/Masterminds/squirrel" "github.com/lib/pq" @@ -643,7 +644,8 @@ func (d *hmsdbPg) UpsertComponents(comps []*base.Component, force bool) (map[str } // Update state and flag fields only in DB for a list of components -// Note: If flag is not set, it will be set to OK (i.e. no flag) +// +// Note: If flag is not set, it will be set to OK (i.e. no flag) func (d *hmsdbPg) BulkUpdateCompState(ids []string, state string, flag string) ([]string, error) { return d.UpdateCompStates(ids, state, flag, false, new(PartInfo)) } @@ -654,7 +656,8 @@ func (d *hmsdbPg) BulkUpdateCompState(ids []string, state string, flag string) ( // // If force = true ignores any starting state restrictions and will // always set ids to 'state', unless it is already set. -// Note: If flag is not set, it will be set to OK (i.e. no flag) +// +// Note: If flag is not set, it will be set to OK (i.e. no flag) func (d *hmsdbPg) UpdateCompStates( ids []string, state string, @@ -686,7 +689,7 @@ func (d *hmsdbPg) UpdateCompStates( affectedIDs := []string{} if numIds == 1 { // Normalize the input as it comes from the user. - idArray := []string{base.NormalizeHMSCompID(ids[0])} + idArray := []string{xnametypes.NormalizeHMSCompID(ids[0])} // Let the Update itself verify the starting states. cnt, err := t.UpdateCompStatesTx(idArray, state, nflag, force, false, pi) @@ -750,7 +753,8 @@ func (d *hmsdbPg) UpdateCompStates( // Update state and flag fields only in DB from those in c // Returns the number of affected rows. < 0 means RowsAffected() is not // supported. -// Note: If flag is not set, it will be set to OK (i.e. no flag) +// +// Note: If flag is not set, it will be set to OK (i.e. no flag) func (d *hmsdbPg) UpdateCompState(c *base.Component) (int64, error) { ids, err := d.UpdateCompStates([]string{c.ID}, c.State, c.Flag, false, new(PartInfo)) @@ -1183,7 +1187,7 @@ func (d *hmsdbPg) DeleteNodeMapByID(id string) (bool, error) { return didDelete, err } -// Delete all Node NID Mapping entries from database. +// Delete all Node NID Mapping entries from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteNodeMapsAll() (int64, error) { t, err := d.Begin() @@ -1290,7 +1294,7 @@ func (d *hmsdbPg) DeletePowerMapByID(id string) (bool, error) { return didDelete, err } -// Delete all Power Mapping entries from database. +// Delete all Power Mapping entries from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeletePowerMapsAll() (int64, error) { t, err := d.Begin() @@ -1379,7 +1383,7 @@ func (d *hmsdbPg) GetHWInvByLocFilter(f_opts ...HWInvLocFiltFunc) ([]*sm.HWInvBy idCol := hwInvAlias + "." + hwInvIdCol idArgs := []string{} for _, id := range f.ID { - idArgs = append(idArgs, base.NormalizeHMSCompID(id)) + idArgs = append(idArgs, xnametypes.NormalizeHMSCompID(id)) } query = query.Where(sq.Eq{idCol: idArgs}) } @@ -1387,7 +1391,7 @@ func (d *hmsdbPg) GetHWInvByLocFilter(f_opts ...HWInvLocFiltFunc) ([]*sm.HWInvBy typeCol := hwInvAlias + "." + hwInvTypeCol tArgs := []string{} for _, t := range f.Type { - normType := base.VerifyNormalizeType(t) + normType := xnametypes.VerifyNormalizeType(t) if normType == "" { return nil, ErrHMSDSArgBadType } @@ -1525,7 +1529,7 @@ func (d *hmsdbPg) GetHWInvByFRUFilter(f_opts ...HWInvLocFiltFunc) ([]*sm.HWInvBy typeCol := hwInvFruAlias + "." + hwInvFruTblTypeCol tArgs := []string{} for _, t := range f.Type { - normType := base.VerifyNormalizeType(t) + normType := xnametypes.VerifyNormalizeType(t) if normType == "" { return nil, ErrHMSDSArgBadType } @@ -1994,7 +1998,7 @@ func (d *hmsdbPg) GetRFEndpointsFilter(f *RedfishEPFilter) ([]*sm.RedfishEndpoin return reps, nil } -// Insert new RedfishEndpoint into database. +// Insert new RedfishEndpoint into dataxnametypes. // Does not update any ComponentEndpoint children. // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -2037,7 +2041,7 @@ func (d *hmsdbPg) InsertRFEndpoints(eps *sm.RedfishEndpointArray) error { return nil } -// Update existing RedfishEndpointArray entry in database. +// Update existing RedfishEndpointArray entry in dataxnametypes. // Does not update any ComponentEndpoint children. // Returns updated entry or nil/nil if not found. If an error occurred, // nil/error will be returned. @@ -2375,7 +2379,7 @@ func (d *hmsdbPg) DeleteRFEndpointByID(id string) (bool, error) { return didDelete, err } -// Delete all RedfishEndpoints from database. +// Delete all RedfishEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteRFEndpointsAll() (int64, error) { t, err := d.Begin() @@ -2434,7 +2438,7 @@ func (d *hmsdbPg) DeleteRFEndpointByIDSetEmpty(id string) (bool, []string, error return true, affectedIDs, nil } -// Delete all RedfishEndpoints from database. +// Delete all RedfishEndpoints from dataxnametypes. // This also deletes all child ComponentEndpoints, and in addition, // sets the State/Components entries for those ComponentEndpoints to Empty/OK // Also returns number of deleted rows, if error is nil. @@ -2572,7 +2576,7 @@ func (d *hmsdbPg) DeleteCompEndpointByID(id string) (bool, error) { return didDelete, err } -// Delete all ComponentEndpoints from database. +// Delete all ComponentEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteCompEndpointsAll() (int64, error) { t, err := d.Begin() @@ -2631,7 +2635,7 @@ func (d *hmsdbPg) DeleteCompEndpointByIDSetEmpty(id string) (bool, []string, err return true, affectedIDs, nil } -// Delete all ComponentEndpoints from database. In addition, +// Delete all ComponentEndpoints from dataxnametypes. In addition, // sets the State/Components entry for each ComponentEndpoint to Empty/OK // Also returns number of deleted rows, if error is nil, and also string array // of those xname IDs that were set to Empty/OK (i.e. not already Empty/OK) @@ -2772,7 +2776,7 @@ func (d *hmsdbPg) DeleteServiceEndpointByID(svc, id string) (bool, error) { return didDelete, err } -// Delete all ServiceEndpoints from database. +// Delete all ServiceEndpoints from dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteServiceEndpointsAll() (int64, error) { t, err := d.Begin() @@ -2898,7 +2902,7 @@ func (d *hmsdbPg) GetCompEthInterfaceFilter(f_opts ...CompEthInterfaceFiltFunc) return ceis, err } -// Insert a new CompEthInterface into the database. +// Insert a new CompEthInterface into the dataxnametypes. // If ID or MAC address already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil func (d *hmsdbPg) InsertCompEthInterface(cei *sm.CompEthInterfaceV2) error { @@ -2937,7 +2941,7 @@ func (d *hmsdbPg) InsertCompEthInterfaces(ceis []*sm.CompEthInterfaceV2) error { return nil } -// Insert/update a CompEthInterface in the database. +// Insert/update a CompEthInterface in the dataxnametypes. // If ID or MAC address already exists, only overwrite ComponentID // and Type fields. // No insertion done on err != nil @@ -3097,7 +3101,7 @@ func (d *hmsdbPg) DeleteCompEthInterfaceByID(id string) (bool, error) { return didDelete, err } -// Delete all CompEthInterfaces from the database. +// Delete all CompEthInterfaces from the dataxnametypes. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteCompEthInterfacesAll() (int64, error) { t, err := d.Begin() @@ -3118,9 +3122,9 @@ func (d *hmsdbPg) DeleteCompEthInterfacesAll() (int64, error) { // Add IP Address mapping to the existing component ethernet interface. // returns: -// - ErrHMSDSNoCompEthInterface if the parent component ethernet interface -// - ErrHMSDSDuplicateKey if the parent component ethernet interface already -// has that IP address +// - ErrHMSDSNoCompEthInterface if the parent component ethernet interface +// - ErrHMSDSDuplicateKey if the parent component ethernet interface already +// has that IP address // // Returns key of new IP Address Mapping id, should be the IP address func (d *hmsdbPg) AddCompEthInterfaceIPAddress(id string, ipmIn *sm.IPAddressMapping) (string, error) { @@ -3341,16 +3345,15 @@ func (d *hmsdbPg) UpsertDiscoveryStatus(stat *sm.DiscoveryStatus) error { // Atomically: // -// 1. Update discovery-writable fields for RedfishEndpoint -// 2. Upsert ComponentEndpointArray into database within the -// same transaction. -// 3. Insert or update array of HWInventoryByLocation structs. -// If PopulatedFRU is present, these is also added to the DB If -// it is not, this effectively "depopulates" the given locations. -// The actual HWInventoryByFRU is stored using within the same -// transaction. -// 4. Inserts or updates HMS Components entries in ComponentArray -// +// 1. Update discovery-writable fields for RedfishEndpoint +// 2. Upsert ComponentEndpointArray into database within the +// same transaction. +// 3. Insert or update array of HWInventoryByLocation structs. +// If PopulatedFRU is present, these is also added to the DB If +// it is not, this effectively "depopulates" the given locations. +// The actual HWInventoryByFRU is stored using within the same +// transaction. +// 4. Inserts or updates HMS Components entries in ComponentArray func (d *hmsdbPg) UpdateAllForRFEndpoint( ep *sm.RedfishEndpoint, ceps *sm.ComponentEndpointArray, @@ -3418,7 +3421,7 @@ func (d *hmsdbPg) UpdateAllForRFEndpoint( nodeList := make([]string, 0, 1) for _, comp := range comps.Components { compMap[comp.ID] = comp - if comp.Type == base.Node.String() { + if comp.Type == xnametypes.Node.String() { nodeList = append(nodeList, comp.ID) } else { d.Log(LOG_INFO, @@ -4633,9 +4636,9 @@ func (d *hmsdbPg) GetCompLocksV2(f sm.CompLockV2Filter) ([]sm.CompLockV2, error) // best try. func (d *hmsdbPg) UpdateCompLocksV2(f sm.CompLockV2Filter, action string) (sm.CompLockV2UpdateResult, error) { var ( - result sm.CompLockV2UpdateResult - affectedIds []string - lockKeys []sm.CompLockV2Key + result sm.CompLockV2UpdateResult + affectedIds []string + lockKeys []sm.CompLockV2Key ) result.Success.ComponentIDs = make([]string, 0, 1) result.Failure = make([]sm.CompLockV2Failure, 0, 1) diff --git a/internal/hmsds/hmsds-postgres_test.go b/internal/hmsds/hmsds-postgres_test.go index 3882d89..1400009 100644 --- a/internal/hmsds/hmsds-postgres_test.go +++ b/internal/hmsds/hmsds-postgres_test.go @@ -33,10 +33,11 @@ import ( "testing" "time" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" stest "github.com/Cray-HPE/hms-smd/v2/pkg/sharedtest" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" + "github.com/Cray-HPE/hms-xname/xnametypes" "github.com/DATA-DOG/go-sqlmock" sq "github.com/Masterminds/squirrel" @@ -557,7 +558,7 @@ func TestPgUpsertComponents(t *testing.T) { compSubTypeCol + " = EXCLUDED." + compSubTypeCol + ", " + compNetTypeCol + " = EXCLUDED." + compNetTypeCol + ", " + compArchCol + " = EXCLUDED." + compArchCol + ", " + - compClassCol + " = EXCLUDED." + compClassCol + + compClassCol + " = EXCLUDED." + compClassCol + " RETURNING " + compIdCol sqq := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) @@ -587,7 +588,7 @@ func TestPgUpsertComponents(t *testing.T) { }{{ comps: []*base.Component{&base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }}, @@ -599,7 +600,7 @@ func TestPgUpsertComponents(t *testing.T) { expectedPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedArgs: []driver.Value{"x0c0s0b0n0"}, expectedInsert: regexp.QuoteMeta(insert1), - expectedRows: [][]driver.Value{ + expectedRows: [][]driver.Value{ []driver.Value{"x0c0s0b0n0"}, }, expectedInArgs: []driver.Value{ @@ -618,13 +619,13 @@ func TestPgUpsertComponents(t *testing.T) { }, { comps: []*base.Component{&base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }}, force: false, dbColumns: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbRows: [][]driver.Value{ + dbRows: [][]driver.Value{ []driver.Value{"x0c0s0b0n0", "Node", "On", "OK", true, "AdminStatus", "Compute", "", 832, "", "Sling", "X86", "", false, false}, }, dbError: nil, @@ -638,13 +639,13 @@ func TestPgUpsertComponents(t *testing.T) { }, { comps: []*base.Component{&base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }}, force: true, dbColumns: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbRows: [][]driver.Value{ + dbRows: [][]driver.Value{ []driver.Value{"x0c0s0b0n0", "Node", "On", "OK", true, "AdminStatus", "Compute", "", 832, "", "Sling", "X86", "", false, false}, }, dbError: nil, @@ -652,7 +653,7 @@ func TestPgUpsertComponents(t *testing.T) { expectedPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedArgs: []driver.Value{"x0c0s0b0n0"}, expectedInsert: regexp.QuoteMeta(insert1), - expectedRows: [][]driver.Value{ + expectedRows: [][]driver.Value{ []driver.Value{"x0c0s0b0n0"}, }, expectedInArgs: []driver.Value{ @@ -667,13 +668,13 @@ func TestPgUpsertComponents(t *testing.T) { comps: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, &base.Component{ ID: "x0c0s0b0n1", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -686,7 +687,7 @@ func TestPgUpsertComponents(t *testing.T) { expectedPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1,$2)"), expectedArgs: []driver.Value{"x0c0s0b0n0", "x0c0s0b0n1"}, expectedInsert: regexp.QuoteMeta(insert2), - expectedRows: [][]driver.Value{ + expectedRows: [][]driver.Value{ []driver.Value{"x0c0s0b0n0"}, []driver.Value{"x0c0s0b0n1"}, }, @@ -716,7 +717,7 @@ func TestPgUpsertComponents(t *testing.T) { comps: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -736,7 +737,7 @@ func TestPgUpsertComponents(t *testing.T) { comps: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -749,7 +750,7 @@ func TestPgUpsertComponents(t *testing.T) { expectedPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedArgs: []driver.Value{"x0c0s0b0n0"}, expectedInsert: regexp.QuoteMeta(insert1), - expectedRows: [][]driver.Value{ + expectedRows: [][]driver.Value{ []driver.Value{"x0c0s0b0n0"}, }, expectedInArgs: []driver.Value{ @@ -1569,14 +1570,14 @@ func TestPgBulkUpdateCompClass(t *testing.T) { func TestPgBulkUpdateCompNID(t *testing.T) { sqq := sq.StatementBuilder.PlaceholderFormat(sq.Dollar) - update, _, _ := sqq.Update(compTable + " " + compTableJoinAlias). - Set(compNIDCol, sq.Expr(compTableSubAlias + "." + compNIDCol)). - Suffix("FROM (VALUES (?,?::BIGINT),(?,?::BIGINT)) AS " + compTableSubAlias + - "(" + compIdCol + ", " + compNIDCol + - ") WHERE " + compTableJoinAlias + "." + compIdCol + " = " + compTableSubAlias + "." + compIdCol, - "x0c0s25b0n0", 800, "x0c0s27b0n0", 864).ToSql() + update, _, _ := sqq.Update(compTable+" "+compTableJoinAlias). + Set(compNIDCol, sq.Expr(compTableSubAlias+"."+compNIDCol)). + Suffix("FROM (VALUES (?,?::BIGINT),(?,?::BIGINT)) AS "+compTableSubAlias+ + "("+compIdCol+", "+compNIDCol+ + ") WHERE "+compTableJoinAlias+"."+compIdCol+" = "+compTableSubAlias+"."+compIdCol, + "x0c0s25b0n0", 800, "x0c0s27b0n0", 864).ToSql() tests := []struct { - comps *[]base.Component + comps *[]base.Component dbUpdateError error expectedUpdatePrepare string expectedUpdateArgs []driver.Value @@ -1656,7 +1657,7 @@ func TestPgGetHWInvByLocQueryFilter(t *testing.T) { preQuery2, preQuery2Args, _ := sq.Select(preQueryCols...). From(hwInvLocTable + " " + hwInvLocAlias). Where(sq.Expr("("+hwInvLocAlias+"."+hwInvLocIdCol+" SIMILAR TO ?)", node1.ID+"([[:alpha:]][[:alnum:]]*)?")). - Where(sq.Eq{hwInvLocAlias + "." + hwInvLocTypeCol: []string{base.Processor.String()}}).ToSql() + Where(sq.Eq{hwInvLocAlias + "." + hwInvLocTypeCol: []string{xnametypes.Processor.String()}}).ToSql() preQuery2Args = append(preQuery2Args, ")([[:alpha:]][[:alnum:]]*)?") query2, _, _ := sqq.Select(columns...). From(hwInvTable+" "+hwInvAlias). @@ -1673,7 +1674,7 @@ func TestPgGetHWInvByLocQueryFilter(t *testing.T) { query4, _, _ := sqq.Select(columns...). From(hwInvTable + " " + hwInvAlias). - Where(sq.Eq{hwInvAlias + "." + hwInvTypeCol: []string{base.Processor.String()}}).ToSql() + Where(sq.Eq{hwInvAlias + "." + hwInvTypeCol: []string{xnametypes.Processor.String()}}).ToSql() tests := []struct { f_opts []HWInvLocFiltFunc @@ -1695,13 +1696,13 @@ func TestPgGetHWInvByLocQueryFilter(t *testing.T) { expectedHwLocs: []*sm.HWInvByLoc{&node1, &proc1}, expectedErr: nil, }, { - f_opts: []HWInvLocFiltFunc{HWInvLoc_ID(node1.ID), HWInvLoc_Type(base.Processor.String()), HWInvLoc_Child}, + f_opts: []HWInvLocFiltFunc{HWInvLoc_ID(node1.ID), HWInvLoc_Type(xnametypes.Processor.String()), HWInvLoc_Child}, dbRows: [][]driver.Value{ []driver.Value{proc1.ID, proc1.Type, proc1.Ordinal, proc1.Status, proc1LocInfo, proc1.PopulatedFRU.FRUID, proc1.PopulatedFRU.Type, proc1.PopulatedFRU.Subtype, proc1FruInfo}, }, dbError: nil, expectedPrepare: regexp.QuoteMeta(query2), - expectedArgs: []driver.Value{node1.ID + "([[:alpha:]][[:alnum:]]*)?", base.Processor.String(), ")([[:alpha:]][[:alnum:]]*)?"}, + expectedArgs: []driver.Value{node1.ID + "([[:alpha:]][[:alnum:]]*)?", xnametypes.Processor.String(), ")([[:alpha:]][[:alnum:]]*)?"}, expectedHwLocs: []*sm.HWInvByLoc{&proc1}, expectedErr: nil, }, { @@ -1724,11 +1725,11 @@ func TestPgGetHWInvByLocQueryFilter(t *testing.T) { expectedHwLocs: nil, expectedErr: ErrHMSDSArgBadRedfishType, }, { - f_opts: []HWInvLocFiltFunc{HWInvLoc_Type(base.Processor.String())}, + f_opts: []HWInvLocFiltFunc{HWInvLoc_Type(xnametypes.Processor.String())}, dbRows: nil, dbError: sql.ErrNoRows, expectedPrepare: regexp.QuoteMeta(query4), - expectedArgs: []driver.Value{base.Processor.String()}, + expectedArgs: []driver.Value{xnametypes.Processor.String()}, expectedHwLocs: nil, expectedErr: nil, }} @@ -1785,7 +1786,7 @@ func TestPgGetHWInvByLocFilter(t *testing.T) { query2, _, _ := sqq.Select(columns...). From(hwInvTable + " " + hwInvAlias). Where(sq.Eq{hwInvAlias + "." + hwInvIdCol: []string{node1.ID}}). - Where(sq.Eq{hwInvAlias + "." + hwInvTypeCol: []string{base.Node.String()}}). + Where(sq.Eq{hwInvAlias + "." + hwInvTypeCol: []string{xnametypes.Node.String()}}). Where(sq.Expr("("+hwInvAlias+"."+hwInvFruInfoCol+" ->> 'Manufacturer' ILIKE ?)", "%cray%")). Where(sq.Eq{hwInvAlias + "." + hwInvFruInfoCol + " ->> 'PartNumber'": []string{node1.PopulatedFRU.HMSNodeFRUInfo.PartNumber}}). Where(sq.Eq{hwInvAlias + "." + hwInvFruInfoCol + " ->> 'SerialNumber'": []string{node1.PopulatedFRU.HMSNodeFRUInfo.SerialNumber}}). @@ -1806,7 +1807,7 @@ func TestPgGetHWInvByLocFilter(t *testing.T) { }, dbError: nil, expectedPrepare: regexp.QuoteMeta(query2), - expectedArgs: []driver.Value{node1.ID, base.Node.String(), "%cray%", node1.PopulatedFRU.HMSNodeFRUInfo.PartNumber, node1.PopulatedFRU.HMSNodeFRUInfo.SerialNumber, node1.PopulatedFRU.FRUID}, + expectedArgs: []driver.Value{node1.ID, xnametypes.Node.String(), "%cray%", node1.PopulatedFRU.HMSNodeFRUInfo.PartNumber, node1.PopulatedFRU.HMSNodeFRUInfo.SerialNumber, node1.PopulatedFRU.FRUID}, expectedHwLocs: []*sm.HWInvByLoc{&node1}, expectedErr: nil, }, { @@ -1878,7 +1879,7 @@ func TestPgGetHWInvByFRUFilter(t *testing.T) { query2, _, _ := sqq.Select(columns...). From(hwInvFruTable + " " + hwInvFruAlias). - Where(sq.Eq{hwInvFruAlias + "." + hwInvFruTblTypeCol: []string{base.Node.String()}}). + Where(sq.Eq{hwInvFruAlias + "." + hwInvFruTblTypeCol: []string{xnametypes.Node.String()}}). Where(sq.Expr("("+hwInvFruAlias+"."+hwInvFruTblInfoCol+" ->> 'Manufacturer' ILIKE ?)", "%cray%")). Where(sq.Eq{hwInvFruAlias + "." + hwInvFruTblInfoCol + " ->> 'PartNumber'": []string{node1.HMSNodeFRUInfo.PartNumber}}). Where(sq.Eq{hwInvFruAlias + "." + hwInvFruTblInfoCol + " ->> 'SerialNumber'": []string{node1.HMSNodeFRUInfo.SerialNumber}}). @@ -1886,7 +1887,7 @@ func TestPgGetHWInvByFRUFilter(t *testing.T) { query3, _, _ := sqq.Select(columns...). From(hwInvFruTable + " " + hwInvFruAlias). - Where(sq.Eq{hwInvFruAlias + "." + hwInvFruTblTypeCol: []string{base.Processor.String()}}).ToSql() + Where(sq.Eq{hwInvFruAlias + "." + hwInvFruTblTypeCol: []string{xnametypes.Processor.String()}}).ToSql() tests := []struct { f_opts []HWInvLocFiltFunc @@ -1914,7 +1915,7 @@ func TestPgGetHWInvByFRUFilter(t *testing.T) { }, dbError: nil, expectedPrepare: regexp.QuoteMeta(query2), - expectedArgs: []driver.Value{base.Node.String(), "%cray%", node1.HMSNodeFRUInfo.PartNumber, node1.HMSNodeFRUInfo.SerialNumber, node1.FRUID}, + expectedArgs: []driver.Value{xnametypes.Node.String(), "%cray%", node1.HMSNodeFRUInfo.PartNumber, node1.HMSNodeFRUInfo.SerialNumber, node1.FRUID}, expectedHwFrus: []*sm.HWInvByFRU{&node1}, expectedErr: nil, }, { @@ -1926,11 +1927,11 @@ func TestPgGetHWInvByFRUFilter(t *testing.T) { expectedHwFrus: nil, expectedErr: ErrHMSDSArgBadRedfishType, }, { - f_opts: []HWInvLocFiltFunc{HWInvLoc_Type(base.Processor.String())}, + f_opts: []HWInvLocFiltFunc{HWInvLoc_Type(xnametypes.Processor.String())}, dbRows: nil, dbError: sql.ErrNoRows, expectedPrepare: regexp.QuoteMeta(query3), - expectedArgs: []driver.Value{base.Processor.String()}, + expectedArgs: []driver.Value{xnametypes.Processor.String()}, expectedHwFrus: nil, expectedErr: nil, }} @@ -2178,7 +2179,7 @@ func TestInsertHWInvHists(t *testing.T) { }{{ hhs: []*sm.HWInvHist{&testHWInvHist1, &testHWInvHist2}, expectedPrepare: regexp.QuoteMeta(insert1), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ testHWInvHist1.ID, testHWInvHist1.FruId, testHWInvHist1.EventType, testHWInvHist2.ID, testHWInvHist2.FruId, testHWInvHist2.EventType, }, @@ -2191,7 +2192,7 @@ func TestInsertHWInvHists(t *testing.T) { }, { hhs: []*sm.HWInvHist{&testHWInvHist1, &testHWInvHist2}, expectedPrepare: regexp.QuoteMeta(insert1), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ testHWInvHist1.ID, testHWInvHist1.FruId, testHWInvHist1.EventType, testHWInvHist2.ID, testHWInvHist2.FruId, testHWInvHist2.EventType, }, @@ -3047,7 +3048,7 @@ func TestPgUpsertServiceEndpoint(t *testing.T) { } func TestPgUpsertServiceEndpoints(t *testing.T) { - upsertSuffix := "ON CONFLICT(" + serviceEPsRFEndpointIDCol + ", "+ serviceEPsRedfishTypeCol + ") DO UPDATE SET " + + upsertSuffix := "ON CONFLICT(" + serviceEPsRFEndpointIDCol + ", " + serviceEPsRedfishTypeCol + ") DO UPDATE SET " + serviceEPsRedfishSubtypeCol + " = EXCLUDED." + serviceEPsRedfishSubtypeCol + ", " + serviceEPsUUIDCol + " = EXCLUDED." + serviceEPsUUIDCol + ", " + serviceEPsODataIDCol + " = EXCLUDED." + serviceEPsODataIDCol + ", " + @@ -3075,7 +3076,7 @@ func TestPgUpsertServiceEndpoints(t *testing.T) { seps: &stest.TestServiceEndpointArrayUpdates, dbError: nil, expectedPrepare: regexp.QuoteMeta(insert2), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ stest.TestServiceEndpointArrayUpdates.ServiceEndpoints[0].RfEndpointID, stest.TestServiceEndpointArrayUpdates.ServiceEndpoints[0].RedfishType, stest.TestServiceEndpointArrayUpdates.ServiceEndpoints[0].RedfishSubtype, @@ -3094,7 +3095,7 @@ func TestPgUpsertServiceEndpoints(t *testing.T) { seps: &stest.TestServiceEndpointArrayUpdate1, dbError: nil, expectedPrepare: regexp.QuoteMeta(insert1), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ stest.TestServiceEndpointArrayUpdate1.ServiceEndpoints[0].RfEndpointID, stest.TestServiceEndpointArrayUpdate1.ServiceEndpoints[0].RedfishType, stest.TestServiceEndpointArrayUpdate1.ServiceEndpoints[0].RedfishSubtype, @@ -3107,7 +3108,7 @@ func TestPgUpsertServiceEndpoints(t *testing.T) { seps: &stest.TestServiceEndpointArrayUpdate1, dbError: sql.ErrNoRows, expectedPrepare: regexp.QuoteMeta(insert1), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ stest.TestServiceEndpointArrayUpdate1.ServiceEndpoints[0].RfEndpointID, stest.TestServiceEndpointArrayUpdate1.ServiceEndpoints[0].RedfishType, stest.TestServiceEndpointArrayUpdate1.ServiceEndpoints[0].RedfishSubtype, @@ -3455,7 +3456,7 @@ func TestInsertCompEthInterfaces(t *testing.T) { }{{ // Test 0 - Insert 2 new rows in: []*sm.CompEthInterfaceV2{&testCompEth1, &testCompEth2}, expectedPrepare: regexp.QuoteMeta(insert1), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ testCompEth1.ID, testCompEth1.Desc, testCompEth1.MACAddr, "NOW()", testCompEth1.CompID, testCompEth1.Type, testCompEth1IPAddrsRaw, "a4bf0138ee67", testCompEth2.Desc, testCompEth2.MACAddr, "NOW()", testCompEth2.CompID, testCompEth2.Type, testCompEth2IPAddrsRaw, }, @@ -3463,7 +3464,7 @@ func TestInsertCompEthInterfaces(t *testing.T) { }, { // Test 1 - Test that database error is passed back in: []*sm.CompEthInterfaceV2{&testCompEth1, &testCompEth2}, expectedPrepare: regexp.QuoteMeta(insert1), - expectedArgs: []driver.Value{ + expectedArgs: []driver.Value{ testCompEth1.ID, testCompEth1.Desc, testCompEth1.MACAddr, "NOW()", testCompEth1.CompID, testCompEth1.Type, testCompEth1IPAddrsRaw, "a4bf0138ee67", testCompEth2.Desc, testCompEth2.MACAddr, "NOW()", testCompEth2.CompID, testCompEth2.Type, testCompEth2IPAddrsRaw, }, @@ -3591,88 +3592,88 @@ func TestDeleteCompEthInterfacesAll(t *testing.T) { func TestGetSCNSubscriptionsAll(t *testing.T) { tests := []struct { - dbColumns []string - dbRows [][]driver.Value - dbError error - expectedPrepare string - expectedSCNSubs *sm.SCNSubscriptionArray + dbColumns []string + dbRows [][]driver.Value + dbError error + expectedPrepare string + expectedSCNSubs *sm.SCNSubscriptionArray }{{ - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{2, `{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`}, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{2, `{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`}, }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), - expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), + expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ sm.SCNSubscription{ - ID: 2, - Subscriber: "hmfd@sms01", - States: []string{"On", "Off"}, - Url: "https://foo/bar", + ID: 2, + Subscriber: "hmfd@sms01", + States: []string{"On", "Off"}, + Url: "https://foo/bar", }, }}, }, { - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{2, `{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`}, - []driver.Value{3, `{"Subscriber":"hmfd@sms02","States":["Off","Ready"],"Url":"https://foo2/bar"}`}, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{2, `{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`}, + []driver.Value{3, `{"Subscriber":"hmfd@sms02","States":["Off","Ready"],"Url":"https://foo2/bar"}`}, }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), - expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), + expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ sm.SCNSubscription{ - ID: 2, - Subscriber: "hmfd@sms01", - States: []string{"On", "Off"}, - Url: "https://foo/bar", + ID: 2, + Subscriber: "hmfd@sms01", + States: []string{"On", "Off"}, + Url: "https://foo/bar", }, sm.SCNSubscription{ - ID: 3, - Subscriber: "hmfd@sms02", - States: []string{"Off", "Ready"}, - Url: "https://foo2/bar", + ID: 3, + Subscriber: "hmfd@sms02", + States: []string{"Off", "Ready"}, + Url: "https://foo2/bar", }, }}, }, { - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{1, `{"Subscriber":"cray-hmnfd-798784bd66-s69mg_4","Roles":["compute","service"],"States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, - []driver.Value{2, `{"Subscriber":"cray-hmnfd-798784bd66-rkvzn_4","Roles":["service"],"States":["Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, - []driver.Value{3, `{"Subscriber":"cray-hmnfd-798784bd66-bp8rc_23","Roles":["compute"],"States":["Empty","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{1, `{"Subscriber":"cray-hmnfd-798784bd66-s69mg_4","Roles":["compute","service"],"States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, + []driver.Value{2, `{"Subscriber":"cray-hmnfd-798784bd66-rkvzn_4","Roles":["service"],"States":["Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, + []driver.Value{3, `{"Subscriber":"cray-hmnfd-798784bd66-bp8rc_23","Roles":["compute"],"States":["Empty","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), - expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), + expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ sm.SCNSubscription{ - ID: 1, - Subscriber: "cray-hmnfd-798784bd66-s69mg_4", - Roles: []string{"compute", "service"}, - States: []string{"Empty", "Populated", "Off", "On", "Standby", "Halt", "Ready"}, - Url: "http://cray-hmnfd/hmi/v1/scn", + ID: 1, + Subscriber: "cray-hmnfd-798784bd66-s69mg_4", + Roles: []string{"compute", "service"}, + States: []string{"Empty", "Populated", "Off", "On", "Standby", "Halt", "Ready"}, + Url: "http://cray-hmnfd/hmi/v1/scn", }, sm.SCNSubscription{ - ID: 2, - Subscriber: "cray-hmnfd-798784bd66-rkvzn_4", - Roles: []string{"service"}, - States: []string{"Populated", "Off", "On", "Standby", "Halt", "Ready"}, - Url: "http://cray-hmnfd/hmi/v1/scn", + ID: 2, + Subscriber: "cray-hmnfd-798784bd66-rkvzn_4", + Roles: []string{"service"}, + States: []string{"Populated", "Off", "On", "Standby", "Halt", "Ready"}, + Url: "http://cray-hmnfd/hmi/v1/scn", }, sm.SCNSubscription{ - ID: 3, - Subscriber: "cray-hmnfd-798784bd66-bp8rc_23", - Roles: []string{"compute"}, - States: []string{"Empty", "Off", "On", "Standby", "Halt", "Ready"}, - Url: "http://cray-hmnfd/hmi/v1/scn", + ID: 3, + Subscriber: "cray-hmnfd-798784bd66-bp8rc_23", + Roles: []string{"compute"}, + States: []string{"Empty", "Off", "On", "Standby", "Halt", "Ready"}, + Url: "http://cray-hmnfd/hmi/v1/scn", }, }}, }, { - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{"", `{}`}, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{"", `{}`}, }, - dbError: sql.ErrNoRows, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), - expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ + dbError: sql.ErrNoRows, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryAll), + expectedSCNSubs: &sm.SCNSubscriptionArray{[]sm.SCNSubscription{ sm.SCNSubscription{}, }}, }} @@ -3713,54 +3714,54 @@ func TestGetSCNSubscriptionsAll(t *testing.T) { func TestGetSCNSubscription(t *testing.T) { tests := []struct { - id int64 - dbColumns []string - dbRows [][]driver.Value - dbError error - expectedPrepare string - expectedArgs []driver.Value - expectedSCNSub *sm.SCNSubscription + id int64 + dbColumns []string + dbRows [][]driver.Value + dbError error + expectedPrepare string + expectedArgs []driver.Value + expectedSCNSub *sm.SCNSubscription }{{ - id: 2, - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{2, `{"Subscriber":"cray-hmnfd-69d99579c5-shpmk_3","States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, - }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryId), - expectedArgs: []driver.Value{2}, - expectedSCNSub: &sm.SCNSubscription{ - ID: 2, - Subscriber: "cray-hmnfd-69d99579c5-shpmk_3", - States: []string{"Empty","Populated","Off","On","Standby","Halt","Ready"}, - Url: "http://cray-hmnfd/hmi/v1/scn", - }, - }, { - id: 3, - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{3, `{"Subscriber":"cray-hmnfd-798784bd66-s69mg_4","Roles":["compute","service"],"States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, - }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryId), - expectedArgs: []driver.Value{3}, - expectedSCNSub: &sm.SCNSubscription{ - ID: 3, - Subscriber: "cray-hmnfd-798784bd66-s69mg_4", - Roles: []string{"compute","service"}, - States: []string{"Empty","Populated","Off","On","Standby","Halt","Ready"}, - Url: "http://cray-hmnfd/hmi/v1/scn", - }, - }, { - id: 0, - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{"", `{}`}, - }, - dbError: sql.ErrNoRows, - expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryId), - expectedArgs: []driver.Value{}, - expectedSCNSub: &sm.SCNSubscription{}, + id: 2, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{2, `{"Subscriber":"cray-hmnfd-69d99579c5-shpmk_3","States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, + }, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryId), + expectedArgs: []driver.Value{2}, + expectedSCNSub: &sm.SCNSubscription{ + ID: 2, + Subscriber: "cray-hmnfd-69d99579c5-shpmk_3", + States: []string{"Empty", "Populated", "Off", "On", "Standby", "Halt", "Ready"}, + Url: "http://cray-hmnfd/hmi/v1/scn", + }, + }, { + id: 3, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{3, `{"Subscriber":"cray-hmnfd-798784bd66-s69mg_4","Roles":["compute","service"],"States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, + }, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryId), + expectedArgs: []driver.Value{3}, + expectedSCNSub: &sm.SCNSubscription{ + ID: 3, + Subscriber: "cray-hmnfd-798784bd66-s69mg_4", + Roles: []string{"compute", "service"}, + States: []string{"Empty", "Populated", "Off", "On", "Standby", "Halt", "Ready"}, + Url: "http://cray-hmnfd/hmi/v1/scn", + }, + }, { + id: 0, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{"", `{}`}, + }, + dbError: sql.ErrNoRows, + expectedPrepare: regexp.QuoteMeta(tGetSCNSubscriptionQueryId), + expectedArgs: []driver.Value{}, + expectedSCNSub: &sm.SCNSubscription{}, }} for i, test := range tests { @@ -3799,52 +3800,52 @@ func TestGetSCNSubscription(t *testing.T) { func TestInsertSCNSubscription(t *testing.T) { tests := []struct { - sub sm.SCNPostSubscription - dbColumns []string - dbRows [][]driver.Value - dbError error - expectedPrepare string - expectedArgs []driver.Value - expectedID int64 + sub sm.SCNPostSubscription + dbColumns []string + dbRows [][]driver.Value + dbError error + expectedPrepare string + expectedArgs []driver.Value + expectedID int64 }{{ - sub: sm.SCNPostSubscription{ - Subscriber: "hmfd@sms01", - States: []string{"On", "Off"}, - Url: "https://foo/bar", - }, - dbColumns: []string{"id"}, - dbRows: [][]driver.Value{ - []driver.Value{4}, - }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tInsertSCNSubscription), - expectedArgs: []driver.Value{"hmfd@sms01https://foo/bar",json.RawMessage(`{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`)}, - expectedID: 4, - }, { - sub: sm.SCNPostSubscription{ - Subscriber: "cray-hmnfd-798784bd66-s69mg_4", - Roles: []string{"compute","service"}, - States: []string{"Empty","Populated","Off","On","Standby","Halt","Ready"}, - Url: "http://cray-hmnfd/hmi/v1/scn", - }, - dbColumns: []string{"id"}, - dbRows: [][]driver.Value{ - []driver.Value{5}, - }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tInsertSCNSubscription), - expectedArgs: []driver.Value{"cray-hmnfd-798784bd66-s69mg_4http://cray-hmnfd/hmi/v1/scn",json.RawMessage(`{"Subscriber":"cray-hmnfd-798784bd66-s69mg_4","Roles":["compute","service"],"States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`)}, - expectedID: 5, - }, { - sub: sm.SCNPostSubscription{}, - dbColumns: []string{"id"}, - dbRows: [][]driver.Value{ - []driver.Value{0}, - }, - dbError: sql.ErrNoRows, - expectedPrepare: regexp.QuoteMeta(tInsertSCNSubscription), - expectedArgs: []driver.Value{"",json.RawMessage(`{}`)}, - expectedID: 0, + sub: sm.SCNPostSubscription{ + Subscriber: "hmfd@sms01", + States: []string{"On", "Off"}, + Url: "https://foo/bar", + }, + dbColumns: []string{"id"}, + dbRows: [][]driver.Value{ + []driver.Value{4}, + }, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tInsertSCNSubscription), + expectedArgs: []driver.Value{"hmfd@sms01https://foo/bar", json.RawMessage(`{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`)}, + expectedID: 4, + }, { + sub: sm.SCNPostSubscription{ + Subscriber: "cray-hmnfd-798784bd66-s69mg_4", + Roles: []string{"compute", "service"}, + States: []string{"Empty", "Populated", "Off", "On", "Standby", "Halt", "Ready"}, + Url: "http://cray-hmnfd/hmi/v1/scn", + }, + dbColumns: []string{"id"}, + dbRows: [][]driver.Value{ + []driver.Value{5}, + }, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tInsertSCNSubscription), + expectedArgs: []driver.Value{"cray-hmnfd-798784bd66-s69mg_4http://cray-hmnfd/hmi/v1/scn", json.RawMessage(`{"Subscriber":"cray-hmnfd-798784bd66-s69mg_4","Roles":["compute","service"],"States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`)}, + expectedID: 5, + }, { + sub: sm.SCNPostSubscription{}, + dbColumns: []string{"id"}, + dbRows: [][]driver.Value{ + []driver.Value{0}, + }, + dbError: sql.ErrNoRows, + expectedPrepare: regexp.QuoteMeta(tInsertSCNSubscription), + expectedArgs: []driver.Value{"", json.RawMessage(`{}`)}, + expectedID: 0, }} for i, test := range tests { @@ -3884,30 +3885,30 @@ func TestInsertSCNSubscription(t *testing.T) { func TestUpdateSCNSubscription(t *testing.T) { tests := []struct { - id int64 - sub sm.SCNPostSubscription - dbError error - expectedPrepare string - expectedArgs []driver.Value - expectedDidUpdate bool + id int64 + sub sm.SCNPostSubscription + dbError error + expectedPrepare string + expectedArgs []driver.Value + expectedDidUpdate bool }{{ - id: 4, - sub: sm.SCNPostSubscription{ - Subscriber: "hmfd@sms01", - States: []string{"On", "Off"}, - Url: "https://foo/bar", - }, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tUpdateSCNSubscription), - expectedArgs: []driver.Value{"hmfd@sms01https://foo/bar",json.RawMessage(`{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`),4}, - expectedDidUpdate: true, - }, { - id: 0, - sub: sm.SCNPostSubscription{}, - dbError: sql.ErrNoRows, - expectedPrepare: regexp.QuoteMeta(tUpdateSCNSubscription), - expectedArgs: []driver.Value{"",json.RawMessage(`{}`),0}, - expectedDidUpdate: false, + id: 4, + sub: sm.SCNPostSubscription{ + Subscriber: "hmfd@sms01", + States: []string{"On", "Off"}, + Url: "https://foo/bar", + }, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tUpdateSCNSubscription), + expectedArgs: []driver.Value{"hmfd@sms01https://foo/bar", json.RawMessage(`{"Subscriber":"hmfd@sms01","States":["On","Off"],"Url":"https://foo/bar"}`), 4}, + expectedDidUpdate: true, + }, { + id: 0, + sub: sm.SCNPostSubscription{}, + dbError: sql.ErrNoRows, + expectedPrepare: regexp.QuoteMeta(tUpdateSCNSubscription), + expectedArgs: []driver.Value{"", json.RawMessage(`{}`), 0}, + expectedDidUpdate: false, }} for i, test := range tests { @@ -3942,48 +3943,48 @@ func TestUpdateSCNSubscription(t *testing.T) { func TestPatchSCNSubscription(t *testing.T) { tests := []struct { - id int64 - op string - sub sm.SCNPatchSubscription - dbColumns []string - dbRows [][]driver.Value - dbError error - expectedQueryPrepare string - expectedUpdatePrepare string - expectedQueryArgs []driver.Value - expectedUpdateArgs []driver.Value - expectedDidPatch bool + id int64 + op string + sub sm.SCNPatchSubscription + dbColumns []string + dbRows [][]driver.Value + dbError error + expectedQueryPrepare string + expectedUpdatePrepare string + expectedQueryArgs []driver.Value + expectedUpdateArgs []driver.Value + expectedDidPatch bool }{{ - id: 4, - op: "add", - sub: sm.SCNPatchSubscription{ - Op: "add", - States: []string{"On", "Off"}, - }, - dbColumns: []string{"id", "subscription"}, - dbRows: [][]driver.Value{ - []driver.Value{4, `{"Subscriber":"cray-hmnfd-69d99579c5-shpmk_3","States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, - }, - dbError: nil, - expectedQueryPrepare: regexp.QuoteMeta(tGetSCNSubscriptionUpdate), - expectedUpdatePrepare: regexp.QuoteMeta(tUpdateSCNSubscription), - expectedQueryArgs: []driver.Value{4}, - expectedUpdateArgs: []driver.Value{"cray-hmnfd-69d99579c5-shpmk_3http://cray-hmnfd/hmi/v1/scn",json.RawMessage(`{"Subscriber":"cray-hmnfd-69d99579c5-shpmk_3","States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`),4}, - expectedDidPatch: true, - }, { - id: 0, - op: "remove", - sub: sm.SCNPatchSubscription{}, - dbColumns: []string{"", ""}, - dbRows: [][]driver.Value{ - []driver.Value{0, `{}`}, - }, - dbError: sql.ErrNoRows, - expectedQueryPrepare: regexp.QuoteMeta(tGetSCNSubscriptionUpdate), - expectedUpdatePrepare: regexp.QuoteMeta(tUpdateSCNSubscription), - expectedQueryArgs: []driver.Value{}, - expectedUpdateArgs: []driver.Value{"",json.RawMessage(`{}`),0}, - expectedDidPatch: false, + id: 4, + op: "add", + sub: sm.SCNPatchSubscription{ + Op: "add", + States: []string{"On", "Off"}, + }, + dbColumns: []string{"id", "subscription"}, + dbRows: [][]driver.Value{ + []driver.Value{4, `{"Subscriber":"cray-hmnfd-69d99579c5-shpmk_3","States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`}, + }, + dbError: nil, + expectedQueryPrepare: regexp.QuoteMeta(tGetSCNSubscriptionUpdate), + expectedUpdatePrepare: regexp.QuoteMeta(tUpdateSCNSubscription), + expectedQueryArgs: []driver.Value{4}, + expectedUpdateArgs: []driver.Value{"cray-hmnfd-69d99579c5-shpmk_3http://cray-hmnfd/hmi/v1/scn", json.RawMessage(`{"Subscriber":"cray-hmnfd-69d99579c5-shpmk_3","States":["Empty","Populated","Off","On","Standby","Halt","Ready"],"Url":"http://cray-hmnfd/hmi/v1/scn"}`), 4}, + expectedDidPatch: true, + }, { + id: 0, + op: "remove", + sub: sm.SCNPatchSubscription{}, + dbColumns: []string{"", ""}, + dbRows: [][]driver.Value{ + []driver.Value{0, `{}`}, + }, + dbError: sql.ErrNoRows, + expectedQueryPrepare: regexp.QuoteMeta(tGetSCNSubscriptionUpdate), + expectedUpdatePrepare: regexp.QuoteMeta(tUpdateSCNSubscription), + expectedQueryArgs: []driver.Value{}, + expectedUpdateArgs: []driver.Value{"", json.RawMessage(`{}`), 0}, + expectedDidPatch: false, }} for i, test := range tests { @@ -4025,23 +4026,23 @@ func TestPatchSCNSubscription(t *testing.T) { func TestDeleteSCNSubscription(t *testing.T) { tests := []struct { - id int64 - dbError error - expectedPrepare string - expectedArgs []driver.Value - expectedDidDelete bool + id int64 + dbError error + expectedPrepare string + expectedArgs []driver.Value + expectedDidDelete bool }{{ - id: 5, - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscription), - expectedArgs: []driver.Value{5}, - expectedDidDelete: true, - }, { - id: 0, - dbError: sql.ErrNoRows, - expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscription), - expectedArgs: []driver.Value{}, - expectedDidDelete: false, + id: 5, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscription), + expectedArgs: []driver.Value{5}, + expectedDidDelete: true, + }, { + id: 0, + dbError: sql.ErrNoRows, + expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscription), + expectedArgs: []driver.Value{}, + expectedDidDelete: false, }} for i, test := range tests { @@ -4076,25 +4077,25 @@ func TestDeleteSCNSubscription(t *testing.T) { func TestDeleteSCNSubscriptionsAll(t *testing.T) { tests := []struct { - dbError error - expectedPrepare string - expectedNumSubsDeleted int64 + dbError error + expectedPrepare string + expectedNumSubsDeleted int64 }{{ - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscriptionAll), - expectedNumSubsDeleted: 1, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscriptionAll), + expectedNumSubsDeleted: 1, }, { - dbError: nil, - expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscriptionAll), - expectedNumSubsDeleted: 5, + dbError: nil, + expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscriptionAll), + expectedNumSubsDeleted: 5, }, { - dbError: sql.ErrNoRows, - expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscriptionAll), - expectedNumSubsDeleted: 0, + dbError: sql.ErrNoRows, + expectedPrepare: regexp.QuoteMeta(tDeleteSCNSubscriptionAll), + expectedNumSubsDeleted: 0, }} for i, test := range tests { - ResetMockDB() + ResetMockDB() mockPG.ExpectBegin() if test.dbError != nil { mockPG.ExpectPrepare(test.expectedPrepare).ExpectExec().WillReturnError(test.dbError) @@ -5135,7 +5136,7 @@ func TestPgDeleteGroupMember(t *testing.T) { dgrp1Update, _, _ := sqq.Delete(compGroupMembersTable). Where("group_id = ?", uuid1). Where("component_id = ?", - base.NormalizeHMSCompID(dgrp1.Members.IDs[0])).ToSql() + xnametypes.NormalizeHMSCompID(dgrp1.Members.IDs[0])).ToSql() dgrp2Query, _, _ := sqq.Select(compGroupsColsSMGroup...). From(compGroupsTable). @@ -5145,7 +5146,7 @@ func TestPgDeleteGroupMember(t *testing.T) { dgrp2Update, _, _ := sqq.Delete(compGroupMembersTable). Where("group_id = ?", uuid2). Where("component_id = ?", - base.NormalizeHMSCompID(dgrp2.Members.IDs[0])).ToSql() + xnametypes.NormalizeHMSCompID(dgrp2.Members.IDs[0])).ToSql() dgrp3Query, _, _ := sqq.Select(compGroupsColsSMGroup...). From(compGroupsTable). @@ -5155,7 +5156,7 @@ func TestPgDeleteGroupMember(t *testing.T) { dgrp3Update, _, _ := sqq.Delete(compGroupMembersTable). Where("group_id = ?", uuid3). Where("component_id = ?", - base.NormalizeHMSCompID(dgrp3x.Members.IDs[0])).ToSql() + xnametypes.NormalizeHMSCompID(dgrp3x.Members.IDs[0])).ToSql() dgrp4Query, _, _ := sqq.Select(compGroupsColsSMGroup...). From(compGroupsTable). @@ -5165,7 +5166,7 @@ func TestPgDeleteGroupMember(t *testing.T) { dgrp4Update, _, _ := sqq.Delete(compGroupMembersTable). Where("group_id = ?", uuid4). Where("component_id = ?", - base.NormalizeHMSCompID(dgrp4x.Members.IDs[0])).ToSql() + xnametypes.NormalizeHMSCompID(dgrp4x.Members.IDs[0])).ToSql() tests := []struct { label string @@ -5885,7 +5886,7 @@ func TestPgDeletePartitionMember(t *testing.T) { dgrp5Update, _, _ := sqq.Delete(compGroupMembersTable). Where("group_id = ?", uuid5). Where("component_id = ?", - base.NormalizeHMSCompID(dgrp5p.Members.IDs[0])).ToSql() + xnametypes.NormalizeHMSCompID(dgrp5p.Members.IDs[0])).ToSql() dgrp6Query, _, _ := sqq.Select(compGroupsColsSMPart...). From(compGroupsTable). @@ -5895,7 +5896,7 @@ func TestPgDeletePartitionMember(t *testing.T) { dgrp6Update, _, _ := sqq.Delete(compGroupMembersTable). Where("group_id = ?", uuid6). Where("component_id = ?", - base.NormalizeHMSCompID(dgrp6p.Members.IDs[0])).ToSql() + xnametypes.NormalizeHMSCompID(dgrp6p.Members.IDs[0])).ToSql() tests := []struct { name string @@ -6399,7 +6400,7 @@ func TestPgInsertCompReservations(t *testing.T) { expectedGetCompIDsPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedGetCompIDsArgs: []driver.Value{"x3000c0s9b0n0"}, dbGetCompIDsReturnCols: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbGetCompIDsReturnRows: [][]driver.Value{ + dbGetCompIDsReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "Node", "Ready", "OK", true, "", "Compute", "", 42, "", "Sling", "X86", "Mountain", false, false}, }, dbInsertError: nil, @@ -6409,9 +6410,9 @@ func TestPgInsertCompReservations(t *testing.T) { dbInsertV2ResReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "x3000c0s9b0n0:dk:de1a20c2-efc9-41ad-b839-1e3cef197d17", "x3000c0s9b0n0:rk:cbff2077-952f-4536-a102-c442227fdc5d"}, }, - expectedSuccess: 1, - expectedFailure: 0, - expectErr: false, + expectedSuccess: 1, + expectedFailure: 0, + expectErr: false, }, { f: sm.CompLockV2Filter{ ID: []string{"x3000c0s9b0n0"}, @@ -6422,7 +6423,7 @@ func TestPgInsertCompReservations(t *testing.T) { expectedGetCompIDsPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedGetCompIDsArgs: []driver.Value{"x3000c0s9b0n0"}, dbGetCompIDsReturnCols: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbGetCompIDsReturnRows: [][]driver.Value{ + dbGetCompIDsReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "Node", "Ready", "OK", true, "", "Compute", "", 42, "", "Sling", "X86", "Mountain", false, true}, }, dbInsertError: nil, @@ -6442,7 +6443,7 @@ func TestPgInsertCompReservations(t *testing.T) { expectedGetCompIDsPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedGetCompIDsArgs: []driver.Value{"x3000c0s9b0n0"}, dbGetCompIDsReturnCols: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbGetCompIDsReturnRows: [][]driver.Value{ + dbGetCompIDsReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "Node", "Ready", "OK", true, "", "Compute", "", 42, "", "Sling", "X86", "Mountain", false, false}, }, dbInsertError: nil, @@ -6462,7 +6463,7 @@ func TestPgInsertCompReservations(t *testing.T) { expectedGetCompIDsPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedGetCompIDsArgs: []driver.Value{"x3000c0s9b0n0"}, dbGetCompIDsReturnCols: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbGetCompIDsReturnRows: [][]driver.Value{ + dbGetCompIDsReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "Node", "Ready", "OK", true, "", "Compute", "", 42, "", "Sling", "X86", "Mountain", true, false}, }, dbInsertError: nil, @@ -6573,14 +6574,14 @@ func TestPgDeleteCompReservationsForce(t *testing.T) { expectedGetCompIDsPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedGetCompIDsArgs: []driver.Value{"x3000c0s9b0n0"}, dbGetCompIDsReturnCols: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbGetCompIDsReturnRows: [][]driver.Value{ + dbGetCompIDsReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "Node", "Ready", "OK", true, "", "Compute", "", 42, "", "Sling", "X86", "Mountain", false, false}, }, dbDeleteError: nil, expectedDeletePrepare: regexp.QuoteMeta(resDeleteReservation), expectedDeleteArgs: []driver.Value{"x3000c0s9b0n0"}, dbDeleteReturnCols: []string{"component_id"}, - dbDeleteReturnRows: [][]driver.Value{ + dbDeleteReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0"}, }, expectedSuccess: 1, @@ -6595,7 +6596,7 @@ func TestPgDeleteCompReservationsForce(t *testing.T) { expectedGetCompIDsPrepare: regexp.QuoteMeta(tGetCompBaseQuery + " WHERE c.id IN ($1)"), expectedGetCompIDsArgs: []driver.Value{"x3000c0s9b0n0"}, dbGetCompIDsReturnCols: []string{"id", "type", "state", "flag", "enabled", "admin", "role", "subrole", "nid", "subtype", "nettype", "arch", "class", "reservation_disabled", "locked"}, - dbGetCompIDsReturnRows: [][]driver.Value{ + dbGetCompIDsReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0", "Node", "Ready", "OK", true, "", "Compute", "", 42, "", "Sling", "X86", "Mountain", false, false}, }, dbDeleteError: nil, @@ -6706,12 +6707,12 @@ func TestPgDeleteCompReservations(t *testing.T) { expectedDeletePrepare: regexp.QuoteMeta(resDeleteReservation), expectedDeleteArgs: []driver.Value{"x3000c0s9b0n0:rk:cbff2077-952f-4536-a102-c442227fdc5d"}, dbDeleteReturnCols: []string{"component_id"}, - dbDeleteReturnRows: [][]driver.Value{ + dbDeleteReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0"}, }, - expectedSuccess: 1, - expectedFailure: 0, - expectErr: false, + expectedSuccess: 1, + expectedFailure: 0, + expectErr: false, }, { f: sm.CompLockV2ReservationFilter{ ReservationKeys: []sm.CompLockV2Key{ @@ -6797,11 +6798,11 @@ func TestPgDeleteCompReservationsExpired(t *testing.T) { dbDeleteError: nil, expectedDeletePrepare: regexp.QuoteMeta(resDeleteReservation), dbDeleteReturnCols: []string{"component_id"}, - dbDeleteReturnRows: [][]driver.Value{ + dbDeleteReturnRows: [][]driver.Value{ []driver.Value{"x3000c0s9b0n0"}, }, - expectedSuccess: 1, - expectErr: false, + expectedSuccess: 1, + expectErr: false, }} for i, test := range tests { diff --git a/internal/hmsds/hmsds-tx-postgres.go b/internal/hmsds/hmsds-tx-postgres.go index ce2ec69..e883891 100644 --- a/internal/hmsds/hmsds-tx-postgres.go +++ b/internal/hmsds/hmsds-tx-postgres.go @@ -32,8 +32,9 @@ import ( "strings" "time" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" + "github.com/Cray-HPE/hms-xname/xnametypes" sq "github.com/Masterminds/squirrel" "github.com/google/uuid" @@ -519,18 +520,18 @@ func (t *hmsdbPgTx) getComponentByIDRawTx(id string, for_update bool) (*base.Com } // Perform corresponding query on DB comps, err := t.queryComponent(fname, FLTR_DEFAULT, query, - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) if err != nil { return nil, err } // Query succeeded. There should be at most 1 row returned... if len(comps) == 0 { t.Log(LOG_INFO, "Info: %s(%s) matched no comps.", - fname, base.NormalizeHMSCompID(id)) + fname, xnametypes.NormalizeHMSCompID(id)) return nil, nil } else if len(comps) > 1 { t.LogAlways("WARNING: %s(%s): multiple comps!.", - fname, base.NormalizeHMSCompID(id)) + fname, xnametypes.NormalizeHMSCompID(id)) } return comps[0], nil } @@ -667,7 +668,7 @@ func (t *hmsdbPgTx) InsertComponentTx(c *base.Component) (int64, error) { enabledFlg = *c.Enabled } // Normalize key - normID := base.NormalizeHMSCompID(c.ID) + normID := xnametypes.NormalizeHMSCompID(c.ID) // Perform insert result, err := stmt.ExecContext(t.ctx, @@ -705,32 +706,38 @@ func (t *hmsdbPgTx) InsertComponentTx(c *base.Component) (int64, error) { // // Example Query: // INSERT INTO components ( -// id, -// type, -// state, -// flag, -// enabled, -// admin, -// role, -// subrole, -// nid, -// subtype, -// nettype, -// arch, -// class, -// reservation_disabled, -// locked) +// +// id, +// type, +// state, +// flag, +// enabled, +// admin, +// role, +// subrole, +// nid, +// subtype, +// nettype, +// arch, +// class, +// reservation_disabled, +// locked) +// // VALUES -// ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15), -// ... -// ($#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#) +// +// ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15), +// ... +// ($#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#, $#) +// // ON CONFLICT(id) DO UPDATE SET -// state = EXCLUDED.state, -// flag = EXCLUDED.flag, -// subtype = EXCLUDED.subtype, -// nettype = EXCLUDED.nettype, -// arch = EXCLUDED.arch, -// class = EXCLUDED.class +// +// state = EXCLUDED.state, +// flag = EXCLUDED.flag, +// subtype = EXCLUDED.subtype, +// nettype = EXCLUDED.nettype, +// arch = EXCLUDED.arch, +// class = EXCLUDED.class +// // RETURNING *; func (t *hmsdbPgTx) InsertComponentsTx(comps []*base.Component) ([]string, error) { results := []string{} @@ -748,7 +755,7 @@ func (t *hmsdbPgTx) InsertComponentsTx(comps []*base.Component) ([]string, error for _, c := range comps { // Normalize key - normID := base.NormalizeHMSCompID(c.ID) + normID := xnametypes.NormalizeHMSCompID(c.ID) // Take out duplicates so that we don't get errors for modifying a row multiple times. if _, ok := valueMap[normID]; ok { continue @@ -795,7 +802,7 @@ func (t *hmsdbPgTx) InsertComponentsTx(comps []*base.Component) ([]string, error compSubTypeCol + " = EXCLUDED." + compSubTypeCol + ", " + compNetTypeCol + " = EXCLUDED." + compNetTypeCol + ", " + compArchCol + " = EXCLUDED." + compArchCol + ", " + - compClassCol + " = EXCLUDED." + compClassCol + + compClassCol + " = EXCLUDED." + compClassCol + " RETURNING " + compIdCol) query = query.PlaceholderFormat(sq.Dollar) @@ -829,7 +836,8 @@ func (t *hmsdbPgTx) InsertComponentsTx(comps []*base.Component) ([]string, error // // Returns the number of affected rows. < 0 means RowsAffected() is not // supported. -// Note: If flag is not set, it will be set to OK (i.e. no flag) +// +// Note: If flag is not set, it will be set to OK (i.e. no flag) func (t *hmsdbPgTx) UpdateCompStatesTx( ids []string, state, flag string, @@ -943,9 +951,9 @@ func (t *hmsdbPgTx) UpdateCompFlagOnlyTx(id string, flag string) (int64, error) return 0, err } // Normalize key - normID := base.NormalizeHMSCompID(id) + normID := xnametypes.NormalizeHMSCompID(id) - // Make update in database. + // Make update in dataxnametypes. result, err := stmt.ExecContext(t.ctx, &flag, &normID) @@ -1035,9 +1043,9 @@ func (t *hmsdbPgTx) UpdateCompEnabledTx(id string, enabled bool) (int64, error) return 0, err } // Normalize key - normID := base.NormalizeHMSCompID(id) + normID := xnametypes.NormalizeHMSCompID(id) - // Make update in database. + // Make update in dataxnametypes. result, err := stmt.ExecContext(t.ctx, &enabledFlg, &normID) @@ -1117,9 +1125,9 @@ func (t *hmsdbPgTx) UpdateCompSwStatusTx(id string, swStatus string) (int64, err return 0, err } // Normalize key - normID := base.NormalizeHMSCompID(id) + normID := xnametypes.NormalizeHMSCompID(id) - // Make update in database. + // Make update in dataxnametypes. result, err := stmt.ExecContext(t.ctx, &swStatus, &normID) @@ -1217,9 +1225,9 @@ func (t *hmsdbPgTx) UpdateCompRoleTx(id string, role, subRole string) (int64, er return 0, err } // Normalize key - normID := base.NormalizeHMSCompID(id) + normID := xnametypes.NormalizeHMSCompID(id) - // Make update in database. + // Make update in dataxnametypes. result, err := stmt.ExecContext(t.ctx, &role, &subRole, @@ -1367,9 +1375,9 @@ func (t *hmsdbPgTx) UpdateCompNIDTx(c *base.Component) error { return err } // Normalize key - normID := base.NormalizeHMSCompID(c.ID) + normID := xnametypes.NormalizeHMSCompID(c.ID) - // Make update in database. + // Make update in dataxnametypes. _, err = stmt.ExecContext(t.ctx, &rawNID, &normID) @@ -1398,7 +1406,7 @@ func (t *hmsdbPgTx) BulkUpdateCompNIDTx(comps []base.Component) error { nidFromCol := compTableSubAlias + "." + compNIDCol // Generate query // Make the column name a sq.Sqlizer so sq will set it as a column name and not a value. - query := sq.Update(compTable + " " + compTableJoinAlias). + query := sq.Update(compTable+" "+compTableJoinAlias). Set(compNIDCol, sq.Expr(nidFromCol)) // sq doesn't have a way to add a FROM statement to an UPDATE. @@ -1408,7 +1416,7 @@ func (t *hmsdbPgTx) BulkUpdateCompNIDTx(comps []base.Component) error { valStr := "" for i, c := range comps { // Normalize key - normID := base.NormalizeHMSCompID(c.ID) + normID := xnametypes.NormalizeHMSCompID(c.ID) // Take out duplicates so that we don't get errors for modifying a row multiple times. if _, ok := valueMap[normID]; ok { continue @@ -1471,7 +1479,7 @@ func (t *hmsdbPgTx) DeleteComponentByIDTx(id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id)) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id)) if err != nil { t.LogAlways("Error: DeleteComponentByIDTx(%s): stmt.Exec: %s", id, err) return false, err @@ -1558,18 +1566,18 @@ func (t *hmsdbPgTx) GetNodeMapByIDTx(id string) (*sm.NodeMap, error) { } // Perform corresponding query on DB nnms, err := t.queryNodeMap("GetNodeMapByIDTx", - getNodeMapByIDQuery, base.NormalizeHMSCompID(id)) + getNodeMapByIDQuery, xnametypes.NormalizeHMSCompID(id)) if err != nil { return nil, err } // Query succeeded. There should be at most 1 row returned... if len(nnms) == 0 { t.Log(LOG_INFO, "Info: GetNodeMapByIDTx(%s) matched 0.", - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) return nil, nil } else if len(nnms) > 1 { t.LogAlways("WARNING: GetNodeMapByIDTx(%s): matched >1!", - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) } return nnms[0], nil } @@ -1612,7 +1620,7 @@ func (t *hmsdbPgTx) InsertNodeMapTx(m *sm.NodeMap) error { return err } // Normalize key - normID := base.NormalizeHMSCompID(m.ID) + normID := xnametypes.NormalizeHMSCompID(m.ID) // Perform insert _, err = stmt.ExecContext(t.ctx, @@ -1649,10 +1657,10 @@ func (t *hmsdbPgTx) DeleteNodeMapByIDTx(id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id)) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id)) if err != nil { t.LogAlways("Error: DeleteNodeMapByIDTx(%s): stmt.Exec: %s", - base.NormalizeHMSCompID(id), err) + xnametypes.NormalizeHMSCompID(id), err) return false, err } @@ -1735,18 +1743,18 @@ func (t *hmsdbPgTx) GetPowerMapByIDTx(id string) (*sm.PowerMap, error) { } // Perform corresponding query on DB ms, err := t.queryPowerMap("GetPowerMapByIDTx", - getPowerMapByIDQuery, base.NormalizeHMSCompID(id)) + getPowerMapByIDQuery, xnametypes.NormalizeHMSCompID(id)) if err != nil { return nil, err } // Query succeeded. There should be at most 1 row returned... if len(ms) == 0 { t.Log(LOG_INFO, "Info: GetPowerMapByIDTx(%s) matched 0.", - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) return nil, nil } else if len(ms) > 1 { t.LogAlways("WARNING: GetPowerMapByIDTx(%s): matched >1!", - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) } return ms[0], nil } @@ -1780,11 +1788,11 @@ func (t *hmsdbPgTx) InsertPowerMapTx(m *sm.PowerMap) error { return err } // Normalize key - normID := base.NormalizeHMSCompID(m.ID) + normID := xnametypes.NormalizeHMSCompID(m.ID) normPwrIds := make([]string, 0, len(m.PoweredBy)) for _, pwrId := range m.PoweredBy { - normPwrIds = append(normPwrIds, base.NormalizeHMSCompID(pwrId)) + normPwrIds = append(normPwrIds, xnametypes.NormalizeHMSCompID(pwrId)) } // Perform insert @@ -1815,10 +1823,10 @@ func (t *hmsdbPgTx) DeletePowerMapByIDTx(id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id)) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id)) if err != nil { t.LogAlways("Error: DeletePowerMapByIDTx(%s): stmt.Exec: %s", - base.NormalizeHMSCompID(id), err) + xnametypes.NormalizeHMSCompID(id), err) return false, err } @@ -1927,18 +1935,18 @@ func (t *hmsdbPgTx) GetHWInvByLocIDTx(id string) (*sm.HWInvByLoc, error) { } // Perform corresponding query on DB hwlocs, err := t.queryHWInvByLoc("GetHWInvByLocIDTx", - getHWInvByLocWithFRUByIDQuery, base.NormalizeHMSCompID(id)) + getHWInvByLocWithFRUByIDQuery, xnametypes.NormalizeHMSCompID(id)) if err != nil { return nil, err } // Query succeeded. There should be at most 1 row returned... if len(hwlocs) == 0 { t.Log(LOG_INFO, "Info: GetHWInvByLocIDTx(%s) matched no entry.", - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) return nil, nil } else if len(hwlocs) > 1 { t.LogAlways("Warning: GetHWInvByLocIDTx(%s): multiple entries!.", - base.NormalizeHMSCompID(id)) + xnametypes.NormalizeHMSCompID(id)) } return hwlocs[0], nil } @@ -2000,7 +2008,7 @@ func (t *hmsdbPgTx) GetHWInvByFRUAllTx() ([]*sm.HWInvByFRU, error) { } // Insert or update HWInventoryByLocation struct (in transaction) -// If PopulatedFRU is present, only the FRUID is added to the database. If +// If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction). @@ -2029,7 +2037,7 @@ func (t *hmsdbPgTx) InsertHWInvByLocTx(hl *sm.HWInvByLoc) error { return err } // Normalize key - normID := base.NormalizeHMSCompID(hl.ID) + normID := xnametypes.NormalizeHMSCompID(hl.ID) // Get the parent node xname for use with partition queries. Components under nodes // (processors, memory, etc.) get the parent_node set to the node above them. For @@ -2037,8 +2045,8 @@ func (t *hmsdbPgTx) InsertHWInvByLocTx(hl *sm.HWInvByLoc) error { pnID := normID // Don't bother checking if the component isn't under a node if strings.Contains(pnID, "n") { - for base.GetHMSType(pnID) != base.Node { - pnID = base.GetHMSCompParent(pnID) + for xnametypes.GetHMSType(pnID) != xnametypes.Node { + pnID = xnametypes.GetHMSCompParent(pnID) // This is to catch components that are not under nodes // but have 'n' in the xname. if pnID == "" { @@ -2066,7 +2074,7 @@ func (t *hmsdbPgTx) InsertHWInvByLocTx(hl *sm.HWInvByLoc) error { } // Insert or update HWInventoryByLocation struct (in transaction) -// If PopulatedFRU is present, only the FRUID is added to the database. If +// If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction). @@ -2083,10 +2091,10 @@ func (t *hmsdbPgTx) BulkInsertHWInvByLocTx(hls []*sm.HWInvByLoc) error { // Generate query query := sq.Insert(hwInvLocTable). Columns(hwInvLocCols...) - + for _, hl := range hls { // Normalize key - normID := base.NormalizeHMSCompID(hl.ID) + normID := xnametypes.NormalizeHMSCompID(hl.ID) // Take out duplicates so that we don't get errors for modifying a row multiple times. if _, ok := valueMap[normID]; ok { @@ -2105,8 +2113,8 @@ func (t *hmsdbPgTx) BulkInsertHWInvByLocTx(hls []*sm.HWInvByLoc) error { fruId.Valid = true } } else { - fruId.Valid = false - } + fruId.Valid = false + } infoJSON, err := hl.EncodeLocationInfo() if err != nil { t.LogAlways("Error: BulkInsertHWInvByLocTx(): EncodeLocationInfo: %s", err) @@ -2119,8 +2127,8 @@ func (t *hmsdbPgTx) BulkInsertHWInvByLocTx(hls []*sm.HWInvByLoc) error { pnID := normID // Don't bother checking if the component isn't under a node if strings.Contains(pnID, "n") { - for base.GetHMSType(pnID) != base.Node { - pnID = base.GetHMSCompParent(pnID) + for xnametypes.GetHMSType(pnID) != xnametypes.Node { + pnID = xnametypes.GetHMSCompParent(pnID) // This is to catch components that are not under nodes // but have 'n' in the xname. if pnID == "" { @@ -2205,7 +2213,7 @@ func (t *hmsdbPgTx) BulkInsertHWInvByFRUTx(hfs []*sm.HWInvByFRU) error { // Generate query query := sq.Insert(hwInvFruTable). Columns(hwInvFruTblCols...) - + for _, hf := range hfs { // Take out duplicates so that we don't get errors for modifying a row multiple times. if _, ok := valueMap[hf.FRUID]; ok { @@ -2260,14 +2268,14 @@ func (t *hmsdbPgTx) DeleteHWInvByLocIDTx(id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id)) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id)) if err != nil { t.LogAlways("Error: DeleteHWInvByLocIDTx(%s): stmt.Exec: %s", - base.NormalizeHMSCompID(id), err) + xnametypes.NormalizeHMSCompID(id), err) return false, err } t.Log(LOG_INFO, "Info: DeleteHWInvByLocIDTx(%s) - %s", - base.NormalizeHMSCompID(id), res) + xnametypes.NormalizeHMSCompID(id), res) // Return true if there was a row affected, false if there were zero. num, err := res.RowsAffected() @@ -2497,7 +2505,7 @@ func (t *hmsdbPgTx) GetHWInvHistLastEventsTx(ids []string) ([]*sm.HWInvHist, err if len(ids) > 0 { query = query.Where(sq.Eq{hwInvHistIdColAlias: ids}) } - + query = query.OrderBy("" + hwInvHistIdColAlias + ", " + hwInvHistTimestampColAlias + " DESC") // Execute @@ -2543,7 +2551,7 @@ func (t *hmsdbPgTx) InsertHWInvHistTx(hh *sm.HWInvHist) error { if eventType == "" { return ErrHMSDSArgBadHWInvHistEventType } - loc := base.VerifyNormalizeCompID(hh.ID) + loc := xnametypes.VerifyNormalizeCompID(hh.ID) if loc == "" { return ErrHMSDSArgBadID } @@ -2582,7 +2590,7 @@ func (t *hmsdbPgTx) InsertHWInvHistsTx(hhs []*sm.HWInvHist) error { if eventType == "" { return ErrHMSDSArgBadHWInvHistEventType } - loc := base.VerifyNormalizeCompID(hh.ID) + loc := xnametypes.VerifyNormalizeCompID(hh.ID) if loc == "" { return ErrHMSDSArgBadID } @@ -2655,7 +2663,7 @@ func (t *hmsdbPgTx) GetRFEndpointByIDTx(id string) (*sm.RedfishEndpoint, error) } // Perform corresponding query on DB eps, err := t.queryRedfishEndpoint("GetRFEndpointByIDTx", - getRFEndpointByIDQuery, base.NormalizeHMSCompID(id)) + getRFEndpointByIDQuery, xnametypes.NormalizeHMSCompID(id)) if err != nil { return nil, err } @@ -2716,7 +2724,7 @@ func (t *hmsdbPgTx) GetRFEndpointsFilterTx(f *RedfishEPFilter) ([]*sm.RedfishEnd return reps, nil } -// Insert new RedfishEndpoint into database. Does not insert any +// Insert new RedfishEndpoint into dataxnametypes. Does not insert any // ComponentEndpoint children.(In transaction.) // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -2740,7 +2748,7 @@ func (t *hmsdbPgTx) InsertRFEndpointTx(ep *sm.RedfishEndpoint) error { t.LogAlways(" InsertRFEndpointTx: decode DiscoveryInfo: %s", err) } // Ensure endpoint name is normalized and valid - normID := base.VerifyNormalizeCompID(ep.ID) + normID := xnametypes.VerifyNormalizeCompID(ep.ID) if normID == "" { t.LogAlways("InsertRFEndpointTx(%s): %s", ep.ID, ErrHMSDSArgBadID) return ErrHMSDSArgBadID @@ -2778,7 +2786,7 @@ func (t *hmsdbPgTx) InsertRFEndpointTx(ep *sm.RedfishEndpoint) error { return nil } -// Insert new RedfishEndpoints into database. Does not insert any +// Insert new RedfishEndpoints into dataxnametypes. Does not insert any // ComponentEndpoint children.(In transaction.) // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -2794,10 +2802,10 @@ func (t *hmsdbPgTx) InsertRFEndpointsTx(eps []*sm.RedfishEndpoint) error { // Generate query query := sq.Insert(rfEPsTable). Columns(rfEPsAllCols...) - + for _, ep := range eps { // Ensure endpoint name is normalized and valid - normID := base.VerifyNormalizeCompID(ep.ID) + normID := xnametypes.VerifyNormalizeCompID(ep.ID) // Take out duplicates so that we don't get errors for modifying a row multiple times. if _, ok := valueMap[normID]; ok { continue @@ -2875,7 +2883,7 @@ func (t *hmsdbPgTx) UpdateRFEndpointTx(ep *sm.RedfishEndpoint) (bool, error) { t.LogAlways("UpdateRFEndpointTx: decode DiscoveryInfo: %s", err) } // Normalized key - normID := base.NormalizeHMSCompID(ep.ID) + normID := xnametypes.NormalizeHMSCompID(ep.ID) // Perform update res, err := stmt.ExecContext(t.ctx, @@ -2929,7 +2937,7 @@ func (t *hmsdbPgTx) UpdateRFEndpointsTx(eps []*sm.RedfishEndpoint) ([]*sm.Redfis // Generate query // Make the column name a sq.Sqlizer so sq will set it as a column name and not a value. - query := sq.Update(rfEPsTable + " r"). + query := sq.Update(rfEPsTable+" r"). Set(rfEPsTypeCol, sq.Expr(rfEPsTypeColAlias)). Set(rfEPsNameCol, sq.Expr(rfEPsNameColAlias)). Set(rfEPsHostnameCol, sq.Expr(rfEPsHostnameColAlias)). @@ -2954,7 +2962,7 @@ func (t *hmsdbPgTx) UpdateRFEndpointsTx(eps []*sm.RedfishEndpoint) ([]*sm.Redfis valStr := "" for i, ep := range eps { // Normalized key - normID := base.NormalizeHMSCompID(ep.ID) + normID := xnametypes.NormalizeHMSCompID(ep.ID) // Take out duplicates so that we don't get errors for modifying a row multiple times. if _, ok := valueMap[normID]; ok { continue @@ -3039,7 +3047,7 @@ func (t *hmsdbPgTx) UpdateRFEndpointNoDiscInfoTx(ep *sm.RedfishEndpoint) (bool, return false, err } // Normalize key - normID := base.NormalizeHMSCompID(ep.ID) + normID := xnametypes.NormalizeHMSCompID(ep.ID) // Perform update res, err := stmt.ExecContext(t.ctx, @@ -3094,7 +3102,7 @@ func (t *hmsdbPgTx) DeleteRFEndpointByIDTx(id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id)) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id)) if err != nil { t.LogAlways("Error: DeleteRFEndpointByIDTx(%s): stmt.Exec: %s", id, err) return false, err @@ -3349,7 +3357,7 @@ func (t *hmsdbPgTx) UpsertCompEndpointTx(cep *sm.ComponentEndpoint) error { t.LogAlways("UpsertCompEndpointTx: decode CompInfo: %s", err) } // Ensure endpoint name is normalized and valid - normID := base.VerifyNormalizeCompID(cep.ID) + normID := xnametypes.VerifyNormalizeCompID(cep.ID) if normID == "" { t.LogAlways("UpsertCompEndpointTx(%s): %s", normID, ErrHMSDSArgBadID) return ErrHMSDSArgBadID @@ -3392,10 +3400,10 @@ func (t *hmsdbPgTx) UpsertCompEndpointsTx(ceps *sm.ComponentEndpointArray) error // Generate query query := sq.Insert(compEPsTable). Columns(compEPsAllCols...) - + for _, cep := range ceps.ComponentEndpoints { // Ensure endpoint name is normalized and valid - normID := base.VerifyNormalizeCompID(cep.ID) + normID := xnametypes.VerifyNormalizeCompID(cep.ID) if normID == "" { t.LogAlways("UpsertCompEndpointTx(%s): %s", normID, ErrHMSDSArgBadID) return ErrHMSDSArgBadID @@ -3449,7 +3457,6 @@ func (t *hmsdbPgTx) UpsertCompEndpointsTx(ceps *sm.ComponentEndpointArray) error return nil } - // Delete ComponentEndpoint with matching xname id from database, if it // exists (in transaction) // Return true if there was a row affected, false if there were zero. @@ -3467,14 +3474,14 @@ func (t *hmsdbPgTx) DeleteCompEndpointByIDTx(id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id)) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id)) if err != nil { t.LogAlways("Error: DeleteCompEndpointByIDTx(%s): stmt.Exec: %s", - base.NormalizeHMSCompID(id), err) + xnametypes.NormalizeHMSCompID(id), err) return false, err } t.Log(LOG_INFO, "Info: DeleteCompEndpointByIDTx(%s) - %s", - base.NormalizeHMSCompID(id), res) + xnametypes.NormalizeHMSCompID(id), res) // Return true if there was a row affected, false if there were zero. num, err := res.RowsAffected() @@ -3531,7 +3538,7 @@ func (t *hmsdbPgTx) SetChildCompStatesCompEndpointsTx( return []string{}, nil } // Should return the same set of xname IDs as 'ids', assuming they are - // actually in the database. Also locks both ComponentEP/RedfishEP tables + // actually in the dataxnametypes. Also locks both ComponentEP/RedfishEP tables // if wrLock is true, which is the main thing. cids, err := t.GetCompEndpointIDsTx(CE_IDs(ids), CE_WRLock) if err != nil || len(cids) == 0 { @@ -3688,7 +3695,7 @@ func (t *hmsdbPgTx) UpsertServiceEndpointTx(sep *sm.ServiceEndpoint) error { return err } // Normalize key - normRFID := base.NormalizeHMSCompID(sep.RfEndpointID) + normRFID := xnametypes.NormalizeHMSCompID(sep.RfEndpointID) // Perform insert res, err := stmt.ExecContext(t.ctx, @@ -3724,14 +3731,14 @@ func (t *hmsdbPgTx) UpsertServiceEndpointsTx(seps *sm.ServiceEndpointArray) erro // Generate query query := sq.Insert(serviceEPsTable). Columns(serviceEPsCols...) - + for _, sep := range seps.ServiceEndpoints { if sep == nil { t.LogAlways("Error: UpsertServiceEndpointsTx(): Service Endpoint was nil.") return ErrHMSDSArgNil } // Normalize key - normRFID := base.NormalizeHMSCompID(sep.RfEndpointID) + normRFID := xnametypes.NormalizeHMSCompID(sep.RfEndpointID) // Take out duplicates so that we don't get errors for modifying a row multiple times. key := normRFID + sep.RedfishType if _, ok := valueMap[key]; ok { @@ -3748,7 +3755,7 @@ func (t *hmsdbPgTx) UpsertServiceEndpointsTx(seps *sm.ServiceEndpointArray) erro sep.OdataID, sep.ServiceInfo) } - query = query.Suffix("ON CONFLICT(" + serviceEPsRFEndpointIDCol + ", "+ serviceEPsRedfishTypeCol + ") DO UPDATE SET " + + query = query.Suffix("ON CONFLICT(" + serviceEPsRFEndpointIDCol + ", " + serviceEPsRedfishTypeCol + ") DO UPDATE SET " + serviceEPsRedfishSubtypeCol + " = EXCLUDED." + serviceEPsRedfishSubtypeCol + ", " + serviceEPsUUIDCol + " = EXCLUDED." + serviceEPsUUIDCol + ", " + serviceEPsODataIDCol + " = EXCLUDED." + serviceEPsODataIDCol + ", " + @@ -3787,7 +3794,7 @@ func (t *hmsdbPgTx) DeleteServiceEndpointByIDTx(svc, id string) (bool, error) { if err != nil { return false, err } - res, err := stmt.ExecContext(t.ctx, base.NormalizeHMSCompID(id), svc) + res, err := stmt.ExecContext(t.ctx, xnametypes.NormalizeHMSCompID(id), svc) if err != nil { t.LogAlways("Error: DeleteServiceEndpointByIDTx(%s,%s): stmt.Exec: %s", svc, id, err) @@ -3892,13 +3899,13 @@ func (t *hmsdbPgTx) InsertCompEthInterfaceTx(cei *sm.CompEthInterfaceV2) error { return ErrHMSDSArgBadArg } if cei.CompID != "" { - cei.CompID = base.VerifyNormalizeCompID(cei.CompID) + cei.CompID = xnametypes.VerifyNormalizeCompID(cei.CompID) if cei.CompID == "" { return ErrHMSDSArgBadID } } if cei.Type != "" { - cei.Type = base.VerifyNormalizeType(cei.Type) + cei.Type = xnametypes.VerifyNormalizeType(cei.Type) if cei.Type == "" { return ErrHMSDSArgBadType } @@ -3938,7 +3945,7 @@ func (t *hmsdbPgTx) InsertCompEthInterfacesTx(ceis []*sm.CompEthInterfaceV2) err // Generate query query := sq.Insert(compEthTable). Columns(compEthCols...) - + for _, cei := range ceis { cei.MACAddr = strings.ToLower(cei.MACAddr) cei.ID = strings.ReplaceAll(cei.MACAddr, ":", "") @@ -3952,13 +3959,13 @@ func (t *hmsdbPgTx) InsertCompEthInterfacesTx(ceis []*sm.CompEthInterfaceV2) err valueMap[cei.ID] = true } if cei.CompID != "" { - cei.CompID = base.VerifyNormalizeCompID(cei.CompID) + cei.CompID = xnametypes.VerifyNormalizeCompID(cei.CompID) if cei.CompID == "" { return ErrHMSDSArgBadID } } if cei.Type != "" { - cei.Type = base.VerifyNormalizeType(cei.Type) + cei.Type = xnametypes.VerifyNormalizeType(cei.Type) if cei.Type == "" { return ErrHMSDSArgBadType } @@ -4007,13 +4014,13 @@ func (t *hmsdbPgTx) InsertCompEthInterfaceCompInfoTx(cei *sm.CompEthInterfaceV2) return ErrHMSDSArgBadArg } if cei.CompID != "" { - cei.CompID = base.VerifyNormalizeCompID(cei.CompID) + cei.CompID = xnametypes.VerifyNormalizeCompID(cei.CompID) if cei.CompID == "" { return ErrHMSDSArgBadID } } if cei.Type != "" { - cei.Type = base.VerifyNormalizeType(cei.Type) + cei.Type = xnametypes.VerifyNormalizeType(cei.Type) if cei.Type == "" { return ErrHMSDSArgBadType } @@ -4056,7 +4063,7 @@ func (t *hmsdbPgTx) InsertCompEthInterfacesCompInfoTx(ceis []*sm.CompEthInterfac // Generate query query := sq.Insert(compEthTable). Columns(compEthCols...) - + for _, cei := range ceis { cei.MACAddr = strings.ToLower(cei.MACAddr) cei.ID = strings.ReplaceAll(cei.MACAddr, ":", "") @@ -4070,13 +4077,13 @@ func (t *hmsdbPgTx) InsertCompEthInterfacesCompInfoTx(ceis []*sm.CompEthInterfac valueMap[cei.ID] = true } if cei.CompID != "" { - cei.CompID = base.VerifyNormalizeCompID(cei.CompID) + cei.CompID = xnametypes.VerifyNormalizeCompID(cei.CompID) if cei.CompID == "" { return ErrHMSDSArgBadID } } if cei.Type != "" { - cei.Type = base.VerifyNormalizeType(cei.Type) + cei.Type = xnametypes.VerifyNormalizeType(cei.Type) if cei.Type == "" { return ErrHMSDSArgBadType } @@ -4147,12 +4154,12 @@ func (t *hmsdbPgTx) UpdateCompEthInterfaceTx(cei *sm.CompEthInterfaceV2, ceip *s } if ceip.CompID != nil { - compNorm := base.VerifyNormalizeCompID(*ceip.CompID) + compNorm := xnametypes.VerifyNormalizeCompID(*ceip.CompID) if compNorm == "" { return false, ErrHMSDSArgBadID } update = update.Set(compEthCompIDCol, compNorm) - ctype := base.GetHMSTypeString(compNorm) + ctype := xnametypes.GetHMSTypeString(compNorm) update = update.Set(compEthTypeCol, ctype) doUpdate = true } @@ -5127,7 +5134,7 @@ func (t *hmsdbPgTx) DeleteMemberTx(uuid, id string) (bool, error) { // Build query - works like AND query := sq.Delete(compGroupMembersTable). Where("group_id = ?", uuid). - Where("component_id = ?", base.NormalizeHMSCompID(id)) + Where("component_id = ?", xnametypes.NormalizeHMSCompID(id)) // Execute - Should delete one row. query = query.PlaceholderFormat(sq.Dollar) @@ -5156,7 +5163,7 @@ func (t *hmsdbPgTx) DeleteMemberTx(uuid, id string) (bool, error) { // //////////////////////////////////////////////////////////////////////////// -// Insert component reservations into the database. +// Insert component reservations into the dataxnametypes. // To Insert reservations without a duration, the component must be locked. // To Insert reservations with a duration, the component must be unlocked. func (t *hmsdbPgTx) InsertCompReservationsTx(ids []string, duration int) ([]sm.CompLockV2Success, string, error) { diff --git a/internal/hmsds/query-postgres.go b/internal/hmsds/query-postgres.go index 7250e49..ad6e24c 100644 --- a/internal/hmsds/query-postgres.go +++ b/internal/hmsds/query-postgres.go @@ -29,7 +29,7 @@ import ( "strconv" "strings" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-smd/v2/pkg/sm" "github.com/lib/pq" @@ -154,9 +154,7 @@ ON CONFLICT(fru_id) DO UPDATE SET subtype = EXCLUDED.subtype, fru_info = EXCLUDED.fru_info;` -// // RedfishEndpoints - Update operations -// const updatePgRFEndpointPrefix = ` UPDATE rf_endpoints SET "type" = ?, @@ -316,9 +314,7 @@ ON CONFLICT(id) DO UPDATE SET const getPgSCNSubID = ` SELECT LASTVAL();` -// // Groups and partitions -// const compGroupsTablePg = pgSchema + "." + compGroupsTable const compGroupMembersTablePg = pgSchema + "." + compGroupMembersTable diff --git a/internal/hmsds/query-shared-sq.go b/internal/hmsds/query-shared-sq.go index f3c5ffc..95c039d 100644 --- a/internal/hmsds/query-shared-sq.go +++ b/internal/hmsds/query-shared-sq.go @@ -30,7 +30,7 @@ import ( "database/sql" "strings" - base "github.com/Cray-HPE/hms-base" + "github.com/Cray-HPE/hms-xname/xnametypes" sq "github.com/Masterminds/squirrel" ) @@ -102,7 +102,7 @@ var compGroupPartCols = []string{ // Queries for various Components column filter options // -// FLTR_DEFAULT +// FLTR_DEFAULT var compColsDefault = []string{ compIdCol, compTypeCol, @@ -121,7 +121,7 @@ var compColsDefault = []string{ compLockedCol, } -// FLTR_STATEONLY +// FLTR_STATEONLY var compColsStateOnly = []string{ compIdCol, compTypeCol, @@ -129,14 +129,14 @@ var compColsStateOnly = []string{ compFlagCol, } -// FLTR_FLAGONLY +// FLTR_FLAGONLY var compColsFlagOnly = []string{ compIdCol, compTypeCol, compFlagCol, } -// FLTR_ROLEONLY +// FLTR_ROLEONLY var compColsRoleOnly = []string{ compIdCol, compTypeCol, @@ -144,14 +144,14 @@ var compColsRoleOnly = []string{ compSubRoleCol, } -// FLTR_NIDONLY +// FLTR_NIDONLY var compColsNIDOnly = []string{ compIdCol, compTypeCol, compNIDCol, } -// FLTR_ID_ONLY +// FLTR_ID_ONLY var compColsIdOnly = []string{ compIdCol, } @@ -159,11 +159,11 @@ var compColsIdOnly = []string{ // These two combine group-related columns in addition to the standard // Component ones. -// FLTR_ALL_W_GROUP +// FLTR_ALL_W_GROUP var compColsAllWithGroup1 []string = compColsDefault var compColsAllWithGroup2 []string = compGroupPartCols -// FLTR_ID_W_GROUP +// FLTR_ID_W_GROUP var compColsIdWithGroup1 []string = compColsIdOnly var compColsIdWithGroup2 []string = compGroupPartCols @@ -280,20 +280,20 @@ const compResTable = `reservations` const compResAlias = `cr` // used during joins, i.e. cr.component.id const ( - compResCompIdCol = `component_id` - compResCreatedCol = `create_timestamp` - compResExpireCol = `expiration_timestamp` - compResDKCol = `deputy_key` - compResRKCol = `reservation_key` + compResCompIdCol = `component_id` + compResCreatedCol = `create_timestamp` + compResExpireCol = `expiration_timestamp` + compResDKCol = `deputy_key` + compResRKCol = `reservation_key` ) // This adds the base table alias to each column. it can later be appended to. const ( - compResCompIdColAlias = compResAlias + "." + compResCompIdCol - compResCreatedColAlias = compResAlias + "." + compResCreatedCol - compResExpireColAlias = compResAlias + "." + compResExpireCol - compResDKColAlias = compResAlias + "." + compResDKCol - compResRKColAlias = compResAlias + "." + compResRKCol + compResCompIdColAlias = compResAlias + "." + compResCompIdCol + compResCreatedColAlias = compResAlias + "." + compResCreatedCol + compResExpireColAlias = compResAlias + "." + compResExpireCol + compResDKColAlias = compResAlias + "." + compResDKCol + compResRKColAlias = compResAlias + "." + compResRKCol ) // reservations table columns. @@ -913,7 +913,7 @@ func selectComponentsHierarchy( // Build a regex for the id. // TODO: Explore the performance implications of making all // the ids one big regex instead of a regex per id. - arg := base.NormalizeHMSCompID(ids[i]) + "([[:alpha:]][[:alnum:]]*)?" + arg := xnametypes.NormalizeHMSCompID(ids[i]) + "([[:alpha:]][[:alnum:]]*)?" args = append(args, arg) } query = query.Where(sq.Expr(filterQuery, args...)) @@ -922,7 +922,7 @@ func selectComponentsHierarchy( // specified literally, (e.g. no component expansion). // No need to use REGEXP. for i := 0; i < len(ids); i++ { - args = append(args, base.NormalizeHMSCompID(ids[i])) + args = append(args, xnametypes.NormalizeHMSCompID(ids[i])) } query = query.Where(sq.Eq{idCol: args}) } @@ -932,7 +932,7 @@ func selectComponentsHierarchy( // Create a select builder based on fieldfilter and the component filter. // If needed, join with group/partition table for additional fields/filtering. -// returns squirrel.SelectBuilder for building onto or sending to database. +// returns squirrel.SelectBuilder for building onto or sending to dataxnametypes. func makeComponentQuery(alias string, f *ComponentFilter, fltr FieldFilter) ( sq.SelectBuilder, error, ) { @@ -1293,7 +1293,7 @@ func getHWInvByLocQuery(f_opts ...HWInvLocFiltFunc) (sq.SelectBuilder, error) { if f.Parents { childId := id for { - childId = base.GetHMSCompParent(childId) + childId = xnametypes.GetHMSCompParent(childId) if len(childId) > 0 { // Put it in a map to ensure uniqueness parentIDs[childId] = true @@ -1311,7 +1311,7 @@ func getHWInvByLocQuery(f_opts ...HWInvLocFiltFunc) (sq.SelectBuilder, error) { filterQuery += "(" + idCol + " SIMILAR TO ?)" } // Build a regex for the id. - arg := base.NormalizeHMSCompID(id) + "([[:alpha:]][[:alnum:]]*)?" + arg := xnametypes.NormalizeHMSCompID(id) + "([[:alpha:]][[:alnum:]]*)?" args = append(args, arg) } } else { @@ -1323,7 +1323,7 @@ func getHWInvByLocQuery(f_opts ...HWInvLocFiltFunc) (sq.SelectBuilder, error) { if f.Parents { childId := id for { - childId = base.GetHMSCompParent(childId) + childId = xnametypes.GetHMSCompParent(childId) if len(childId) > 0 { // Put it in a map to ensure uniqueness parentIDs[childId] = true @@ -1340,7 +1340,7 @@ func getHWInvByLocQuery(f_opts ...HWInvLocFiltFunc) (sq.SelectBuilder, error) { } parentIDs = make(map[string]bool) } - args = append(args, base.NormalizeHMSCompID(id)) + args = append(args, xnametypes.NormalizeHMSCompID(id)) } filterQuery, args, _ = sq.Eq{idCol: args}.ToSql() } @@ -1350,7 +1350,7 @@ func getHWInvByLocQuery(f_opts ...HWInvLocFiltFunc) (sq.SelectBuilder, error) { if len(f.Type) > 0 && !(f.Parents && f.Children) { targs := []string{} for _, t := range f.Type { - normType := base.VerifyNormalizeType(t) + normType := xnametypes.VerifyNormalizeType(t) if normType == "" { return query, ErrHMSDSArgBadType } diff --git a/internal/hmsds/query-shared.go b/internal/hmsds/query-shared.go index 8863f16..0d0865b 100644 --- a/internal/hmsds/query-shared.go +++ b/internal/hmsds/query-shared.go @@ -24,9 +24,11 @@ package hmsds import ( "fmt" - base "github.com/Cray-HPE/hms-base" - "github.com/Cray-HPE/hms-smd/v2/pkg/sm" "strings" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-smd/v2/pkg/sm" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // Matches generic query sources in external API, but with real table names, @@ -249,9 +251,8 @@ DELETE FROM components ` const deleteComponentByIDQuery = deleteComponentPrefix + suffixByID const deleteComponentsAllQuery = deleteComponentPrefix + ";" -//getCompIDPrefix +// getCompIDPrefix // Node xname->NID mapping -// const getNodeMapPrefix = ` SELECT id, @@ -282,7 +283,6 @@ const deleteNodeMapByIDQuery = deleteNodeMapPrefix + suffixByID const deleteNodeMapsAllQuery = deleteNodeMapPrefix + ";" // Power mapping -// const getPowerMapPrefix = ` SELECT id, @@ -568,7 +568,7 @@ func buildCompEPQuery(baseQuery string, f *CompEPFilter) (string, []interface{}, if err != nil { return baseQuery, q.args, ErrHMSDSArgBadRedfishType } - err = q.doQueryArg("type", f.Type, base.VerifyNormalizeType) + err = q.doQueryArg("type", f.Type, xnametypes.VerifyNormalizeType) if err != nil { return baseQuery, q.args, ErrHMSDSArgBadType } @@ -595,7 +595,7 @@ func buildRedfishEPQuery(baseQuery string, f *RedfishEPFilter) (string, []interf if err := q.doQueryArg("uuid", f.UUID, nil); err != nil { return baseQuery, q.args, ErrHMSDSArgBadArg } - err := q.doQueryArg("type", f.Type, base.VerifyNormalizeType) + err := q.doQueryArg("type", f.Type, xnametypes.VerifyNormalizeType) if err != nil { return baseQuery, q.args, ErrHMSDSArgBadType } @@ -672,7 +672,7 @@ func (q *preparedQuery) setCompUpdateArgs(f *ComponentFilter) error { if q == nil { return ErrHMSDSArgNil } - err := q.doUpdateArg("type", f.Type, nil, base.VerifyNormalizeType, false) + err := q.doUpdateArg("type", f.Type, nil, xnametypes.VerifyNormalizeType, false) if err != nil { return ErrHMSDSArgBadType } @@ -739,7 +739,7 @@ func (q *preparedQuery) setCompWhereQuery(f *ComponentFilter, cont bool) error { if err != nil { return ErrHMSDSArgBadID } - err = q.doQueryArg("type", f.Type, base.VerifyNormalizeType) + err = q.doQueryArg("type", f.Type, xnametypes.VerifyNormalizeType) if err != nil { return ErrHMSDSArgBadType } @@ -890,7 +890,7 @@ func buildBulkCompUpdateQuery(baseQuery string, ids []string) (string, []interfa } else { filterQuery += " WHERE (id = ?" } - args = append(args, base.NormalizeHMSCompID(ids[i])) + args = append(args, xnametypes.NormalizeHMSCompID(ids[i])) } filterQuery += ");" return filterQuery, args, nil @@ -1301,7 +1301,7 @@ func nidStrTransform(checkStr string) string { // If xname is valid, returns normalized xname, otherwise returns empty // string. func validXNameFilter(xname string) string { - return base.VerifyNormalizeCompID(xname) + return xnametypes.VerifyNormalizeCompID(xname) } // If group or partion name is valid, return it normalized, else return diff --git a/internal/slsapi/slsapi.go b/internal/slsapi/slsapi.go index 160f8bd..ddb428f 100644 --- a/internal/slsapi/slsapi.go +++ b/internal/slsapi/slsapi.go @@ -26,13 +26,15 @@ import ( "crypto/tls" "encoding/json" "fmt" - "github.com/hashicorp/go-retryablehttp" - "github.com/sirupsen/logrus" "io/ioutil" "net/http" "net/url" - base "github.com/Cray-HPE/hms-base" "time" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" + "github.com/hashicorp/go-retryablehttp" + "github.com/sirupsen/logrus" ) const DefaultSlsUrl string = "http://cray-sls/" @@ -49,13 +51,13 @@ type slsReady struct { } type NodeHardware struct { - Parent string `json:"Parent"` - Children []string `json:"Children"` - Xname string `json:"Xname"` - Type string `json:"Type"` - Class string `json:"Class"` - TypeString base.HMSType `json:"TypeString"` - ExtraProperties ComptypeNode `json:"ExtraProperties"` + Parent string `json:"Parent"` + Children []string `json:"Children"` + Xname string `json:"Xname"` + Type string `json:"Type"` + Class string `json:"Class"` + TypeString xnametypes.HMSType `json:"TypeString"` + ExtraProperties ComptypeNode `json:"ExtraProperties"` } type ComptypeNode struct { @@ -165,10 +167,10 @@ func (sls *SLS) GetNodeInfo(id string) (NodeInfo, error) { // Grab the fields we care about nodeInfo := NodeInfo{ - NID: nh.ExtraProperties.NID, - Role: nh.ExtraProperties.Role, + NID: nh.ExtraProperties.NID, + Role: nh.ExtraProperties.Role, SubRole: nh.ExtraProperties.SubRole, - Class: nh.Class, + Class: nh.Class, } return nodeInfo, nil diff --git a/internal/slsapi/slsapi_test.go b/internal/slsapi/slsapi_test.go index 4aec690..1dccc03 100644 --- a/internal/slsapi/slsapi_test.go +++ b/internal/slsapi/slsapi_test.go @@ -28,13 +28,13 @@ package slsapi import ( "bytes" - "github.com/hashicorp/go-retryablehttp" "io/ioutil" "net/http" "net/url" "os" "testing" - "github.com/Cray-HPE/hms-base" + + "github.com/hashicorp/go-retryablehttp" ) var client *retryablehttp.Client @@ -109,7 +109,7 @@ func TestIsReady(t *testing.T) { for i, test := range tests { sls := SLS{ - Url: test.SLSUrl, + Url: test.SLSUrl, Client: test.Client, } out, err := sls.IsReady() @@ -138,30 +138,30 @@ func TestGetNodeInfo(t *testing.T) { expectedInfo ComptypeNode expectErr bool }{{ - SLSUrl: defaultUrl, - Client: client, - id: "x0c0s0b0n0", + SLSUrl: defaultUrl, + Client: client, + id: "x0c0s0b0n0", expectedInfo: ComptypeNode{ NID: 1, Role: "Application", }, - expectErr: false, + expectErr: false, }, { - SLSUrl: defaultUrl, - Client: client, - id: "x0c0s1b0n0", + SLSUrl: defaultUrl, + Client: client, + id: "x0c0s1b0n0", expectedInfo: ComptypeNode{ Role: "Application", }, - expectErr: false, + expectErr: false, }, { - SLSUrl: defaultUrl, - Client: client, - id: "x0c0s2b0n0", + SLSUrl: defaultUrl, + Client: client, + id: "x0c0s2b0n0", expectedInfo: ComptypeNode{ - NID: 1, + NID: 1, }, - expectErr: false, + expectErr: false, }, { SLSUrl: defaultUrl, Client: client, @@ -196,7 +196,7 @@ func TestGetNodeInfo(t *testing.T) { for i, test := range tests { sls := SLS{ - Url: test.SLSUrl, + Url: test.SLSUrl, Client: test.Client, } out, err := sls.GetNodeInfo(test.id) @@ -284,18 +284,18 @@ const testPayloadSLSAPI_comp_noData = ` func NewRTFuncSLSAPI() RTFunc { return func(req *http.Request) *http.Response { bad := true - if (len(req.Header) > 0) { - vals,ok := req.Header[base.USERAGENT] - if (ok) { - for _,v := range(vals) { - if (v == testSvcName) { + if len(req.Header) > 0 { + vals, ok := req.Header[xnametypes.USERAGENT] + if ok { + for _, v := range vals { + if v == testSvcName { bad = false break } } } } - if (bad) { + if bad { return &http.Response{ StatusCode: http.StatusInternalServerError, // Send mock response for rpath diff --git a/pkg/redfish/redfish.go b/pkg/redfish/redfish.go index b953065..29a9bc2 100644 --- a/pkg/redfish/redfish.go +++ b/pkg/redfish/redfish.go @@ -35,9 +35,10 @@ const ( ) // Resource link, often found in collection array or "Links" section. -// Example: { -// "@odata.id": "/redfish/v1/Systems/System.Embedded.1" -// } +// +// Example: { +// "@odata.id": "/redfish/v1/Systems/System.Embedded.1" +// } type ResourceID struct { Oid string `json:"@odata.id"` } @@ -121,7 +122,8 @@ type Storage GenericCollection // JSON decoded collection struct of Redfish type "EthernetInterfaceCollection" // Examples: /redfish/v1/Systems//EthernetInterfaces -// /redfish/v1/Managers//EthernetInterfaces +// +// /redfish/v1/Managers//EthernetInterfaces type EthernetInterfaceCollection GenericCollection // JSON decoded collection struct of Redfish type "SerialInterfaceCollection" @@ -170,7 +172,8 @@ type ServiceRootLinks struct { } // JSON decoded struct returned from an entry in the BMC "Managers" collection -// Example: /redfish/v1/Managers/iDRAC.Embedded.1 +// +// Example: /redfish/v1/Managers/iDRAC.Embedded.1 type Manager struct { OContext string `json:"@odata.context"` Oid string `json:"@odata.id"` @@ -271,7 +274,8 @@ type ManagerLinks struct { } // JSON decoded struct returned from the BMC of type "Chassis" -// Example: /redfish/v1/Chassis/System.Embedded.1 +// +// Example: /redfish/v1/Chassis/System.Embedded.1 type Chassis struct { OContext string `json:"@odata.context"` Oid string `json:"@odata.id"` @@ -402,7 +406,9 @@ type ChassisFRUInfoRF struct { } // Redfish pass-through from Redfish Processor -// Example: /redfish/v1/Systems/System.Embedded.1 +// +// Example: /redfish/v1/Systems/System.Embedded.1 +// // This is the set of Redfish fields for this object that HMS understands // and/or finds useful. Those assigned to either the *LocationInfo // or *FRUInfo subfields consitiute the type specific fields in the @@ -507,7 +513,8 @@ type SystemFRUInfoRF struct { // JSON decoded struct returned from Redfish of type "EthernetInterface" // Example: -// /redfish/v1/Systems/System.Embedded.1/EthernetInterfaces/NIC.Integrated.1-3-1 +// +// /redfish/v1/Systems/System.Embedded.1/EthernetInterfaces/NIC.Integrated.1-3-1 type EthernetInterface struct { OContext string `json:"@odata.context"` Oid string `json:"@odata.id"` @@ -902,15 +909,19 @@ type Task struct { // // There is a "Registries" link at the service root that has a link to // message registries that may be specific to the implementation. -// e.g. /redfish/v1/Registries -> /redfish/v1/Registries/Messages/En +// +// e.g. /redfish/v1/Registries -> /redfish/v1/Registries/Messages/En // // "Standard" registries are available at: -// http://redfish.dmtf.org/schemas/registries -// For example: http://redfish.dmtf.org/schemas/registries/v1/Base.1.1.0.json +// +// http://redfish.dmtf.org/schemas/registries +// +// For example: http://redfish.dmtf.org/schemas/registries/v1/xnametypes.1.1.0.json // // The MessageId format is registry.version.message. -// e.g. Base.1.0.0.PropertyUnknown (Standard Redfish Base schema) -// iDRAC.1.4.0.AMP0300 (via /redfish/v1/Registries/Messages/En) +// +// e.g. xnametypes.1.0.0.PropertyUnknown (Standard Redfish Base schema) +// iDRAC.1.4.0.AMP0300 (via /redfish/v1/Registries/Messages/En) type Message struct { MessageId string `json:"MessageId"` Message string `json:"Message"` @@ -973,7 +984,9 @@ type HttpPushUriApplyTime struct { // the message in the message registry. ExtendedInfo - An array of message // objects describing one or more error message(s). // Schemas are available at: -// https://redfish.dmtf.org/redfish/schema_index +// +// https://redfish.dmtf.org/redfish/schema_index +// // redfish-error: https://redfish.dmtf.org/schemas/redfish-error.v1_0_0.json type RedfishErrorContents struct { Code string `json:"code"` @@ -984,7 +997,9 @@ type RedfishErrorContents struct { // RedfishError - Contains an error payload from a Redfish service. Error - // Contains properties used to describe an error from a Redfish Service. // Schemas are available at: -// https://redfish.dmtf.org/redfish/schema_index +// +// https://redfish.dmtf.org/redfish/schema_index +// // redfish-error: https://redfish.dmtf.org/schemas/redfish-error.v1_0_0.json type RedfishError struct { Error RedfishErrorContents `json:"error"` diff --git a/pkg/redfish/rfcomponents-assembly.go b/pkg/redfish/rfcomponents-assembly.go index 5b9ef65..8aa3bed 100644 --- a/pkg/redfish/rfcomponents-assembly.go +++ b/pkg/redfish/rfcomponents-assembly.go @@ -26,7 +26,8 @@ import ( "encoding/json" "fmt" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) ///////////////////////////////////////////////////////////////////////////// @@ -276,7 +277,7 @@ func (r *EpNodeAccelRiser) discoverLocalPhase2() { r.Flag = base.FlagOK.String() } // Check if we have something valid to insert into the data store - if (base.GetHMSType(r.ID) == base.NodeAccelRiser) && (r.Type == base.NodeAccelRiser.String()) { + if (xnametypes.GetHMSType(r.ID) == xnametypes.NodeAccelRiser) && (r.Type == xnametypes.NodeAccelRiser.String()) { errlog.Printf("NodeAccelRiser discoverLocalPhase2: VALID xname ID ('%s') and Type ('%s') for: %s\n", r.ID, r.Type, r.NodeAccelRiserURL) } else { diff --git a/pkg/redfish/rfcomponents-hpe.go b/pkg/redfish/rfcomponents-hpe.go index 0e83b51..04b4663 100644 --- a/pkg/redfish/rfcomponents-hpe.go +++ b/pkg/redfish/rfcomponents-hpe.go @@ -29,7 +29,8 @@ import ( "strconv" "strings" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) ///////////////////////////////////////////////////////////////////////////// @@ -45,10 +46,10 @@ type EpHpeDevice struct { InventoryData - DeviceURL string `json:"deviceURL"` // Full URL to this RF Assembly obj - ParentOID string `json:"parentOID"` // odata.id for parent - ParentType string `json:"parentType"` // Chassis - LastStatus string `json:"LastStatus"` + DeviceURL string `json:"deviceURL"` // Full URL to this RF Assembly obj + ParentOID string `json:"parentOID"` // odata.id for parent + ParentType string `json:"parentType"` // Chassis + LastStatus string `json:"LastStatus"` DeviceRF HpeDevice `json:"DeviceRF"` deviceRaw *json.RawMessage @@ -191,23 +192,23 @@ func (d *EpHpeDevice) discoverLocalPhase2() { // GPUs are under HPE devices on HPE hardware d.Ordinal = d.epRF.getHpeDeviceOrdinal(d) if strings.ToLower(d.RedfishSubtype) == "gpu" && - !strings.Contains(strings.ToLower(d.DeviceRF.Name), "switch") && - !strings.Contains(strings.ToLower(d.DeviceRF.Location), "baseboard") { + !strings.Contains(strings.ToLower(d.DeviceRF.Name), "switch") && + !strings.Contains(strings.ToLower(d.DeviceRF.Location), "baseboard") { d.ID = d.systemRF.ID + "a" + strconv.Itoa(d.Ordinal) - d.Type = base.NodeAccel.String() + d.Type = xnametypes.NodeAccel.String() } else if strings.Contains(strings.ToLower(d.RedfishSubtype), "nic") && - (strings.Contains(strings.ToLower(d.DeviceRF.Manufacturer), "mellanox") || - strings.Contains(strings.ToLower(d.DeviceRF.Manufacturer), "hpe") || - strings.Contains(strings.ToLower(d.DeviceRF.Manufacturer), "bei")) { + (strings.Contains(strings.ToLower(d.DeviceRF.Manufacturer), "mellanox") || + strings.Contains(strings.ToLower(d.DeviceRF.Manufacturer), "hpe") || + strings.Contains(strings.ToLower(d.DeviceRF.Manufacturer), "bei")) { // Accept Mellanox or Cassini HSN NICs so we ignore non-HSN NICs. // Cassini shows as HPE instead of BEI in Proliant iLO redfish // implementations so we check for both just incase this changes // in the future. d.ID = d.systemRF.ID + "h" + strconv.Itoa(d.Ordinal) - d.Type = base.NodeHsnNic.String() + d.Type = xnametypes.NodeHsnNic.String() } else { // What to do with non-GPUs, trash for now? - d.Type = base.HMSTypeInvalid.String() + d.Type = xnametypes.HMSTypeInvalid.String() d.LastStatus = RedfishSubtypeNoSupport return } @@ -228,8 +229,8 @@ func (d *EpHpeDevice) discoverLocalPhase2() { d.Flag = base.FlagOK.String() } // Check if we have something valid to insert into the data store - if (base.GetHMSType(d.ID) != base.NodeAccel || d.Type != base.NodeAccel.String()) && - (base.GetHMSType(d.ID) != base.NodeHsnNic || d.Type != base.NodeHsnNic.String()) { + if (xnametypes.GetHMSType(d.ID) != xnametypes.NodeAccel || d.Type != xnametypes.NodeAccel.String()) && + (xnametypes.GetHMSType(d.ID) != xnametypes.NodeHsnNic || d.Type != xnametypes.NodeHsnNic.String()) { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s') for: %s\n", d.ID, d.Type, d.DeviceURL) d.LastStatus = VerificationFailed return @@ -255,10 +256,10 @@ func (ep *RedfishEP) getHpeDeviceOrdinal(d *EpHpeDevice) int { // Accept Mellanox or Cassini HSN NICs so we ignore non-HSN NICs. // Cassini shows as HPE instead of BEI in Proliant iLO redfish // implementations so we check for both just incase this changes - // in the future. + // in the future. if strings.Contains(strings.ToLower(device.DeviceRF.Manufacturer), "mellanox") || - strings.Contains(strings.ToLower(device.DeviceRF.Manufacturer), "hpe") || - strings.Contains(strings.ToLower(device.DeviceRF.Manufacturer), "bei") { + strings.Contains(strings.ToLower(device.DeviceRF.Manufacturer), "hpe") || + strings.Contains(strings.ToLower(device.DeviceRF.Manufacturer), "bei") { dsOIDs = append(dsOIDs, oid) } } else { diff --git a/pkg/redfish/rfcomponents-network.go b/pkg/redfish/rfcomponents-network.go index 675502e..fbe4c00 100644 --- a/pkg/redfish/rfcomponents-network.go +++ b/pkg/redfish/rfcomponents-network.go @@ -26,7 +26,8 @@ import ( "encoding/json" "fmt" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) ///////////////////////////////////////////////////////////////////////////// @@ -187,7 +188,7 @@ func (na *EpNetworkAdapter) discoverLocalPhase2() { na.FRUID = generatedFRUID // Check if we have something valid to insert into the data store - if (base.GetHMSType(na.ID) == base.NodeHsnNic) && (na.Type == base.NodeHsnNic.String()) { + if (xnametypes.GetHMSType(na.ID) == xnametypes.NodeHsnNic) && (na.Type == xnametypes.NodeHsnNic.String()) { errlog.Printf("NetworkAdapter discoverLocalPhase2: VALID xname ID ('%s') and Type ('%s') for: %s\n", na.ID, na.Type, na.NetworkAdapterURL) } else { diff --git a/pkg/redfish/rfcomponents-power.go b/pkg/redfish/rfcomponents-power.go index 9e97a39..3693dae 100644 --- a/pkg/redfish/rfcomponents-power.go +++ b/pkg/redfish/rfcomponents-power.go @@ -28,7 +28,8 @@ import ( "sort" "strconv" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" //"strings" ) @@ -76,7 +77,7 @@ type EpPDUs struct { // This should be the only way this struct is created. func NewEpPDU(epRF *RedfishEP, odataID ResourceID, rawOrdinal int) *EpPDU { pdu := new(EpPDU) - pdu.Type = base.HMSTypeInvalid.String() // Must be updated later + pdu.Type = xnametypes.HMSTypeInvalid.String() // Must be updated later pdu.OdataID = odataID.Oid pdu.BaseOdataID = odataID.Basename() pdu.RedfishType = PDUType @@ -239,7 +240,7 @@ func (pdu *EpPDU) discoverLocalPhase2() { // There may be outlet types that are not supported. pdu.Ordinal = pdu.epRF.getPDUOrdinal(pdu) pdu.Type = pdu.epRF.getPDUHMSType(pdu, pdu.Ordinal) - if pdu.Type == base.HMSTypeInvalid.String() { + if pdu.Type == xnametypes.HMSTypeInvalid.String() { pdu.LastStatus = RedfishSubtypeNoSupport return } @@ -249,8 +250,8 @@ func (pdu *EpPDU) discoverLocalPhase2() { pdu.discoverComponentState() // Check if we have something valid to insert into the data store - if base.GetHMSTypeString(pdu.ID) != pdu.Type || - pdu.Type == base.HMSTypeInvalid.String() || pdu.Type == "" { + if xnametypes.GetHMSTypeString(pdu.ID) != pdu.Type || + pdu.Type == xnametypes.HMSTypeInvalid.String() || pdu.Type == "" { errlog.Printf("PDU: Error: Bad xname ID ('%s') or Type ('%s') for %s\n", pdu.ID, pdu.Type, pdu.PDUURL) @@ -344,7 +345,7 @@ type EpOutlets struct { // This should be the only way this struct is created. func NewEpOutlet(pdu *EpPDU, odataID ResourceID, rawOrdinal int) *EpOutlet { out := new(EpOutlet) - out.Type = base.HMSTypeInvalid.String() // Must be updated later + out.Type = xnametypes.HMSTypeInvalid.String() // Must be updated later out.OdataID = odataID.Oid out.BaseOdataID = odataID.Basename() out.RedfishType = OutletType @@ -458,7 +459,7 @@ func (out *EpOutlet) discoverLocalPhase2() { // There may be outlet types that are not supported. out.Ordinal = out.epRF.getOutletOrdinal(out) out.Type = out.epRF.getOutletHMSType(out) - if out.Type == base.HMSTypeInvalid.String() { + if out.Type == xnametypes.HMSTypeInvalid.String() { out.LastStatus = RedfishSubtypeNoSupport return } @@ -468,8 +469,8 @@ func (out *EpOutlet) discoverLocalPhase2() { out.discoverComponentState() // Check if we have something valid to insert into the data store - if base.GetHMSTypeString(out.ID) != out.Type || - out.Type == base.HMSTypeInvalid.String() || out.Type == "" { + if xnametypes.GetHMSTypeString(out.ID) != out.Type || + out.Type == xnametypes.HMSTypeInvalid.String() || out.Type == "" { errlog.Printf("Outlet: Error: Bad ID ('%s') or Type ('%s') for %s\n", out.ID, out.Type, out.OutletURL) @@ -535,7 +536,7 @@ func (out *EpOutlet) discoverComponentState() { // the same xname. func (ep *RedfishEP) getPDUHMSID(pdu *EpPDU, hmsType string, ordinal int) string { // Note every hmsType and ordinal pair must get a unique xname ID - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -544,7 +545,7 @@ func (ep *RedfishEP) getPDUHMSID(pdu *EpPDU, hmsType string, ordinal int) string // Ordinal was never set. return "" } - if hmsType == base.CabinetPDU.String() { + if hmsType == xnametypes.CabinetPDU.String() { return pdu.epRF.ID + "p" + strconv.Itoa(ordinal) } // Something went wrong @@ -554,11 +555,11 @@ func (ep *RedfishEP) getPDUHMSID(pdu *EpPDU, hmsType string, ordinal int) string // Get the HMS type of the Cabinet PDU func (ep *RedfishEP) getPDUHMSType(pdu *EpPDU, ordinal int) string { // There can 1 or more Cabinet PDUs under a Cabinet PDU controller - if ep.Type == base.CabinetPDUController.String() && ordinal >= 0 { - return base.CabinetPDU.String() + if ep.Type == xnametypes.CabinetPDUController.String() && ordinal >= 0 { + return xnametypes.CabinetPDU.String() } // Shouldn't happen - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() } // Determines based on discovered info and original list order what the @@ -579,7 +580,7 @@ func (ep *RedfishEP) getPDUOrdinal(pdu *EpPDU) int { // the same as the parent RedfishEndpoint's xname ID. func (ep *RedfishEP) getOutletHMSID(out *EpOutlet, hmsType string, ordinal int) string { // Note every hmsType and ordinal pair must get a unique xname ID - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -588,13 +589,13 @@ func (ep *RedfishEP) getOutletHMSID(out *EpOutlet, hmsType string, ordinal int) // Ordinal was never set (properly) return "" } - if hmsType == base.CabinetPDUOutlet.String() { + if hmsType == xnametypes.CabinetPDUOutlet.String() { // Do not start at zero for the jJ portion of the xname, // start at one. We keep the ordinal at the original value for // consistency in hwinv so ordinal 0 => xXmMpPj1 return out.epPDU.ID + "j" + strconv.Itoa(ordinal+1) } - if hmsType == base.CabinetPDUPowerConnector.String() { + if hmsType == xnametypes.CabinetPDUPowerConnector.String() { // Do not start at zero for the jJ portion of the xname, // start at one. We keep the ordinal at the original value for // consistency in hwinv so ordinal 0 => xXmMpPj1 @@ -607,11 +608,11 @@ func (ep *RedfishEP) getOutletHMSID(out *EpOutlet, hmsType string, ordinal int) // Get the HMS type of the Outlet func (ep *RedfishEP) getOutletHMSType(out *EpOutlet) string { // Just one? That's this endpoint's type. - if out.epPDU.Type == base.CabinetPDU.String() { - return base.CabinetPDUPowerConnector.String() + if out.epPDU.Type == xnametypes.CabinetPDU.String() { + return xnametypes.CabinetPDUPowerConnector.String() } // Shouldn't happen - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() } // Determines based on discovered info and original list order what the @@ -870,7 +871,7 @@ func (p *EpPowerSupply) discoverLocalPhase2() { p.Flag = base.FlagOK.String() } // Check if we have something valid to insert into the data store - if ((base.GetHMSType(p.ID) == base.CMMRectifier) || (base.GetHMSType(p.ID) == base.NodeEnclosurePowerSupply)) && (p.Type == base.CMMRectifier.String() || p.Type == base.NodeEnclosurePowerSupply.String()) { + if ((xnametypes.GetHMSType(p.ID) == xnametypes.CMMRectifier) || (xnametypes.GetHMSType(p.ID) == xnametypes.NodeEnclosurePowerSupply)) && (p.Type == xnametypes.CMMRectifier.String() || p.Type == xnametypes.NodeEnclosurePowerSupply.String()) { if rfVerbose > 0 { errlog.Printf("PowerSupply discoverLocalPhase2: VALID xname ID ('%s') and Type ('%s') for: %s\n", p.ID, p.Type, p.PowerSupplyURL) diff --git a/pkg/redfish/rfcomponents-storage.go b/pkg/redfish/rfcomponents-storage.go index 70f4359..ae192c2 100644 --- a/pkg/redfish/rfcomponents-storage.go +++ b/pkg/redfish/rfcomponents-storage.go @@ -28,7 +28,8 @@ import ( "sort" "strconv" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) ///////////////////////////////////////////////////////////////////////////// @@ -60,7 +61,7 @@ type EpStorage struct { func NewEpStorage(sys *EpSystem, odataID ResourceID) *EpStorage { s := new(EpStorage) s.OdataID = odataID.Oid - s.Type = "" //should be base.Storage.String() + s.Type = "" //should be xnametypes.Storage.String() s.BaseOdataID = odataID.Basename() s.RedfishType = "" //should be StorageType s.RfEndpointID = sys.epRF.ID @@ -113,7 +114,7 @@ type EpStorageCollections struct { func NewEpStorageCollection(s *EpStorage, odataID ResourceID, rawOrdinal int) *EpStorageCollection { sc := new(EpStorageCollection) sc.OdataID = odataID.Oid - sc.Type = base.StorageGroup.String() + sc.Type = xnametypes.StorageGroup.String() sc.BaseOdataID = odataID.Basename() sc.RedfishType = StorageGroupType sc.RfEndpointID = s.epRF.ID @@ -240,7 +241,7 @@ type EpDrives struct { func NewEpDrive(s *EpStorageCollection, odataID ResourceID, rawOrdinal int) *EpDrive { d := new(EpDrive) d.OdataID = odataID.Oid - d.Type = base.Drive.String() + d.Type = xnametypes.Drive.String() d.BaseOdataID = odataID.Basename() d.RedfishType = DriveType d.RfEndpointID = s.epRF.ID @@ -372,8 +373,8 @@ func (d *EpDrive) discoverLocalPhase2() { d.Flag = base.FlagOK.String() } // Check if we have something valid to insert into the data store - if base.GetHMSType(d.ID) != base.Drive || - d.Type != base.Drive.String() { + if xnametypes.GetHMSType(d.ID) != xnametypes.Drive || + d.Type != xnametypes.Drive.String() { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s') for: %s\n", d.ID, d.Type, d.DriveURL) d.LastStatus = VerificationFailed diff --git a/pkg/redfish/rfcomponents.go b/pkg/redfish/rfcomponents.go index 58b881e..8586177 100644 --- a/pkg/redfish/rfcomponents.go +++ b/pkg/redfish/rfcomponents.go @@ -30,7 +30,8 @@ import ( "strings" "time" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) ///////////////////////////////////////////////////////////////////////////// @@ -81,7 +82,7 @@ type ComponentSystemInfo struct { Actions *ComputerSystemActions `json:"Actions,omitempty"` EthNICInfo []*EthernetNICInfo `json:"EthernetNICInfo,omitempty"` PowerCtlInfo - Controls []*Control `json:"Controls,omitempty"` + Controls []*Control `json:"Controls,omitempty"` } type ComponentManagerInfo struct { @@ -142,10 +143,10 @@ type CrayPwrLimit struct { } type PwrCtlOEMHPE struct { - PowerLimit CrayPwrLimit `json:"PowerLimit"` - PowerRegulationEnabled bool `json:"PowerRegulationEnabled"` - Status string `json:"Status"` - Target string `json:"Target"` + PowerLimit CrayPwrLimit `json:"PowerLimit"` + PowerRegulationEnabled bool `json:"PowerRegulationEnabled"` + Status string `json:"Status"` + Target string `json:"Target"` } type PwrCtlRelatedItem struct { @@ -220,7 +221,7 @@ type EpChassisSet struct { // This should be the only way this struct is created. func NewEpChassis(epRF *RedfishEP, odataID ResourceID, rawOrdinal int) *EpChassis { c := new(EpChassis) - c.Type = base.HMSTypeInvalid.String() // Must be updated later + c.Type = xnametypes.HMSTypeInvalid.String() // Must be updated later c.OdataID = odataID.Oid c.BaseOdataID = odataID.Basename() c.RedfishType = ChassisType @@ -394,7 +395,7 @@ func (c *EpChassis) discoverLocalPhase2() { } // There may be chassis types that are not supported. c.Type = c.epRF.getChassisHMSType(c) - if c.Type == base.HMSTypeInvalid.String() { + if c.Type == xnametypes.HMSTypeInvalid.String() { c.LastStatus = RedfishSubtypeNoSupport return } @@ -414,12 +415,12 @@ func (c *EpChassis) discoverLocalPhase2() { c.NetType = base.NetSling.String() // Check if we have something valid to insert into the data store - hmsType := base.GetHMSType(c.ID) - if (!base.IsHMSTypeContainer(hmsType) && - hmsType != base.MgmtSwitch && - hmsType != base.MgmtHLSwitch && - hmsType != base.CDUMgmtSwitch) || - c.Type != hmsType.String() { + hmsType := xnametypes.GetHMSType(c.ID) + if (!xnametypes.IsHMSTypeContainer(hmsType) && + hmsType != xnametypes.MgmtSwitch && + hmsType != xnametypes.MgmtHLSwitch && + hmsType != xnametypes.CDUMgmtSwitch) || + c.Type != hmsType.String() { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s' != %s) for %s\n", c.ID, c.Type, hmsType.String(), c.ChassisURL) c.LastStatus = VerificationFailed @@ -440,7 +441,7 @@ func (c *EpChassis) discoverLocalPhase2() { func (c *EpChassis) discoverComponentState() { // HSNBoard here is a workaround, should never be legitmately absent. if c.ChassisRF.Status.State != "Absent" || - c.Type == base.HSNBoard.String() { + c.Type == xnametypes.HSNBoard.String() { // Chassis status is too unpredictable and no clear what Ready // means anyways since it's not a node or a controller. So just @@ -554,7 +555,7 @@ type EpManagers struct { // This should be the only way this struct is created. func NewEpManager(epRF *RedfishEP, odataID ResourceID, rawOrdinal int) *EpManager { m := new(EpManager) - m.Type = base.HMSTypeInvalid.String() // Must be set properly later + m.Type = xnametypes.HMSTypeInvalid.String() // Must be set properly later m.OdataID = odataID.Oid m.BaseOdataID = odataID.Basename() m.RedfishType = ManagerType @@ -710,7 +711,7 @@ func (m *EpManager) discoverLocalPhase2() { } m.Ordinal = m.epRF.getManagerOrdinal(m) m.Type = m.epRF.getManagerHMSType(m) - if m.Type == base.HMSTypeInvalid.String() { + if m.Type == xnametypes.HMSTypeInvalid.String() { m.LastStatus = RedfishSubtypeNoSupport return } @@ -738,8 +739,8 @@ func (m *EpManager) discoverLocalPhase2() { m.NetType = base.NetSling.String() // Check if we have something valid to insert into the data store - hmsType := base.GetHMSType(m.ID) - if !base.IsHMSTypeController(hmsType) || m.Type != hmsType.String() { + hmsType := xnametypes.GetHMSType(m.ID) + if !xnametypes.IsHMSTypeController(hmsType) || m.Type != hmsType.String() { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s') for %s\n", m.ID, m.Type, m.ManagerURL) m.LastStatus = VerificationFailed @@ -935,7 +936,7 @@ type EpSystem struct { // associate it with nodes (systems) so we record it here. Assembly *EpAssembly `json:"Assembly"` NodeAccelRisers EpNodeAccelRisers `json:"NodeAccelRisers"` - + // HpeDevice info comes from the Chassis level HPE OEM Links but we // associate it with nodes (systems) so we record it here. We discover // GPUs on HPE hardware as an HpeDevice. @@ -975,7 +976,7 @@ type EpSystems struct { // This should be the only way this struct is created. func NewEpSystem(epRF *RedfishEP, odataID ResourceID, rawOrdinal int) *EpSystem { s := new(EpSystem) - s.Type = base.Node.String() + s.Type = xnametypes.Node.String() s.OdataID = odataID.Oid s.BaseOdataID = odataID.Basename() s.RedfishType = ComputerSystemType @@ -1192,7 +1193,7 @@ func (s *EpSystem) discoverRemotePhase1() { } } control := Control{ - URL: url.Oid, + URL: url.Oid, Control: rfControl, } s.Controls = append(s.Controls, &control) @@ -1226,7 +1227,7 @@ func (s *EpSystem) discoverRemotePhase1() { if s.PowerInfo.OEM.HPE.Links.AccPowerService.Oid == "" { break } - + path = s.PowerInfo.OEM.HPE.Links.AccPowerService.Oid hpeAccPowerServiceJSON, err := s.epRF.GETRelative(path) if err != nil || hpeAccPowerServiceJSON == nil { @@ -1661,7 +1662,7 @@ func (s *EpSystem) discoverLocalPhase2() { s.discoverComponentState() // Check if we have something valid to insert into the data store - if base.GetHMSType(s.ID) != base.Node || s.Type != base.Node.String() { + if xnametypes.GetHMSType(s.ID) != xnametypes.Node || s.Type != xnametypes.Node.String() { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s') for %s\n", s.ID, s.Type, s.SystemURL) s.LastStatus = VerificationFailed @@ -1920,7 +1921,7 @@ type EpEthInterfaces struct { func NewEpEthInterface(e *RedfishEP, pOID, pType string, odataID ResourceID, rawOrdinal int) *EpEthInterface { ei := new(EpEthInterface) ei.OdataID = odataID.Oid - ei.Type = base.HMSTypeInvalid.String() // Not used in inventory/state-tracking + ei.Type = xnametypes.HMSTypeInvalid.String() // Not used in inventory/state-tracking ei.BaseOdataID = odataID.Basename() ei.RedfishType = EthernetInterfaceType ei.RfEndpointID = e.ID @@ -2021,7 +2022,7 @@ type EpProcessors struct { func NewEpProcessor(s *EpSystem, odataID ResourceID, rawOrdinal int) *EpProcessor { p := new(EpProcessor) p.OdataID = odataID.Oid - p.Type = base.Processor.String() + p.Type = xnametypes.Processor.String() p.BaseOdataID = odataID.Basename() p.RedfishType = ProcessorType p.RfEndpointID = s.epRF.ID @@ -2135,7 +2136,7 @@ func (p *EpProcessor) discoverLocalPhase2() { p.Ordinal = p.epRF.getProcessorOrdinal(p) if strings.ToLower(p.RedfishSubtype) == "gpu" { p.ID = p.sysRF.ID + "a" + strconv.Itoa(p.Ordinal) - p.Type = base.NodeAccel.String() + p.Type = xnametypes.NodeAccel.String() } else { p.ID = p.sysRF.ID + "p" + strconv.Itoa(p.Ordinal) } @@ -2159,9 +2160,9 @@ func (p *EpProcessor) discoverLocalPhase2() { errlog.Printf("Using untrackable FRUID: %s\n", generatedFRUID) } p.FRUID = generatedFRUID - + // Discover processor arch - if p.Type == base.Processor.String() { + if p.Type == xnametypes.Processor.String() { p.Arch = GetProcessorArch(p) } } else { @@ -2171,10 +2172,10 @@ func (p *EpProcessor) discoverLocalPhase2() { p.Flag = base.FlagOK.String() } // Check if we have something valid to insert into the data store - if (base.GetHMSType(p.ID) != base.Processor || - p.Type != base.Processor.String()) && - (base.GetHMSType(p.ID) != base.NodeAccel || - p.Type != base.NodeAccel.String()) { + if (xnametypes.GetHMSType(p.ID) != xnametypes.Processor || + p.Type != xnametypes.Processor.String()) && + (xnametypes.GetHMSType(p.ID) != xnametypes.NodeAccel || + p.Type != xnametypes.NodeAccel.String()) { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s') for: %s\n", p.ID, p.Type, p.ProcessorURL) p.LastStatus = VerificationFailed @@ -2228,7 +2229,7 @@ type EpMemoryMods struct { func NewEpMemory(s *EpSystem, odataID ResourceID, rawOrdinal int) *EpMemory { m := new(EpMemory) m.OdataID = odataID.Oid - m.Type = base.Memory.String() + m.Type = xnametypes.Memory.String() m.BaseOdataID = odataID.Basename() m.RedfishType = MemoryType m.RfEndpointID = s.epRF.ID @@ -2345,7 +2346,7 @@ func (m *EpMemory) discoverLocalPhase2() { if m.MemoryRF.Status.State == "" && m.MemoryRF.SerialNumber == "NO DIMM" { m.MemoryRF.Status.State = "Absent" } - + if m.MemoryRF.Status.State != "Absent" { m.Status = "Populated" m.State = base.StatePopulated.String() @@ -2363,7 +2364,7 @@ func (m *EpMemory) discoverLocalPhase2() { m.Flag = base.FlagOK.String() } // Check if we have something valid to insert into the data store - if base.GetHMSType(m.ID) != base.Memory || m.Type != base.Memory.String() { + if xnametypes.GetHMSType(m.ID) != xnametypes.Memory || m.Type != xnametypes.Memory.String() { errlog.Printf("Error: Bad xname ID ('%s') or Type ('%s') for %s\n", m.ID, m.Type, m.MemoryURL) m.LastStatus = VerificationFailed diff --git a/pkg/redfish/rfcomponents_test.go b/pkg/redfish/rfcomponents_test.go index 6b2f100..975262c 100644 --- a/pkg/redfish/rfcomponents_test.go +++ b/pkg/redfish/rfcomponents_test.go @@ -32,8 +32,8 @@ import ( "net/http" "testing" - base "github.com/Cray-HPE/hms-base" "github.com/Cray-HPE/hms-certs/pkg/hms_certs" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // RoundTrip method override @@ -835,8 +835,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { } } // Verify xname and type - stype := base.GetHMSType(s.ID) - if stype != base.Node || s.Type != stype.String() { + stype := xnametypes.GetHMSType(s.ID) + if stype != xnametypes.Node || s.Type != stype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", s.ID, s.Type, sysId) } @@ -866,7 +866,7 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { return fmt.Errorf("ManagerId: " + v.ManagerId + ": bad Target/AllowableValues") } // Verify xname and type - mtype := base.GetHMSTypeString(m.ID) + mtype := xnametypes.GetHMSTypeString(m.ID) if m.ID == "" || mtype != v.ManagerType || m.Type != v.ManagerType { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", m.ID, m.Type, v.ManagerId) @@ -891,8 +891,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { return fmt.Errorf("NodeEnclosureId: " + neId + ": bad Target/AllowableValues") } // Verify xname and type - ctype := base.GetHMSType(c.ID) - if ctype != base.NodeEnclosure || c.Type != ctype.String() { + ctype := xnametypes.GetHMSType(c.ID) + if ctype != xnametypes.NodeEnclosure || c.Type != ctype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", c.ID, c.Type, neId) } @@ -915,8 +915,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { return fmt.Errorf("ChassisEnclosureId: " + ceId + ": bad Target/AllowableValues") } // Verify xname and type - ctype := base.GetHMSType(c.ID) - if ctype != base.Chassis || c.Type != ctype.String() { + ctype := xnametypes.GetHMSType(c.ID) + if ctype != xnametypes.Chassis || c.Type != ctype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", c.ID, c.Type, ceId) } @@ -939,8 +939,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { return fmt.Errorf("ComputeBladeId: " + cbId + ": bad Target/AllowableValues") } // Verify xname and type - cbtype := base.GetHMSType(cb.ID) - if cbtype != base.ComputeModule || cb.Type != cbtype.String() { + cbtype := xnametypes.GetHMSType(cb.ID) + if cbtype != xnametypes.ComputeModule || cb.Type != cbtype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", cb.ID, cb.Type, cbId) } @@ -968,8 +968,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { return fmt.Errorf("RouterBladeId: " + rbId + ": bad Target/AllowableValues") } // Verify xname and type - rbtype := base.GetHMSType(rb.ID) - if rbtype != base.RouterModule || rb.Type != rbtype.String() { + rbtype := xnametypes.GetHMSType(rb.ID) + if rbtype != xnametypes.RouterModule || rb.Type != rbtype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", rb.ID, rb.Type, rbId) } @@ -994,8 +994,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { // No current actions to verify. // Verify xname and type - pdutype := base.GetHMSType(pdu.ID) - if pdutype != base.CabinetPDU || pdu.Type != pdutype.String() { + pdutype := xnametypes.GetHMSType(pdu.ID) + if pdutype != xnametypes.CabinetPDU || pdu.Type != pdutype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", pdu.ID, pdu.Type, pduId) } @@ -1068,8 +1068,8 @@ func VerifyGetRootInfo(e *RedfishEP, v RedfishEPVerifyInfo) error { // No current actions to verify. // Verify xname and type - outtype := base.GetHMSType(out.ID) - if outtype != base.CabinetPDUPowerConnector || out.Type != outtype.String() { + outtype := xnametypes.GetHMSType(out.ID) + if outtype != xnametypes.CabinetPDUPowerConnector || out.Type != outtype.String() { return fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", out.ID, out.Type, outId) } @@ -15274,7 +15274,7 @@ const testPayloadRtsPDUManagers_BMC_NICs_Dedicated = ` "Messages": [ { "@odata.type": "#Message.v1_0_0.Message", - "MessageId": "Base.1.0.SettingsFailed", + "MessageId": "xnametypes.1.0.SettingsFailed", "RelatedProperties": [ "#/IPv6Addresses/PrefixLength" ] diff --git a/pkg/redfish/rfendpoints.go b/pkg/redfish/rfendpoints.go index 097612c..0953ec0 100644 --- a/pkg/redfish/rfendpoints.go +++ b/pkg/redfish/rfendpoints.go @@ -38,8 +38,9 @@ import ( "time" "unicode" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" "github.com/Cray-HPE/hms-certs/pkg/hms_certs" + "github.com/Cray-HPE/hms-xname/xnametypes" ) const PKG_VERSION = "0.2" @@ -165,7 +166,6 @@ var ErrRFDiscILOLicenseReq = errors.New("iLO License Required") // ///////////////////////////////////////////////////////////////////////////// -// // 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, @@ -175,11 +175,12 @@ var ErrRFDiscILOLicenseReq = errors.New("iLO License Required") // 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. +// +// 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"` @@ -334,17 +335,17 @@ func NewRedfishEPDescription(rep *RawRedfishEP) (*RedfishEPDescription, error) { err := fmt.Errorf("No xname ID found") return nil, err } - ep.ID = base.NormalizeHMSCompID(ep.ID) + ep.ID = xnametypes.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 { + hmsType := xnametypes.GetHMSType(ep.ID) + if xnametypes.IsHMSTypeController(hmsType) || + hmsType == xnametypes.MgmtSwitch || + hmsType == xnametypes.MgmtHLSwitch || + hmsType == xnametypes.CDUMgmtSwitch { ep.Type = hmsType.String() - } else if hmsType == base.HMSTypeInvalid { + } else if hmsType == xnametypes.HMSTypeInvalid { // No type found. Not a valid xname err := fmt.Errorf("%s is not a valid locational xname ID", ep.ID) return nil, err @@ -571,7 +572,7 @@ type RedfishEP struct { // Create RedfishEP struct from a validated RedfishEndpointDescription. // The description would be generated from user-supplied RawEndpoints and/or -// retrieved from the database. +// retrieved from the dataxnametypes. // 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) { @@ -875,7 +876,7 @@ func (ep *RedfishEP) GetRootInfo() { path = ep.OdataID + "/Chassis" } chassisJSON, err := ep.GETRelative(path) - if err != nil && !base.ControllerHasChassisStr(ep.Type) { + if err != nil && !xnametypes.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 @@ -1073,7 +1074,7 @@ func (ep *RedfishEP) GetSystems() string { // This is the CMC special name. Skip discovering this node // that shouldn't exist. - if base.GetHMSType(ep.ID) == base.NodeBMC && + if xnametypes.GetHMSType(ep.ID) == xnametypes.NodeBMC && strings.HasSuffix(ep.ID, "b999") { return HTTPsGetOk } @@ -1084,7 +1085,7 @@ func (ep *RedfishEP) GetSystems() string { path = ep.OdataID + "/Systems" } systemsJSON, err := ep.GETRelative(path) - if err != nil && !base.ControllerHasSystemsStr(ep.Type) { + if err != nil && !xnametypes.ControllerHasSystemsStr(ep.Type) { // Don't expect systems, so if the collection is missing, just // mark there as being zero move on. ep.NumSystems = 0 @@ -1142,12 +1143,12 @@ func (ep *RedfishEP) CheckPrePhase1() error { ep.ID, ep.Hostname, ep.Domain) return err } - hmsType := base.GetHMSType(ep.ID) - if (!base.IsHMSTypeController(hmsType) && - hmsType != base.MgmtSwitch && - hmsType != base.MgmtHLSwitch && - hmsType != base.CDUMgmtSwitch) || - ep.Type != hmsType.String() { + hmsType := xnametypes.GetHMSType(ep.ID) + if (!xnametypes.IsHMSTypeController(hmsType) && + hmsType != xnametypes.MgmtSwitch && + hmsType != xnametypes.MgmtHLSwitch && + hmsType != xnametypes.CDUMgmtSwitch) || + ep.Type != hmsType.String() { err := fmt.Errorf("bad xname ID ('%s') or Type ('%s') for %s\n", ep.ID, ep.Type, ep.FQDN) return err @@ -1192,7 +1193,7 @@ func (ep *RedfishEP) CheckPrePhase1() error { // Need to know real (not raw ordinal) and HMS type first. // Post phase 1 discovery. func (ep *RedfishEP) getChassisHMSID(c *EpChassis, hmsType string, ordinal int) string { - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -1201,9 +1202,9 @@ func (ep *RedfishEP) getChassisHMSID(c *EpChassis, hmsType string, ordinal int) // Invalid ordinal or initial -1 value. return "" } - if hmsTypeStr == base.MgmtSwitch.String() || - hmsTypeStr == base.MgmtHLSwitch.String() || - hmsTypeStr == base.CDUMgmtSwitch.String() { + if hmsTypeStr == xnametypes.MgmtSwitch.String() || + hmsTypeStr == xnametypes.MgmtHLSwitch.String() || + hmsTypeStr == xnametypes.CDUMgmtSwitch.String() { return ep.ID } // If the RedfishEndpoint ID is valid, there will be a b in the xname. @@ -1212,32 +1213,32 @@ func (ep *RedfishEP) getChassisHMSID(c *EpChassis, hmsType string, ordinal int) // Bad RFEndpoint xname - not a BMC - may match other component return "" } - if hmsTypeStr == base.HSNBoard.String() { + if hmsTypeStr == xnametypes.HSNBoard.String() { // If RouterBMC is x0c0r0b[0-9], enclosure is x0c0r0e[0-9] return epIDSplit[0] + "e" + epIDSplit[1] } - if hmsTypeStr == base.NodeEnclosure.String() { + if hmsTypeStr == xnametypes.NodeEnclosure.String() { // If NodeBMC is x0c0s0b[0-9]+, enclosure is x0c0s0e[0-9]+ return epIDSplit[0] + "e" + epIDSplit[1] } - if hmsTypeStr == base.Chassis.String() { + if hmsTypeStr == xnametypes.Chassis.String() { // Top-level Chassis for x0c0b0 is x0c0 return epIDSplit[0] } - if hmsTypeStr == base.ComputeModule.String() { - if ep.Type == base.ChassisBMC.String() { + if hmsTypeStr == xnametypes.ComputeModule.String() { + if ep.Type == xnametypes.ChassisBMC.String() { // Chassis + s + ordinal return epIDSplit[0] + "s" + strconv.FormatInt(int64(ordinal), 10) } // Shouldn't happen. This should be the only possibility for now. return "" } - if hmsTypeStr == base.RouterModule.String() { - if ep.Type == base.ChassisBMC.String() { + if hmsTypeStr == xnametypes.RouterModule.String() { + if ep.Type == xnametypes.ChassisBMC.String() { // Chassis + r + ordinal return epIDSplit[0] + "r" + strconv.FormatInt(int64(ordinal), 10) } - if ep.Type == base.RouterBMC.String() { + if ep.Type == xnametypes.RouterBMC.String() { // Already have Chassis +r in the path, remove bmc portion return epIDSplit[0] } @@ -1255,17 +1256,17 @@ func (ep *RedfishEP) getChassisHMSID(c *EpChassis, hmsType string, ordinal int) func (ep *RedfishEP) getChassisHMSType(c *EpChassis) string { switch c.RedfishSubtype { case RFSubtypeEnclosure: - if ep.Type == base.ChassisBMC.String() && + if ep.Type == xnametypes.ChassisBMC.String() && IsManufacturer(c.ChassisRF.Manufacturer, CrayMfr) != 0 { // ChassisBMC and is not non-Cray, must be the Chassis itself // by convention. - return base.Chassis.String() + return xnametypes.Chassis.String() } - if ep.Type == base.RouterBMC.String() { + if ep.Type == xnametypes.RouterBMC.String() { // RouterBMC, must be the Chassis itself (Router card or TOR // enclosure) by convention. We only have slingshot at the // moment so no need to guess. - return base.HSNBoard.String() + return xnametypes.HSNBoard.String() } // NodeEnclosures may be RackMount, Enclosure. fallthrough @@ -1273,46 +1274,46 @@ func (ep *RedfishEP) getChassisHMSType(c *EpChassis) string { if ep.NumSystems > 0 { // Does the endpoint contain nodes? // For now assume NodeEnclosure. - return base.NodeEnclosure.String() + return xnametypes.NodeEnclosure.String() } else { - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() } case RFSubtypeStandAlone: if IsManufacturer(c.ChassisRF.Manufacturer, GigabyteMfr) != 0 && ep.NumSystems > 0 { // Is gigabyte ChassisBMC and has nodes, it is the node enclosure. - return base.NodeEnclosure.String() + return xnametypes.NodeEnclosure.String() } else { - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() } case RFSubtypeBlade: - if ep.Type == base.ChassisBMC.String() { + if ep.Type == xnametypes.ChassisBMC.String() { // If is not non-Cray and Chassis BMC, but be compute or router // blade. // TODO: When there is something more reliable than the name of // the blade to use, use that instead. if IsManufacturer(c.ChassisRF.Manufacturer, CrayMfr) != 0 { if strings.HasPrefix(strings.ToLower(c.ChassisRF.Id), "blade") { - return base.ComputeModule.String() + return xnametypes.ComputeModule.String() } if strings.HasPrefix(strings.ToLower(c.ChassisRF.Id), "perif") { - return base.RouterModule.String() + return xnametypes.RouterModule.String() } } } - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() case RFSubtypeDrawer: - if ep.Type == base.MgmtSwitch.String() || - ep.Type == base.MgmtHLSwitch.String() || - ep.Type == base.CDUMgmtSwitch.String() { + if ep.Type == xnametypes.MgmtSwitch.String() || + ep.Type == xnametypes.MgmtHLSwitch.String() || + ep.Type == xnametypes.CDUMgmtSwitch.String() { return ep.Type } - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() default: // Other types are usually subcomponents we don't track and are // often not represented very consistently by different manufacturers. errlog.Printf("getChassisHMSType default case: c.RedfishSubtype: %s", c.RedfishSubtype) - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() } } @@ -1364,7 +1365,7 @@ func (ep *RedfishEP) getChassisOrdinal(c *EpChassis) int { // Given ordinal and type of a system, return the xname of a // ComputerSystem. func (ep *RedfishEP) getSystemHMSID(s *EpSystem, hmsType string, ordinal int) string { - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -1374,7 +1375,7 @@ func (ep *RedfishEP) getSystemHMSID(s *EpSystem, hmsType string, ordinal int) st errlog.Printf("BUG: Bad ordinal.") return "" } - if hmsTypeStr == base.Node.String() { + if hmsTypeStr == xnametypes.Node.String() { // Only one type to support at the moment, node. xnameID := ep.ID + "n" + strconv.Itoa(ordinal) return xnameID @@ -1398,7 +1399,7 @@ func (ep *RedfishEP) getSystemOrdinalAndType(s *EpSystem) (int, string) { return -1, hmsType } else { - hmsType = base.Node.String() + hmsType = xnametypes.Node.String() } // Count the lower ordered chassis that are the same type as m for _, sys := range ep.Systems.OIDs { @@ -1496,7 +1497,7 @@ func (ep *RedfishEP) getStorageCollectionOrdinal(sc *EpStorageCollection) int { // Need to know real (not raw ordinal) and HMS type first. // Post phase 1 discovery. func (ep *RedfishEP) getPowerSupplyHMSID(p *EpPowerSupply, hmsType string, ordinal int) string { - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -1514,11 +1515,11 @@ func (ep *RedfishEP) getPowerSupplyHMSID(p *EpPowerSupply, hmsType string, ordin // Post phase 1 discovery. func (ep *RedfishEP) getPowerSupplyHMSType(p *EpPowerSupply) string { parentChassisType := ep.getChassisHMSType(p.chassisRF) - if parentChassisType == base.NodeEnclosure.String() { - return base.NodeEnclosurePowerSupply.String() + if parentChassisType == xnametypes.NodeEnclosure.String() { + return xnametypes.NodeEnclosurePowerSupply.String() } - if parentChassisType == base.Chassis.String() { - return base.CMMRectifier.String() + if parentChassisType == xnametypes.Chassis.String() { + return xnametypes.CMMRectifier.String() } return "" } @@ -1552,7 +1553,7 @@ func (ep *RedfishEP) getPowerSupplyOrdinal(p *EpPowerSupply) int { // Need to know real (not raw ordinal) and HMS type first. // Post phase 1 discovery. func (ep *RedfishEP) getNodeAccelRiserHMSID(r *EpNodeAccelRiser, hmsType string, ordinal int) string { - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -1569,7 +1570,7 @@ func (ep *RedfishEP) getNodeAccelRiserHMSID(r *EpNodeAccelRiser, hmsType string, // special here, namely, "skip it"/"not supported". // Post phase 1 discovery. func (ep *RedfishEP) getNodeAccelRiserHMSType(r *EpNodeAccelRiser) string { - return base.NodeAccelRiser.String() + return xnametypes.NodeAccelRiser.String() } // Determined based on discovered info and original list order that the @@ -1601,7 +1602,7 @@ func (ep *RedfishEP) getNodeAccelRiserOrdinal(r *EpNodeAccelRiser) int { // Need to know real (not raw ordinal) and HMS type first. // Post phase 1 discovery. func (ep *RedfishEP) getNetworkAdapterHMSID(na *EpNetworkAdapter, hmsType string, ordinal int) string { - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -1619,7 +1620,7 @@ func (ep *RedfishEP) getNetworkAdapterHMSID(na *EpNetworkAdapter, hmsType string // special here, namely, "skip it"/"not supported". // Post phase 1 discovery. func (ep *RedfishEP) getNetworkAdapterHMSType(na *EpNetworkAdapter) string { - return base.NodeHsnNic.String() + return xnametypes.NodeHsnNic.String() } // Determined based on discovered info and original list order that the @@ -1769,7 +1770,7 @@ func getStandardFRUID(hmstype, id, manufacturer, partnumber, serialnumber string // the same as the parent RedfishEndpoint's xname ID. func (ep *RedfishEP) getManagerHMSID(m *EpManager, hmsType string, ordinal int) string { // Note every hmsType and ordinal pair must get a unique xname ID - hmsTypeStr := base.VerifyNormalizeType(hmsType) + hmsTypeStr := xnametypes.VerifyNormalizeType(hmsType) if hmsTypeStr == "" { // This is an error or a skipped type. return "" @@ -1792,10 +1793,10 @@ func (ep *RedfishEP) getManagerHMSID(m *EpManager, hmsType string, ordinal int) // particular Redfish endpoint xname and type. func (ep *RedfishEP) getManagerHMSType(m *EpManager) string { // Don't discover Management switch BMCs. - if ep.Type == base.MgmtSwitch.String() || - ep.Type == base.MgmtHLSwitch.String() || - ep.Type == base.CDUMgmtSwitch.String() { - return base.HMSTypeInvalid.String() + if ep.Type == xnametypes.MgmtSwitch.String() || + ep.Type == xnametypes.MgmtHLSwitch.String() || + ep.Type == xnametypes.CDUMgmtSwitch.String() { + return xnametypes.HMSTypeInvalid.String() } // Just one? That's this endpoint's type. // example: RouterBMC @@ -1808,21 +1809,21 @@ func (ep *RedfishEP) getManagerHMSType(m *EpManager) string { } if len(m.ManagedSystems) > 0 { // Does it manage any systems (i.e. nodes)? NodeBMC. - return base.NodeBMC.String() + return xnametypes.NodeBMC.String() } if m.ManagerRF.ManagerType == RFSubtypeEnclosureManager { // Cassini NodeBMCs look like ChassisBMCs because they're missing the // Links.ManagerForServers field. If the managerType is "EnclosureManager", // check to see if there are any Systems at all. if ep.NumSystems > 0 { - return base.NodeBMC.String() + return xnametypes.NodeBMC.String() } - return base.ChassisBMC.String() + return xnametypes.ChassisBMC.String() } // TODO: Multiple managers. We don't roll up managers // so there should only be one per redfish endpoint. If // that ever changes we will need to do more work. - return base.HMSTypeInvalid.String() + return xnametypes.HMSTypeInvalid.String() } // Determines based on discovered info and original list order what the @@ -1930,14 +1931,17 @@ func GetProcessorArch(p *EpProcessor) (procArch string) { if rfArch == "" { rfArch = p.ProcessorRF.InstructionSet } - switch(rfArch) { + switch rfArch { case "": procArch = base.ArchUnknown.String() - case ProcessorArchX86: fallthrough + case ProcessorArchX86: + fallthrough case ProcessorInstructionSetX86_64: procArch = base.ArchX86.String() - case ProcessorArchARM: fallthrough - case ProcessorInstructionSetARMA32: fallthrough + case ProcessorArchARM: + fallthrough + case ProcessorInstructionSetARMA32: + fallthrough case ProcessorInstructionSetARMA64: procArch = base.ArchARM.String() default: @@ -1977,23 +1981,22 @@ var CrayEXDescrArchMap = map[string]string{ "blancapeaknc": base.ArchARM.String(), } - func GetSystemArch(s *EpSystem) string { sysArch := base.ArchUnknown.String() // Search the processor collection for the architecture. for _, proc := range s.Processors.OIDs { - if proc.Type != base.Processor.String() { + if proc.Type != xnametypes.Processor.String() { // Skip GPUs continue } if sysArch == base.ArchUnknown.String() || - (sysArch == base.ArchOther.String() && - proc.Arch != base.ArchUnknown.String()) { + (sysArch == base.ArchOther.String() && + proc.Arch != base.ArchUnknown.String()) { // Try for the best identification (X86/ARM > Other > UNKNOWN). sysArch = proc.Arch } if sysArch != base.ArchUnknown.String() && - sysArch != base.ArchOther.String() { + sysArch != base.ArchOther.String() { // Found x86 or ARM break } @@ -2004,7 +2007,7 @@ func GetSystemArch(s *EpSystem) string { // for the processors or the processor collection wasn't present. Try to // determine the processor architecture based on the node's model. if sysArch == base.ArchUnknown.String() && - IsManufacturer(s.SystemRF.Manufacturer, CrayMfr) == 1 { + IsManufacturer(s.SystemRF.Manufacturer, CrayMfr) == 1 { if len(s.SystemRF.Model) > 0 { rfModel := strings.ToLower(s.SystemRF.Model) for matchStr, arch := range CrayEXModelArchMap { diff --git a/pkg/redfish/rfservices.go b/pkg/redfish/rfservices.go index b1b318e..1db3f58 100644 --- a/pkg/redfish/rfservices.go +++ b/pkg/redfish/rfservices.go @@ -25,7 +25,7 @@ package rf import ( //"bytes" "encoding/json" - //base "github.com/Cray-HPE/hms-base" + //base "github.com/Cray-HPE/hms-base/v2" //"io/ioutil" //"path" //"strings" diff --git a/pkg/service-reservations/interface.go b/pkg/service-reservations/interface.go index 2709a10..f00c040 100644 --- a/pkg/service-reservations/interface.go +++ b/pkg/service-reservations/interface.go @@ -35,10 +35,10 @@ import ( "sync" "time" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-smd/v2/pkg/sm" "github.com/hashicorp/go-retryablehttp" "github.com/sirupsen/logrus" - "github.com/Cray-HPE/hms-base" - "github.com/Cray-HPE/hms-smd/v2/pkg/sm" ) const HSM_DEFAULT_RESERVATION_PATH = "/hsm/v2/locks/service/reservations" @@ -79,8 +79,8 @@ type Production struct { logger *logrus.Logger } -//This uses the rigid implementation, so we will assume for EVERY operation that is all or nothing. This could be -//pretty easily extended to support the flexible implementation, but this wasnt needed for FAS/CAPMC +// This uses the rigid implementation, so we will assume for EVERY operation that is all or nothing. This could be +// pretty easily extended to support the flexible implementation, but this wasnt needed for FAS/CAPMC type ServiceReservation interface { Init(stateManagerServer string, reservationPath string, defaultTermMinutes int, logger *logrus.Logger) @@ -165,11 +165,11 @@ func (i *Production) Init(stateManagerServer string, reservationPath string, def func (i *Production) InitInstance(stateManagerServer string, reservationPath string, defaultTermMinutes int, logger *logrus.Logger, svcName string) { serviceName = svcName - i.Init(stateManagerServer,reservationPath,defaultTermMinutes,logger) + i.Init(stateManagerServer, reservationPath, defaultTermMinutes, logger) } -//Lets make this really simple; Im going to wake up and see what expires in the next 30 seconds; -//then I will renew those things +// Lets make this really simple; Im going to wake up and see what expires in the next 30 seconds; +// then I will renew those things func (i *Production) doRenewal() { for ; ; time.Sleep(time.Duration(DefaultSleepTime) * time.Second) { @@ -257,9 +257,9 @@ func (i *Production) doRenew(reservationKeys []Key, flex bool) (ReservationRelea } renewalParameters := ReservationRenewalParameters{ - ProcessingModel: processingModel, + ProcessingModel: processingModel, ReservationDuration: i.defaultTermMinutes, - ReservationKeys: reservationKeys, + ReservationKeys: reservationKeys, } if len(renewalParameters.ReservationKeys) == 0 { @@ -349,7 +349,7 @@ func (i *Production) Aquire(xnames []string) error { i.logger.WithField("error", err).Error("Aquire() - END") return err } - base.SetHTTPUserAgent(newRequest,serviceName) + base.SetHTTPUserAgent(newRequest, serviceName) reqContext, _ := context.WithTimeout(context.Background(), time.Second*40) req, err := retryablehttp.FromRequest(newRequest) @@ -388,7 +388,7 @@ func (i *Production) Aquire(xnames []string) error { return err } - if (len(response.Success) < len(xnames)) { + if len(response.Success) < len(xnames) { // because we have HARDCODED rigid; if failure > 0 or successes < xnames, // success MUST == 0 err = errors.New("at least one xname could not be reserved") @@ -425,7 +425,7 @@ func (i *Production) Aquire(xnames []string) error { } } -func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse,error) { +func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse, error) { var resResponse ReservationCreateResponse i.logger.Trace("SoftAquire() - START") @@ -443,16 +443,16 @@ func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse,erro newRequest, err := http.NewRequest("POST", targetURL.String(), bytes.NewBuffer([]byte(stringReservation))) if err != nil { i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err } - base.SetHTTPUserAgent(newRequest,serviceName) + base.SetHTTPUserAgent(newRequest, serviceName) reqContext, _ := context.WithTimeout(context.Background(), time.Second*40) req, err := retryablehttp.FromRequest(newRequest) req = req.WithContext(reqContext) if err != nil { i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err } req.Header.Add("Content-Type", "application/json") @@ -461,7 +461,7 @@ func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse,erro resp, err := i.httpClient.Do(req) if err != nil { i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err } //process response @@ -469,7 +469,7 @@ func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse,erro body, err := ioutil.ReadAll(resp.Body) if err != nil { i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err } i.logger.WithField("response", string(body)).Trace("SoftAquire() - Recieved response") @@ -480,7 +480,7 @@ func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse,erro err = json.Unmarshal(body, &resResponse) if err != nil { i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err } for _, v := range resResponse.Success { @@ -501,22 +501,22 @@ func (i *Production) FlexAquire(xnames []string) (ReservationCreateResponse,erro _ = json.Unmarshal(body, &pResponse) err = errors.New(pResponse.Detail) i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err default: err = errors.New(string(body)) i.logger.WithField("error", err).Error("SoftAquire() - END") - return resResponse,err + return resResponse, err } - return resResponse,nil + return resResponse, nil } -//Restarts periodic renew for already owned reservations +// Restarts periodic renew for already owned reservations func (i *Production) Reacquire(reservations []Reservation, flex bool) (ReservationReleaseRenewResponse, error) { var ( - response ReservationReleaseRenewResponse - resKeys []Key + response ReservationReleaseRenewResponse + resKeys []Key ) i.logger.Trace("Reacquire() - START") @@ -526,7 +526,7 @@ func (i *Production) Reacquire(reservations []Reservation, flex bool) (Reservati for _, res := range reservations { resMap[res.Xname] = res key := Key{ - ID: res.Xname, + ID: res.Xname, Key: res.ReservationKey, } resKeys = append(resKeys, key) @@ -567,7 +567,7 @@ func (i *Production) Check(xnames []string) bool { return valid } -func (i *Production) FlexCheck(xnames []string) (ReservationCreateResponse,bool) { +func (i *Production) FlexCheck(xnames []string) (ReservationCreateResponse, bool) { var retData ReservationCreateResponse i.logger.Trace("SoftCheck() - START") @@ -576,18 +576,18 @@ func (i *Production) FlexCheck(xnames []string) (ReservationCreateResponse,bool) if comp, ok := i.reservedMap[xname]; ok { retData.Success = append(retData.Success, ReservationCreateSuccessResponse{ID: comp.Xname, - DeputyKey: comp.DeputyKey, - ReservationKey: comp.ReservationKey, - ExpirationTime: comp.Expiration.Format(time.RFC3339)}) + DeputyKey: comp.DeputyKey, + ReservationKey: comp.ReservationKey, + ExpirationTime: comp.Expiration.Format(time.RFC3339)}) } else { - i.logger.Tracef("SoftCheck() - no reservation match for '%s'",xname) + i.logger.Tracef("SoftCheck() - no reservation match for '%s'", xname) retData.Failure = append(retData.Failure, FailureResponse{ID: xname, Reason: "Reservation not found."}) valid = false } } - return retData,valid + return retData, valid } func (i *Production) Release(xnames []string) error { @@ -630,7 +630,7 @@ func (i *Production) Release(xnames []string) error { i.logger.WithField("error", err).Error("Release() - END") return err } - base.SetHTTPUserAgent(newRequest,serviceName) + base.SetHTTPUserAgent(newRequest, serviceName) reqContext, _ := context.WithTimeout(context.Background(), time.Second*40) req, err := retryablehttp.FromRequest(newRequest) @@ -704,14 +704,14 @@ func (i *Production) Release(xnames []string) error { } } -func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewResponse,error) { +func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewResponse, error) { var retData ReservationReleaseRenewResponse i.logger.Trace("SoftRelease() - START") if len(xnames) == 0 { i.logger.Trace("SoftRelease() - END -> nothing to do ") err := errors.New("empty set; failing release operation") - return retData,err + return retData, err } var releaseParams ReservationReleaseParameters @@ -730,8 +730,8 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon releaseParams.ReservationKeys = append(releaseParams.ReservationKeys, key) } else { // xname not in map - retData.Failure = append(retData.Failure,FailureResponse{ID: xname, - Reason: "Reservation not found."}) + retData.Failure = append(retData.Failure, FailureResponse{ID: xname, + Reason: "Reservation not found."}) err := errors.New(xname + " not found in reservation map") i.logger.WithField("error", err).Error("SoftRelease() - END") } @@ -745,16 +745,16 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon newRequest, err := http.NewRequest("POST", targetURL.String(), bytes.NewBuffer(marshalReleaseParams)) if err != nil { i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err } - base.SetHTTPUserAgent(newRequest,serviceName) + base.SetHTTPUserAgent(newRequest, serviceName) reqContext, _ := context.WithTimeout(context.Background(), time.Second*40) req, err := retryablehttp.FromRequest(newRequest) req = req.WithContext(reqContext) if err != nil { i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err } req.Header.Add("Content-Type", "application/json") @@ -763,7 +763,7 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon resp, err := i.httpClient.Do(req) if err != nil { i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err } //process response @@ -771,7 +771,7 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon body, err := ioutil.ReadAll(resp.Body) if err != nil { i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err } i.logger.WithField("response", string(body)).Trace("SoftRelease() - Received response") @@ -782,7 +782,7 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon err = json.Unmarshal(body, &response) if err != nil { i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err } i.logger.WithFields(logrus.Fields{"Total": response.Counts.Total, @@ -796,10 +796,10 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon i.reservationMutex.Lock() delete(i.reservedMap, xname) i.reservationMutex.Unlock() - retData.Success.ComponentIDs = append(retData.Success.ComponentIDs,xname) + retData.Success.ComponentIDs = append(retData.Success.ComponentIDs, xname) } } - retData.Failure = append(retData.Failure,unMapped...) + retData.Failure = append(retData.Failure, unMapped...) retData.Counts.Success = len(retData.Success.ComponentIDs) retData.Counts.Failure = len(retData.Failure) @@ -810,15 +810,15 @@ func (i *Production) FlexRelease(xnames []string) (ReservationReleaseRenewRespon _ = json.Unmarshal(body, &response) err = errors.New(response.Detail) i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err default: err = errors.New(string(body)) i.logger.WithField("error", err).Error("SoftRelease() - END") - return retData,err + return retData, err } - return retData,nil + return retData, nil } func (i *Production) update() { @@ -849,7 +849,7 @@ func (i *Production) update() { i.logger.WithField("error", err).Error("update() - END") return } - base.SetHTTPUserAgent(newRequest,serviceName) + base.SetHTTPUserAgent(newRequest, serviceName) reqContext, _ := context.WithTimeout(context.Background(), time.Second*40) req, err := retryablehttp.FromRequest(newRequest) @@ -927,84 +927,82 @@ func (i *Production) Status() (res map[string]Reservation) { return res } -func (i *Production) ValidateDeputyKeys(keys []Key) (ReservationCheckResponse,error) { +func (i *Production) ValidateDeputyKeys(keys []Key) (ReservationCheckResponse, error) { var lockArray sm.CompLockV2DeputyKeyArray var jdata sm.CompLockV2ReservationResult var retData ReservationCheckResponse rmap := make(map[string]bool) - for _,comp := range(keys) { + for _, comp := range keys { rmap[comp.ID] = true - if (comp.Key != "") { + if comp.Key != "" { lockArray.DeputyKeys = append(lockArray.DeputyKeys, sm.CompLockV2Key{ID: comp.ID, Key: comp.Key}) } } - ba,baerr := json.Marshal(&lockArray) - if (baerr != nil) { - return retData,fmt.Errorf("Error marshalling deputy key array: %v",baerr) + ba, baerr := json.Marshal(&lockArray) + if baerr != nil { + return retData, fmt.Errorf("Error marshalling deputy key array: %v", baerr) } baseURL := i.stateManagerServer + i.reservationPath + "/check" - newRequest,err := http.NewRequest(http.MethodPost,baseURL,bytes.NewBuffer(ba)) - if (err != nil) { - return retData,fmt.Errorf("Error constructing HTTP request for deputy key check: %v", + newRequest, err := http.NewRequest(http.MethodPost, baseURL, bytes.NewBuffer(ba)) + if err != nil { + return retData, fmt.Errorf("Error constructing HTTP request for deputy key check: %v", err) } req, err := retryablehttp.FromRequest(newRequest) - reqContext,_ := context.WithTimeout(context.Background(), 40*time.Second) + reqContext, _ := context.WithTimeout(context.Background(), 40*time.Second) req = req.WithContext(reqContext) - rsp,rsperr := i.httpClient.Do(req) - if (rsperr != nil) { - return retData,fmt.Errorf("Error sending http request for deputy key check: %v", + rsp, rsperr := i.httpClient.Do(req) + if rsperr != nil { + return retData, fmt.Errorf("Error sending http request for deputy key check: %v", rsperr) } switch statusCode := rsp.StatusCode; statusCode { case http.StatusOK: - body,bderr := ioutil.ReadAll(rsp.Body) - if (bderr != nil) { - return retData,fmt.Errorf("Error reading http response for deputy key check: %v", + body, bderr := ioutil.ReadAll(rsp.Body) + if bderr != nil { + return retData, fmt.Errorf("Error reading http response for deputy key check: %v", bderr) } - err = json.Unmarshal(body,&jdata) - if (err != nil) { - return retData,fmt.Errorf("Error unmarshalling response for deputy key check: %v", + err = json.Unmarshal(body, &jdata) + if err != nil { + return retData, fmt.Errorf("Error unmarshalling response for deputy key check: %v", err) } //Populate success/failure - for _,comp := range(jdata.Success) { - delete(rmap,comp.ID) + for _, comp := range jdata.Success { + delete(rmap, comp.ID) retData.Success = append(retData.Success, ReservationCheckSuccessResponse{ID: comp.ID, - DeputyKey: comp.DeputyKey, + DeputyKey: comp.DeputyKey, ExpirationTime: comp.ExpirationTime}) } - for _,comp := range(jdata.Failure) { - delete(rmap,comp.ID) + for _, comp := range jdata.Failure { + delete(rmap, comp.ID) retData.Failure = append(retData.Failure, FailureResponse{ID: comp.ID, Reason: comp.Reason}) } //Any remaining map entries mean the key was not found or was invalid. - for k,_ := range(rmap) { + for k, _ := range rmap { retData.Failure = append(retData.Failure, FailureResponse{ID: k, Reason: "Key not found, invalid, or expired"}) } - default: - return retData,fmt.Errorf("Error response from deputy key check: %d", + return retData, fmt.Errorf("Error response from deputy key check: %d", statusCode) } - return retData,nil + return retData, nil } - diff --git a/pkg/sharedtest/util.go b/pkg/sharedtest/util.go index be9ecc0..fda4414 100644 --- a/pkg/sharedtest/util.go +++ b/pkg/sharedtest/util.go @@ -22,9 +22,7 @@ package sharedtest -import ( - base "github.com/Cray-HPE/hms-base" -) +import base "github.com/Cray-HPE/hms-base/v2" func CompareComp(comp1 *base.Component, comp2 *base.Component) bool { return CompareComps([]*base.Component{comp1}, []*base.Component{comp2}) diff --git a/pkg/sm/compethinterfaces.go b/pkg/sm/compethinterfaces.go index 172c17f..01000db 100644 --- a/pkg/sm/compethinterfaces.go +++ b/pkg/sm/compethinterfaces.go @@ -28,7 +28,8 @@ package sm import ( "strings" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // @@ -75,11 +76,11 @@ func NewCompEthInterface(desc, macAddr, ipAddr, compID string) (*CompEthInterfac } cei.IPAddr = ipAddr if compID != "" { - cei.CompID = base.VerifyNormalizeCompID(compID) + cei.CompID = xnametypes.VerifyNormalizeCompID(compID) if cei.CompID == "" { return nil, ErrCompEthInterfaceBadCompID } - cei.Type = base.GetHMSTypeString(cei.CompID) + cei.Type = xnametypes.GetHMSTypeString(cei.CompID) } return cei, nil } @@ -150,11 +151,11 @@ func NewCompEthInterfaceV2(desc, macAddr, compID string, ipAddrs []IPAddressMapp } } if compID != "" { - cei.CompID = base.VerifyNormalizeCompID(compID) + cei.CompID = xnametypes.VerifyNormalizeCompID(compID) if cei.CompID == "" { return nil, ErrCompEthInterfaceBadCompID } - cei.Type = base.GetHMSTypeString(cei.CompID) + cei.Type = xnametypes.GetHMSTypeString(cei.CompID) } return cei, nil } diff --git a/pkg/sm/compethinterfaces_test.go b/pkg/sm/compethinterfaces_test.go index d88d653..5dee1ae 100644 --- a/pkg/sm/compethinterfaces_test.go +++ b/pkg/sm/compethinterfaces_test.go @@ -26,7 +26,7 @@ import ( "reflect" "testing" - base "github.com/Cray-HPE/hms-base" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // @@ -52,7 +52,7 @@ func TestNewCompEthInterface(t *testing.T) { MACAddr: "a4:bf:01:38:ee:65", IPAddr: "10.254.2.14", CompID: "x3000c0s26b0", - Type: base.NodeBMC.String(), + Type: xnametypes.NodeBMC.String(), }, expectedErr: nil, }, { // Test 1 - Minimal info @@ -109,7 +109,7 @@ func TestNewCompEthInterfaceV2(t *testing.T) { {IPAddr: "10.254.2.14"}, }, CompID: "x3000c0s26b0", - Type: base.NodeBMC.String(), + Type: xnametypes.NodeBMC.String(), }, expectedErr: nil, }, { // Test 1 - Minimal info @@ -167,7 +167,7 @@ func TestCompEthInterfaceV2ToV1(t *testing.T) { MACAddr: "a4:bf:01:38:ee:65", IPAddr: "10.254.2.14", CompID: "x3000c0s26b0", - Type: base.NodeBMC.String(), + Type: xnametypes.NodeBMC.String(), }, }, { // Test 1 - Minimal info macAddr: "a4:bf:01:38:ee:65", @@ -189,7 +189,7 @@ func TestCompEthInterfaceV2ToV1(t *testing.T) { MACAddr: "a4:bf:01:38:ee:65", IPAddr: "10.254.2.14", CompID: "x3000c0s26b0", - Type: base.NodeBMC.String(), + Type: xnametypes.NodeBMC.String(), }, }} for i, test := range tests { diff --git a/pkg/sm/complocks.go b/pkg/sm/complocks.go index 7e1777d..5e02082 100644 --- a/pkg/sm/complocks.go +++ b/pkg/sm/complocks.go @@ -29,7 +29,8 @@ package sm import ( "strings" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) ////////////////////////////// @@ -66,7 +67,7 @@ const ( var processingModelMap = map[string]bool{ CLProcessingModelRigid: true, - CLProcessingModelFlex: true, + CLProcessingModelFlex: true, } func VerifyNormalizeProcessingModel(pm string) string { @@ -198,7 +199,7 @@ func (cl *CompLockV2Filter) VerifyNormalize() error { } func (clk *CompLockV2Key) VerifyNormalize() error { - clk.ID = base.VerifyNormalizeCompID(clk.ID) + clk.ID = xnametypes.VerifyNormalizeCompID(clk.ID) if clk.ID == "" { return base.ErrHMSTypeInvalid } diff --git a/pkg/sm/complocks_test.go b/pkg/sm/complocks_test.go index 1e6db4b..b92e9f7 100644 --- a/pkg/sm/complocks_test.go +++ b/pkg/sm/complocks_test.go @@ -28,7 +28,7 @@ import ( "reflect" "testing" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" ) // diff --git a/pkg/sm/comps.go b/pkg/sm/comps.go index fd4f7fd..8ea5daf 100644 --- a/pkg/sm/comps.go +++ b/pkg/sm/comps.go @@ -24,7 +24,9 @@ package sm import ( "fmt" - base "github.com/Cray-HPE/hms-base" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // The payload for a Components POST @@ -45,12 +47,12 @@ func NewCompPost(comps []base.Component, force bool) (*ComponentsPost, error) { cp := new(ComponentsPost) for _, comp := range comps { c := new(base.Component) - c.ID = base.VerifyNormalizeCompID(comp.ID) + c.ID = xnametypes.VerifyNormalizeCompID(comp.ID) if len(c.ID) == 0 { err := fmt.Errorf("xname ID '%s' is invalid", comp.ID) return nil, err } - c.Type = base.GetHMSTypeString(c.ID) + c.Type = xnametypes.GetHMSTypeString(c.ID) c.State = base.VerifyNormalizeState(comp.State) if len(c.State) == 0 { err := fmt.Errorf("state '%s' is invalid", comp.State) @@ -108,14 +110,14 @@ func NewCompPost(comps []base.Component, force bool) (*ComponentsPost, error) { func (cp *ComponentsPost) VerifyNormalize() error { for _, comp := range cp.Components { - normID := base.VerifyNormalizeCompID(comp.ID) + normID := xnametypes.VerifyNormalizeCompID(comp.ID) if len(normID) == 0 { err := fmt.Errorf("xname ID '%s' is invalid", comp.ID) return err } else { comp.ID = normID } - comp.Type = base.GetHMSTypeString(comp.ID) + comp.Type = xnametypes.GetHMSTypeString(comp.ID) normState := base.VerifyNormalizeState(comp.State) if len(normState) == 0 { err := fmt.Errorf("state '%s' is invalid", comp.State) @@ -184,12 +186,12 @@ func (cp *ComponentsPost) VerifyNormalize() error { func NewCompPut(comp base.Component, force bool) (*ComponentPut, error) { cp := new(ComponentPut) c := &cp.Component - c.ID = base.VerifyNormalizeCompID(comp.ID) + c.ID = xnametypes.VerifyNormalizeCompID(comp.ID) if len(c.ID) == 0 { err := fmt.Errorf("xname ID '%s' is invalid", comp.ID) return nil, err } - c.Type = base.GetHMSTypeString(c.ID) + c.Type = xnametypes.GetHMSTypeString(c.ID) c.State = base.VerifyNormalizeState(comp.State) if len(c.State) == 0 { err := fmt.Errorf("state '%s' is invalid", comp.State) @@ -245,14 +247,14 @@ func NewCompPut(comp base.Component, force bool) (*ComponentPut, error) { func (cp *ComponentPut) VerifyNormalize() error { c := &cp.Component - normID := base.VerifyNormalizeCompID(c.ID) + normID := xnametypes.VerifyNormalizeCompID(c.ID) if len(normID) == 0 { err := fmt.Errorf("xname ID '%s' is invalid", c.ID) return err } else { c.ID = normID } - c.Type = base.GetHMSTypeString(c.ID) + c.Type = xnametypes.GetHMSTypeString(c.ID) normState := base.VerifyNormalizeState(c.State) if len(normState) == 0 { err := fmt.Errorf("state '%s' is invalid", c.State) diff --git a/pkg/sm/comps_test.go b/pkg/sm/comps_test.go index a52a838..35039ed 100644 --- a/pkg/sm/comps_test.go +++ b/pkg/sm/comps_test.go @@ -25,8 +25,10 @@ package sm import ( "fmt" "reflect" - base "github.com/Cray-HPE/hms-base" "testing" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // @@ -50,7 +52,7 @@ func TestNewCompPost(t *testing.T) { Components: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -137,7 +139,7 @@ func TestNewCompPost(t *testing.T) { Components: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), Role: base.RoleCompute.String(), @@ -146,7 +148,7 @@ func TestNewCompPost(t *testing.T) { }, &base.Component{ ID: "x0c0s0b0n1", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -190,7 +192,7 @@ func TestVerifyNormalizeCompPost(t *testing.T) { Components: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -388,7 +390,7 @@ func TestVerifyNormalizeCompPost(t *testing.T) { Components: []*base.Component{ &base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), Role: base.RoleCompute.String(), @@ -397,7 +399,7 @@ func TestVerifyNormalizeCompPost(t *testing.T) { }, &base.Component{ ID: "x0c0s0b0n1", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -434,7 +436,7 @@ func TestNewCompPut(t *testing.T) { expectedOut: &ComponentPut{ Component: base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -512,7 +514,7 @@ func TestNewCompPut(t *testing.T) { expectedOut: &ComponentPut{ Component: base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), Role: base.RoleCompute.String(), @@ -551,7 +553,7 @@ func TestVerifyNormalizeCompPut(t *testing.T) { expectedOut: ComponentPut{ Component: base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), }, @@ -688,7 +690,7 @@ func TestVerifyNormalizeCompPut(t *testing.T) { expectedOut: ComponentPut{ Component: base.Component{ ID: "x0c0s0b0n0", - Type: base.Node.String(), + Type: xnametypes.Node.String(), State: base.StateEmpty.String(), Flag: base.FlagOK.String(), Role: base.RoleCompute.String(), diff --git a/pkg/sm/endpoints.go b/pkg/sm/endpoints.go index 35c2e79..0e18243 100644 --- a/pkg/sm/endpoints.go +++ b/pkg/sm/endpoints.go @@ -24,7 +24,8 @@ package sm import ( "encoding/json" - base "github.com/Cray-HPE/hms-base" + + base "github.com/Cray-HPE/hms-base/v2" rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" ) @@ -158,7 +159,8 @@ type ComponentEndpointArray struct { // RF type-specific name. // // NOTEs: The location info should be that produced by EncodeComponentInfo. -// MODIFIES caller. +// +// MODIFIES caller. func (cep *ComponentEndpoint) DecodeComponentInfo(infoJSON []byte) error { var err error diff --git a/pkg/sm/events.go b/pkg/sm/events.go index 54ecff1..80654a3 100644 --- a/pkg/sm/events.go +++ b/pkg/sm/events.go @@ -22,9 +22,7 @@ package sm -import ( - base "github.com/Cray-HPE/hms-base" -) +import base "github.com/Cray-HPE/hms-base/v2" type SMEventType string diff --git a/pkg/sm/groups.go b/pkg/sm/groups.go index e2727d5..84caf08 100644 --- a/pkg/sm/groups.go +++ b/pkg/sm/groups.go @@ -26,8 +26,10 @@ package sm import ( "regexp" - base "github.com/Cray-HPE/hms-base" "strings" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // @@ -91,7 +93,7 @@ func (ms *Members) Verify() error { } ms.verified = true for _, id := range ms.IDs { - if ok := base.IsHMSCompIDValid(id); ok == false { + if ok := xnametypes.IsHMSCompIDValid(id); ok == false { return base.ErrHMSTypeInvalid } } @@ -105,7 +107,7 @@ func (ms *Members) Normalize() { } ms.normalized = true for i, id := range ms.IDs { - ms.IDs[i] = base.NormalizeHMSCompID(id) + ms.IDs[i] = xnametypes.NormalizeHMSCompID(id) } } @@ -161,7 +163,7 @@ func (g *Group) Normalize() { } // Check input fields of a group. If no error is returned, the result should -// be ok to put into the database. +// be ok to put into the dataxnametypes. func (g *Group) Verify() error { if g.verified == true { return nil @@ -265,14 +267,14 @@ func (p *Partition) Normalize() { } // Check input fields of a group. If no error is returned, the result should -// be ok to put into the database. +// be ok to put into the dataxnametypes. func (p *Partition) Verify() error { if p.verified == true { return nil } p.verified = true - if base.GetHMSType(p.Name) != base.Partition { + if xnametypes.GetHMSType(p.Name) != xnametypes.Partition { return ErrPartBadName } for _, f := range p.Tags { diff --git a/pkg/sm/groups_test.go b/pkg/sm/groups_test.go index 477d190..18dffdf 100644 --- a/pkg/sm/groups_test.go +++ b/pkg/sm/groups_test.go @@ -24,8 +24,9 @@ package sm import ( "reflect" - base "github.com/Cray-HPE/hms-base" "testing" + + base "github.com/Cray-HPE/hms-base/v2" ) // diff --git a/pkg/sm/hwinv.go b/pkg/sm/hwinv.go index 1f6ae0a..b19f00d 100644 --- a/pkg/sm/hwinv.go +++ b/pkg/sm/hwinv.go @@ -27,8 +27,9 @@ import ( "regexp" "strconv" - base "github.com/Cray-HPE/hms-base" + base "github.com/Cray-HPE/hms-base/v2" rf "github.com/Cray-HPE/hms-smd/v2/pkg/redfish" + "github.com/Cray-HPE/hms-xname/xnametypes" ) var ErrHWLocInvalid = base.NewHMSError("sm", "ID is empty or not a valid xname") @@ -159,143 +160,143 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW } var err error for _, hwloc := range hwlocs { - switch base.ToHMSType(hwloc.Type) { + switch xnametypes.ToHMSType(hwloc.Type) { // HWInv based on Redfish "Chassis" Type. - case base.Cabinet: + case xnametypes.Cabinet: if hwinv.Cabinets == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.Cabinets = &arr } *hwinv.Cabinets = append(*hwinv.Cabinets, hwloc) - case base.Chassis: + case xnametypes.Chassis: if hwinv.Chassis == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.Chassis = &arr } *hwinv.Chassis = append(*hwinv.Chassis, hwloc) - case base.ComputeModule: + case xnametypes.ComputeModule: if hwinv.ComputeModules == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.ComputeModules = &arr } *hwinv.ComputeModules = append(*hwinv.ComputeModules, hwloc) - case base.RouterModule: + case xnametypes.RouterModule: if hwinv.RouterModules == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.RouterModules = &arr } *hwinv.RouterModules = append(*hwinv.RouterModules, hwloc) - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: if hwinv.NodeEnclosures == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.NodeEnclosures = &arr } *hwinv.NodeEnclosures = append(*hwinv.NodeEnclosures, hwloc) - case base.HSNBoard: + case xnametypes.HSNBoard: if hwinv.HSNBoards == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.HSNBoards = &arr } *hwinv.HSNBoards = append(*hwinv.HSNBoards, hwloc) - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: if hwinv.MgmtSwitches == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.MgmtSwitches = &arr } *hwinv.MgmtSwitches = append(*hwinv.MgmtSwitches, hwloc) - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: if hwinv.MgmtHLSwitches == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.MgmtHLSwitches = &arr } *hwinv.MgmtHLSwitches = append(*hwinv.MgmtHLSwitches, hwloc) - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: if hwinv.CDUMgmtSwitches == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.CDUMgmtSwitches = &arr } *hwinv.CDUMgmtSwitches = append(*hwinv.CDUMgmtSwitches, hwloc) - case base.Node: + case xnametypes.Node: if hwinv.Nodes == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.Nodes = &arr } *hwinv.Nodes = append(*hwinv.Nodes, hwloc) - case base.NodeAccel: + case xnametypes.NodeAccel: if hwinv.NodeAccels == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.NodeAccels = &arr } *hwinv.NodeAccels = append(*hwinv.NodeAccels, hwloc) - case base.Processor: + case xnametypes.Processor: if hwinv.Processors == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.Processors = &arr } *hwinv.Processors = append(*hwinv.Processors, hwloc) - case base.Memory: + case xnametypes.Memory: if hwinv.Memory == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.Memory = &arr } *hwinv.Memory = append(*hwinv.Memory, hwloc) - case base.Drive: + case xnametypes.Drive: if hwinv.Drives == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.Drives = &arr } *hwinv.Drives = append(*hwinv.Drives, hwloc) - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: if hwinv.NodeHsnNICs == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.NodeHsnNICs = &arr } *hwinv.NodeHsnNICs = append(*hwinv.NodeHsnNICs, hwloc) - case base.CabinetPDU: + case xnametypes.CabinetPDU: if hwinv.CabinetPDUs == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.CabinetPDUs = &arr } *hwinv.CabinetPDUs = append(*hwinv.CabinetPDUs, hwloc) - case base.CabinetPDUOutlet: + case xnametypes.CabinetPDUOutlet: fallthrough - case base.CabinetPDUPowerConnector: + case xnametypes.CabinetPDUPowerConnector: if hwinv.CabinetPDUOutlets == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.CabinetPDUOutlets = &arr } *hwinv.CabinetPDUOutlets = append(*hwinv.CabinetPDUOutlets, hwloc) - case base.CMMRectifier: + case xnametypes.CMMRectifier: if hwinv.CMMRectifiers == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.CMMRectifiers = &arr } *hwinv.CMMRectifiers = append(*hwinv.CMMRectifiers, hwloc) - case base.NodeEnclosurePowerSupply: + case xnametypes.NodeEnclosurePowerSupply: if hwinv.NodeEnclosurePowerSupplies == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.NodeEnclosurePowerSupplies = &arr } *hwinv.NodeEnclosurePowerSupplies = append(*hwinv.NodeEnclosurePowerSupplies, hwloc) - case base.NodeAccelRiser: + case xnametypes.NodeAccelRiser: if hwinv.NodeAccelRisers == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.NodeAccelRisers = &arr } *hwinv.NodeAccelRisers = append(*hwinv.NodeAccelRisers, hwloc) - case base.NodeBMC: + case xnametypes.NodeBMC: if hwinv.NodeBMCs == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.NodeBMCs = &arr } *hwinv.NodeBMCs = append(*hwinv.NodeBMCs, hwloc) - case base.RouterBMC: + case xnametypes.RouterBMC: if hwinv.RouterBMCs == nil { arr := make([]*HWInvByLoc, 0, 1) hwinv.RouterBMCs = &arr } *hwinv.RouterBMCs = append(*hwinv.RouterBMCs, hwloc) - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err = base.ErrHMSTypeInvalid // Not supported for this type. default: @@ -341,7 +342,7 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW // Processors are children of Node if procArray != nil { for _, p := range *procArray { - parentID := base.GetHMSCompParent(p.ID) + parentID := xnametypes.GetHMSCompParent(p.ID) parent, ok := nmap[parentID] if !ok { errlog.Printf("ERROR: Could not find node key %s for %s", @@ -364,7 +365,7 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW // NodeAccels (GPUs) are children of Node if nodeAccelArray != nil { for _, na := range *nodeAccelArray { - parentID := base.GetHMSCompParent(na.ID) + parentID := xnametypes.GetHMSCompParent(na.ID) parent, ok := nmap[parentID] if !ok { errlog.Printf("ERROR: Could not find node key %s for %s", @@ -387,7 +388,7 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW // Memory modules are children of Node if memArray != nil { for _, m := range *memArray { - parentID := base.GetHMSCompParent(m.ID) + parentID := xnametypes.GetHMSCompParent(m.ID) parent, ok := nmap[parentID] if !ok { errlog.Printf("ERROR: Could not find node key %s for %s", @@ -412,8 +413,8 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW if driveArray != nil { for _, d := range *driveArray { parentID := d.ID - for base.GetHMSType(parentID) != base.Node { - parentID = base.GetHMSCompParent(parentID) + for xnametypes.GetHMSType(parentID) != xnametypes.Node { + parentID = xnametypes.GetHMSCompParent(parentID) } parent, ok := nmap[parentID] if !ok { @@ -438,7 +439,7 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW // HSN NICs are children of Nodes if hsnNicArray != nil { for _, n := range *hsnNicArray { - parentID := base.GetHMSCompParent(n.ID) + parentID := xnametypes.GetHMSCompParent(n.ID) parent, ok := nmap[parentID] if !ok { errlog.Printf("ERROR: Could not find node key %s for %s", @@ -462,7 +463,7 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW // NodeAccelRisers are children of Nodes if nodeAccelRiserArray != nil { for _, n := range *nodeAccelRiserArray { - parentID := base.GetHMSCompParent(n.ID) + parentID := xnametypes.GetHMSCompParent(n.ID) parent, ok := nmap[parentID] if !ok { errlog.Printf("ERROR: Could not find node key %s for %s", @@ -504,7 +505,7 @@ func NewSystemHWInventory(hwlocs []*HWInvByLoc, xName, format string) (*SystemHW // CabinetPDUOutlets are children of CabinetPDUs if cabPDUArray != nil { for _, out := range *cabPDUArray { - parentID := base.GetHMSCompParent(out.ID) + parentID := xnametypes.GetHMSCompParent(out.ID) parent, ok := pdumap[parentID] if !ok { errlog.Printf("ERROR: Could not find pdu key %s for %s", @@ -543,9 +544,9 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { re := regexp.MustCompile(`[0-9]+$`) for _, hwloc := range hwlocs { - hwloc.ID = base.NormalizeHMSCompID(hwloc.ID) - hmsType := base.GetHMSType(hwloc.ID) - if hmsType == base.HMSTypeInvalid { + hwloc.ID = xnametypes.NormalizeHMSCompID(hwloc.ID) + hmsType := xnametypes.GetHMSType(hwloc.ID) + if hmsType == xnametypes.HMSTypeInvalid { return hls, ErrHWLocInvalid //TODO: Define error } hwloc.Type = hmsType.String() @@ -557,7 +558,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { } hwloc.PopulatedFRU.Type = hwloc.Type switch hmsType { - case base.Cabinet: + case xnametypes.Cabinet: if hwloc.HMSCabinetLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -577,7 +578,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.Chassis: + case xnametypes.Chassis: if hwloc.HMSChassisLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -597,7 +598,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.ComputeModule: + case xnametypes.ComputeModule: if hwloc.HMSComputeModuleLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -617,7 +618,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.RouterModule: + case xnametypes.RouterModule: if hwloc.HMSRouterModuleLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -637,7 +638,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: if hwloc.HMSNodeEnclosureLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -657,7 +658,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.HSNBoard: + case xnametypes.HSNBoard: if hwloc.HMSHSNBoardLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -677,7 +678,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: if hwloc.HMSMgmtSwitchLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -697,7 +698,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: if hwloc.HMSMgmtHLSwitchLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -717,7 +718,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: if hwloc.HMSCDUMgmtSwitchLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -737,7 +738,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.Node: + case xnametypes.Node: if hwloc.HMSNodeLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -757,7 +758,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.NodeAccel: + case xnametypes.NodeAccel: if hwloc.HMSNodeAccelLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -777,7 +778,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.Processor: + case xnametypes.Processor: if hwloc.HMSProcessorLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -797,7 +798,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.Memory: + case xnametypes.Memory: if hwloc.HMSMemoryLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -817,7 +818,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.Drive: + case xnametypes.Drive: if hwloc.HMSDriveLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -837,7 +838,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: if hwloc.HMSHSNNICLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -851,7 +852,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.CabinetPDU: + case xnametypes.CabinetPDU: if hwloc.HMSPDULocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -871,9 +872,9 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.CabinetPDUOutlet: + case xnametypes.CabinetPDUOutlet: fallthrough - case base.CabinetPDUPowerConnector: + case xnametypes.CabinetPDUPowerConnector: if hwloc.HMSOutletLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -887,7 +888,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { if hwloc.PopulatedFRU.FRUID == "" { hwloc.PopulatedFRU.FRUID = "FRUIDfor" + hwloc.ID } - case base.CMMRectifier: + case xnametypes.CMMRectifier: if hwloc.HMSCMMRectifierLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -910,7 +911,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.NodeEnclosurePowerSupply: + case xnametypes.NodeEnclosurePowerSupply: if hwloc.HMSNodeEnclosurePowerSupplyLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -933,7 +934,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.NodeAccelRiser: + case xnametypes.NodeAccelRiser: if hwloc.HMSNodeAccelRiserLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -957,7 +958,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.NodeBMC: + case xnametypes.NodeBMC: if hwloc.HMSNodeBMCLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -977,7 +978,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.RouterBMC: + case xnametypes.RouterBMC: if hwloc.HMSRouterBMCLocationInfo == nil { return hls, ErrHWInvMissingLoc } @@ -997,7 +998,7 @@ func NewHWInvByLocs(hwlocs []HWInvByLoc) ([]*HWInvByLoc, error) { errlog.Printf("FRUID Error: %s\n", err.Error()) errlog.Printf("Using untrackable FRUID: %s\n", hwloc.PopulatedFRU.FRUID) } - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: return hls, base.ErrHMSTypeInvalid // Not supported for this type. default: @@ -1100,10 +1101,12 @@ const ( // for the type with the proper type-specific name. // // NOTEs: The location info should be that produced by EncodeLocationInfo. -// MODIFIES caller. +// +// MODIFIES caller. // // Return: If err != nil hw is unmodified, -// Else, the type's *LocationInfo pointer is set to the expected struct. +// +// Else, the type's *LocationInfo pointer is set to the expected struct. func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { var ( err error @@ -1123,61 +1126,61 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { rfNodeAccelRiserLocationInfo *rf.NodeAccelRiserLocationInfoRF ) - switch base.ToHMSType(hw.Type) { + switch xnametypes.ToHMSType(hw.Type) { // HWInv based on Redfish "Chassis" Type. Identical structs (for now). - case base.Cabinet: + case xnametypes.Cabinet: fallthrough - case base.Chassis: + case xnametypes.Chassis: fallthrough - case base.ComputeModule: + case xnametypes.ComputeModule: fallthrough - case base.RouterModule: + case xnametypes.RouterModule: fallthrough - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: fallthrough - case base.HSNBoard: + case xnametypes.HSNBoard: fallthrough - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: fallthrough - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: fallthrough - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: rfChassisLocationInfo = new(rf.ChassisLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfChassisLocationInfo) if err == nil { // Assign struct to appropriate name for type. - switch base.ToHMSType(hw.Type) { - case base.Cabinet: + switch xnametypes.ToHMSType(hw.Type) { + case xnametypes.Cabinet: hw.HMSCabinetLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocCabinet - case base.Chassis: + case xnametypes.Chassis: hw.HMSChassisLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocChassis - case base.ComputeModule: + case xnametypes.ComputeModule: hw.HMSComputeModuleLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocComputeModule - case base.RouterModule: + case xnametypes.RouterModule: hw.HMSRouterModuleLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocRouterModule - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: hw.HMSNodeEnclosureLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocNodeEnclosure - case base.HSNBoard: + case xnametypes.HSNBoard: hw.HMSHSNBoardLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocHSNBoard - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: hw.HMSMgmtSwitchLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocMgmtSwitch - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: hw.HMSMgmtHLSwitchLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocMgmtHLSwitch - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: hw.HMSCDUMgmtSwitchLocationInfo = rfChassisLocationInfo hw.HWInventoryByLocationType = HWInvByLocCDUMgmtSwitch } } // HWInv based on Redfish "System" Type. - case base.Node: + case xnametypes.Node: rfSystemLocationInfo = new(rf.SystemLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfSystemLocationInfo) if err == nil { @@ -1185,7 +1188,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocNode } // HWInv based on "GPU" type - case base.NodeAccel: + case xnametypes.NodeAccel: rfNodeAccelLocationInfo = new(rf.ProcessorLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfNodeAccelLocationInfo) if err == nil { @@ -1193,7 +1196,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocNodeAccel } // HWInv based on Redfish "Processor" Type. - case base.Processor: + case xnametypes.Processor: rfProcessorLocationInfo = new(rf.ProcessorLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfProcessorLocationInfo) if err == nil { @@ -1201,7 +1204,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocProcessor } // HWInv based on Redfish "Memory" Type. - case base.Memory: + case xnametypes.Memory: rfMemoryLocationInfo = new(rf.MemoryLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfMemoryLocationInfo) if err == nil { @@ -1209,7 +1212,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocMemory } // HWInv based on Redfish "Drive" Type. - case base.Drive: + case xnametypes.Drive: rfDriveLocationInfo = new(rf.DriveLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfDriveLocationInfo) if err == nil { @@ -1217,7 +1220,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocDrive } // HWInv based on Redfish "HSN NIC" Type. - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: rfHSNNICLocationInfo = new(rf.NALocationInfoRF) err = json.Unmarshal(locInfoJSON, rfHSNNICLocationInfo) if err == nil { @@ -1225,7 +1228,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocHSNNIC } // HWInv based on Redfish "PowerDistribution" (aka PDU) Type. - case base.CabinetPDU: + case xnametypes.CabinetPDU: rfPDULocationInfo = new(rf.PowerDistributionLocationInfo) err = json.Unmarshal(locInfoJSON, rfPDULocationInfo) if err == nil { @@ -1233,44 +1236,44 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocPDU } // HWInv based on Redfish "Outlet" (e.g. of a PDU) Type. - case base.CabinetPDUOutlet: + case xnametypes.CabinetPDUOutlet: fallthrough - case base.CabinetPDUPowerConnector: + case xnametypes.CabinetPDUPowerConnector: rfOutletLocationInfo = new(rf.OutletLocationInfo) err = json.Unmarshal(locInfoJSON, rfOutletLocationInfo) if err == nil { hw.HMSOutletLocationInfo = rfOutletLocationInfo hw.HWInventoryByLocationType = HWInvByLocOutlet } - case base.CMMRectifier: + case xnametypes.CMMRectifier: rfCMMRectifierLocationInfo = new(rf.PowerSupplyLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfCMMRectifierLocationInfo) if err == nil { hw.HMSCMMRectifierLocationInfo = rfCMMRectifierLocationInfo hw.HWInventoryByLocationType = HWInvByLocCMMRectifier } - case base.NodeEnclosurePowerSupply: + case xnametypes.NodeEnclosurePowerSupply: rfNodeEnclosurePowerSupplyLocationInfo = new(rf.PowerSupplyLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfNodeEnclosurePowerSupplyLocationInfo) if err == nil { hw.HMSNodeEnclosurePowerSupplyLocationInfo = rfNodeEnclosurePowerSupplyLocationInfo hw.HWInventoryByLocationType = HWInvByLocNodeEnclosurePowerSupply } - case base.NodeAccelRiser: + case xnametypes.NodeAccelRiser: rfNodeAccelRiserLocationInfo = new(rf.NodeAccelRiserLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfNodeAccelRiserLocationInfo) if err == nil { hw.HMSNodeAccelRiserLocationInfo = rfNodeAccelRiserLocationInfo hw.HWInventoryByLocationType = HWInvByLocNodeAccelRiser } - case base.NodeBMC: + case xnametypes.NodeBMC: rfNodeBMCLocationInfo = new(rf.ManagerLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfNodeBMCLocationInfo) if err == nil { hw.HMSNodeBMCLocationInfo = rfNodeBMCLocationInfo hw.HWInventoryByLocationType = HWInvByLocNodeBMC } - case base.RouterBMC: + case xnametypes.RouterBMC: rfRouterBMCLocationInfo = new(rf.ManagerLocationInfoRF) err = json.Unmarshal(locInfoJSON, rfRouterBMCLocationInfo) if err == nil { @@ -1278,7 +1281,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { hw.HWInventoryByLocationType = HWInvByLocRouterBMC } // No match - not a valid HMSType, always an error - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err = base.ErrHMSTypeInvalid default: err = base.ErrHMSTypeUnsupported @@ -1286,77 +1289,77 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { return err } -// // This function encode's the hwinv's type-specific LocationInfo struct // into a free-form JSON byte array that can be stored schema-less in the -// database. +// dataxnametypes. // // NOTE: This function is the counterpart to DecodeLocationInfo(). // // Returns: type's location info as JSON []byte representation, err = nil -// Else, err != nil if encoding failed (and location_info is empty) +// +// Else, err != nil if encoding failed (and location_info is empty) func (hw *HWInvByLoc) EncodeLocationInfo() ([]byte, error) { var err error var locInfoJSON []byte - switch base.ToHMSType(hw.Type) { + switch xnametypes.ToHMSType(hw.Type) { // HWInv based on Redfish "Chassis" Type. - case base.Cabinet: + case xnametypes.Cabinet: locInfoJSON, err = json.Marshal(hw.HMSCabinetLocationInfo) - case base.Chassis: + case xnametypes.Chassis: locInfoJSON, err = json.Marshal(hw.HMSChassisLocationInfo) - case base.ComputeModule: + case xnametypes.ComputeModule: locInfoJSON, err = json.Marshal(hw.HMSComputeModuleLocationInfo) - case base.RouterModule: + case xnametypes.RouterModule: locInfoJSON, err = json.Marshal(hw.HMSRouterModuleLocationInfo) - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: locInfoJSON, err = json.Marshal(hw.HMSNodeEnclosureLocationInfo) - case base.HSNBoard: + case xnametypes.HSNBoard: locInfoJSON, err = json.Marshal(hw.HMSHSNBoardLocationInfo) - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: locInfoJSON, err = json.Marshal(hw.HMSMgmtSwitchLocationInfo) - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: locInfoJSON, err = json.Marshal(hw.HMSMgmtHLSwitchLocationInfo) - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: locInfoJSON, err = json.Marshal(hw.HMSCDUMgmtSwitchLocationInfo) // HWInv based on Redfish "System" Type. - case base.Node: + case xnametypes.Node: locInfoJSON, err = json.Marshal(hw.HMSNodeLocationInfo) // HWInv based on "GPU" type - case base.NodeAccel: + case xnametypes.NodeAccel: locInfoJSON, err = json.Marshal(hw.HMSNodeAccelLocationInfo) // HWInv based on Redfish "Processor" Type. - case base.Processor: + case xnametypes.Processor: locInfoJSON, err = json.Marshal(hw.HMSProcessorLocationInfo) // HWInv based on Redfish "Memory" Type. - case base.Memory: + case xnametypes.Memory: locInfoJSON, err = json.Marshal(hw.HMSMemoryLocationInfo) // HWInv based on Redfish "Drive" Type. - case base.Drive: + case xnametypes.Drive: locInfoJSON, err = json.Marshal(hw.HMSDriveLocationInfo) // HWInv based on Redfish "HSN NIC" Type. - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: locInfoJSON, err = json.Marshal(hw.HMSHSNNICLocationInfo) // HWInv based on Redfish "PowerDistribution" (aka PDU) Type. - case base.CabinetPDU: + case xnametypes.CabinetPDU: locInfoJSON, err = json.Marshal(hw.HMSPDULocationInfo) // HWInv based on Redfish "Outlet" (e.g. of a PDU) Type. - case base.CabinetPDUOutlet: + case xnametypes.CabinetPDUOutlet: fallthrough - case base.CabinetPDUPowerConnector: + case xnametypes.CabinetPDUPowerConnector: locInfoJSON, err = json.Marshal(hw.HMSOutletLocationInfo) - case base.CMMRectifier: + case xnametypes.CMMRectifier: locInfoJSON, err = json.Marshal(hw.HMSCMMRectifierLocationInfo) - case base.NodeEnclosurePowerSupply: + case xnametypes.NodeEnclosurePowerSupply: locInfoJSON, err = json.Marshal(hw.HMSNodeEnclosurePowerSupplyLocationInfo) - case base.NodeAccelRiser: + case xnametypes.NodeAccelRiser: locInfoJSON, err = json.Marshal(hw.HMSNodeAccelRiserLocationInfo) - case base.NodeBMC: + case xnametypes.NodeBMC: locInfoJSON, err = json.Marshal(hw.HMSNodeBMCLocationInfo) - case base.RouterBMC: + case xnametypes.RouterBMC: locInfoJSON, err = json.Marshal(hw.HMSRouterBMCLocationInfo) // No match - not a valid HMS Type, always an error - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err = base.ErrHMSTypeInvalid // Not supported for this type. default: @@ -1450,10 +1453,12 @@ const ( // for the type with the proper type-specific name. // // NOTEs: The fruInfoJSON array should be that produced by EncodeFRUInfo. -// MODIFIES caller. +// +// MODIFIES caller. // // Return: If err != nil hf is unmodified and operation failed. -// Else, the type's *FRUInfo pointer is set to the expected struct. +// +// Else, the type's *FRUInfo pointer is set to the expected struct. func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { var ( err error = nil @@ -1473,61 +1478,61 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { rfNodeAccelRiserFRUInfo *rf.NodeAccelRiserFRUInfoRF ) - switch base.ToHMSType(hf.Type) { + switch xnametypes.ToHMSType(hf.Type) { // HWInv based on Redfish "Chassis" Type. Identical structs (for now). - case base.Cabinet: + case xnametypes.Cabinet: fallthrough - case base.Chassis: + case xnametypes.Chassis: fallthrough - case base.ComputeModule: + case xnametypes.ComputeModule: fallthrough - case base.RouterModule: + case xnametypes.RouterModule: fallthrough - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: fallthrough - case base.HSNBoard: + case xnametypes.HSNBoard: fallthrough - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: fallthrough - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: fallthrough - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: rfChassisFRUInfo = new(rf.ChassisFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfChassisFRUInfo) if err == nil { // Assign struct to appropriate name for type. - switch base.ToHMSType(hf.Type) { - case base.Cabinet: + switch xnametypes.ToHMSType(hf.Type) { + case xnametypes.Cabinet: hf.HMSCabinetFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUCabinet - case base.Chassis: + case xnametypes.Chassis: hf.HMSChassisFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUChassis - case base.ComputeModule: + case xnametypes.ComputeModule: hf.HMSComputeModuleFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUComputeModule - case base.RouterModule: + case xnametypes.RouterModule: hf.HMSRouterModuleFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRURouterModule - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: hf.HMSNodeEnclosureFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUNodeEnclosure - case base.HSNBoard: + case xnametypes.HSNBoard: hf.HMSHSNBoardFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUHSNBoard - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: hf.HMSMgmtSwitchFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUMgmtSwitch - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: hf.HMSMgmtHLSwitchFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUMgmtHLSwitch - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: hf.HMSCDUMgmtSwitchFRUInfo = rfChassisFRUInfo hf.HWInventoryByFRUType = HWInvByFRUCDUMgmtSwitch } } // HWInv based on Redfish "System" Type. - case base.Node: + case xnametypes.Node: rfSystemFRUInfo = new(rf.SystemFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfSystemFRUInfo) if err == nil { @@ -1535,7 +1540,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUNode } // HWInv based on "GPU" type - case base.NodeAccel: + case xnametypes.NodeAccel: rfNodeAccelFRUInfo = new(rf.ProcessorFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfNodeAccelFRUInfo) if err == nil { @@ -1543,7 +1548,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUNodeAccel } // HWInv based on Redfish "Processor" Type. - case base.Processor: + case xnametypes.Processor: rfProcessorFRUInfo = new(rf.ProcessorFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfProcessorFRUInfo) if err == nil { @@ -1551,7 +1556,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUProcessor } // HWInv based on Redfish "Memory" Type. - case base.Memory: + case xnametypes.Memory: rfMemoryFRUInfo = new(rf.MemoryFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfMemoryFRUInfo) if err == nil { @@ -1559,7 +1564,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUMemory } // HWInv based on Redfish "Drive" Type. - case base.Drive: + case xnametypes.Drive: rfDriveFRUInfo = new(rf.DriveFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfDriveFRUInfo) if err == nil { @@ -1567,7 +1572,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUDrive } // HWInv based on Redfish "Memory" Type. - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: rfHSNNICFRUInfo = new(rf.NAFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfHSNNICFRUInfo) if err == nil { @@ -1575,7 +1580,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUHSNNIC } // HWInv based on Redfish "PowerDistribution" Type. - case base.CabinetPDU: + case xnametypes.CabinetPDU: rfPDUFRUInfo = new(rf.PowerDistributionFRUInfo) err = json.Unmarshal(fruInfoJSON, rfPDUFRUInfo) if err == nil { @@ -1583,9 +1588,9 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUPDU } // HWInv based on Redfish "Outlet" (e.g. of a PDU) Type. - case base.CabinetPDUOutlet: + case xnametypes.CabinetPDUOutlet: fallthrough - case base.CabinetPDUPowerConnector: + case xnametypes.CabinetPDUPowerConnector: rfOutletFRUInfo = new(rf.OutletFRUInfo) err = json.Unmarshal(fruInfoJSON, rfOutletFRUInfo) if err == nil { @@ -1593,7 +1598,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUOutlet } // HWInv based on Redfish "PowerSupply" Type. - case base.CMMRectifier: + case xnametypes.CMMRectifier: rfCMMRectifierFRUInfo = new(rf.PowerSupplyFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfCMMRectifierFRUInfo) if err == nil { @@ -1601,7 +1606,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUCMMRectifier } // HWInv based on Redfish "PowerSupply" Type. - case base.NodeEnclosurePowerSupply: + case xnametypes.NodeEnclosurePowerSupply: rfNodeEnclosurePowerSupplyFRUInfo = new(rf.PowerSupplyFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfNodeEnclosurePowerSupplyFRUInfo) if err == nil { @@ -1609,7 +1614,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUNodeEnclosurePowerSupply } // HWInv based on Redfish "NodeAccelRiser" Type. - case base.NodeAccelRiser: + case xnametypes.NodeAccelRiser: rfNodeAccelRiserFRUInfo = new(rf.NodeAccelRiserFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfNodeAccelRiserFRUInfo) if err == nil { @@ -1617,7 +1622,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUNodeAccelRiser } // HWInv based on Redfish "Manager" Type. - case base.NodeBMC: + case xnametypes.NodeBMC: rfNodeBMCFRUInfo = new(rf.ManagerFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfNodeBMCFRUInfo) if err == nil { @@ -1625,7 +1630,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRUNodeBMC } // HWInv based on Redfish "Manager" Type. - case base.RouterBMC: + case xnametypes.RouterBMC: rfRouterBMCFRUInfo = new(rf.ManagerFRUInfoRF) err = json.Unmarshal(fruInfoJSON, rfRouterBMCFRUInfo) if err == nil { @@ -1633,7 +1638,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { hf.HWInventoryByFRUType = HWInvByFRURouterBMC } // No match - not a valid HMSType, always an error - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err = base.ErrHMSTypeInvalid default: err = base.ErrHMSTypeUnsupported @@ -1641,82 +1646,82 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { return err } -// // This function encode's the hwinv's type-specific FRU info struct // into a free-form JSON byte array that can be stored schema-less in the -// database. +// dataxnametypes. // // NOTE: This function is the counterpart to DecodeFRUInfo(). // // Returns: FRU's info as JSON []byte representation, err = nil -// Else, err != nil if encoding failed (plus, []byte value is empty) +// +// Else, err != nil if encoding failed (plus, []byte value is empty) func (hf *HWInvByFRU) EncodeFRUInfo() ([]byte, error) { var err error var fruInfoJSON []byte - switch base.ToHMSType(hf.Type) { + switch xnametypes.ToHMSType(hf.Type) { // HWInv based on Redfish "Chassis" Type. - case base.Cabinet: + case xnametypes.Cabinet: fruInfoJSON, err = json.Marshal(hf.HMSCabinetFRUInfo) - case base.Chassis: + case xnametypes.Chassis: fruInfoJSON, err = json.Marshal(hf.HMSChassisFRUInfo) - case base.ComputeModule: + case xnametypes.ComputeModule: fruInfoJSON, err = json.Marshal(hf.HMSComputeModuleFRUInfo) - case base.RouterModule: + case xnametypes.RouterModule: fruInfoJSON, err = json.Marshal(hf.HMSRouterModuleFRUInfo) - case base.NodeEnclosure: + case xnametypes.NodeEnclosure: fruInfoJSON, err = json.Marshal(hf.HMSNodeEnclosureFRUInfo) - case base.HSNBoard: + case xnametypes.HSNBoard: fruInfoJSON, err = json.Marshal(hf.HMSHSNBoardFRUInfo) - case base.MgmtSwitch: + case xnametypes.MgmtSwitch: fruInfoJSON, err = json.Marshal(hf.HMSMgmtSwitchFRUInfo) - case base.MgmtHLSwitch: + case xnametypes.MgmtHLSwitch: fruInfoJSON, err = json.Marshal(hf.HMSMgmtHLSwitchFRUInfo) - case base.CDUMgmtSwitch: + case xnametypes.CDUMgmtSwitch: fruInfoJSON, err = json.Marshal(hf.HMSCDUMgmtSwitchFRUInfo) // HWInv based on Redfish "System" Type. - case base.Node: + case xnametypes.Node: fruInfoJSON, err = json.Marshal(hf.HMSNodeFRUInfo) // HWInv based on "GPU" type - case base.NodeAccel: + case xnametypes.NodeAccel: fruInfoJSON, err = json.Marshal(hf.HMSNodeAccelFRUInfo) // HWInv based on Redfish "Processor" Type. - case base.Processor: + case xnametypes.Processor: fruInfoJSON, err = json.Marshal(hf.HMSProcessorFRUInfo) // HWInv based on Redfish "Memory" Type. - case base.Memory: + case xnametypes.Memory: fruInfoJSON, err = json.Marshal(hf.HMSMemoryFRUInfo) // HWInv based on Redfish "Processor" Type. - case base.Drive: + case xnametypes.Drive: fruInfoJSON, err = json.Marshal(hf.HMSDriveFRUInfo) // HWInv based on Redfish "HSN NIC" Type. - case base.NodeHsnNic: + case xnametypes.NodeHsnNic: fruInfoJSON, err = json.Marshal(hf.HMSHSNNICFRUInfo) // HWInv based on Redfish "PowerDistribution" (aka PDU) Type. - case base.CabinetPDU: + case xnametypes.CabinetPDU: fruInfoJSON, err = json.Marshal(hf.HMSPDUFRUInfo) // HWInv based on Redfish "Outlet" (e.g. of a PDU) Type. - case base.CabinetPDUOutlet: + case xnametypes.CabinetPDUOutlet: fallthrough - case base.CabinetPDUPowerConnector: + case xnametypes.CabinetPDUPowerConnector: fruInfoJSON, err = json.Marshal(hf.HMSOutletFRUInfo) // HWInv based on Redfish "PowerSupply" Type. - case base.CMMRectifier: + case xnametypes.CMMRectifier: fruInfoJSON, err = json.Marshal(hf.HMSCMMRectifierFRUInfo) // HWInv based on Redfish "PowerSupply" Type. - case base.NodeEnclosurePowerSupply: + case xnametypes.NodeEnclosurePowerSupply: fruInfoJSON, err = json.Marshal(hf.HMSNodeEnclosurePowerSupplyFRUInfo) // HWInv based on Redfish "NodeAccelRiser" Type. - case base.NodeAccelRiser: + case xnametypes.NodeAccelRiser: fruInfoJSON, err = json.Marshal(hf.HMSNodeAccelRiserFRUInfo) // HWInv based on Redfish "Manager" Type. - case base.NodeBMC: + case xnametypes.NodeBMC: fruInfoJSON, err = json.Marshal(hf.HMSNodeBMCFRUInfo) // HWInv based on Redfish "Manager" Type. - case base.RouterBMC: + case xnametypes.RouterBMC: fruInfoJSON, err = json.Marshal(hf.HMSRouterBMCFRUInfo) // No match - not a valid HMS Type, always an error - case base.HMSTypeInvalid: + case xnametypes.HMSTypeInvalid: err = base.ErrHMSTypeInvalid // Not supported for this type. default: diff --git a/pkg/sm/hwinvhist.go b/pkg/sm/hwinvhist.go index 3841d1e..db5aa6f 100644 --- a/pkg/sm/hwinvhist.go +++ b/pkg/sm/hwinvhist.go @@ -24,7 +24,8 @@ package sm import ( "strings" - base "github.com/Cray-HPE/hms-base" + + base "github.com/Cray-HPE/hms-base/v2" ) var ErrHWHistEventTypeInvalid = base.NewHMSError("sm", "Invalid hardware inventory history event type") @@ -61,7 +62,7 @@ type HWInvHist struct { } type HWInvHistArray struct { - ID string `json:"ID"` // xname or FruId (if ByFRU) + ID string `json:"ID"` // xname or FruId (if ByFRU) History []*HWInvHist `json:"History"` } @@ -89,7 +90,7 @@ func NewHWInvHistResp(hwHists []*HWInvHist, format HWInvHistFmt) (*HWInvHistResp compHistMap[id] = idx idx++ compHistArray := HWInvHistArray{ - ID: id, + ID: id, History: []*HWInvHist{hwHist}, } compHist.Components = append(compHist.Components, compHistArray) diff --git a/pkg/sm/misc.go b/pkg/sm/misc.go index af28d21..485ee23 100644 --- a/pkg/sm/misc.go +++ b/pkg/sm/misc.go @@ -27,7 +27,8 @@ import ( "fmt" "log" "os" - base "github.com/Cray-HPE/hms-base" + + "github.com/Cray-HPE/hms-xname/xnametypes" ) //////////////////////////////////////////////////////////////////////////// @@ -128,7 +129,7 @@ func NewStateRFPollJob(xname string, delay, poll, lifetime, keepAlive int) (*Job // SRFP Job specific fields data := new(SrfpJobData) - data.CompId = base.VerifyNormalizeCompID(xname) + data.CompId = xnametypes.VerifyNormalizeCompID(xname) data.Delay = delay data.Poll = poll job.Data = data diff --git a/pkg/sm/nodemap.go b/pkg/sm/nodemap.go index 125e4fd..a1f756c 100644 --- a/pkg/sm/nodemap.go +++ b/pkg/sm/nodemap.go @@ -25,7 +25,9 @@ package sm import ( "encoding/json" "fmt" - base "github.com/Cray-HPE/hms-base" + + base "github.com/Cray-HPE/hms-base/v2" + "github.com/Cray-HPE/hms-xname/xnametypes" ) // An entry mapping a node xname to a NID @@ -47,8 +49,8 @@ type NodeMapArray struct { // used for query responses. func NewNodeMap(id, role, subRole string, nid int, nodeInfo *json.RawMessage) (*NodeMap, error) { m := new(NodeMap) - idNorm := base.NormalizeHMSCompID(id) - if base.GetHMSType(idNorm) != base.Node { + idNorm := xnametypes.NormalizeHMSCompID(id) + if xnametypes.GetHMSType(idNorm) != xnametypes.Node { err := fmt.Errorf("xname ID '%s' is invalid or not a node", id) return nil, err } diff --git a/pkg/sm/powermap.go b/pkg/sm/powermap.go index ed11a6d..e6dda1e 100644 --- a/pkg/sm/powermap.go +++ b/pkg/sm/powermap.go @@ -24,7 +24,8 @@ package sm import ( "fmt" - base "github.com/Cray-HPE/hms-base" + + "github.com/Cray-HPE/hms-xname/xnametypes" ) // An entry mapping an xname to a power supplies @@ -36,7 +37,7 @@ type PowerMap struct { // This wraps basic PowerMap data with the structure used for query responses. func NewPowerMap(id string, poweredBy []string) (*PowerMap, error) { m := new(PowerMap) - idNorm := base.VerifyNormalizeCompID(id) + idNorm := xnametypes.VerifyNormalizeCompID(id) if idNorm == "" { err := fmt.Errorf("xname ID '%s' is invalid", id) return nil, err @@ -44,7 +45,7 @@ func NewPowerMap(id string, poweredBy []string) (*PowerMap, error) { m.ID = idNorm if len(poweredBy) > 0 { for _, pwrId := range poweredBy { - normPwrID := base.VerifyNormalizeCompID(pwrId) + normPwrID := xnametypes.VerifyNormalizeCompID(pwrId) if normPwrID == "" { err := fmt.Errorf("Power supply xname ID '%s' is invalid", pwrId) return nil, err diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/.gitignore b/vendor/github.com/Cray-HPE/hms-base/v2/.gitignore new file mode 100644 index 0000000..485dee6 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/.gitignore @@ -0,0 +1 @@ +.idea diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/.version b/vendor/github.com/Cray-HPE/hms-base/v2/.version new file mode 100644 index 0000000..38f77a6 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/.version @@ -0,0 +1 @@ +2.0.1 diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/CHANGELOG.md b/vendor/github.com/Cray-HPE/hms-base/v2/CHANGELOG.md new file mode 100644 index 0000000..ca368c0 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/CHANGELOG.md @@ -0,0 +1,269 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + + +## [2.0.1] - 2022-01-21 + +### Changed + +- repatriated HMSError types from hms-xname +- updated arti link to artifactory.algol60.net + +## [2.0.0] - 2021-12-13 + +### Changed + +- CASMHMS-5180: Moved HMSTypes and related functions to the new hms-xname repo under the xnametypes package. + +## [1.15.1] - 2021-08-09 + +### Changed + +- Added GitHub configuration files and fixed snyk warning. + +## [1.15.0] - 2021-07-16 + +### Changed + +- Replaced Stash Go module name with GitHub version. + +## [1.14.0] - 2021-07-01 + +### Changed + +- Bumped version to represent migration to GitHub. + +## [1.13.0] - 2021-06-28 + +### Security + +- CASMHMS-4898 - Updated base container images for security updates. + +## [1.12.2] - 2021-05-03 + +### Changed + +- Allow valid nodeAccel type xnames for more than 8 GPUs + +## [1.12.1] - 2021-04-02 + +### Changed + +- Updated Dockerfiles to pull base images from Artifactory instead of DTR. + +## [1.12.0] - 2021-01-26 + +### Added + +- Update Licence info in source files. + +## [1.11.1] - 2021-01-19 + +### Added + +- Added a function to add a User-Agent header to an http request. + +## [1.11.0] - 2021-01-14 + +### Changed + +- fix versions.. + +## [1.9.0] - 2021-01-14 + +### Changed + +- Updated license file. + +## [1.8.5] - 2020-12-18 + +### Changed + +- CASMHMS-4295 - Changed the regex for the partition hmstype to accept p# and p#.# + +## [1.8.4] - 2020-12-2 + +### Added + +- CASMHMS-4246 - Added CDUMgmtSwitch to HMS types. + +## [1.8.3] - 2020-11-24 + +### Added + +- CASMHMS-4239 - Added MgmtHLSwitch to HMS types. + +## [1.8.2] - 2020-11-16 + +### Added + +- CASMHMS-4087 - Added NodeAccelRiser to HMS types. + +## [1.8.1] - 2020-10-16 + +### Security + +- CASMHMS-4105 - Updated base Golang Alpine image to resolve libcrypto vulnerability. + +## [1.8.0] - 2020-09-02 + +### Changed + +- CASMHMS-3922 - Updated components to include reservation disabled and locked status. + +## [1.7.3] - 2020-05-01 + +### Changed + +- CASMHMS-3403 - Updated regex used for cmmrectifiers to allow more than 3 xnames to be validated per chassis + +## [1.7.2] - 2020-04-27 + +### Changed + +- CASMHMS-2968 - Updated hms-base to use trusted baseOS. + +## [1.7.1] - 2020-04-09 + +### Added + +- The NodeEnclosurePowerSupply type to HMS types + +## [1.7.0] - 2020-03-18 + +### Changed + +- Changed the valid component role and subrole values to be extendable via configfile. + +### Added + +- A config file watcher to pick up any new roles/subroles defined in the config file. + +## [1.6.4] - 2020-03-13 + +### Changed + +- Changed the component state transition Ready->On to be invalid + +## [1.6.3] - 2020-03-06 + +### Added + +- Definitions for HMS hardware Class (River/Mountian/Hill) + +## [1.6.2] - 2020-02-13 + +### Added + +- Added functions for listing out all valid values for the enums defined in hms-base (HMS Type, State, Role, etc). + +## [1.6.1] - 2020-01-29 + +### Added + +- The Drive and StorageGroup types to HMS types + +## [1.6.0] - 2019-12-11 + +### Changed + +- Split this module into a separate package from hms-common + +## [1.5.5] - 2019-12-02 + +### Added + +- The SNMPAuthPass and SNMPPrivPass fields to the CompCredentials struct + +## [1.5.4] - 2019-11-22 + +### Added + +- Definitions for subroles + +## [1.5.3] - 2019-10-04 + +### Added + +- Extended securestorage mock Vault adapter to also function as a more + generalized storage mechanism for complex unit test case scenarios. All + existing functionality is preserved. Use as a generalized store requires + initializing InputLookup.Key (or InputLookupKeys.KeyPath) and setting + LookupNum (or LookupKeysNum) to -1. + +## [1.5.2] - 2019-10-03 + +### Fixed + +- Synced up with the HMS Component Naming Convention. Note that this introduces +some incompatibilties with previous versions. + +## [1.5.1] - 2019-09-18 + +### Added + +- Added the "Locked" component flag to base. + +## [1.5.0] - 2019-08-13 + +### Added + +- Added SMNetManager already in use in REDS/MEDS to common library. + +## [1.4.2] - 2019-08-07 + +### Fixed + +- Segmentation fault in decode logic of secure store when a nil structure (i.e., no results) are returned from Vault. + +## [1.4.1] - 2019-08-01 + +### Added + +- Management role to base + +## [1.4.0] - 2019-07-30 + +### Added + +- Added the securestorage package that performs basic actions (Store, Lookup, etc) on a chosen secure backing store. The initial list of backing stores only includes Vault. +- Added the compcredentials package that performs common component credential operations with the securestorage package. + +## [1.3.0] - 2019-07-08 + +### Added + +- Added HTTP library that utilizes retryablehttp to perform HTTP operations and optionally unmarshal the returned value into an interface. + +## [1.2.0] - 2019-05-18 + +### Changed + +- Added changes for CabinetPDU support +- Tweak to state change table + +## [1.1.0] - 2019-05-13 + +### Removed + +- Removed `hmsds`, `sharedtest`, `sm`, and `redfish` packages from this repo as they are actually SMD specific and therefore belong in that repo. + +## [1.0.0] - 2019-05-13 + +### Added + +- This is the initial release of the `hms-common` repo. It contains everything that was in `hms-services` at the time with the major exception of being `go mod` based now. + +### Changed + +### Deprecated + +### Removed + +### Fixed + +### Security diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/LICENSE b/vendor/github.com/Cray-HPE/hms-base/v2/LICENSE new file mode 100644 index 0000000..62daac7 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/LICENSE @@ -0,0 +1,21 @@ +MIT License + +(C) Copyright [2021] 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. diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/Makefile b/vendor/github.com/Cray-HPE/hms-base/v2/Makefile new file mode 100644 index 0000000..437f7b6 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/Makefile @@ -0,0 +1,29 @@ +# +# MIT License +# +# (C) Copyright [2018-2022] 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. +# + +all: unittest +.PHONY: unittest + +unittest: + go test ./... -cover diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/configWatch.go b/vendor/github.com/Cray-HPE/hms-base/v2/configWatch.go new file mode 100644 index 0000000..d4e99a3 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/configWatch.go @@ -0,0 +1,151 @@ +// MIT License +// +// (C) Copyright [2020-2021] 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 base + +import ( + "encoding/json" + "fmt" + "github.com/fsnotify/fsnotify" + "io/ioutil" + "log" + "os" + "path" + "strings" +) + +var configWatch *fsnotify.Watcher + +type configIn struct { + Defs struct { + Role []string `json:"Role"` + SubRole []string `json:"SubRole"` + } `json:"HMSExtendedDefinitions"` +} + +// main +func InitTypes(configpath string) error { + if configpath == "" { + return fmt.Errorf("InitTypes: No config file to watch") + } + err := watchConfig(configpath) + if err != nil { + return err + } + return nil +} + +func watchConfig(configpath string) error { + if configWatch != nil { + // Already watching a file + return nil + } + // configpath must not be a directory + if strings.HasSuffix(configpath, "/") { + return fmt.Errorf("watchConfig: Configpath must not be a directory: %s", configpath) + } + // Must be the absolute path + if !path.IsAbs(configpath) { + return fmt.Errorf("watchConfig: Must be the absolute path: %s", configpath) + } + + // Get the directory path + configdir := path.Dir(configpath) + // Load the file contents + loadFile(configpath) + + // Create the file watcher + configWatch, err := fsnotify.NewWatcher() + if err != nil { + return err + } + done := make(chan bool) + go func() { + defer configWatch.Close() + for { + select { + // watch for events + case <-configWatch.Events: + loadFile(configpath) + // watch for errors + case err := <-configWatch.Errors: + log.Printf("ERROR: watchConfig: %s\n", err) + + case <-done: + configWatch = nil + return + } + } + }() + // Mounting a configmap makes the configfile a symlink which will + // not trigger change events. Watch the directory instead for changes. + if err := configWatch.Add(configdir); err != nil { + done <- true + return err + } + return nil +} + +func loadFile(file string) { + // Attempt to read from file + config := new(configIn) + + f, err := os.Open(file) + if err != nil { + log.Printf("Warning: loadFile: Failed to open config %s: %s\n", file, err) + return + } + defer f.Close() + + bytes, _ := ioutil.ReadAll(f) + err = json.Unmarshal(bytes, config) + if err != nil { + if _, ok := err.(*json.UnmarshalTypeError); ok { + log.Printf("Warning: loadFile: bad field(s) skipped: %s: %s\n", file, err) + } else { + log.Printf("Warning: loadFile: Failed to decode config %s: %s\n", file, err) + return + } + } + + // Reload the role maps with the defaults + our extended values + hmsRoleMap = map[string]string{} + for key, val := range defaultHMSRoleMap { + hmsRoleMap[key] = val + } + if config.Defs.Role != nil && len(config.Defs.Role) != 0 { + for _, val := range config.Defs.Role { + key := strings.ToLower(val) + hmsRoleMap[key] = val + } + } + hmsSubRoleMap = map[string]string{} + for key, val := range defaultHMSSubRoleMap { + hmsSubRoleMap[key] = val + } + if config.Defs.SubRole != nil && len(config.Defs.SubRole) != 0 { + for _, val := range config.Defs.SubRole { + key := strings.ToLower(val) + hmsSubRoleMap[key] = val + } + } +} diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/doc.go b/vendor/github.com/Cray-HPE/hms-base/v2/doc.go new file mode 100644 index 0000000..f7d554f --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/doc.go @@ -0,0 +1,37 @@ +// MIT License +// +// (C) Copyright [2018, 2021] 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. + +// This package contains shared utility functions for HMS Go code. +// +// HMS Type and Component Definitions +// +// These are functions that define common types that are used to describe HMS +// component data that represents system components and valid values for that +// data. +// +// HMS Errors and RFC 7807 ProblemDetails +// +// These are common methods for defining a custom HMS error type and producing +// RFC 7807-compliant ProblemDetails payloads for reporting problems that occur +// during HMS API calls. +// +package base diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/go.mod b/vendor/github.com/Cray-HPE/hms-base/v2/go.mod new file mode 100644 index 0000000..5ec025f --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/go.mod @@ -0,0 +1,9 @@ +module github.com/Cray-HPE/hms-base/v2 + +go 1.16 + +require ( + github.com/fsnotify/fsnotify v1.4.9 + github.com/hashicorp/go-cleanhttp v0.5.1 // indirect + github.com/hashicorp/go-retryablehttp v0.5.4 +) diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/go.sum b/vendor/github.com/Cray-HPE/hms-base/v2/go.sum new file mode 100644 index 0000000..6d536fa --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/go.sum @@ -0,0 +1,9 @@ +github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4= +github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= +github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-retryablehttp v0.5.4 h1:1BZvpawXoJCWX6pNtow9+rpEj+3itIlutiqnntI6jOE= +github.com/hashicorp/go-retryablehttp v0.5.4/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9 h1:L2auWcuQIvxz9xSEqzESnV/QN/gNRXNApHi3fYwl2w0= +golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/hmserr.go b/vendor/github.com/Cray-HPE/hms-base/v2/hmserr.go new file mode 100644 index 0000000..ec90dea --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/hmserr.go @@ -0,0 +1,481 @@ +// MIT License +// +// (C) Copyright [2018, 2021] 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 base + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" +) + +//////////////////////////////////////////////////////////////////////////// +// +// RFC 7807-compliant Problem Details struct +// +//////////////////////////////////////////////////////////////////////////// + +const ProblemDetailsHTTPStatusType = "about:blank" +const ProblemDetailContentType = "application/problem+json" + +// RFC 7807 Problem Details +// +// These are the officially-specified fields. The implementation +// is allowed to add new ones, but we'll stick with these for now. +// Almost all are optional, however, and blank fields are not encoded +// if they are the empty string (which is fine +// +// The only required field is Type and is expected to be a URL that +// should describe the problem type when dereferenced. It's not intended +// to be a dead link, but I don't think clients are allowed to assume it's +// not, either. We don't implement a way of serving these URLs here, +// in any case. It's not obligatory to have a lot of different problem +// types, or even desirable if the client can just andling them all the +// same basic way. +// +// The only non-URL that is allowed for Type is "about:blank", but only in +// the situation where the semantics of the problem can be understood okay +// as a basic HTTP error. In this case Title should be the official HTTP +// status code string, not something custom. You are free to put anything +// you want in Detail however, so if you already have an error function +// that returns an error string, you can easily convert it into one of these +// generic HTTP errors. In fact, we offer a shortcut to doing this. +// +// If Type is a URL, Title should describe the problem type. If you are +// doing this, and not just using type:"about:blank" and the HTTP error, +// for the title, it should be because you have some kind of problem that +// needs, or could benefit from, special or more involved treatment that +// the URL describes when dereferenced. +// +// Detail explains in a human readible way what happened when a specific +// problem occurred. +// +// Instance is another URI describing a specific occurrence of a problem. So +// within a particular Type and Title (a general problem type) the Detail +// and Instance document a specific incident in which that problem occurred. +// Or at least that's the general idea. +// +// Status is the numerical HTTP status code. It is optional, and if present, +// should match at least the intended HTTP code in the header, though this +// is not strictly required. +// +// For more info, reading RFC 7807 would obviously be the authoritative source. +type ProblemDetails struct { + Type string `json:"type"` // either url or "about:blank" + Title string `json:"title,omitempty"` + Detail string `json:"detail,omitempty"` + Instance string `json:"instance,omitempty"` + Status int `json:"status,omitempty"` +} + +// New full ProblemDetails, will all fields specified. +// Type is the only required field, and if any of the other args are left +// as the empty string, the fields won't appear in the JSON output at all. +// +// p := base.NewProblemDetails( +// "https://example.com/probs/MyProblem", +// "My Problem's Title", +// "Details for this problem", +// "/instances/myprob/1", +// http.StatusBadRequest, +// ) +func NewProblemDetails(ptype, title, detail, instance string, status int) *ProblemDetails { + p := new(ProblemDetails) + p.Type = ptype + p.Title = title + p.Detail = detail + p.Instance = instance + p.Status = status + + return p +} + +// New generic ProblemDetails for errors that are just based on the +// HTTP status code. Type and Title are filled in based on the +// status code. +// +// There is no need for a URL in this case, as the Type is allowed to be +// "about:blank" if title is just the Status code text and there is no special +// handling needed beside the usual for that HTTP (error) StatusCode. +// +// NOTE: Status should only be filled in using http.Status* instead of a +// literal number. +// +// 'status' will be treated as http.StatusBadRequest (400) if it does +// not match a valid http status code. +// +// Example: +// p := base.NewProblemDetailsStatus(http.StatusNotFound, "No such component") +// Produces a struct p with the following fields +// &ProblemDetails{ +// Type: "about:blank", +// Title: "Not Found", +// Detail: "No such component", +// Status: 404, +// } +func NewProblemDetailsStatus(detail string, status int) *ProblemDetails { + p := new(ProblemDetails) + p.Type = ProblemDetailsHTTPStatusType + p.Title = http.StatusText(status) + // Got bad status type, default to 400 + if p.Title == "" { + p.Status = http.StatusBadRequest + p.Title = http.StatusText(p.Status) + } else { + p.Status = status + } + p.Detail = detail + + return p +} + +// Create a new ProblemDetails struct copied from p with only detail and +// instance (optionally) updated. If either field is the empty string, it +// will not be updated and the parent values will be used. +// +// The basic idea here is to be able to define a few prototype ProblemDetails +// with the Type and Title filled in (along with a default Detail and HTTP +// Status code, if desired), and then create a child copy when a problem +// actually occurs with the specific Detail and (optionally) instance +// URI filled in. +// +// Example: +// p := base.NewProblemDetails( +// "https://example.com/probs/MyProblem", +// "My Problem's Title", +// "Generic details for this problem type", +// "/instances/myprobs/", +// http.StatusBadRequest, +// ) +// +// // Copy updates Detail and instance +// pChild := p.NewChild("Specific details for this problem", "/instances/myprobs/1") +// +// // Copy has updated Detail field only +// // i.e. p.Instance == pChildDetailOnly.Instance +// pChildDetailOnly := p.NewChild("Specific details for this problem", "") +// +// // Strict copy only, new ProblemDetails has identical fields. +// pCopy := p.NewChild("", "") +func (p *ProblemDetails) NewChild(detail, instance string) *ProblemDetails { + newProb := new(ProblemDetails) + newProb.Type = p.Type + newProb.Title = p.Title + newProb.Status = p.Status + if detail != "" { + newProb.Detail = detail + } else { + newProb.Detail = p.Detail + } + if instance != "" { + newProb.Instance = instance + } else { + newProb.Instance = p.Instance + } + + return newProb +} + +/////////////////////////////////////////////////////////////////////////// +// http.ResponseWriter response formatting for ProblemDetails +/////////////////////////////////////////////////////////////////////////// + +// Send specially-coded RFC7807 Problem Details response. A set ProblemDetails +// struct is expected ('p') and should always contain at least Type to conform +// to the spec (we will always print the Type field, but it would contain the +// empty string if unset which isn't technically valid for the spec. +// +// The HTTP status code in the header is set to the 'status' arg if it is +// NON-zero. If 'status' = 0, then 'p'.Status will be used. If that is +// unset (i.e. 0) also, we will use a default error code of 400. +// +// For example: +// p := base.NewProblemDetails( +// "https://example.com/probs/MyProblem", +// "My Problem's Title", +// "Detail for this problem", +// "/instances/myprob/1", +// http.StatusConflict) // 409 +// ... +// if err != nil { +// base.SendProblemDetails(w, p, 0) +// return +// } +// +// ...will include the following in the response header: +// HTTP/1.1 409 Conflict +// Content-Type: application/problem+json +// With the following body: +// { +// "Type": "https://example.com/probs/MyProblem", +// "Title": "My Problem's Title", +// "Detail": "Detail for this problem", +// "Instance": "/instances/myprob/1", +// "Status": 409 +// } +func SendProblemDetails(w http.ResponseWriter, p *ProblemDetails, status int) error { + // Set proper content type for RFC 7807 Problem details + w.Header().Set("Content-Type", ProblemDetailContentType) + // Variable 'status' is preferred over p.Status, which might not be set, + // being an optional field. + realStatus := status + if status == 0 { + realStatus = p.Status + } + // We shouldn't be returning an actual 0. This is the fall back. + if realStatus == 0 { + realStatus = http.StatusBadRequest + } + w.WriteHeader(realStatus) + err := json.NewEncoder(w).Encode(p) + if err != nil { + retErr := fmt.Errorf("couldn't encode a JSON problem response: %s\n", err) + return retErr + } + return nil +} + +// Generate and then send a generic RFC 7807 problem response based on a +// HTTP status code ('status') and a message string ('msg'). This +// generates a generic title and type based on the HTTP 'status' code. The +// ProblemDetails "Detail" field is filled in using 'msg'. +// +// If you are already returning just a simple error message and want an +// easy way to convert this into a basic (but valid) RFC7807 ProblemDetails, +// this is almost a drop-in replacement. +// +// // If request was for a component that is not in DB, send RFC 7807 +// // ProblemDetails and exit HTTP handler +// err := GetComponentFromDB(component_from_query) +// if err != nil { +// base.SendProblemDetailsGeneric(w, http.StatusNotFound, "No such component") +// return +// } +// +// The above will include the following in the response header: +// HTTP/1.1 404 Not Found +// Content-Type: application/problem+json +// With the following body: +// { +// "Type": "about:blank", +// "Title": "Not Found", +// "Detail": "No such component", +// "Status": 404 +// } +func SendProblemDetailsGeneric(w http.ResponseWriter, status int, msg string) error { + problem := NewProblemDetailsStatus(msg, status) + err := SendProblemDetails(w, problem, problem.Status) + return err +} + +//////////////////////////////////////////////////////////////////////////// +// +// +// HMSError - Custom Go 'error' type for HMS. +// +// +//////////////////////////////////////////////////////////////////////////// + +const HMSErrorUnsetDefault = "no error message or class set" + +// Custom Go 'error' type for HMS - Implements Error() +// +// Works like a standard Go 'error', but can be distinguished +// as an HMS-specific error with an optional class for better +// handling upstream. An RFC7807 error can optionally be added +// in case we need to pass those through multiple layers- but +// without forcing us to (since they still look like regular +// Go errors). Note that this is just a starting point. We can +// attach other types of info later if we want. +// +// Part of the motivation is so we can determine which errors +// are safe to return to users, i.e. we don't want to give +// them things that expose details about the database structure. +// +// Can attach custom RFC7807 response if needed. +type HMSError struct { + // Used to identify similar groups of errors to higher-level software. + Class string `json:"class"` + + // Message, used as error string for Error() + Message string `json:"message"` + + // Optional full ProblemDetails + Problem *ProblemDetails `json:"problem,omitempty"` +} + +// New HMSError, with message string and optional class. +// +// A subsequent call to AddProblem() can associate a ProblemDetails with it. +// By default Problem pointer is nil (again, this is optional functionality) +func NewHMSError(class, msg string) *HMSError { + newErr := new(HMSError) + newErr.Class = class + newErr.Message = msg + + return newErr +} + +// Implement Error() interface - This makes it so an HMSError can be +// returned anywhere an ordinary Go 'error' is returned. +// +// The receiver of an 'error' can then use one of the IsHMSError* or HasHMSError +// functions to test if it is an HMSError, and if so, to obtain the additional +// fields. +// +func (e *HMSError) Error() string { + if e.Message != "" { + return e.Message + } else if e.Class != "" { + return e.Class + } else { + return HMSErrorUnsetDefault + } +} + +// See if an error (some thing implementing Error() interface is an HMSError +// +// Returns 'true' if err is HMSError +// Returns 'false' if err is something else that implements Error() +func IsHMSError(err error) bool { + _, ok := err.(*HMSError) + if !ok { + return false + } else { + return true + } +} + +// Test and retrieve HMSError info, if error is in fact of that type. +// +// If bool is 'true', HMSError will be a non-nil HMSError with the expected +// extended HMSError fields. +// +// If bool is 'false', err is not an HMSError and *HMSError will be nil +func GetHMSError(err error) (*HMSError, bool) { + hmserr, ok := err.(*HMSError) + if !ok { + return nil, false + } else { + return hmserr, true + } +} + +// Return true if 'class' exactly matches Class field for HMSError +func (e *HMSError) IsClass(class string) bool { + if class == e.Class { + return true + } + return false +} + +// Return true if 'class' matches Class field for HMSError (case insensitive) +func (e *HMSError) IsClassIgnCase(class string) bool { + if strings.ToLower(class) == strings.ToLower(e.Class) { + return true + } + return false +} + +// Returns false if 'err' is not an HMSError, or, if it is, if 'class' doesn't +// match the HMSError's Class field. +func IsHMSErrorClass(err error, class string) bool { + hmserr, ok := GetHMSError(err) + if !ok { + return false + } + return hmserr.IsClass(class) +} + +// Returns false if 'err' is not an HMSError, or, if it is, if 'class' doesn't +// match the HMSError's Class field (case insensitive). +func IsHMSErrorClassIgnCase(err error, class string) bool { + hmserr, ok := GetHMSError(err) + if !ok { + return false + } + return hmserr.IsClassIgnCase(class) +} + +// Add an ProblemDetails to be associated with e +// +// Note: This simply associates the pointer to p with e. There is no +// new ProblemDetails created and no deep copy is performed. +func (e *HMSError) AddProblem(p *ProblemDetails) { + e.Problem = p +} + +// If e has a ProblemDetails associated with it, return a pointer to it +// If not, return nil. +func (e *HMSError) GetProblem() *ProblemDetails { + return e.Problem +} + +// Create a new HMSError that is a copy of e, except with an updated "Message" +// field if 'msg' is not the empty string. Conversely, if 'msg' IS +// the empty string, i.e. "", the operation is equivalent to a copy. +// +// Note: This DOES NOT COPY ProblemDetails if added with AddProblem. +// Instead, use NewChildWithProblem() for cases like this (or if you're +// unsure). +// +// The (newerr).Problem pointer is always set to nil with this function. +func (e *HMSError) NewChild(msg string) *HMSError { + newErr := new(HMSError) + newErr.Class = e.Class + if msg != "" { + newErr.Message = msg + } else { + newErr.Message = e.Message + } + return newErr +} + +// Create a newly-allocated child HMSError, deep-copying the parent, including +// any ProblemDetails that (may) have been associated using AddProblem(). +// +// In addition to copying, the 'msg' arg (if non-empty) is used to overwrite +// HMSError's "Message" and (if ProblemDetails are present) the ProblemDetails +// "Detail" field is also set to the same string. +// +// The ProblemDetails 'Instance' is also updated if the 'instance' arg is a +// non-empty string. +// +// If both 'msg' and 'instance' are unset the result is effectively a simple +// (deep) copy of e (including a deep copy of e.Problem). +// +// This method basically combines the functionality of both the HMSError +// and ProblemDetails NewChild() functions. +func (e *HMSError) NewChildWithProblem(msg, instance string) *HMSError { + newErr := new(HMSError) + newErr.Class = e.Class + if msg != "" { + newErr.Message = msg + } else { + newErr.Message = e.Message + } + if e.Problem != nil { + newErr.Problem = e.Problem.NewChild(msg, instance) + } + return newErr +} diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/hmstypes.go b/vendor/github.com/Cray-HPE/hms-base/v2/hmstypes.go new file mode 100644 index 0000000..775d0e2 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/hmstypes.go @@ -0,0 +1,518 @@ +// MIT License +// +// (C) Copyright [2018-2022] 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 base + +import ( + "encoding/json" + "strings" +) + +// Use HMS-wrapped errors. Subsequent errors will be children of this one. +var e = NewHMSError("hms", "GenericError") + +// +// State field used in component, set in response to events by state manager. +// 1.0.0 +// +type HMSState string + +// Valid state values for components - should refect hardware state +// Enabled/Disabled is a separate boolean field, as the component should +// still have it's actual physical state known and tracked at all times, so +// we know what it is when it is enabled. It also avoids the primary case +// where admins need to modify the state field manually. +// +// NOTE: there will be no state between on and ready. If the managed plane +// software does not have heartbeats, On is as high as it will ever get. +// So "active" is not useful. 'Paused' is not in scope now that the software +// status field exists. +const ( + StateUnknown HMSState = "Unknown" // The State is unknown. Appears missing but has not been confirmed as empty. + StateEmpty HMSState = "Empty" // The location is not populated with a component + StatePopulated HMSState = "Populated" // Present (not empty), but no further track can or is being done. + StateOff HMSState = "Off" // Present but powered off + StateOn HMSState = "On" // Powered on. If no heartbeat mechanism is available, it's software state may be unknown. + + StateStandby HMSState = "Standby" // No longer Ready and presumed dead. It typically means HB has been lost (w/alert). + StateHalt HMSState = "Halt" // No longer Ready and halted. OS has been gracefully shutdown or panicked (w/ alert). + StateReady HMSState = "Ready" // Both On and Ready to provide its expected services, i.e. used for jobs. + + // Retired (actually never used) states: + // StateActive HMSState = "Active" // If level-2 systems without hb monitoring can make a distinction between on and booting/booted. + // StatePaused HMSState = "Paused" // Was in a Ready state, but is temporarily unavailable due to admin action or a transient issue. +) + +var ErrHMSStateInvalid = e.NewChild("was not a valid HMS state") +var ErrHMSStateUnsupported = e.NewChild("HMSState value not supported for this operation") +var ErrHMSNeedForce = e.NewChild("operation not allowed and not forced.") +var ErrHMSTypeInvalid = e.NewChild("got HMSTypeInvalid instead of valid type") +var ErrHMSTypeUnsupported = e.NewChild("HMSType value not supported for this operation") // TODO should this be in base? + +// For case-insensitive verification and normalization of state strings +var hmsStateMap = map[string]HMSState{ + "unknown": StateUnknown, + "empty": StateEmpty, + "populated": StatePopulated, + "off": StateOff, + "on": StateOn, + "standby": StateStandby, + "halt": StateHalt, + "ready": StateReady, +} + +func GetHMSStateList() []string { + hmsStateList := []string{} + for _, state := range hmsStateMap { + hmsStateList = append(hmsStateList, state.String()) + } + return hmsStateList +} + +// Returns the given state string (adjusting any capitalization differences), +// if a valid state is given. Else, return the empty string. +func VerifyNormalizeState(stateStr string) string { + stateLower := strings.ToLower(stateStr) + value, ok := hmsStateMap[stateLower] + if ok != true { + return "" + } else { + return value.String() + } +} + +// Specifies valid STARTING states before changing to the indicated state, +// at least without forcing the change, which would normally be a bad idea. +// An empty array means "None without forcing. +var hmsValidStartStatesMap = map[string][]string{ + "unknown": []string{}, // Force/HSM only + "empty": []string{}, // Force/HSM only + "populated": []string{}, // Force/HSM only + "off": []string{string(StateOff), string(StateOn), string(StateStandby), string(StateHalt), string(StateReady)}, + "on": []string{string(StateOn), string(StateOff), string(StateStandby), string(StateHalt)}, + "standby": []string{string(StateStandby), string(StateReady)}, + "halt": []string{string(StateHalt), string(StateReady)}, + "ready": []string{string(StateReady), string(StateOn), string(StateOff), string(StateStandby), string(StateHalt)}, // Last three are needed (for now) if RF events break. +} + +// If ok == true, beforeStates contain valid current states a +// component can be in if it is being transitioned to afterState without +// being forced (either because it is a bad idea, or the state should +// only be set by HSM and not by other software). An empty array means 'None +// without force=true +// +// If ok == false, afterState matched no valid HMS State (case insensitive) +func GetValidStartStates(afterState string) (beforeStates []string, ok bool) { + stateLower := strings.ToLower(afterState) + beforeStates, ok = hmsValidStartStatesMap[stateLower] + return +} + +// Same as above, but with force flag. If not found, returns +// ErrHMSStateInvalid. If can only be forced, and force = false, +// error will be ErrHMSNeedForce. Otherwise list of starting states. +// If force = true and no errors, an empty array means no restrictions. +func GetValidStartStateWForce( + afterState string, + force bool, +) (beforeStates []string, err error) { + + beforeStates = []string{} + // See if transition is valid. + if force == false { + var ok bool + beforeStates, ok = GetValidStartStates(afterState) + if !ok { + err = ErrHMSStateInvalid + } else if len(beforeStates) == 0 { + err = ErrHMSNeedForce + } + } + return +} + +// Check to see if the state is above on (on is the highest we will get +// from Redfish, so these are state set by higher software layers) +func IsPostBootState(stateStr string) bool { + stateLower := strings.ToLower(stateStr) + value, ok := hmsStateMap[stateLower] + if ok != true { + return false + } else { + switch value { + //case StateActive: + // fallthrough + case StateStandby: + fallthrough + case StateHalt: + fallthrough + case StateReady: + return true + //case StatePaused: + // return true + default: + return false + } + } +} + +// Allow HMSState to be treated as a standard string type. +func (s HMSState) String() string { return string(s) } + +// +// Flag field used in component, set in response to events by state manager. +// 1.0.0 +// + +type HMSFlag string + +// Valid flag values. +const ( + FlagUnknown HMSFlag = "Unknown" + FlagOK HMSFlag = "OK" // Functioning properly + FlagWarning HMSFlag = "Warning" // Continues to operate, but has an issue that may require attention. + FlagAlert HMSFlag = "Alert" // No longer operating as expected. The state may also have changed due to error. + FlagLocked HMSFlag = "Locked" // Another service has reserved this component. +) + +// For case-insensitive verification and normalization of flag strings +var hmsFlagMap = map[string]HMSFlag{ + "unknown": FlagUnknown, + "ok": FlagOK, + "warning": FlagWarning, + "warn": FlagWarning, + "alert": FlagAlert, + "locked": FlagLocked, +} + +// Get a list of all valid HMS flags +func GetHMSFlagList() []string { + hmsFlagList := []string{} + for _, flag := range hmsFlagMap { + hmsFlagList = append(hmsFlagList, flag.String()) + } + return hmsFlagList +} + +// Returns the given flag string (adjusting any capitalization differences), +// if a valid flag was given. Else, return the empty string. +func VerifyNormalizeFlag(flagStr string) string { + flagLower := strings.ToLower(flagStr) + value, ok := hmsFlagMap[flagLower] + if ok != true { + return "" + } else { + return value.String() + } +} + +// As above, but if flag is the empty string, then return FlagOK. +// If non-empty and invalid, return the empty string. +func VerifyNormalizeFlagOK(flag string) string { + if flag == "" { + return FlagOK.String() + } + return VerifyNormalizeFlag(flag) +} + +// Allow HMSFlag to be treated as a standard string type. +func (f HMSFlag) String() string { return string(f) } + +// +// Role of component +// 1.0.0 +// + +type HMSRole string + +// Valid role values. +const ( + RoleCompute HMSRole = "Compute" + RoleService HMSRole = "Service" + RoleSystem HMSRole = "System" + RoleApplication HMSRole = "Application" + RoleStorage HMSRole = "Storage" + RoleManagement HMSRole = "Management" +) + +// For case-insensitive verification and normalization of role strings +var defaultHMSRoleMap = map[string]string{ + "compute": RoleCompute.String(), + "service": RoleService.String(), + "system": RoleSystem.String(), + "application": RoleApplication.String(), + "storage": RoleStorage.String(), + "management": RoleManagement.String(), +} + +var hmsRoleMap = defaultHMSRoleMap + +// Get a list of all valid HMS roles +func GetHMSRoleList() []string { + hmsRoleList := []string{} + for _, role := range hmsRoleMap { + hmsRoleList = append(hmsRoleList, role) + } + return hmsRoleList +} + +// Returns the given role string (adjusting any capitalization differences), +// if a valid role was given. Else, return the empty string. +func VerifyNormalizeRole(roleStr string) string { + roleLower := strings.ToLower(roleStr) + value, ok := hmsRoleMap[roleLower] + if ok != true { + return "" + } else { + return value + } +} + +// Allow HMSRole to be treated as a standard string type. +func (r HMSRole) String() string { return string(r) } + +// +// SubRole of component +// 1.0.0 +// + +type HMSSubRole string + +// Valid SubRole values. +const ( + SubRoleMaster HMSSubRole = "Master" + SubRoleWorker HMSSubRole = "Worker" + SubRoleStorage HMSSubRole = "Storage" +) + +// For case-insensitive verification and normalization of SubRole strings +var defaultHMSSubRoleMap = map[string]string{ + "master": SubRoleMaster.String(), + "worker": SubRoleWorker.String(), + "storage": SubRoleStorage.String(), +} + +var hmsSubRoleMap = defaultHMSSubRoleMap + +// Get a list of all valid HMS subroles +func GetHMSSubRoleList() []string { + hmsSubRoleList := []string{} + for _, subrole := range hmsSubRoleMap { + hmsSubRoleList = append(hmsSubRoleList, subrole) + } + return hmsSubRoleList +} + +// Returns the given SubRole string (adjusting any capitalization differences), +// if a valid SubRole was given. Else, return the empty string. +func VerifyNormalizeSubRole(subRoleStr string) string { + subRoleLower := strings.ToLower(subRoleStr) + value, ok := hmsSubRoleMap[subRoleLower] + if ok != true { + return "" + } else { + return value + } +} + +// Allow HMSSubRole to be treated as a standard string type. +func (r HMSSubRole) String() string { return string(r) } + +// +// HMSNetType - type of high speed network +// 1.0.0 +// + +type HMSNetType string + +const ( + NetSling HMSNetType = "Sling" + NetInfiniband HMSNetType = "Infiniband" + NetEthernet HMSNetType = "Ethernet" + NetOEM HMSNetType = "OEM" // Placeholder for non-slingshot + NetNone HMSNetType = "None" +) + +// For case-insensitive verification and normalization of HSN network types +var hmsNetTypeMap = map[string]HMSNetType{ + "sling": NetSling, + "infiniband": NetInfiniband, + "ethernet": NetEthernet, + "oem": NetOEM, + "none": NetNone, +} + +// Get a list of all valid HMS NetTypes +func GetHMSNetTypeList() []string { + hmsNetTypeList := []string{} + for _, netType := range hmsNetTypeMap { + hmsNetTypeList = append(hmsNetTypeList, netType.String()) + } + return hmsNetTypeList +} + +// Returns the given net type string (adjusting any capitalization differences), +// if a valid netType was given. Else, return the empty string. +func VerifyNormalizeNetType(netTypeStr string) string { + netTypeLower := strings.ToLower(netTypeStr) + value, ok := hmsNetTypeMap[netTypeLower] + if ok != true { + return "" + } else { + return value.String() + } +} + +// Allow HMSNetType to be treated as a standard string type. +func (r HMSNetType) String() string { return string(r) } + +// +// HMSArch - binary type needed for component +// 1.0.0 +// + +type HMSArch string + +const ( + ArchX86 HMSArch = "X86" + ArchARM HMSArch = "ARM" + ArchUnknown HMSArch = "UNKNOWN" + ArchOther HMSArch = "Other" +) + +// For case-insensitive verification and normalization of HSN network types +var hmsArchMap = map[string]HMSArch{ + "x86": ArchX86, + "arm": ArchARM, + "unknown": ArchUnknown, + "other": ArchOther, +} + +// Get a list of all valid HMS Arch +func GetHMSArchList() []string { + hmsArchList := []string{} + for _, arch := range hmsArchMap { + hmsArchList = append(hmsArchList, arch.String()) + } + return hmsArchList +} + +// Returns the given arch string (adjusting any capitalization differences), +// if a valid arch was given. Else, return the empty string. +func VerifyNormalizeArch(archStr string) string { + archLower := strings.ToLower(archStr) + value, ok := hmsArchMap[archLower] + if ok != true { + return "" + } else { + return value.String() + } +} + +// Allow HMSArch to be treated as a standard string type. +func (r HMSArch) String() string { return string(r) } + +// +// HMSClass - Physical hardware profile +// 1.0.0 +// + +type HMSClass string + +const ( + ClassRiver HMSClass = "River" + ClassMountain HMSClass = "Mountain" + ClassHill HMSClass = "Hill" +) + +// For case-insensitive verification and normalization of HMS Class +var hmsClassMap = map[string]HMSClass{ + "river": ClassRiver, + "mountain": ClassMountain, + "hill": ClassHill, +} + +// Get a list of all valid HMS Class +func GetHMSClassList() []string { + hmsClassList := []string{} + for _, class := range hmsClassMap { + hmsClassList = append(hmsClassList, class.String()) + } + return hmsClassList +} + +// Returns the given class string (adjusting any capitalization differences), +// if a valid class was given. Else, return the empty string. +func VerifyNormalizeClass(classStr string) string { + classLower := strings.ToLower(classStr) + value, ok := hmsClassMap[classLower] + if ok != true { + return "" + } else { + return value.String() + } +} + +// Allow HMSClass to be treated as a standard string type. +func (r HMSClass) String() string { return string(r) } + +// +// This is the equivalent to rs_node_t in Cascade. It is the minimal +// amount of of information for tracking component state and other vital +// info at an abstract level. The hwinv is for component-type specific +// fields and detailed HW attributes, i.e. just like XC. +// +// For most HMS operations (and non-inventory ones in the managed plane) +// this info should be sufficient. We want to keep it minimal for speed. +// Those fields that are not fixed at discovery should be those that can +// change outside of discovery in response to system activity, i.e. hwinv +// should contain only fields that are basically static between discoveries +// of the endpoint. Things like firmware versions might be an exception, +// but that would be a separate process SM would +// +// 1.0.0 +// +type Component struct { + ID string `json:"ID"` + Type string `json:"Type"` + State string `json:"State,omitempty"` + Flag string `json:"Flag,omitempty"` + Enabled *bool `json:"Enabled,omitempty"` + SwStatus string `json:"SoftwareStatus,omitempty"` + Role string `json:"Role,omitempty"` + SubRole string `json:"SubRole,omitempty"` + NID json.Number `json:"NID,omitempty"` + Subtype string `json:"Subtype,omitempty"` + NetType string `json:"NetType,omitempty"` + Arch string `json:"Arch,omitempty"` + Class string `json:"Class,omitempty"` + ReservationDisabled bool `json:"ReservationDisabled,omitempty"` + Locked bool `json:"Locked,omitempty"` +} + +// A collection of 0-n Components. It could just be an ordinary +// array but we want to save the option to have indentifying info, etc. +// packaged with it, e.g. the query parameters or options that produced it, +// especially if there are fewer fields than normal being included. +type ComponentArray struct { + Components []*Component `json:"Components"` +} diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/http.go b/vendor/github.com/Cray-HPE/hms-base/v2/http.go new file mode 100644 index 0000000..29eb808 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/http.go @@ -0,0 +1,223 @@ +// MIT License +// +// (C) Copyright [2019-2021] 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 base + +import ( + "bytes" + "context" + "crypto/tls" + "encoding/json" + "fmt" + "github.com/hashicorp/go-retryablehttp" + "io/ioutil" + "net/http" + "os" + "time" +) + +// Package to slightly abstract some of the most mundane of HTTP interactions. Primary intention is as a JSON +// getter and parser, with the latter being a generic interface that can be converted to a custom structure. +type HTTPRequest struct { + Context context.Context // Context to pass to the underlying HTTP client. + FullURL string // The full URL to pass to the HTTP client. + Method string // HTTP method to use. + Payload []byte // Bytes payload to pass if desired of ContentType. + Auth *Auth // Basic authentication if necessary using Auth struct. + Timeout time.Duration // Timeout for entire transaction. + SkipTLSVerify bool // Ignore TLS verification errors? + ExpectedStatusCode int // Expected HTTP status return code. + ContentType string // HTTP content type of Payload. +} + +// These are used to reduce duplication when adding User-Agent headers to requests. + +const USERAGENT = "User-Agent" + +func GetServiceInstanceName() (string, error) { + return os.Hostname() +} + +func SetHTTPUserAgent(req *http.Request, instName string) { + if req == nil { + return + } + + //See if this User Agent is already in place + + found := false + _, ok := req.Header[USERAGENT] + + if ok { + for _, v := range req.Header[USERAGENT] { + if v == instName { + found = true + break + } + } + } + + if !found { + req.Header.Add(USERAGENT, instName) + } +} + +// NewHTTPRequest creates a new HTTPRequest with default settings. +func NewHTTPRequest(fullURL string) *HTTPRequest { + return &HTTPRequest{ + Context: context.Background(), + FullURL: fullURL, + Method: "GET", + Payload: nil, + Auth: nil, + Timeout: 30 * time.Second, + SkipTLSVerify: false, + ExpectedStatusCode: http.StatusOK, + ContentType: "application/json", + } +} + +func (request *HTTPRequest) String() string { + return fmt.Sprintf( + "Context: %s, "+ + "Method: %s, "+ + "Full URL: %s, "+ + "Payload: %s, "+ + "Auth: (%s), "+ + "Timeout: %d, "+ + "SkipTLSVerify: %t, "+ + "ExpectedStatusCode: %d, "+ + "ContentType: %s", + request.Context, + request.Method, + request.FullURL, + string(request.Payload), + request.Auth, + request.Timeout, + request.SkipTLSVerify, + request.ExpectedStatusCode, + request.ContentType) +} + +// HTTP basic authentication structure. +type Auth struct { + Username string + Password string +} + +// Custom String function to prevent passwords from being printed directly (accidentally) to output. +func (auth Auth) String() string { + return fmt.Sprintf("Username: %s, Password: ", auth.Username) +} + +// Functions + +// Given a HTTPRequest this function will facilitate the desired operation using the retryablehttp package to gracefully +// retry should the connection fail. +func (request *HTTPRequest) DoHTTPAction() (payloadBytes []byte, err error) { + // Sanity check + if request.FullURL == "" { + err = fmt.Errorf("URL can not be empty") + return + } + + // Setup the common HTTP request stuff. + transport := &http.Transport{ + TLSClientConfig: &tls.Config{InsecureSkipVerify: request.SkipTLSVerify}, + } + client := retryablehttp.NewClient() + client.HTTPClient.Timeout = request.Timeout + client.HTTPClient.Transport = transport + + var req *retryablehttp.Request + + // If there's a payload, make sure to include it. + if request.Payload == nil { + req, _ = retryablehttp.NewRequest(request.Method, request.FullURL, nil) + } else { + req, _ = retryablehttp.NewRequest(request.Method, request.FullURL, bytes.NewBuffer(request.Payload)) + } + + // Set the context to the same we were given on the way in. + req = req.WithContext(request.Context) + + req.Header.Set("Content-Type", request.ContentType) + + if request.Auth != nil { + req.SetBasicAuth(request.Auth.Username, request.Auth.Password) + } + + resp, doErr := client.Do(req) + if doErr != nil { + err = fmt.Errorf("unable to do request: %s", doErr) + return + } + + // Make sure we get the status code we expect. + if resp.StatusCode != request.ExpectedStatusCode { + err = fmt.Errorf("received unexpected status code: %d", resp.StatusCode) + return + } + + // Get the payload. + payloadBytes, readErr := ioutil.ReadAll(resp.Body) + if readErr != nil { + err = fmt.Errorf("unable to read response body: %s", readErr) + return + } + + err = resp.Body.Close() + if err != nil { + return + } + + return +} + +// Returns an interface for the response body for a given request by calling DoHTTPAction and unmarshaling. +// As such, do NOT call this method unless you expect a JSON body in return! +// +// A powerful way to use this function is by feeding its result to the mapstructure package's Decode method: +// v := request.GetBodyForHTTPRequest() +// myTypeInterface := v.(map[string]interface{}) +// var myPopulatedStruct MyType +// mapstructure.Decode(myTypeInterface, &myPopulatedStruct) +// In this way you can generically make all your HTTP requests and essentially "cast" the resulting interface to a +// structure of your choosing using it as normal after that point. Just make sure to infer the correct type for `v`. +func (request *HTTPRequest) GetBodyForHTTPRequest() (v interface{}, err error) { + payloadBytes, err := request.DoHTTPAction() + if err != nil { + return + } + + stringPayloadBytes := string(payloadBytes) + if stringPayloadBytes != "" { + // If we've made it to here we have all we need, unmarshal. + jsonErr := json.Unmarshal(payloadBytes, &v) + if jsonErr != nil { + err = fmt.Errorf("unable to unmarshal payload: %s", jsonErr) + return + } + } + + return +} diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/util.go b/vendor/github.com/Cray-HPE/hms-base/v2/util.go new file mode 100644 index 0000000..0aca163 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/util.go @@ -0,0 +1,93 @@ +// MIT License +// +// (C) Copyright [2019, 2021] 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 base + +import ( + "strings" + "unicode" +) + +// Returns true if s is alphanumeric only (only letters and numbers, no +// punctuation or spaces. +func IsAlphaNum(s string) bool { + alphaNumFunc := func(c rune) bool { + return !unicode.IsLetter(c) && !unicode.IsNumber(c) + } + // Make sure s is alphanumeric. + idx := strings.IndexFunc(s, alphaNumFunc) + if idx != -1 { + return false + } + return true +} + +// Returns true if s is numeric only (only numbers, no letters, +// punctuation or spaces. +func IsNumeric(s string) bool { + numFunc := func(c rune) bool { + return !unicode.IsNumber(c) + } + // Make sure s is numeric. + idx := strings.IndexFunc(s, numFunc) + if idx != -1 { + return false + } + return true +} + +// Remove leading zeros, i.e. for each run of numbers, trim off leading +// zeros so each run starts with either non-zero, or is a single zero. +func RemoveLeadingZeros(s string) string { + //var b strings.Builder // Go 1.10 + b := []byte("") + + // base case + length := len(s) + if length < 2 { + return s + } + // Look for 0 after letter and before number. Skip these and + // pretend the previous value was still a letter for the next + // round, to catch multiple leading zeros. + i := 0 + lastLetter := true + for ; i < length-1; i++ { + if s[i] == '0' && lastLetter == true { + if unicode.IsNumber(rune(s[i+1])) { + // leading zero + continue + } + } + if unicode.IsNumber(rune(s[i])) { + lastLetter = false + } else { + lastLetter = true + } + // b.WriteByte(s[i]) // Go 1.10 + b = append(b, s[i]) + } + //b.WriteByte(s[i]) // Go 1.10 + //return b.String() + b = append(b, s[i]) + return string(b) +} diff --git a/vendor/github.com/Cray-HPE/hms-base/v2/worker-pool.go b/vendor/github.com/Cray-HPE/hms-base/v2/worker-pool.go new file mode 100644 index 0000000..259f0e1 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-base/v2/worker-pool.go @@ -0,0 +1,196 @@ +// MIT License +// +// (C) Copyright [2018, 2021] 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 base + +import ( + "log" +) + +/////////////////////////////////////////////////////////////////////////////// +// Job interface +/////////////////////////////////////////////////////////////////////////////// + +type JobType int +type JobStatus int + +const ( + JSTAT_DEFAULT JobStatus = 0 + JSTAT_QUEUED JobStatus = 1 + JSTAT_PROCESSING JobStatus = 2 + JSTAT_COMPLETE JobStatus = 3 + JSTAT_CANCELLED JobStatus = 4 + JSTAT_ERROR JobStatus = 5 + JSTAT_MAX JobStatus = 6 +) + +var JStatString = map[JobStatus]string{ + JSTAT_DEFAULT: "JSTAT_DEFAULT", + JSTAT_QUEUED: "JSTAT_QUEUED", + JSTAT_PROCESSING: "JSTAT_PROCESSING", + JSTAT_COMPLETE: "JSTAT_COMPLETE", + JSTAT_CANCELLED: "JSTAT_CANCELLED", + JSTAT_ERROR: "JSTAT_ERROR", + JSTAT_MAX: "JSTAT_MAX", +} + +type Job interface { + Log(format string, a ...interface{}) + //New(t JobType) + Type() JobType + //JobSCN() JobSCN + Run() + GetStatus() (JobStatus, error) + SetStatus(JobStatus, error) (JobStatus, error) + Cancel() JobStatus +} + +/////////////////////////////////////////////////////////////////////////////// +// Workers +/////////////////////////////////////////////////////////////////////////////// +type Worker struct { + WorkerPool chan chan Job + JobChannel chan Job + StopChannel chan bool +} + +// Create a new worker +func NewWorker(workerPool chan chan Job) Worker { + jChan := make(chan Job) + stopChan := make(chan bool) + return Worker{workerPool, jChan, stopChan} +} + +// Start a worker to start consuming Jobs +func (w Worker) Start() { + go func() { + for { + // Tell the dispatcher that this worker is available + w.WorkerPool <- w.JobChannel + + select { + case <-w.StopChannel: + // Received a stop signal + log.Print("Worker Stopping") + return + case job := <-w.JobChannel: + // Received a job! + job.Run() + if status, _ := job.GetStatus(); status != JSTAT_ERROR { + job.SetStatus(JSTAT_COMPLETE, nil) + } + } + } + }() +} + +// Send as stop signal to the worker +func (w Worker) Stop() { + go func() { + w.StopChannel <- true + }() +} + +/////////////////////////////////////////////////////////////////////////////// +// WorkerPool +/////////////////////////////////////////////////////////////////////////////// +type WorkerPool struct { + Workers []Worker + Pool chan chan Job + JobQueue chan Job + StopChannel chan bool +} + +// Create a new pool of workers +func NewWorkerPool(maxWorkers, maxJobQueue int) *WorkerPool { + workers := make([]Worker, maxWorkers) + pool := make(chan chan Job, maxWorkers) + jobQueue := make(chan Job, maxJobQueue) + stopChan := make(chan bool) + return &WorkerPool{workers, pool, jobQueue, stopChan} +} + +// Starts all of the workers and the job dispatcher +func (p *WorkerPool) Run() { + // Start the workers + for i, _ := range p.Workers { + worker := NewWorker(p.Pool) + worker.Start() + p.Workers[i] = worker + } + + go p.dispatch() +} + +// Hands out jobs to available workers +func (p *WorkerPool) dispatch() { + for { + // Wait for a job or a stop signal + select { + case <-p.StopChannel: + break + case job := <-p.JobQueue: + // Wait for a free worker or a stop signal + select { + case <-p.StopChannel: + break + case jobChannel := <-p.Pool: + if status, _ := job.GetStatus(); status != JSTAT_CANCELLED { + job.SetStatus(JSTAT_PROCESSING, nil) + // Send the job to the worker + jobChannel <- job + } + } + } + } + log.Print("Stopping Workers") + // Send a stop signal to all of the workers + for _, worker := range p.Workers { + worker.Stop() + } + log.Print("Stopping Dispatcher") +} + +// Queue a job. Returns 1 if the operation would +// block because the work queue is full. +func (p *WorkerPool) Queue(job Job) int { + if job == nil { + //Error + return -1 + } + select { + case p.JobQueue <- job: + job.SetStatus(JSTAT_QUEUED, nil) + //Job queued + default: + //WOULDBLOCK + return 1 + } + return 0 +} + +// Command the dispatcher to stop itself and all workers +func (p *WorkerPool) Stop() { + go func() { + p.StopChannel <- true + }() +} diff --git a/vendor/github.com/Cray-HPE/hms-xname/LICENSE b/vendor/github.com/Cray-HPE/hms-xname/LICENSE new file mode 100644 index 0000000..eaf7da4 --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-xname/LICENSE @@ -0,0 +1,21 @@ +MIT License + +(C) Copyright 2021-2022 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. diff --git a/vendor/github.com/Cray-HPE/hms-xname/xnametypes/hmstypes.go b/vendor/github.com/Cray-HPE/hms-xname/xnametypes/hmstypes.go new file mode 100644 index 0000000..222f0ff --- /dev/null +++ b/vendor/github.com/Cray-HPE/hms-xname/xnametypes/hmstypes.go @@ -0,0 +1,871 @@ +// +// MIT License +// +// (C) Copyright 2018-2022 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 xnametypes + +import ( + "fmt" + "regexp" + "strings" + "unicode" +) + +// +// HMS Component type. This is the top-level classification. There may be +// subtypes as required by HMS. This is above the Redfish type and there is +// no particular relationship to anything in Redfish (or whatever else at a +// lower level) implied. +// +// 1.0.0 +// + +type HMSType string + +// This is an enum (though they have no numeric values in ReST and we don't +// want to store them that way since we could get bit by renumbering. +// the down-side is that we will have to normalize capitalization +// differences. This isn't a huge problem since the type field should only +// be modified by discovery. It shouldn't be changed by the user, since +// it must map to a corresponding cname and we can't change its hierarchical +// relationship. +const ( + CDU HMSType = "CDU" // dD + CDUMgmtSwitch HMSType = "CDUMgmtSwitch" // dDwW + CabinetCDU HMSType = "CabinetCDU" // xXdD + Cabinet HMSType = "Cabinet" // xX + CabinetBMC HMSType = "CabinetBMC" // xXbB + CabinetPDUController HMSType = "CabinetPDUController" // xXmM + CabinetPDU HMSType = "CabinetPDU" // xXmMpP + CabinetPDUNic HMSType = "CabinetPDUNic" // xXmMiI + CabinetPDUOutlet HMSType = "CabinetPDUOutlet" // xXmMpPjJ DEPRECATED + CabinetPDUPowerConnector HMSType = "CabinetPDUPowerConnector" // xXmMpPvV + + Chassis HMSType = "Chassis" // xXcC + ChassisBMC HMSType = "ChassisBMC" // xXcCbB + ChassisBMCNic HMSType = "ChassisBMCNic" // xXcCbBiI + CMMRectifier HMSType = "CMMRectifier" // xXcCtT + CMMFpga HMSType = "CMMFpga" // xXcCfF + CEC HMSType = "CEC" // xXeE + ComputeModule HMSType = "ComputeModule" // xXcCsS + RouterModule HMSType = "RouterModule" // xXcCrR + NodeBMC HMSType = "NodeBMC" // xXcCsSbB + NodeBMCNic HMSType = "NodeBMCNic" // xXcCsSbBiI + NodeEnclosure HMSType = "NodeEnclosure" // xXcCsSeE + NodeEnclosurePowerSupply HMSType = "NodeEnclosurePowerSupply" // xXcCsSeEtT + NodePowerConnector HMSType = "NodePowerConnector" // xXcCsSjJ + Node HMSType = "Node" // xXcCsSbBnN + Processor HMSType = "Processor" // xXcCsSbBnNpP + StorageGroup HMSType = "StorageGroup" // xXcCsSbBnNgG + Drive HMSType = "Drive" // xXcCsSbBnNgGkK + NodeNic HMSType = "NodeNic" // xXcCsSbBnNiI + NodeHsnNic HMSType = "NodeHsnNic" // xXcCsSbBnNhH + Memory HMSType = "Memory" // xXcCsSbBnNdD + NodeAccel HMSType = "NodeAccel" // xXcCsSbBnNaA + NodeAccelRiser HMSType = "NodeAccelRiser" // xXcCsSbBnNrR + NodeFpga HMSType = "NodeFpga" // xXcCsSbBfF + HSNAsic HMSType = "HSNAsic" // xXcCrRaA + RouterFpga HMSType = "RouterFpga" // xXcCrRfF + RouterTOR HMSType = "RouterTOR" // xXcCrRtT + RouterTORFpga HMSType = "RouterTORFpga" // xXcCrRtTfF + RouterBMC HMSType = "RouterBMC" // xXcCrRbB + RouterBMCNic HMSType = "RouterBMCNic" // xXcCrRbBiI + RouterPowerConnector HMSType = "RouterPowerConnector" // xXcCrRvV + + HSNBoard HMSType = "HSNBoard" // xXcCrReE + HSNLink HMSType = "HSNLink" // xXcCrRaAlL + HSNConnector HMSType = "HSNConnector" // xXcCrRjJ + HSNConnectorPort HMSType = "HSNConnectorPort" // xXcCrRjJpP + MgmtSwitch HMSType = "MgmtSwitch" // xXcCwW + MgmtHLSwitchEnclosure HMSType = "MgmtHLSwitchEnclosure" // xXcChH + MgmtHLSwitch HMSType = "MgmtHLSwitch" // xXcChHsS + MgmtSwitchConnector HMSType = "MgmtSwitchConnector" // xXcCwWjJ + + // Special types and wildcards + SMSBox HMSType = "SMSBox" // smsN + Partition HMSType = "Partition" // pH.S + System HMSType = "System" // s0 + HMSTypeAll HMSType = "All" // all + HMSTypeAllComp HMSType = "AllComp" // all_comp + HMSTypeAllSvc HMSType = "AllSvc" // all_svc + HMSTypeInvalid HMSType = "INVALID" // Not a valid type/xname +) + +type HMSCompRecognitionEntry struct { + Type HMSType + ParentType HMSType + ExampleString string + Regex *regexp.Regexp + GenStr string + NumArgs int +} + +// Component recognition table keyed by normalized (i.e. all lowercase) +// component name. +// WARNING: if you modify this map you MUST regenerate the xnames, see https://github.com/Cray-HPE/hms-xname#code-generation +var hmsCompRecognitionTable = map[string]HMSCompRecognitionEntry{ + "invalid": { + HMSTypeInvalid, + HMSTypeInvalid, + "INVALID", + regexp.MustCompile("INVALID"), + "INVALID", + 0, + }, + "hmstypeall": { + HMSTypeAll, + HMSTypeInvalid, + "all", + regexp.MustCompile("^all$"), + "all", + 0, + }, + "hmstypeallsvc": { + HMSTypeAllSvc, + HMSTypeInvalid, + "all_svc", + regexp.MustCompile("^all_svc$"), + "all_svc", + 0, + }, + "hmstypeallcomp": { + HMSTypeAllComp, + HMSTypeInvalid, + "all_comp", + regexp.MustCompile("^all_comp$"), + "all_comp", + 0, + }, + "partition": { + Partition, + HMSTypeInvalid, + "pH.S", + regexp.MustCompile("^p([0-9]+)(.([0-9]+))?$"), + "p%d.%d", + 2, + }, + "system": { + System, + HMSTypeInvalid, + "sS", + regexp.MustCompile("^s0$"), + "s0", + 0, + }, + "smsbox": { + SMSBox, + HMSTypeInvalid, + "smsN", + regexp.MustCompile("^sms([0-9]+)$"), + "sms%d", + 1, + }, + "cdu": { + CDU, + System, + "dD", + regexp.MustCompile("^d([0-9]+)$"), + "d%d", + 1, + }, + "cdumgmtswitch": { + CDUMgmtSwitch, + CDU, + "dDwW", + regexp.MustCompile("^d([0-9]+)w([0-9]+)$"), + "d%dw%d", + 2, + }, + "cabinetcdu": { + CabinetCDU, + Cabinet, + "xXdD", + regexp.MustCompile("^x([0-9]{1,4})d([0-1])$"), + "x%dd%d", + 2, + }, + "cabinetpducontroller": { + CabinetPDUController, + Cabinet, + "xXmM", + regexp.MustCompile("^x([0-9]{1,4})m([0-3])$"), + "x%dm%d", + 2, + }, + "cabinetpdu": { + CabinetPDU, + CabinetPDUController, + "xXmMpP", + regexp.MustCompile("^x([0-9]{1,4})m([0-3])p([0-7])$"), + "x%dm%dp%d", + 3, + }, + "cabinetpdunic": { + CabinetPDUNic, + CabinetPDUController, + "xXmMpPiI", + regexp.MustCompile("^x([0-9]{1,4})m([0-3])i([0-3])$"), + "x%dm%di%d", + 3, + }, + "cabinetpduoutlet": { + CabinetPDUOutlet, + CabinetPDU, + "xXmMpPjJ", + regexp.MustCompile("^x([0-9]{1,4})m([0-3])p([0-7])j([1-9][0-9]*)$"), + "x%dm%dp%dj%d", + 4, + }, + "cabinetpdupowerconnector": { + CabinetPDUPowerConnector, + CabinetPDU, + "xXmMpPvV", + regexp.MustCompile("^x([0-9]{1,4})m([0-3])p([0-7])v([1-9][0-9]*)$"), + "x%dm%dp%dv%d", + 4, + }, + "cec": { + CEC, + Cabinet, + "xXeE", + regexp.MustCompile("^x([0-9]{1,4})e([0-1])$"), + "x%de%d", + 2, + }, + "cabinet": { + Cabinet, + System, + "xX", + regexp.MustCompile("^x([0-9]{1,4})$"), + "x%d", + 1, + }, + "cabinetbmc": { + CabinetBMC, + Cabinet, + "xXbB", + regexp.MustCompile("^x([0-9]{1,4})b([0])$"), + "x%db%d", + 2, + }, + "chassis": { + Chassis, + Cabinet, + "xXcC", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])$"), + "x%dc%d", + 2, + }, + "chassisbmc": { + ChassisBMC, + Chassis, + "xXcCbB", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])b([0])$"), + "x%dc%db%d", + 3, + }, + "chassisbmcnic": { + ChassisBMCNic, + ChassisBMC, + "xXcCbBiI", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])b([0])i([0-3])$"), + "x%dc%db%di%d", + 4, + }, + "cmmfpga": { + CMMFpga, + Chassis, + "xXcCfF", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])f([0])$"), + "x%dc%df%d", + 3, + }, + "cmmrectifier": { + CMMRectifier, + Chassis, + "xXcCtT", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])t([0-9])$"), + "x%dc%dt%d", + 3, + }, + "computemodule": { + ComputeModule, + Chassis, + "xXcCsS", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)$"), + "x%dc%ds%d", + 3, + }, + "storagegroup": { + StorageGroup, + Node, + "xXcCsSbBnNgG", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)g([0-9]+)$"), + "x%dc%ds%db%dn%dg%d", + 6, + }, + "drive": { + Drive, + StorageGroup, + "xXcCsSbBnNgGkK", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)g([0-9]+)k([0-9]+)$"), + "x%dc%ds%db%dn%dg%dk%d", + 7, + }, + "nodefpga": { + NodeFpga, + NodeEnclosure, + "xXcCsSbBfF", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)f([0])$"), + "x%dc%ds%db%df%d", + 5, + }, + "nodebmc": { + NodeBMC, + ComputeModule, + "xXcCsSbB", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)$"), + "x%dc%ds%db%d", + 4, + }, + "nodebmcnic": { + NodeBMCNic, + NodeBMC, + "xXcCsSbBiI", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)i([0-3])$"), + "x%dc%ds%db%di%d", + 5, + }, + "nodeenclosure": { + NodeEnclosure, + ComputeModule, + "xXcCsSbBeE", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)e([0-9]+)$"), + "x%dc%ds%de%d", + 4, + }, + "nodeenclosurepowersupply": { + NodeEnclosurePowerSupply, + NodeEnclosure, + "xXcCsSbBeEtT", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)e([0-9]+)t([0-9]+)$"), + "x%dc%ds%de%dt%d", + 5, + }, + "nodepowerconnector": { // 'j' is deprecated, should be 'v' + NodePowerConnector, + ComputeModule, + "xXcCsSv", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)[jv]([1-2])$"), + "x%dc%ds%dv%d", + 4, + }, + "hsnboard": { + HSNBoard, + RouterModule, + "xXcCrReE", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)e([0-9]+)$"), + "x%dc%dr%de%d", + 4, + }, + "node": { + Node, + NodeBMC, // Controlling entity is an nC or COTS BMC + "xXcCsSbBnN", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)$"), + "x%dc%ds%db%dn%d", + 5, + }, + "nodenic": { + NodeNic, + Node, + "xXcCsSbBnNiI", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)i([0-3])$"), + "x%dc%ds%db%dn%di%d", + 6, + }, + "nodehsnnic": { + NodeHsnNic, + Node, + "xXcCsSbBnNhH", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)h([0-3])$"), + "x%dc%ds%db%dn%dh%d", + 6, + }, + "nodeaccel": { + NodeAccel, + Node, + "xXcCsSbBnNaA", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)a([0-9]+)$"), + "x%dc%ds%db%dn%da%d", + 6, + }, + "nodeaccelriser": { + NodeAccelRiser, + Node, + "xXcCsSbBnNrR", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)r([0-7])$"), + "x%dc%ds%db%dn%dr%d", + 6, + }, + "memory": { + Memory, + Node, // Parent is actually a socket but we'll use node + "xXcCsSbBnNdD", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)d([0-9]+)$"), + "x%dc%ds%db%dn%dd%d", + 6, + }, + "processor": { + Processor, + Node, + "xXcCsSbBnNpP", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])s([0-9]+)b([0-9]+)n([0-9]+)p([0-3])$"), + "x%dc%ds%db%dn%dp%d", + 6, + }, + "routermodule": { + RouterModule, + Chassis, + "xXcCrR", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)$"), + "x%dc%dr%d", + 3, + }, + "routerfpga": { + RouterFpga, + RouterModule, + "xXcCrRfF", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)f([01])$"), + "x%dc%dr%df%d", + 4, + }, + "routertor": { + RouterTOR, + RouterModule, + "xXcCrRtT", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)t([0-9]+)$"), + "x%dc%dr%dt%d", + 4, + }, + "routertorfpga": { + RouterTORFpga, + RouterTOR, + "xXcCrRtTfF", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)t([0-9]+)f([0-1])$"), + "x%dc%dr%dt%df%d", + 5, + }, + "routerbmc": { + RouterBMC, + RouterModule, + "xXcCrRbB", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)b([0-9]+)$"), + "x%dc%dr%db%d", + 4, + }, + "routerbmcnic": { + RouterBMCNic, + RouterBMC, + "xXcCrRbBiI", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)b([0-9]+)i([0-3])$"), + "x%dc%dr%db%di%d", + 5, + }, + "routerpowerconnector": { + RouterPowerConnector, + RouterModule, + "xXcCrRvV", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)v([1-2])$"), + "x%dc%dr%dv%d", + 4, + }, + "hsnasic": { + HSNAsic, + RouterModule, + "xXcCrRaA", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)a([0-3])$"), + "x%dc%dr%da%d", + 4, + }, + "hsnconnector": { + HSNConnector, + RouterModule, + "xXcCrRjJ", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)j([1-9][0-9]*)$"), + "x%dc%dr%dj%d", + 4, + }, + "hsnconnectorport": { + HSNConnectorPort, + HSNConnector, + "xXcCrRjJpP", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)j([1-9][0-9]*)p([012])$"), + "x%dc%dr%dj%dp%d", + 5, + }, + "hsnlink": { + HSNLink, + HSNAsic, + "xXcCrRaAlL", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])r([0-9]+)a([0-3])l([0-9]+)$"), + "x%dc%dr%da%dl%d", + 5, + }, + "mgmtswitch": { + MgmtSwitch, + Chassis, + "xXcCwW", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])w([1-9][0-9]*)$"), + "x%dc%dw%d", + 3, + }, + "mgmtswitchconnector": { + MgmtSwitchConnector, + MgmtSwitch, + "xXcCwWjJ", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])w([1-9][0-9]*)j([1-9][0-9]*)$"), + "x%dc%dw%dj%d", + 4, + }, + "mgmthlswitchenclosure": { + MgmtHLSwitchEnclosure, + Chassis, + "xXcChH", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])h([1-9][0-9]*)$"), + "x%dc%dh%d", + 3, + }, + "mgmthlswitch": { + MgmtHLSwitch, + MgmtHLSwitchEnclosure, + "xXcChHsS", + regexp.MustCompile("^x([0-9]{1,4})c([0-7])h([1-9][0-9]*)s([1-9])$"), + "x%dc%dh%ds%d", + 4, + }, + // Module: { // ComputeModule or RouterModule. Can we support this? + // Module,hss/base hss/smd hss/sm hss/hmsds + // Chassis, + // "^x([0-9]{1,4})c([0-7])([sr])([0-9]+)$", + // "x%dc%d%s%d" + // }, +} + +func GetHMSCompRecognitionTable() map[string]HMSCompRecognitionEntry { + copy := map[string]HMSCompRecognitionEntry{} + + for k, v := range hmsCompRecognitionTable { + copy[k] = v + } + + return copy +} + +// Get the HMSType for a given xname, based on its pattern in the recognition +// table above. +// If no string matches, HMSTypeInvalid is returned. +func GetHMSType(xname string) HMSType { + for _, compEntry := range hmsCompRecognitionTable { + if compEntry.Regex.MatchString(xname) { + return compEntry.Type + } + } + return HMSTypeInvalid +} + +// Get the HMSType for a given xname, based on its pattern in the recognition +// table above (string version). +// If no type matches, the empty string is returned. +func GetHMSTypeString(xname string) string { + hmsType := GetHMSType(xname) + if hmsType == HMSTypeInvalid { + return "" + } + return hmsType.String() +} + +func GetHMSTypeList() []string { + hmsTypeList := []string{} + for _, compEntry := range hmsCompRecognitionTable { + hmsTypeList = append(hmsTypeList, compEntry.Type.String()) + } + return hmsTypeList +} + +// Returns whether hmsType is a controller type, i.e. that +// would host a Redfish entry point +func IsHMSTypeController(hmsType HMSType) bool { + switch hmsType { + case ChassisBMC: + fallthrough + case RouterBMC: + fallthrough + case NodeBMC: + fallthrough + case CabinetPDUController: + return true + default: + return false + } +} + +// Returns whether hmsTypeStr matches a controller type, i.e. that +// would host a Redfish entry point +func IsHMSTypeStrController(hmsTypeStr string) bool { + hmsType := ToHMSType(hmsTypeStr) + return IsHMSTypeController(hmsType) +} + +// Returns whether hmsType does not expect System collections to be +// present, or if so, non-empty. +func ControllerHasSystems(hmsType HMSType) bool { + switch hmsType { + case NodeBMC: + return true + default: + return false + } +} + +// String version of above. +func ControllerHasSystemsStr(hmsTypeStr string) bool { + hmsType := ToHMSType(hmsTypeStr) + return ControllerHasSystems(hmsType) +} + +// Normally every controller should has 1+ Chassis, but certain special +// types may not, and we don't use them if even if they are there. +func ControllerHasChassis(hmsType HMSType) bool { + switch hmsType { + case CabinetPDUController: + return false + default: + return true + } +} + +// String version of above. +func ControllerHasChassisStr(hmsTypeStr string) bool { + hmsType := ToHMSType(hmsTypeStr) + return ControllerHasChassis(hmsType) +} + +// Returns whether hmsType is a container type, i.e. that +// contains other components but is not a logical type (i.e. Node, +// that may or may not be a discrete hardware module), or a +// specialized terminal subcomponent (HSNAsic, Processor, etc.) +// +// NOTE: This is used specifically for Redfish "Chassis" components. +// so non-Chassis (e.g. PDUs) don't apply (different type, outlets are +// not really separate physical pieces) +func IsHMSTypeContainer(hmsType HMSType) bool { + switch hmsType { + case Cabinet: + fallthrough + case Chassis: + fallthrough + case ComputeModule: + fallthrough + case RouterModule: + fallthrough + case NodeEnclosure: + return true + case HSNBoard: + return true + default: + return false + } +} + +// Returns whether hmsTypeStr matches a container type, i.e. that +// contains other components but is not a logical type (i.e. Node, +// that may or may not be a discrete hardware module), or a +// specialized terminal subcomponent (HSNAsic, Processor, etc.) +func IsHMSTypeStrContainer(hmsTypeStr string) bool { + hmsType := ToHMSType(hmsTypeStr) + return IsHMSTypeContainer(hmsType) +} + +// Returns the given HMS type string (adjusting any capitalization differences), +// if a valid HMS component type was given. Else, return the empty string. +func VerifyNormalizeType(typeStr string) string { + typeLower := strings.ToLower(typeStr) + value, ok := hmsCompRecognitionTable[typeLower] + if ok != true { + return "" + } else { + return value.Type.String() + } +} + +// Returns the given HMSType (adjusting any capitalization differences), +// if a valid HMS component type string was given. Else, return HMSTypeINVALID. +func ToHMSType(typeStr string) HMSType { + typeLower := strings.ToLower(typeStr) + value, ok := hmsCompRecognitionTable[typeLower] + if ok != true { + return HMSTypeInvalid + } else { + return value.Type + } +} + +// GetHMSTypeFormatString for a given HMSType will return the corresponding +// fmt.Sprintf compatible format string, and the number of verbs are required +// for the format string. +func GetHMSTypeFormatString(hmsType HMSType) (string, int, error) { + typeLower := strings.ToLower(hmsType.String()) + if value, ok := hmsCompRecognitionTable[typeLower]; ok { + return value.GenStr, value.NumArgs, nil + } + + return "", 0, fmt.Errorf("unknown HMSType: %s", hmsType) +} + +// GetHMSTypeRegex for a given HMSType will return the regular expression +// that matches to match xnames of that HMSType. +func GetHMSTypeRegex(hmsType HMSType) (*regexp.Regexp, error) { + typeLower := strings.ToLower(hmsType.String()) + if value, ok := hmsCompRecognitionTable[typeLower]; ok { + return value.Regex, nil + } + + return nil, fmt.Errorf("unknown HMSType: %s", hmsType) +} + +// Allow HMSType to be treated as a standard string type. +func (t HMSType) String() string { return string(t) } + +// Given a properly formatted xname, get its immediate parent. +// i.e. x0c0s22b11 would become x0c0s22 +func GetHMSCompParent(xname string) string { + hmsType := GetHMSType(xname) + if hmsType == CDU || hmsType == Cabinet { + return "s0" + } + + // Trim all trailing numbers, then in the result, trim all trailing + // letters. + pstr := strings.TrimRightFunc(xname, + func(r rune) bool { return unicode.IsNumber(r) }) + pstr = strings.TrimRightFunc(pstr, + func(r rune) bool { return unicode.IsLetter(r) }) + return pstr +} + +// This lower-cases the xname id does other normalization so we +// always represent the same location with the same string. +// NOTE: this does not validate the xname, so do not use it +// to see if it is valid. However, any string post +// normalization should still be as invalid or valid as an xname as it +// was prior to this call. +func NormalizeHMSCompID(xname string) string { + xnameNorm := RemoveLeadingZeros(strings.TrimSpace(xname)) + return strings.ToLower(xnameNorm) +} + +// Returns true if xname is valid, i.e. matches some format for a +// valid HMS component type. False if it is invalid. +func IsHMSCompIDValid(xname string) bool { + hmsType := GetHMSType(xname) + if hmsType == HMSTypeInvalid { + return false + } + return true +} + +// Returns the given xname ID string (adjusting for any capitalization and +// whitespace and leading zero differences) if a valid xname was given. +// Else, return the empty string. +func VerifyNormalizeCompID(idStr string) string { + idNorm := NormalizeHMSCompID(idStr) + if IsHMSCompIDValid(idNorm) == true { + return idNorm + } else { + return "" + } +} + +// ValidateCompIDs validates an array of component IDs (xnames) into +// valid and invalid arrays optionally adding duplicates to the invalid +// array or discarding them. +func ValidateCompIDs(compIDs []string, dupsValid bool) ([]string, []string) { + seen := make(map[string]bool) + valid := []string{} + invalid := []string{} + + for _, compID := range compIDs { + if _, s := seen[compID]; !s { + seen[compID] = true + if IsHMSCompIDValid(compID) { + valid = append(valid, compID) + } else { + invalid = append(invalid, compID) + } + } else { + if !dupsValid { + invalid = append(invalid, compID) + } + } + } + + return valid, invalid +} + +// Remove leading zeros, i.e. for each run of numbers, trim off leading +// zeros so each run starts with either non-zero, or is a single zero. +// This has been duplicated from hms-base, but it allows the packages to be independent. +func RemoveLeadingZeros(s string) string { + //var b strings.Builder // Go 1.10 + b := []byte("") + + // base case + length := len(s) + if length < 2 { + return s + } + // Look for 0 after letter and before number. Skip these and + // pretend the previous value was still a letter for the next + // round, to catch multiple leading zeros. + i := 0 + lastLetter := true + for ; i < length-1; i++ { + if s[i] == '0' && lastLetter == true { + if unicode.IsNumber(rune(s[i+1])) { + // leading zero + continue + } + } + if unicode.IsNumber(rune(s[i])) { + lastLetter = false + } else { + lastLetter = true + } + // b.WriteByte(s[i]) // Go 1.10 + b = append(b, s[i]) + } + //b.WriteByte(s[i]) // Go 1.10 + //return b.String() + b = append(b, s[i]) + return string(b) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 095d671..8bed4b7 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,8 @@ # github.com/Cray-HPE/hms-base v1.15.0 -## explicit github.com/Cray-HPE/hms-base +# github.com/Cray-HPE/hms-base/v2 v2.0.1 +## explicit +github.com/Cray-HPE/hms-base/v2 # github.com/Cray-HPE/hms-certs v1.3.2 ## explicit github.com/Cray-HPE/hms-certs/pkg/hms_certs @@ -18,6 +20,7 @@ github.com/Cray-HPE/hms-msgbus github.com/Cray-HPE/hms-securestorage # github.com/Cray-HPE/hms-xname v1.2.0 ## explicit +github.com/Cray-HPE/hms-xname/xnametypes # github.com/DATA-DOG/go-sqlmock v1.3.3 ## explicit github.com/DATA-DOG/go-sqlmock From 81a24fc4d438908b5b58dbf3ce437e8e7886f94d Mon Sep 17 00:00:00 2001 From: Ryan Sjostrand Date: Wed, 30 Aug 2023 09:42:44 -0500 Subject: [PATCH 3/3] Checkin --- cmd/smd/discover.go | 12 ++++++------ cmd/smd/hmsdsmock_test.go | 24 +++++++++++------------ cmd/smd/smd-api.go | 14 +++++++------- internal/hbtdapi/hbtdapi_test.go | 3 ++- internal/hmsds/hmsds-api.go | 30 ++++++++++++++--------------- internal/hmsds/hmsds-postgres.go | 24 +++++++++++------------ internal/hmsds/hmsds-tx-postgres.go | 22 ++++++++++----------- internal/hmsds/query-shared-sq.go | 2 +- internal/slsapi/slsapi_test.go | 3 ++- pkg/redfish/rfendpoints.go | 2 +- pkg/sm/groups.go | 4 ++-- pkg/sm/hwinv.go | 4 ++-- 12 files changed, 73 insertions(+), 71 deletions(-) diff --git a/cmd/smd/discover.go b/cmd/smd/discover.go index 33ed04a..f33dd96 100644 --- a/cmd/smd/discover.go +++ b/cmd/smd/discover.go @@ -39,11 +39,11 @@ import ( // in the rf package to associate it with basic data needed to place it // within the system and extra HMS-level metadata. // We do this discovery and then use the resulting data to create HMS-level -// structures and place them in the dataxnametypes. +// structures and place them in the database. // // Args: // -// eps is a set of RedfishEndpoints retrieved from the dataxnametypes. +// eps is a set of RedfishEndpoints retrieved from the database. // id is the id of the DiscoveryStatus object to write status to. func (s *SmD) discoverFromEndpoints(eps []*sm.RedfishEndpoint, id uint, update, force bool) { idsFiltered := make([]string, 0, len(eps)) @@ -128,7 +128,7 @@ func (s *SmD) discoverFromEndpoints(eps []*sm.RedfishEndpoint, id uint, update, // // Args: // -// ep is a single RedfishEndpoint retrieved from the dataxnametypes. +// ep is a single RedfishEndpoint retrieved from the database. // id is the id of the DiscoveryStatus object to write status to. func (s *SmD) discoverFromEndpoint(ep *sm.RedfishEndpoint, id uint, force bool) { if ep.RediscOnUpdate != true { @@ -198,7 +198,7 @@ func (s *SmD) doDiscovery(rfEP *rf.RedfishEP) { rfEP.GetRootInfo() // Create/update HMS-level components from the retrieved discovery data - // from Redfish. This also inserts the data into the dataxnametypes. + // from Redfish. This also inserts the data into the database. s.updateFromRfEndpoint(rfEP) } @@ -309,7 +309,7 @@ func (s *SmD) updateFromRfEndpoint(rfEP *rf.RedfishEP) error { savedPw = ep.Password savedUn = ep.User if s.readVault { - // Empty the password so it doesn't get stored in the dataxnametypes. + // Empty the password so it doesn't get stored in the database. ep.Password = "" } } @@ -389,7 +389,7 @@ func (s *SmD) updateFromRfEndpoint(rfEP *rf.RedfishEP) error { if err != nil { // If we fail to store credentials in vault, we'll lose the // credentials and the component endpoints associated with - // them will still be successfully in the dataxnametypes. + // them will still be successfully in the database. s.LogAlways("Failed to store credentials for %s in Vault - %s", cep.ID, err) savedErr = err } diff --git a/cmd/smd/hmsdsmock_test.go b/cmd/smd/hmsdsmock_test.go index 4b12a13..b6ce67c 100644 --- a/cmd/smd/hmsdsmock_test.go +++ b/cmd/smd/hmsdsmock_test.go @@ -1611,7 +1611,7 @@ func (d *hmsdbtest) DeleteNodeMapByID(id string) (bool, error) { return d.t.DeleteNodeMapByID.Return.changed, d.t.DeleteNodeMapByID.Return.err } -// Delete all Node NID Mapping entries from dataxnametypes. +// Delete all Node NID Mapping entries from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteNodeMapsAll() (int64, error) { return d.t.DeleteNodeMapsAll.Return.numRows, d.t.DeleteNodeMapsAll.Return.err @@ -1655,7 +1655,7 @@ func (d *hmsdbtest) DeletePowerMapByID(id string) (bool, error) { return d.t.DeletePowerMapByID.Return.changed, d.t.DeletePowerMapByID.Return.err } -// Delete all Power Mapping entries from dataxnametypes. +// Delete all Power Mapping entries from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeletePowerMapsAll() (int64, error) { return d.t.DeletePowerMapsAll.Return.numRows, d.t.DeletePowerMapsAll.Return.err @@ -1892,7 +1892,7 @@ func (d *hmsdbtest) GetRFEndpointsFilter(f *hmsds.RedfishEPFilter) ([]*sm.Redfis return d.t.GetRFEndpointsFilter.Return.entries, d.t.GetRFEndpointsFilter.Return.err } -// Insert new RedfishEndpoint into dataxnametypes. +// Insert new RedfishEndpoint into database. // Does not update any ComponentEndpoint children. // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -1911,7 +1911,7 @@ func (d *hmsdbtest) InsertRFEndpoints(eps *sm.RedfishEndpointArray) error { return d.t.InsertRFEndpoints.Return.err } -// Update existing RedfishEndpointArray entry in dataxnametypes. +// Update existing RedfishEndpointArray entry in database. // Does not update any ComponentEndpoint children. // Returns updated entry or nil/nil if not found. If an error occurred, // nil/error will be returned. @@ -1973,7 +1973,7 @@ func (d *hmsdbtest) DeleteRFEndpointByID(id string) (bool, error) { return d.t.DeleteRFEndpointByID.Return.changed, d.t.DeleteRFEndpointByID.Return.err } -// Delete all RedfishEndpoints from dataxnametypes. +// Delete all RedfishEndpoints from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteRFEndpointsAll() (int64, error) { return d.t.DeleteRFEndpointsAll.Return.numRows, d.t.DeleteRFEndpointsAll.Return.err @@ -1990,7 +1990,7 @@ func (d *hmsdbtest) DeleteRFEndpointByIDSetEmpty(id string) (bool, []string, err d.t.DeleteRFEndpointByIDSetEmpty.Return.err } -// Delete all RedfishEndpoints from dataxnametypes. +// Delete all RedfishEndpoints from database. // This also deletes all child ComponentEndpoints, and in addition, // sets the State/Components entries for those ComponentEndpoints to Empty/OK // Also returns number of deleted rows, if error is nil. @@ -2049,7 +2049,7 @@ func (d *hmsdbtest) DeleteCompEndpointByID(id string) (bool, error) { return d.t.DeleteCompEndpointByID.Return.changed, d.t.DeleteCompEndpointByID.Return.err } -// Delete all ComponentEndpoints from dataxnametypes. +// Delete all ComponentEndpoints from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteCompEndpointsAll() (int64, error) { return d.t.DeleteCompEndpointsAll.Return.numRows, d.t.DeleteCompEndpointsAll.Return.err @@ -2067,7 +2067,7 @@ func (d *hmsdbtest) DeleteCompEndpointByIDSetEmpty(id string) (bool, []string, e d.t.DeleteCompEndpointByIDSetEmpty.Return.err } -// Delete all ComponentEndpoints from dataxnametypes. In addition, +// Delete all ComponentEndpoints from database. In addition, // sets the State/Components entry for each ComponentEndpoint to Empty/OK // Also returns number of deleted rows, if error is nil, and also string array // of those xname IDs that were set to Empty/OK (i.e. not already Empty/OK) @@ -2128,7 +2128,7 @@ func (d *hmsdbtest) DeleteServiceEndpointByID(svc, id string) (bool, error) { return d.t.DeleteServiceEndpointByID.Return.changed, d.t.DeleteServiceEndpointByID.Return.err } -// Delete all ServiceEndpoints from dataxnametypes. +// Delete all ServiceEndpoints from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteServiceEndpointsAll() (int64, error) { return d.t.DeleteServiceEndpointsAll.Return.numRows, d.t.DeleteServiceEndpointsAll.Return.err @@ -2155,7 +2155,7 @@ func (d *hmsdbtest) GetCompEthInterfaceFilter(f_opts ...hmsds.CompEthInterfaceFi return d.t.GetCompEthInterfaceFilter.Return.ceis, d.t.GetCompEthInterfaceFilter.Return.err } -// Insert a new CompEthInterface into the dataxnametypes. +// Insert a new CompEthInterface into the database. // If ID or MAC address already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil func (d *hmsdbtest) InsertCompEthInterface(cei *sm.CompEthInterfaceV2) error { @@ -2172,7 +2172,7 @@ func (d *hmsdbtest) InsertCompEthInterfaces(ceis []*sm.CompEthInterfaceV2) error return d.t.InsertCompEthInterfaces.Return.err } -// Insert/update a CompEthInterface in the dataxnametypes. +// Insert/update a CompEthInterface in the database. // If ID or MAC address already exists, only overwrite ComponentID // and Type fields. // No insertion done on err != nil @@ -2223,7 +2223,7 @@ func (d *hmsdbtest) DeleteCompEthInterfaceByID(id string) (bool, error) { return d.t.DeleteCompEthInterfaceByID.Return.didDelete, d.t.DeleteCompEthInterfaceByID.Return.err } -// Delete all CompEthInterfaces from the dataxnametypes. +// Delete all CompEthInterfaces from the database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbtest) DeleteCompEthInterfacesAll() (int64, error) { return d.t.DeleteCompEthInterfacesAll.Return.numRows, d.t.DeleteCompEthInterfacesAll.Return.err diff --git a/cmd/smd/smd-api.go b/cmd/smd/smd-api.go index 5242c70..e30f460 100644 --- a/cmd/smd/smd-api.go +++ b/cmd/smd/smd-api.go @@ -2251,7 +2251,7 @@ func (s *SmD) doRedfishEndpointPut(w http.ResponseWriter, r *http.Request) { // redfish endpoint changes we just made in the database? If we // fail to store credentials in vault, we'll lose the credentials // and the redfish endpoints associated with them will still be - // successfully in the dataxnametypes. I think this is ok for now + // successfully in the database. I think this is ok for now // since the future plan is for HSM to only read credentials // from Vault. Other services like REDS should be writing the // credentials to Vault. @@ -2355,7 +2355,7 @@ func (s *SmD) doRedfishEndpointPatch(w http.ResponseWriter, r *http.Request) { // redfish endpoint changes we just made in the database? If we // fail to store credentials in vault, we'll lose the credentials // and the redfish endpoints associated with them will still be - // successfully in the dataxnametypes. I think this is ok for now + // successfully in the database. I think this is ok for now // since the future plan is for HSM to only read credentials // from Vault. Other services like REDS should be writing the // credentials to Vault. @@ -2479,7 +2479,7 @@ func (s *SmD) doRedfishEndpointsPost(w http.ResponseWriter, r *http.Request) { // endpoints we just inserted into the database? If we fail to // store credentials in vault, we'll lose the credentials and // the redfish endpoints associated with them will still be - // successfully in the dataxnametypes. I think this is ok for now + // successfully in the database. I think this is ok for now // since the future plan is for HSM to only read credentials // from Vault. Other services like REDS should be writing the // credentials to Vault. @@ -3384,7 +3384,7 @@ func (s *SmD) doPostSCNSubscription(w http.ResponseWriter, r *http.Request) { } s.scnSubLock.Lock() - // Insert the subscription into the dataxnametypes. + // Insert the subscription into the database. // Existing subscriptions will be updated. id, err := s.db.InsertSCNSubscription(*subIn) if err != nil { @@ -3556,7 +3556,7 @@ func (s *SmD) doPutSCNSubscription(w http.ResponseWriter, r *http.Request) { } s.scnSubLock.Lock() - // Update the subscription in the dataxnametypes. + // Update the subscription in the database. didUpdate, err := s.db.UpdateSCNSubscription(id, *subIn) if err != nil { s.scnSubLock.Unlock() @@ -3677,7 +3677,7 @@ func (s *SmD) doPatchSCNSubscription(w http.ResponseWriter, r *http.Request) { } s.scnSubLock.Lock() - // Patch the subscription in the dataxnametypes. + // Patch the subscription in the database. didPatch, err := s.db.PatchSCNSubscription(id, patchIn.Op, *patchIn) if err != nil { s.scnSubLock.Unlock() @@ -3692,7 +3692,7 @@ func (s *SmD) doPatchSCNSubscription(w http.ResponseWriter, r *http.Request) { // Patch the cached subscription table. // Look for an existing subscription. Patch it. // Note: There is a possibility that the cached subscription table is out - // of sync with the dataxnametypes. Patch what we have anyway. We'll get + // of sync with the database. Patch what we have anyway. We'll get // corrected by the SCNSubscriptionRefresh() thread. for i, sub := range s.scnSubs.SubscriptionList { if sub.ID == id { diff --git a/internal/hbtdapi/hbtdapi_test.go b/internal/hbtdapi/hbtdapi_test.go index 6b8896c..fa054d2 100644 --- a/internal/hbtdapi/hbtdapi_test.go +++ b/internal/hbtdapi/hbtdapi_test.go @@ -34,6 +34,7 @@ import ( "os" "testing" + base "github.com/Cray-HPE/hms-base/v2" "github.com/hashicorp/go-retryablehttp" ) @@ -204,7 +205,7 @@ func NewRTFuncSLSAPI() RTFunc { return func(req *http.Request) *http.Response { bad := true if len(req.Header) > 0 { - vals, ok := req.Header[xnametypes.USERAGENT] + vals, ok := req.Header[base.USERAGENT] if ok { for _, v := range vals { if v == testSvcName { diff --git a/internal/hmsds/hmsds-api.go b/internal/hmsds/hmsds-api.go index d49273a..ec15029 100644 --- a/internal/hmsds/hmsds-api.go +++ b/internal/hmsds/hmsds-api.go @@ -299,7 +299,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteNodeMapByID(id string) (bool, error) - // Delete all Node NID Mapping entries from dataxnametypes. + // Delete all Node NID Mapping entries from database. // Also returns number of deleted rows, if error is nil. DeleteNodeMapsAll() (int64, error) @@ -325,7 +325,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeletePowerMapByID(id string) (bool, error) - // Delete all Power Mapping entries from dataxnametypes. + // Delete all Power Mapping entries from database. // Also returns number of deleted rows, if error is nil. DeletePowerMapsAll() (int64, error) @@ -467,7 +467,7 @@ type HMSDB interface { // do not match ALL of the non-empty strings in the filter struct GetRFEndpointsFilter(f *RedfishEPFilter) ([]*sm.RedfishEndpoint, error) - // Insert new RedfishEndpoint into dataxnametypes. + // Insert new RedfishEndpoint into database. // Does not insert any ComponentEndpoint children. // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -480,7 +480,7 @@ type HMSDB interface { // No insertions are done on err != nil InsertRFEndpoints(eps *sm.RedfishEndpointArray) error - // Update existing RedfishEndpointArray entry in dataxnametypes. + // Update existing RedfishEndpointArray entry in database. // Does not update any ComponentEndpoint children. // Returns updated entry or nil/nul if not found. If an error occurred, // nil/error will be returned. @@ -519,7 +519,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteRFEndpointByID(id string) (bool, error) - // Delete all RedfishEndpoints from dataxnametypes. + // Delete all RedfishEndpoints from database. // Also returns number of deleted rows, if error is nil. DeleteRFEndpointsAll() (int64, error) @@ -529,7 +529,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteRFEndpointByIDSetEmpty(id string) (bool, []string, error) - // Delete all RedfishEndpoints from dataxnametypes. + // Delete all RedfishEndpoints from database. // This also deletes all child ComponentEndpoints, and in addition, // sets the State/Components entries for those ComponentEndpoints to Empty/OK // Also returns number of deleted rows, if error is nil. @@ -566,7 +566,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteCompEndpointByID(id string) (bool, error) - // Delete all ComponentEndpoints from dataxnametypes. + // Delete all ComponentEndpoints from database. // Also returns number of deleted rows, if error is nil. DeleteCompEndpointsAll() (int64, error) @@ -577,7 +577,7 @@ type HMSDB interface { // string array returns the single xname ID that changed state or is empty. DeleteCompEndpointByIDSetEmpty(id string) (bool, []string, error) - // Delete all ComponentEndpoints from dataxnametypes. In addition, + // Delete all ComponentEndpoints from database. In addition, // sets the State/Components entry for each ComponentEndpoint to Empty/OK // Also returns number of deleted rows, if error is nil, and also string array // of those xname IDs that were set to Empty/OK (i.e. not already Empty/OK) @@ -614,7 +614,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteServiceEndpointByID(svc, id string) (bool, error) - // Delete all ServiceEndpoints from dataxnametypes. + // Delete all ServiceEndpoints from database. // Also returns number of deleted rows, if error is nil. DeleteServiceEndpointsAll() (int64, error) @@ -630,7 +630,7 @@ type HMSDB interface { // do not match ALL of the non-empty strings in the filter struct GetCompEthInterfaceFilter(f_opts ...CompEthInterfaceFiltFunc) ([]*sm.CompEthInterfaceV2, error) - // Insert a new CompEthInterface into the dataxnametypes. + // Insert a new CompEthInterface into the database. // If ID or MAC address already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil InsertCompEthInterface(cei *sm.CompEthInterfaceV2) error @@ -641,7 +641,7 @@ type HMSDB interface { // No insertions are done on err != nil InsertCompEthInterfaces(ceis []*sm.CompEthInterfaceV2) error - // Insert/update a CompEthInterface in the dataxnametypes. + // Insert/update a CompEthInterface in the database. // If ID or MAC address already exists, only overwrite ComponentID // and Type fields. // No insertion done on err != nil @@ -675,7 +675,7 @@ type HMSDB interface { // Return true if there was a row affected, false if there were zero. DeleteCompEthInterfaceByID(id string) (bool, error) - // Delete all CompEthInterfaces from the dataxnametypes. + // Delete all CompEthInterfaces from the database. // Also returns number of deleted rows, if error is nil. DeleteCompEthInterfacesAll() (int64, error) @@ -1161,7 +1161,7 @@ type HMSDBTx interface { GetHWInvByFRUAllTx() ([]*sm.HWInvByFRU, error) // Insert or update HWInventoryByLocation struct (in transaction) - // If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If + // If PopulatedFRU is present, only the FRUID is added to the database. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction), as @@ -1169,7 +1169,7 @@ type HMSDBTx interface { InsertHWInvByLocTx(hl *sm.HWInvByLoc) error // Insert or update HWInventoryByLocation structs (in transaction) - // If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If + // If PopulatedFRU is present, only the FRUID is added to the database. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction), as @@ -1543,7 +1543,7 @@ type HMSDBTx interface { // Component Lock Management // // // - // Insert component reservations into the dataxnametypes. + // Insert component reservations into the database. // To Insert reservations without a duration, the component must be locked. // To Insert reservations with a duration, the component must be unlocked. InsertCompReservationsTx(ids []string, duration int) ([]sm.CompLockV2Success, string, error) diff --git a/internal/hmsds/hmsds-postgres.go b/internal/hmsds/hmsds-postgres.go index acf5225..4192b18 100644 --- a/internal/hmsds/hmsds-postgres.go +++ b/internal/hmsds/hmsds-postgres.go @@ -1187,7 +1187,7 @@ func (d *hmsdbPg) DeleteNodeMapByID(id string) (bool, error) { return didDelete, err } -// Delete all Node NID Mapping entries from dataxnametypes. +// Delete all Node NID Mapping entries from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteNodeMapsAll() (int64, error) { t, err := d.Begin() @@ -1294,7 +1294,7 @@ func (d *hmsdbPg) DeletePowerMapByID(id string) (bool, error) { return didDelete, err } -// Delete all Power Mapping entries from dataxnametypes. +// Delete all Power Mapping entries from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeletePowerMapsAll() (int64, error) { t, err := d.Begin() @@ -1998,7 +1998,7 @@ func (d *hmsdbPg) GetRFEndpointsFilter(f *RedfishEPFilter) ([]*sm.RedfishEndpoin return reps, nil } -// Insert new RedfishEndpoint into dataxnametypes. +// Insert new RedfishEndpoint into database. // Does not update any ComponentEndpoint children. // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -2041,7 +2041,7 @@ func (d *hmsdbPg) InsertRFEndpoints(eps *sm.RedfishEndpointArray) error { return nil } -// Update existing RedfishEndpointArray entry in dataxnametypes. +// Update existing RedfishEndpointArray entry in database. // Does not update any ComponentEndpoint children. // Returns updated entry or nil/nil if not found. If an error occurred, // nil/error will be returned. @@ -2379,7 +2379,7 @@ func (d *hmsdbPg) DeleteRFEndpointByID(id string) (bool, error) { return didDelete, err } -// Delete all RedfishEndpoints from dataxnametypes. +// Delete all RedfishEndpoints from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteRFEndpointsAll() (int64, error) { t, err := d.Begin() @@ -2438,7 +2438,7 @@ func (d *hmsdbPg) DeleteRFEndpointByIDSetEmpty(id string) (bool, []string, error return true, affectedIDs, nil } -// Delete all RedfishEndpoints from dataxnametypes. +// Delete all RedfishEndpoints from database. // This also deletes all child ComponentEndpoints, and in addition, // sets the State/Components entries for those ComponentEndpoints to Empty/OK // Also returns number of deleted rows, if error is nil. @@ -2576,7 +2576,7 @@ func (d *hmsdbPg) DeleteCompEndpointByID(id string) (bool, error) { return didDelete, err } -// Delete all ComponentEndpoints from dataxnametypes. +// Delete all ComponentEndpoints from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteCompEndpointsAll() (int64, error) { t, err := d.Begin() @@ -2635,7 +2635,7 @@ func (d *hmsdbPg) DeleteCompEndpointByIDSetEmpty(id string) (bool, []string, err return true, affectedIDs, nil } -// Delete all ComponentEndpoints from dataxnametypes. In addition, +// Delete all ComponentEndpoints from database. In addition, // sets the State/Components entry for each ComponentEndpoint to Empty/OK // Also returns number of deleted rows, if error is nil, and also string array // of those xname IDs that were set to Empty/OK (i.e. not already Empty/OK) @@ -2776,7 +2776,7 @@ func (d *hmsdbPg) DeleteServiceEndpointByID(svc, id string) (bool, error) { return didDelete, err } -// Delete all ServiceEndpoints from dataxnametypes. +// Delete all ServiceEndpoints from database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteServiceEndpointsAll() (int64, error) { t, err := d.Begin() @@ -2902,7 +2902,7 @@ func (d *hmsdbPg) GetCompEthInterfaceFilter(f_opts ...CompEthInterfaceFiltFunc) return ceis, err } -// Insert a new CompEthInterface into the dataxnametypes. +// Insert a new CompEthInterface into the database. // If ID or MAC address already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil func (d *hmsdbPg) InsertCompEthInterface(cei *sm.CompEthInterfaceV2) error { @@ -2941,7 +2941,7 @@ func (d *hmsdbPg) InsertCompEthInterfaces(ceis []*sm.CompEthInterfaceV2) error { return nil } -// Insert/update a CompEthInterface in the dataxnametypes. +// Insert/update a CompEthInterface in the database. // If ID or MAC address already exists, only overwrite ComponentID // and Type fields. // No insertion done on err != nil @@ -3101,7 +3101,7 @@ func (d *hmsdbPg) DeleteCompEthInterfaceByID(id string) (bool, error) { return didDelete, err } -// Delete all CompEthInterfaces from the dataxnametypes. +// Delete all CompEthInterfaces from the database. // Also returns number of deleted rows, if error is nil. func (d *hmsdbPg) DeleteCompEthInterfacesAll() (int64, error) { t, err := d.Begin() diff --git a/internal/hmsds/hmsds-tx-postgres.go b/internal/hmsds/hmsds-tx-postgres.go index e883891..85bb0dd 100644 --- a/internal/hmsds/hmsds-tx-postgres.go +++ b/internal/hmsds/hmsds-tx-postgres.go @@ -953,7 +953,7 @@ func (t *hmsdbPgTx) UpdateCompFlagOnlyTx(id string, flag string) (int64, error) // Normalize key normID := xnametypes.NormalizeHMSCompID(id) - // Make update in dataxnametypes. + // Make update in database. result, err := stmt.ExecContext(t.ctx, &flag, &normID) @@ -1045,7 +1045,7 @@ func (t *hmsdbPgTx) UpdateCompEnabledTx(id string, enabled bool) (int64, error) // Normalize key normID := xnametypes.NormalizeHMSCompID(id) - // Make update in dataxnametypes. + // Make update in database. result, err := stmt.ExecContext(t.ctx, &enabledFlg, &normID) @@ -1127,7 +1127,7 @@ func (t *hmsdbPgTx) UpdateCompSwStatusTx(id string, swStatus string) (int64, err // Normalize key normID := xnametypes.NormalizeHMSCompID(id) - // Make update in dataxnametypes. + // Make update in database. result, err := stmt.ExecContext(t.ctx, &swStatus, &normID) @@ -1227,7 +1227,7 @@ func (t *hmsdbPgTx) UpdateCompRoleTx(id string, role, subRole string) (int64, er // Normalize key normID := xnametypes.NormalizeHMSCompID(id) - // Make update in dataxnametypes. + // Make update in database. result, err := stmt.ExecContext(t.ctx, &role, &subRole, @@ -1377,7 +1377,7 @@ func (t *hmsdbPgTx) UpdateCompNIDTx(c *base.Component) error { // Normalize key normID := xnametypes.NormalizeHMSCompID(c.ID) - // Make update in dataxnametypes. + // Make update in database. _, err = stmt.ExecContext(t.ctx, &rawNID, &normID) @@ -2008,7 +2008,7 @@ func (t *hmsdbPgTx) GetHWInvByFRUAllTx() ([]*sm.HWInvByFRU, error) { } // Insert or update HWInventoryByLocation struct (in transaction) -// If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If +// If PopulatedFRU is present, only the FRUID is added to the database. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction). @@ -2074,7 +2074,7 @@ func (t *hmsdbPgTx) InsertHWInvByLocTx(hl *sm.HWInvByLoc) error { } // Insert or update HWInventoryByLocation struct (in transaction) -// If PopulatedFRU is present, only the FRUID is added to the dataxnametypes. If +// If PopulatedFRU is present, only the FRUID is added to the database. If // it is not, this effectively "depopulates" the given location. // The actual HWInventoryByFRU struct must be stored FIRST using the // corresponding function (presumably within the same transaction). @@ -2724,7 +2724,7 @@ func (t *hmsdbPgTx) GetRFEndpointsFilterTx(f *RedfishEPFilter) ([]*sm.RedfishEnd return reps, nil } -// Insert new RedfishEndpoint into dataxnametypes. Does not insert any +// Insert new RedfishEndpoint into database. Does not insert any // ComponentEndpoint children.(In transaction.) // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -2786,7 +2786,7 @@ func (t *hmsdbPgTx) InsertRFEndpointTx(ep *sm.RedfishEndpoint) error { return nil } -// Insert new RedfishEndpoints into dataxnametypes. Does not insert any +// Insert new RedfishEndpoints into database. Does not insert any // ComponentEndpoint children.(In transaction.) // If ID or FQDN already exists, return ErrHMSDSDuplicateKey // No insertion done on err != nil @@ -3538,7 +3538,7 @@ func (t *hmsdbPgTx) SetChildCompStatesCompEndpointsTx( return []string{}, nil } // Should return the same set of xname IDs as 'ids', assuming they are - // actually in the dataxnametypes. Also locks both ComponentEP/RedfishEP tables + // actually in the database. Also locks both ComponentEP/RedfishEP tables // if wrLock is true, which is the main thing. cids, err := t.GetCompEndpointIDsTx(CE_IDs(ids), CE_WRLock) if err != nil || len(cids) == 0 { @@ -5163,7 +5163,7 @@ func (t *hmsdbPgTx) DeleteMemberTx(uuid, id string) (bool, error) { // //////////////////////////////////////////////////////////////////////////// -// Insert component reservations into the dataxnametypes. +// Insert component reservations into the database. // To Insert reservations without a duration, the component must be locked. // To Insert reservations with a duration, the component must be unlocked. func (t *hmsdbPgTx) InsertCompReservationsTx(ids []string, duration int) ([]sm.CompLockV2Success, string, error) { diff --git a/internal/hmsds/query-shared-sq.go b/internal/hmsds/query-shared-sq.go index 95c039d..b202dd5 100644 --- a/internal/hmsds/query-shared-sq.go +++ b/internal/hmsds/query-shared-sq.go @@ -932,7 +932,7 @@ func selectComponentsHierarchy( // Create a select builder based on fieldfilter and the component filter. // If needed, join with group/partition table for additional fields/filtering. -// returns squirrel.SelectBuilder for building onto or sending to dataxnametypes. +// returns squirrel.SelectBuilder for building onto or sending to database. func makeComponentQuery(alias string, f *ComponentFilter, fltr FieldFilter) ( sq.SelectBuilder, error, ) { diff --git a/internal/slsapi/slsapi_test.go b/internal/slsapi/slsapi_test.go index 1dccc03..4ec5a30 100644 --- a/internal/slsapi/slsapi_test.go +++ b/internal/slsapi/slsapi_test.go @@ -34,6 +34,7 @@ import ( "os" "testing" + base "github.com/Cray-HPE/hms-base/v2" "github.com/hashicorp/go-retryablehttp" ) @@ -285,7 +286,7 @@ func NewRTFuncSLSAPI() RTFunc { return func(req *http.Request) *http.Response { bad := true if len(req.Header) > 0 { - vals, ok := req.Header[xnametypes.USERAGENT] + vals, ok := req.Header[base.USERAGENT] if ok { for _, v := range vals { if v == testSvcName { diff --git a/pkg/redfish/rfendpoints.go b/pkg/redfish/rfendpoints.go index 0953ec0..94ce944 100644 --- a/pkg/redfish/rfendpoints.go +++ b/pkg/redfish/rfendpoints.go @@ -572,7 +572,7 @@ type RedfishEP struct { // Create RedfishEP struct from a validated RedfishEndpointDescription. // The description would be generated from user-supplied RawEndpoints and/or -// retrieved from the dataxnametypes. +// 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) { diff --git a/pkg/sm/groups.go b/pkg/sm/groups.go index 84caf08..ce2ae2b 100644 --- a/pkg/sm/groups.go +++ b/pkg/sm/groups.go @@ -163,7 +163,7 @@ func (g *Group) Normalize() { } // Check input fields of a group. If no error is returned, the result should -// be ok to put into the dataxnametypes. +// be ok to put into the database. func (g *Group) Verify() error { if g.verified == true { return nil @@ -267,7 +267,7 @@ func (p *Partition) Normalize() { } // Check input fields of a group. If no error is returned, the result should -// be ok to put into the dataxnametypes. +// be ok to put into the database. func (p *Partition) Verify() error { if p.verified == true { return nil diff --git a/pkg/sm/hwinv.go b/pkg/sm/hwinv.go index b19f00d..4e4add5 100644 --- a/pkg/sm/hwinv.go +++ b/pkg/sm/hwinv.go @@ -1291,7 +1291,7 @@ func (hw *HWInvByLoc) DecodeLocationInfo(locInfoJSON []byte) error { // This function encode's the hwinv's type-specific LocationInfo struct // into a free-form JSON byte array that can be stored schema-less in the -// dataxnametypes. +// database. // // NOTE: This function is the counterpart to DecodeLocationInfo(). // @@ -1648,7 +1648,7 @@ func (hf *HWInvByFRU) DecodeFRUInfo(fruInfoJSON []byte) error { // This function encode's the hwinv's type-specific FRU info struct // into a free-form JSON byte array that can be stored schema-less in the -// dataxnametypes. +// database. // // NOTE: This function is the counterpart to DecodeFRUInfo(). //