From 6f25b01be5e7d61ade140bc7dc23e299f67a25f2 Mon Sep 17 00:00:00 2001 From: Chris Grindstaff Date: Mon, 21 Aug 2023 13:44:51 -0400 Subject: [PATCH 1/2] feat: enable more golanglint linters --- .golangci.yml | 20 +- cmd/admin/admin.go | 12 +- cmd/collectors/commonutils_test.go | 72 ++--- cmd/collectors/ems/ems.go | 16 +- cmd/collectors/ems/ems_test.go | 10 +- cmd/collectors/rest/plugins/disk/disk.go | 5 +- cmd/collectors/rest/plugins/health/health.go | 9 +- cmd/collectors/rest/plugins/sensor/sensor.go | 12 +- cmd/collectors/rest/plugins/svm/svm.go | 32 +- cmd/collectors/rest/plugins/volume/volume.go | 42 +-- .../volumeanalytics/volumeanalytics.go | 4 +- cmd/collectors/rest/rest.go | 7 +- cmd/collectors/restperf/plugins/disk/disk.go | 10 +- cmd/collectors/restperf/plugins/fcvi/fcvi.go | 5 +- .../restperf/plugins/volumetag/volumetag.go | 5 +- cmd/collectors/restperf/restperf.go | 282 +++++++++--------- cmd/collectors/storagegrid/rest/client.go | 4 +- cmd/collectors/storagegrid/storagegrid.go | 3 +- cmd/collectors/zapi/collector/parsers.go | 11 +- cmd/collectors/zapi/collector/zapi.go | 19 +- cmd/collectors/zapi/plugins/sensor/sensor.go | 12 +- .../zapi/plugins/sensor/sensor_test.go | 8 +- .../plugins/snapmirror/snapmirror_test.go | 60 +--- cmd/collectors/zapi/plugins/svm/svm.go | 60 ++-- cmd/collectors/zapi/plugins/volume/volume.go | 5 +- cmd/collectors/zapiperf/plugins/disk/disk.go | 8 +- .../externalserviceoperation.go | 5 +- cmd/collectors/zapiperf/plugins/fcvi/fcvi.go | 5 +- .../zapiperf/plugins/headroom/headroom.go | 5 +- .../zapiperf/plugins/volumetag/volumetag.go | 5 +- cmd/collectors/zapiperf/zapiperf.go | 79 +++-- cmd/collectors/zapiperf/zapiperf_test.go | 2 +- cmd/exporters/influxdb/influxdb.go | 8 +- cmd/exporters/prometheus/httpd.go | 6 +- cmd/exporters/prometheus/prometheus.go | 2 +- cmd/harvest/harvest.go | 2 +- cmd/harvest/version/version.go | 3 +- cmd/poller/collector/asup.go | 3 +- cmd/poller/plugin/labelagent/label_agent.go | 6 +- .../plugin/labelagent/label_agent_test.go | 26 +- cmd/poller/plugin/labelagent/parse_rules.go | 18 +- cmd/poller/plugin/metricagent/metric_agent.go | 3 +- cmd/poller/plugin/plugin.go | 52 ++-- cmd/poller/plugin/test/plugin_test.go | 2 +- cmd/poller/poller.go | 21 +- cmd/poller/schedule/schedule.go | 97 +++--- cmd/tools/doctor/doctor.go | 3 +- cmd/tools/doctor/restZapiDiff.go | 9 +- cmd/tools/generate/counter.go | 4 +- cmd/tools/grafana/grafana.go | 4 +- cmd/tools/rest/client.go | 6 +- cmd/tools/rest/rest.go | 12 +- cmd/tools/template/template_test.go | 3 +- cmd/tools/zapi/export.go | 2 +- pkg/api/ontapi/zapi/client.go | 22 +- pkg/conf/conf.go | 3 +- pkg/logging/logger.go | 2 +- pkg/test/node_test.go | 2 +- pkg/tree/node/node.go | 29 +- pkg/tree/node/node_test.go | 2 +- pkg/util/util.go | 3 +- 61 files changed, 541 insertions(+), 648 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 84affe444..8a848b94f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,29 +1,44 @@ linters: disable-all: true enable: + - asasalint + - bidichk - bodyclose + - contextcheck + - dogsled - dupword + - durationcheck - errcheck + - errchkjson - errname - errorlint + - exhaustive - exportloopref + - gocheckcompilerdirectives - gosec - gosimple - govet - ineffassign - makezero + - mirror - nilerr - nolintlint - nonamedreturns - nosprintfhostport + - reassign + - revive - staticcheck - stylecheck - tenv - - thelper + - tenv + - testableexamples - typecheck - unconvert - unparam - unused + - usestdlibvars + - wastedassign + - zerologlint issues: max-issues-per-linter: 0 @@ -38,3 +53,6 @@ linters-settings: thelper: test: begin: false + gocritic: + disabled-tags: + - style diff --git a/cmd/admin/admin.go b/cmd/admin/admin.go index 41daf6845..e1d976c6e 100644 --- a/cmd/admin/admin.go +++ b/cmd/admin/admin.go @@ -98,19 +98,19 @@ func (a *Admin) APISD(w http.ResponseWriter, r *http.Request) { return } } - if r.Method == "PUT" { + if r.Method == http.MethodPut { a.apiPublish(w, r) - } else if r.Method == "GET" { - w.WriteHeader(200) + } else if r.Method == http.MethodGet { + w.WriteHeader(http.StatusOK) _, _ = w.Write(a.makeTargets()) } else { - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) } } func (a *Admin) setupLogger() { zerolog.SetGlobalLevel(zerolog.InfoLevel) - zerolog.ErrorStackMarshaler = logging.MarshalStack + zerolog.ErrorStackMarshaler = logging.MarshalStack //nolint:reassign a.logger = zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}). With().Caller().Timestamp().Logger() @@ -128,7 +128,7 @@ func (a *Admin) apiPublish(w http.ResponseWriter, r *http.Request) { err := decoder.Decode(&publish) if err != nil { a.logger.Err(err).Msg("Unable to parse publish json") - w.WriteHeader(400) + w.WriteHeader(http.StatusBadRequest) return } a.pollerToPromAddr.Set(publish.Name, publish, a.expireAfter) diff --git a/cmd/collectors/commonutils_test.go b/cmd/collectors/commonutils_test.go index 56c63ec3a..d7d37f060 100644 --- a/cmd/collectors/commonutils_test.go +++ b/cmd/collectors/commonutils_test.go @@ -44,9 +44,7 @@ func testWithoutGroupType(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "" && instance.GetLabel("protectionSourceType") == "" { - // OK - } else { + if instance.GetLabel("protectedBy") != "" || instance.GetLabel("protectionSourceType") != "" { t.Errorf("Labels protectedBy= %s, expected empty and protectionSourceType= %s, expected empty", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -57,9 +55,7 @@ func testSvmdr(t *testing.T, instance *matrix.Instance) { instance.SetLabel("source_volume", "") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "storage_vm" && instance.GetLabel("protectionSourceType") == "storage_vm" { - // OK - } else { + if instance.GetLabel("protectedBy") != "storage_vm" || instance.GetLabel("protectionSourceType") != "storage_vm" { t.Errorf("Labels protectedBy= %s, expected: storage_vm and protectionSourceType= %s, expected: storage_vm", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -71,9 +67,7 @@ func testConstituentVolumeWithinSvmdr(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test1") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "storage_vm" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "storage_vm" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: storage_vm and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -83,9 +77,7 @@ func testCg(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test123:/cg/") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "cg" && instance.GetLabel("protectionSourceType") == "cg" { - // OK - } else { + if instance.GetLabel("protectedBy") != "cg" || instance.GetLabel("protectionSourceType") != "cg" { t.Errorf("Labels protectedBy= %s, expected: cg and protectionSourceType= %s, expected: cg", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -95,9 +87,7 @@ func testConstituentVolumeWithinCg(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test123") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "cg" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "cg" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: cg and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -106,9 +96,7 @@ func testNegativeCase1(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "infinitevol") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "not_mapped" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "not_mapped" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: not_mapped", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -120,9 +108,7 @@ func testNegativeCase2(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test123:") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "not_mapped" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "not_mapped" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: not_mapped", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -131,9 +117,7 @@ func testGroupTypeNone(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "none") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -142,9 +126,7 @@ func testGroupTypeFlexgroup(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "flexgroup") UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -155,9 +137,7 @@ func testStrictSyncMirror(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "strict_sync_mirror") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "sync_mirror_strict" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "sync_mirror_strict" { t.Errorf("Labels derived_relationship_type= %s, expected: sync_mirror_strict", instance.GetLabel("derived_relationship_type")) } } @@ -167,9 +147,7 @@ func testSyncMirror(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "sync_mirror") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "sync_mirror" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "sync_mirror" { t.Errorf("Labels derived_relationship_type= %s, expected: sync_mirror", instance.GetLabel("derived_relationship_type")) } } @@ -179,9 +157,7 @@ func testMirrorVault(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "mirror_vault") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "mirror_vault" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "mirror_vault" { t.Errorf("Labels derived_relationship_type= %s, expected: mirror_vault", instance.GetLabel("derived_relationship_type")) } } @@ -191,9 +167,7 @@ func testAutomatedFailover(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "automated_failover") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "sync_mirror" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "sync_mirror" { t.Errorf("Labels derived_relationship_type= %s, expected: sync_mirror", instance.GetLabel("derived_relationship_type")) } } @@ -203,9 +177,7 @@ func testOtherPolicyType(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "vault") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "vault" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "vault" { t.Errorf("Labels derived_relationship_type= %s, expected: vault", instance.GetLabel("derived_relationship_type")) } } @@ -215,9 +187,7 @@ func testWithNoPolicyType(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "extended_data_protection" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "extended_data_protection" { t.Errorf("Labels derived_relationship_type= %s, expected: extended_data_protection", instance.GetLabel("derived_relationship_type")) } } @@ -227,9 +197,7 @@ func testWithNoPolicyTypeNoRelationshipType(t *testing.T, instance *matrix.Insta instance.SetLabel("policy_type", "") UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "" { t.Errorf("Labels derived_relationship_type= %s, expected: \"\"(empty)", instance.GetLabel("derived_relationship_type")) } } @@ -240,9 +208,7 @@ func testOlderTimestampThanDuration(t *testing.T) { duration := 5 * time.Minute isOlder := IsTimestampOlderThanDuration(time.Now(), timestamp, duration) - if isOlder { - // OK - } else { + if !isOlder { t.Errorf("timestamp= %f is older than duration %s", timestamp, duration.String()) } } @@ -252,9 +218,7 @@ func testNewerTimestampThanDuration(t *testing.T) { duration := 2 * time.Hour isOlder := IsTimestampOlderThanDuration(time.Now(), timestamp, duration) - if !isOlder { - // OK - } else { + if isOlder { t.Errorf("timestamp= %f is newer than duration %s", timestamp, duration.String()) } } diff --git a/cmd/collectors/ems/ems.go b/cmd/collectors/ems/ems.go index 530558e19..5468336bc 100644 --- a/cmd/collectors/ems/ems.go +++ b/cmd/collectors/ems/ems.go @@ -114,11 +114,7 @@ func (e *Ems) Init(a *collector.AbstractCollector) error { return err } - if err = e.InitMatrix(); err != nil { - return err - } - - return nil + return e.InitMatrix() } func (e *Ems) InitMatrix() error { @@ -359,7 +355,8 @@ func (e *Ems) PollData() (map[string]*matrix.Matrix, error) { } toTime := clusterTime.Unix() timeFilter := e.getTimeStampFilter(clusterTime) - filter := append(e.Filter, timeFilter) + filter := e.Filter + filter = append(filter, timeFilter) // build hrefs up to maxURLSize var hrefs []string @@ -534,13 +531,13 @@ func (e *Ems) HandleResults(result []gjson.Result, prop map[string][]*emsProp) ( } // Check matches at all same name ems - isMatch := false + var isMatch bool // Check matches at each ems - isMatchPs := false + var isMatchPs bool // Check instance count at all same name ems instanceLabelCount := uint64(0) // Check instance count at each ems - instanceLabelCountPs := uint64(0) + var instanceLabelCountPs uint64 // parse ems properties for the instance if ps, ok := prop[msgName]; ok { @@ -609,7 +606,6 @@ func (e *Ems) HandleResults(result []gjson.Result, prop map[string][]*emsProp) ( } } if !isMatchPs { - instanceLabelCountPs = 0 continue } diff --git a/cmd/collectors/ems/ems_test.go b/cmd/collectors/ems/ems_test.go index d75f65b0e..b66836850 100644 --- a/cmd/collectors/ems/ems_test.go +++ b/cmd/collectors/ems/ems_test.go @@ -57,7 +57,7 @@ func NewEms() *Ems { ac := collector.New("Ems", "Ems", &opts, emsParams(emsConfgPath), nil) e := &Ems{} if err := e.Init(ac); err != nil { - log.Fatal().Err(err) + log.Fatal().Err(err).Send() } // Changed the resolve_after for 2 issuing ems for auto resolve testing e.resolveAfter["LUN.offline"] = 1 * time.Second @@ -102,9 +102,7 @@ func (e *Ems) testBookendIssuingEms(t *testing.T, path string) { } // Test for matches - filter if generatedEmsName == "hm.alert.raised" { - if instance.GetLabel("alert_id") == "RaidLeftBehindAggrAlert" { - // OK - } else { + if instance.GetLabel("alert_id") != "RaidLeftBehindAggrAlert" { t.Errorf("Labels alert_id= %s, expected: RaidLeftBehindAggrAlert", instance.GetLabel("alert_id")) } } @@ -142,9 +140,7 @@ func (e *Ems) testBookendResolvingEms(t *testing.T, path string) { } // Test for matches - filter if generatedEmsName == "hm.alert.raised" { - if instance.GetLabel("alert_id") == "RaidLeftBehindAggrAlert" && ok && val == 0.0 { - // OK - } else { + if instance.GetLabel("alert_id") != "RaidLeftBehindAggrAlert" || !ok || val != 0.0 { t.Errorf("Labels alert_id= %s, expected: RaidLeftBehindAggrAlert, metric value = %f, expected: 0.0", instance.GetLabel("alert_id"), val) } } diff --git a/cmd/collectors/rest/plugins/disk/disk.go b/cmd/collectors/rest/plugins/disk/disk.go index 9a585b4c3..c2a94d63e 100644 --- a/cmd/collectors/rest/plugins/disk/disk.go +++ b/cmd/collectors/rest/plugins/disk/disk.go @@ -1,6 +1,5 @@ -/* - * Copyright NetApp Inc, 2021 All rights reserved - */ +// Copyright NetApp Inc, 2021 All rights reserved + package disk import ( diff --git a/cmd/collectors/rest/plugins/health/health.go b/cmd/collectors/rest/plugins/health/health.go index b2a3a2575..01eb40153 100644 --- a/cmd/collectors/rest/plugins/health/health.go +++ b/cmd/collectors/rest/plugins/health/health.go @@ -66,11 +66,7 @@ func (h *Health) Init() error { return err } - if err = h.client.Init(5); err != nil { - return err - } - - return nil + return h.client.Init(5) } func (h *Health) initAllMatrix() error { @@ -457,8 +453,7 @@ func (h *Health) collectSupportAlerts() { } toTime := clusterTime.Unix() timeFilter := h.getTimeStampFilter(clusterTime) - addFilter := []string{"suppress=false"} - filter := append(addFilter, timeFilter) + filter := append([]string{"suppress=false"}, timeFilter) records, err := h.getSupportAlerts(filter) if err != nil { diff --git a/cmd/collectors/rest/plugins/sensor/sensor.go b/cmd/collectors/rest/plugins/sensor/sensor.go index f78085eaa..fa0b241e5 100644 --- a/cmd/collectors/rest/plugins/sensor/sensor.go +++ b/cmd/collectors/rest/plugins/sensor/sensor.go @@ -245,31 +245,27 @@ func (my *Sensor) calculateEnvironmentMetrics(data *matrix.Matrix) ([]*matrix.Ma currentKey := currentKeys[i] voltageKey := voltageKeys[i] - //get values + // get values currentSensorValue := v.currentSensor[currentKey] voltageSensorValue := v.voltageSensor[voltageKey] // convert units if currentSensorValue.unit == "mA" { currentSensorValue.value = currentSensorValue.value / 1000 - } else if currentSensorValue.unit == "A" { - // do nothing - } else { + } else if currentSensorValue.unit != "A" { my.Logger.Warn().Str("unit", currentSensorValue.unit).Float64("value", currentSensorValue.value).Msg("unknown current unit") } if voltageSensorValue.unit == "mV" { voltageSensorValue.value = voltageSensorValue.value / 1000 - } else if voltageSensorValue.unit == "V" { - // do nothing - } else { + } else if voltageSensorValue.unit != "V" { my.Logger.Warn().Str("unit", voltageSensorValue.unit).Float64("value", voltageSensorValue.value).Msg("unknown voltage unit") } p := currentSensorValue.value * voltageSensorValue.value if !strings.EqualFold(voltageSensorValue.name, "in") && !strings.EqualFold(currentSensorValue.name, "in") { - p = p / 0.93 //If the sensor names to do NOT contain "IN" or "in", then we need to adjust the power to account for loss in the power supply. We will use 0.93 as the power supply efficiency factor for all systems. + p = p / 0.93 // If the sensor names to do NOT contain "IN" or "in", then we need to adjust the power to account for loss in the power supply. We will use 0.93 as the power supply efficiency factor for all systems. } sumPower += p diff --git a/cmd/collectors/rest/plugins/svm/svm.go b/cmd/collectors/rest/plugins/svm/svm.go index ef272348d..016d704a7 100644 --- a/cmd/collectors/rest/plugins/svm/svm.go +++ b/cmd/collectors/rest/plugins/svm/svm.go @@ -23,20 +23,20 @@ var weakCiphers = regexp.MustCompile("(.*)_cbc.*") type SVM struct { *plugin.AbstractPlugin - nsswitchInfo map[string]nsswitch + nsswitchInfo map[string]Nsswitch kerberosInfo map[string]string - fpolicyInfo map[string]fpolicy + fpolicyInfo map[string]Fpolicy iscsiServiceInfo map[string]string iscsiCredentialInfo map[string]string client *rest.Client } -type nsswitch struct { +type Nsswitch struct { nsdb []string nssource []string } -type fpolicy struct { +type Fpolicy struct { name string enable string } @@ -62,9 +62,9 @@ func (my *SVM) Init() error { if err = my.client.Init(5); err != nil { return err } - my.nsswitchInfo = make(map[string]nsswitch) + my.nsswitchInfo = make(map[string]Nsswitch) my.kerberosInfo = make(map[string]string) - my.fpolicyInfo = make(map[string]fpolicy) + my.fpolicyInfo = make(map[string]Fpolicy) my.iscsiServiceInfo = make(map[string]string) my.iscsiCredentialInfo = make(map[string]string) @@ -167,15 +167,15 @@ func (my *SVM) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matrix, error) return nil, nil } -func (my *SVM) GetNSSwitchInfo(data *matrix.Matrix) (map[string]nsswitch, error) { +func (my *SVM) GetNSSwitchInfo(data *matrix.Matrix) (map[string]Nsswitch, error) { var ( - vserverNsswitchMap map[string]nsswitch - ns nsswitch + vserverNsswitchMap map[string]Nsswitch + ns Nsswitch ok bool ) - vserverNsswitchMap = make(map[string]nsswitch) + vserverNsswitchMap = make(map[string]Nsswitch) for _, svmInstance := range data.GetInstances() { svmName := svmInstance.GetLabel("svm") @@ -191,7 +191,7 @@ func (my *SVM) GetNSSwitchInfo(data *matrix.Matrix) (map[string]nsswitch, error) ns.nsdb = append(ns.nsdb, nsdb) ns.nssource = append(ns.nssource, nssourcelist...) } else { - ns = nsswitch{nsdb: []string{nsdb}, nssource: nssourcelist} + ns = Nsswitch{nsdb: []string{nsdb}, nssource: nssourcelist} } vserverNsswitchMap[svmName] = ns } @@ -231,14 +231,14 @@ func (my *SVM) GetKerberosConfig() (map[string]string, error) { return svmKerberosMap, nil } -func (my *SVM) GetFpolicy() (map[string]fpolicy, error) { +func (my *SVM) GetFpolicy() (map[string]Fpolicy, error) { var ( result []gjson.Result - svmFpolicyMap map[string]fpolicy + svmFpolicyMap map[string]Fpolicy err error ) - svmFpolicyMap = make(map[string]fpolicy) + svmFpolicyMap = make(map[string]Fpolicy) query := "api/protocols/fpolicy" fpolicyFields := []string{"svm.name", "policies.enabled", "policies.name"} href := rest.BuildHref("", strings.Join(fpolicyFields, ","), nil, "", "", "", "", query) @@ -252,11 +252,11 @@ func (my *SVM) GetFpolicy() (map[string]fpolicy, error) { fpolicyName := fpolicyData.Get("policies.name").String() svmName := fpolicyData.Get("svm.name").String() if _, ok := svmFpolicyMap[svmName]; !ok { - svmFpolicyMap[svmName] = fpolicy{name: fpolicyName, enable: fpolicyEnable} + svmFpolicyMap[svmName] = Fpolicy{name: fpolicyName, enable: fpolicyEnable} } else { // If svm is already present, update the status value only if it is false if svmFpolicyMap[svmName].enable == "false" { - svmFpolicyMap[svmName] = fpolicy{name: fpolicyName, enable: fpolicyEnable} + svmFpolicyMap[svmName] = Fpolicy{name: fpolicyName, enable: fpolicyEnable} } } } diff --git a/cmd/collectors/rest/plugins/volume/volume.go b/cmd/collectors/rest/plugins/volume/volume.go index e03c68b1b..966dc6df1 100644 --- a/cmd/collectors/rest/plugins/volume/volume.go +++ b/cmd/collectors/rest/plugins/volume/volume.go @@ -138,29 +138,29 @@ func (my *Volume) handleARWProtection(data *matrix.Matrix) { // If all volumes are in learning mode --> "Learning Mode" // Else indicates arwStatus for all volumes are enabled --> "Active Mode" for _, volume := range data.GetInstances() { - if arwState := volume.GetLabel("antiRansomwareState"); arwState == "" { - // Case where REST call don't return `antiRansomwareState` field, arwStatus show as 'Not Monitoring' + arwState := volume.GetLabel("antiRansomwareState") + if arwState == "" { + // Case where REST calls don't return `antiRansomwareState` field, arwStatus show as 'Not Monitoring' arwStatusValue = "Not Monitoring" break - } else { - if arwState == "disabled" { - arwStatusValue = "Not Monitoring" - break - } else if arwState == "dry_run" || arwState == "enable_paused" { - arwStartTime := volume.GetLabel("anti_ransomware_start_time") - if arwStartTime == "" || arwStatusValue == "Switch to Active Mode" { - continue - } - // If ARW startTime is more than 30 days old, which indicates that learning mode has been finished. - if arwStartTimeValue, err = time.Parse(time.RFC3339, arwStartTime); err != nil { - my.Logger.Error().Err(err).Msg("Failed to parse arw start time") - arwStartTimeValue = time.Now() - } - if time.Since(arwStartTimeValue).Hours() > HoursInMonth { - arwStatusValue = "Switch to Active Mode" - } else { - arwStatusValue = "Learning Mode" - } + } + if arwState == "disabled" { + arwStatusValue = "Not Monitoring" + break + } else if arwState == "dry_run" || arwState == "enable_paused" { + arwStartTime := volume.GetLabel("anti_ransomware_start_time") + if arwStartTime == "" || arwStatusValue == "Switch to Active Mode" { + continue + } + // If ARW startTime is more than 30 days old, which indicates that learning mode has been finished. + if arwStartTimeValue, err = time.Parse(time.RFC3339, arwStartTime); err != nil { + my.Logger.Error().Err(err).Msg("Failed to parse arw start time") + arwStartTimeValue = time.Now() + } + if time.Since(arwStartTimeValue).Hours() > HoursInMonth { + arwStatusValue = "Switch to Active Mode" + } else { + arwStatusValue = "Learning Mode" } } } diff --git a/cmd/collectors/rest/plugins/volumeanalytics/volumeanalytics.go b/cmd/collectors/rest/plugins/volumeanalytics/volumeanalytics.go index c23549f08..1b24d7312 100644 --- a/cmd/collectors/rest/plugins/volumeanalytics/volumeanalytics.go +++ b/cmd/collectors/rest/plugins/volumeanalytics/volumeanalytics.go @@ -176,7 +176,7 @@ func (v *VolumeAnalytics) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matr } } } - if len(mtBytesUsedValues) == len(mtBytesUsedPercentages) && len(mtBytesUsedValues) == len(mtBytesUsedLabels) { + if len(mtBytesUsedValues) == len(mtBytesUsedPercentages) && len(mtBytesUsedValues) == len(mtBytesUsedLabels) { //nolint:gocritic for i, mv := range mtBytesUsedValues { key := "modified_value_" + mtBytesUsedLabels[i] @@ -212,7 +212,7 @@ func (v *VolumeAnalytics) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matr } } - if len(atBytesUsedValues) == len(atBytesUsedPercentages) && len(atBytesUsedValues) == len(atBytesUsedLabels) { + if len(atBytesUsedValues) == len(atBytesUsedPercentages) && len(atBytesUsedValues) == len(atBytesUsedLabels) { //nolint:gocritic for i, av := range atBytesUsedValues { key := "access_value_" + atBytesUsedLabels[i] diff --git a/cmd/collectors/rest/rest.go b/cmd/collectors/rest/rest.go index 2314e908a..29cd05947 100644 --- a/cmd/collectors/rest/rest.go +++ b/cmd/collectors/rest/rest.go @@ -629,13 +629,16 @@ func (r *Rest) CollectAutoSupport(p *collector.Payload) { } if r.Object == "Node" || r.Name == "ems" { - nodeIds, err := r.getNodeUuids() + var ( + nodeIds []collector.ID + err error + ) + nodeIds, err = r.getNodeUuids() if err != nil { // log but don't return so the other info below is collected r.Logger.Error(). Err(err). Msg("Unable to get nodes.") - nodeIds = make([]collector.ID, 0) } info.Ids = nodeIds p.Nodes = &info diff --git a/cmd/collectors/restperf/plugins/disk/disk.go b/cmd/collectors/restperf/plugins/disk/disk.go index 03855a07d..3f1e49b63 100644 --- a/cmd/collectors/restperf/plugins/disk/disk.go +++ b/cmd/collectors/restperf/plugins/disk/disk.go @@ -125,7 +125,7 @@ func (d *Disk) Init() error { shelfMetric["frus => psu"] = []string{ "^^id => psu_id", "^installed => enabled", - //"^location", + // "^location", "^part_number", "^serial_number => serial", "^psu.model => type", @@ -456,7 +456,7 @@ func (d *Disk) calculateAggrPower(data *matrix.Matrix, output []*matrix.Matrix) for _, v1 := range v.disks { c := len(v1.aggregates) if c > 0 { - diskWithAggregateCount += 1 + diskWithAggregateCount++ } } if diskWithAggregateCount != 0 { @@ -731,14 +731,14 @@ func (d *Disk) initAggrPowerMatrix() { } func (d *Disk) initMaps() { - //reset shelf Power + // reset shelf Power d.ShelfMap = make(map[string]*shelf) - //reset diskmap + // reset diskmap d.diskMap = make(map[string]*disk) d.diskNameMap = make(map[string]*disk) - //reset aggrmap + // reset aggrmap d.aggrMap = make(map[string]*aggregate) } diff --git a/cmd/collectors/restperf/plugins/fcvi/fcvi.go b/cmd/collectors/restperf/plugins/fcvi/fcvi.go index 5274d211c..6dbba32ad 100644 --- a/cmd/collectors/restperf/plugins/fcvi/fcvi.go +++ b/cmd/collectors/restperf/plugins/fcvi/fcvi.go @@ -30,10 +30,7 @@ func (f *FCVI) Init() error { return err } - if err = f.client.Init(5); err != nil { - return err - } - return nil + return f.client.Init(5) } func (f *FCVI) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matrix, error) { diff --git a/cmd/collectors/restperf/plugins/volumetag/volumetag.go b/cmd/collectors/restperf/plugins/volumetag/volumetag.go index e91b7f58a..77628ea86 100644 --- a/cmd/collectors/restperf/plugins/volumetag/volumetag.go +++ b/cmd/collectors/restperf/plugins/volumetag/volumetag.go @@ -29,10 +29,7 @@ func (v *VolumeTag) Init() error { return err } - if err = v.client.Init(5); err != nil { - return err - } - return nil + return v.client.Init(5) } func (v *VolumeTag) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matrix, error) { diff --git a/cmd/collectors/restperf/restperf.go b/cmd/collectors/restperf/restperf.go index 121140c90..dbf65c1a8 100644 --- a/cmd/collectors/restperf/restperf.go +++ b/cmd/collectors/restperf/restperf.go @@ -137,20 +137,20 @@ func (r *RestPerf) Init(a *collector.AbstractCollector) error { func (r *RestPerf) InitQOSLabels() error { if isWorkloadObject(r.Prop.Query) || isWorkloadDetailObject(r.Prop.Query) { - if qosLabels := r.Params.GetChildS("qos_labels"); qosLabels == nil { + qosLabels := r.Params.GetChildS("qos_labels") + if qosLabels == nil { return errs.New(errs.ErrMissingParam, "qos_labels") - } else { - r.perfProp.qosLabels = make(map[string]string) - for _, label := range qosLabels.GetAllChildContentS() { - - display := strings.ReplaceAll(label, "-", "_") - before, after, found := strings.Cut(label, "=>") - if found { - label = strings.TrimSpace(before) - display = strings.TrimSpace(after) - } - r.perfProp.qosLabels[label] = display + } + r.perfProp.qosLabels = make(map[string]string) + for _, label := range qosLabels.GetAllChildContentS() { + + display := strings.ReplaceAll(label, "-", "_") + before, after, found := strings.Cut(label, "=>") + if found { + label = strings.TrimSpace(before) + display = strings.TrimSpace(after) } + r.perfProp.qosLabels[label] = display } } return nil @@ -158,7 +158,7 @@ func (r *RestPerf) InitQOSLabels() error { func (r *RestPerf) InitMatrix() error { mat := r.Matrix[r.Object] - //init perf properties + // init perf properties r.perfProp.latencyIoReqd = r.loadParamInt("latency_io_reqd", latencyIoReqd) r.perfProp.isCacheEmpty = true // overwrite from abstract collector @@ -433,7 +433,7 @@ func parseMetricResponses(instanceData gjson.Result, metric map[string]*rest2.Me ms := strings.Split(m, ",") for range ms { finalLabels = append(finalLabels, label+arrayKeyToken+subLabelSlice[vLen]) - vLen += 1 + vLen++ } if vLen > len(subLabelSlice) { return false @@ -502,7 +502,7 @@ func parseMetricResponse(instanceData gjson.Result, metric string) *metricRespon ms := strings.Split(m, ",") for range ms { finalLabels = append(finalLabels, label+arrayKeyToken+subLabelSlice[vLen]) - vLen += 1 + vLen++ } if vLen > len(subLabelSlice) { break @@ -580,32 +580,32 @@ func (r *RestPerf) processWorkLoadCounter() (map[string]*matrix.Matrix, error) { wait.SetExportable(false) visits.SetExportable(false) - if resourceMap := r.Params.GetChildS("resource_map"); resourceMap == nil { + resourceMap := r.Params.GetChildS("resource_map") + if resourceMap == nil { return nil, errs.New(errs.ErrMissingParam, "resource_map") - } else { - for _, x := range resourceMap.GetChildren() { - for _, wm := range workloadDetailMetrics { - name := x.GetNameS() + wm - resource := x.GetContentS() - - if m := mat.GetMetric(name); m != nil { - continue - } - if m, err := mat.NewMetricFloat64(name, wm); err != nil { - return nil, err - } else { - r.perfProp.counterInfo[name] = &counter{ - name: wm, - description: "", - counterType: r.perfProp.counterInfo[service.GetName()].counterType, - unit: r.perfProp.counterInfo[service.GetName()].unit, - denominator: "ops", - } - m.SetLabel("resource", resource) + } + for _, x := range resourceMap.GetChildren() { + for _, wm := range workloadDetailMetrics { + name := x.GetNameS() + wm + resource := x.GetContentS() - r.Logger.Debug().Str("name", name).Str("resource", resource).Msg("added workload latency metric") - } + if m := mat.GetMetric(name); m != nil { + continue } + m, err := mat.NewMetricFloat64(name, wm) + if err != nil { + return nil, err + } + r.perfProp.counterInfo[name] = &counter{ + name: wm, + description: "", + counterType: r.perfProp.counterInfo[service.GetName()].counterType, + unit: r.perfProp.counterInfo[service.GetName()].unit, + denominator: "ops", + } + m.SetLabel("resource", resource) + + r.Logger.Debug().Str("name", name).Str("resource", resource).Msg("added workload latency metric") } } } @@ -864,123 +864,121 @@ func (r *RestPerf) pollData(startTime time.Time, perfRecords []rest.PerfRecord) } } continue - } else { - if f.isArray { - labels := strings.Split(f.label, ",") - values := strings.Split(f.value, ",") - - if len(labels) != len(values) { - // warn & skip - r.Logger.Warn(). - Str("labels", f.label). - Str("value", f.value). - Msg("labels don't match parsed values") - continue - } - - // ONTAP does not have a `type` for histogram. Harvest tests the `desc` field to determine - // if a counter is a histogram - isHistogram = false - description := strings.ToLower(r.perfProp.counterInfo[name].description) - if len(labels) > 0 && strings.Contains(description, "histogram") { - key := name + ".bucket" - histogramMetric = curMat.GetMetric(key) - if histogramMetric != nil { - r.Logger.Trace().Str("metric", key).Msg("Updating array metric attributes") - } else { - histogramMetric, err = curMat.NewMetricFloat64(key, metric.Label) - if err != nil { - r.Logger.Error().Err(err).Str("key", key).Msg("unable to create histogram metric") - continue - } - } - histogramMetric.SetArray(true) - histogramMetric.SetExportable(metric.Exportable) - histogramMetric.SetBuckets(&labels) - isHistogram = true - } + } + if f.isArray { + labels := strings.Split(f.label, ",") + values := strings.Split(f.value, ",") + + if len(labels) != len(values) { + // warn & skip + r.Logger.Warn(). + Str("labels", f.label). + Str("value", f.value). + Msg("labels don't match parsed values") + continue + } - for i, label := range labels { - k := name + arrayKeyToken + label - metr, ok := curMat.GetMetrics()[k] - if !ok { - if metr, err = curMat.NewMetricFloat64(k, metric.Label); err != nil { - r.Logger.Error().Err(err). - Str("name", k). - Msg("NewMetricFloat64") - continue - } - if x := strings.Split(label, arrayKeyToken); len(x) == 2 { - metr.SetLabel("metric", x[0]) - metr.SetLabel("submetric", x[1]) - } else { - metr.SetLabel("metric", label) - } - // differentiate between array and normal counter - metr.SetArray(true) - metr.SetExportable(metric.Exportable) - if isHistogram { - // Save the index of this label so the labels can be exported in order - metr.SetLabel("comment", strconv.Itoa(i)) - // Save the bucket name so the flattened metrics can find their bucket when exported - metr.SetLabel("bucket", name+".bucket") - metr.SetHistogram(true) - } - } - if err = metr.SetValueString(instance, values[i]); err != nil { - r.Logger.Error(). - Err(err). - Str("name", name). - Str("label", label). - Str("value", values[i]). - Int("instIndex", instIndex). - Msg("Set value failed") + // ONTAP does not have a `type` for histogram. Harvest tests the `desc` field to determine + // if a counter is a histogram + isHistogram = false + description := strings.ToLower(r.perfProp.counterInfo[name].description) + if len(labels) > 0 && strings.Contains(description, "histogram") { + key := name + ".bucket" + histogramMetric = curMat.GetMetric(key) + if histogramMetric != nil { + r.Logger.Trace().Str("metric", key).Msg("Updating array metric attributes") + } else { + histogramMetric, err = curMat.NewMetricFloat64(key, metric.Label) + if err != nil { + r.Logger.Error().Err(err).Str("key", key).Msg("unable to create histogram metric") continue - } else { - r.Logger.Trace(). - Str("name", name). - Str("label", label). - Str("value", values[i]). - Int("instIndex", instIndex). - Msg("Set name.label = value") - count++ } } - } else { - metr, ok := curMat.GetMetrics()[name] + histogramMetric.SetArray(true) + histogramMetric.SetExportable(metric.Exportable) + histogramMetric.SetBuckets(&labels) + isHistogram = true + } + + for i, label := range labels { + k := name + arrayKeyToken + label + metr, ok := curMat.GetMetrics()[k] if !ok { - if metr, err = curMat.NewMetricFloat64(name, metric.Label); err != nil { + if metr, err = curMat.NewMetricFloat64(k, metric.Label); err != nil { r.Logger.Error().Err(err). - Str("name", name). - Int("instIndex", instIndex). + Str("name", k). Msg("NewMetricFloat64") + continue } - } - metr.SetExportable(metric.Exportable) - if c, err := strconv.ParseFloat(f.value, 64); err == nil { - if err = metr.SetValueFloat64(instance, c); err != nil { - r.Logger.Error().Err(err). - Str("key", metric.Name). - Str("metric", metric.Label). - Int("instIndex", instIndex). - Msg("Unable to set float key on metric") + if x := strings.Split(label, arrayKeyToken); len(x) == 2 { + metr.SetLabel("metric", x[0]) + metr.SetLabel("submetric", x[1]) } else { - r.Logger.Trace(). - Int("instIndex", instIndex). - Str("key", instanceKey). - Str("counter", name). - Str("value", f.value). - Msg("Set metric") + metr.SetLabel("metric", label) } - } else { + // differentiate between array and normal counter + metr.SetArray(true) + metr.SetExportable(metric.Exportable) + if isHistogram { + // Save the index of this label so the labels can be exported in order + metr.SetLabel("comment", strconv.Itoa(i)) + // Save the bucket name so the flattened metrics can find their bucket when exported + metr.SetLabel("bucket", name+".bucket") + metr.SetHistogram(true) + } + } + if err = metr.SetValueString(instance, values[i]); err != nil { + r.Logger.Error(). + Err(err). + Str("name", name). + Str("label", label). + Str("value", values[i]). + Int("instIndex", instIndex). + Msg("Set value failed") + continue + } + r.Logger.Trace(). + Str("name", name). + Str("label", label). + Str("value", values[i]). + Int("instIndex", instIndex). + Msg("Set name.label = value") + count++ + } + } else { + metr, ok := curMat.GetMetrics()[name] + if !ok { + if metr, err = curMat.NewMetricFloat64(name, metric.Label); err != nil { + r.Logger.Error().Err(err). + Str("name", name). + Int("instIndex", instIndex). + Msg("NewMetricFloat64") + } + } + metr.SetExportable(metric.Exportable) + if c, err := strconv.ParseFloat(f.value, 64); err == nil { + if err = metr.SetValueFloat64(instance, c); err != nil { r.Logger.Error().Err(err). Str("key", metric.Name). Str("metric", metric.Label). Int("instIndex", instIndex). - Msg("Unable to parse float value") + Msg("Unable to set float key on metric") + } else { + r.Logger.Trace(). + Int("instIndex", instIndex). + Str("key", instanceKey). + Str("counter", name). + Str("value", f.value). + Msg("Set metric") } - count++ + } else { + r.Logger.Error().Err(err). + Str("key", metric.Name). + Str("metric", metric.Label). + Int("instIndex", instIndex). + Msg("Unable to parse float value") } + count++ } } else { r.Logger.Warn().Str("counter", name).Msg("Counter is missing or unable to parse.") @@ -1049,8 +1047,10 @@ func (r *RestPerf) pollData(startTime time.Time, perfRecords []rest.PerfRecord) } // order metrics, such that those requiring base counters are processed last - orderedMetrics := append(orderedNonDenominatorMetrics, orderedDenominatorMetrics...) - orderedKeys := append(orderedNonDenominatorKeys, orderedDenominatorKeys...) + orderedMetrics := orderedNonDenominatorMetrics + orderedMetrics = append(orderedMetrics, orderedDenominatorMetrics...) + orderedKeys := orderedNonDenominatorKeys + orderedKeys = append(orderedKeys, orderedDenominatorKeys...) // Calculate timestamp delta first since many counters require it for postprocessing. // Timestamp has "raw" property, so it isn't post-processed automatically diff --git a/cmd/collectors/storagegrid/rest/client.go b/cmd/collectors/storagegrid/rest/client.go index 00a495ba8..d8feb4d08 100644 --- a/cmd/collectors/storagegrid/rest/client.go +++ b/cmd/collectors/storagegrid/rest/client.go @@ -241,7 +241,7 @@ func (c *Client) fetch() ([]byte, error) { //goland:noinspection GoUnhandledErrorResult defer response.Body.Close() - if response.StatusCode != 200 { + if response.StatusCode != http.StatusOK { if body, err = io.ReadAll(response.Body); err == nil { return nil, errs.NewStorageGridErr(response.StatusCode, body) } @@ -373,7 +373,7 @@ func (c *Client) fetchTokenWithAuthRetry() error { return err } - if response.StatusCode != 200 { + if response.StatusCode != http.StatusOK { return errs.NewStorageGridErr(response.StatusCode, body) } diff --git a/cmd/collectors/storagegrid/storagegrid.go b/cmd/collectors/storagegrid/storagegrid.go index f2362a533..1d20fa6da 100644 --- a/cmd/collectors/storagegrid/storagegrid.go +++ b/cmd/collectors/storagegrid/storagegrid.go @@ -136,9 +136,8 @@ func (s *StorageGrid) InitCache() error { func (s *StorageGrid) PollData() (map[string]*matrix.Matrix, error) { if s.Props.Query == "prometheus" { return s.pollPrometheusMetrics() - } else { - return s.pollRest() } + return s.pollRest() } func (s *StorageGrid) pollPrometheusMetrics() (map[string]*matrix.Matrix, error) { diff --git a/cmd/collectors/zapi/collector/parsers.go b/cmd/collectors/zapi/collector/parsers.go index 56f3d08be..b88c1eccb 100644 --- a/cmd/collectors/zapi/collector/parsers.go +++ b/cmd/collectors/zapi/collector/parsers.go @@ -14,8 +14,8 @@ import ( func ParseShortestPath(m *matrix.Matrix, l map[string]string) []string { - prefix := make([]string, 0) - keys := make([][]string, 0) + var prefix []string + var keys [][]string for key := range m.GetMetrics() { keys = append(keys, strings.Split(key, ".")) @@ -24,9 +24,9 @@ func ParseShortestPath(m *matrix.Matrix, l map[string]string) []string { keys = append(keys, strings.Split(key, ".")) } - max := util.MinLen(keys) + minLen := util.MinLen(keys) - for i := 0; i < max; i++ { + for i := 0; i < minLen; i++ { if util.AllSame(keys, i) { prefix = append(prefix, keys[0][i]) } else { @@ -93,7 +93,8 @@ func (z *Zapi) HandleCounter(path []string, content string) string { name = strings.TrimSpace(strings.TrimLeft(name, "^")) - fullPath = append(path, name) + fullPath = path + fullPath = append(fullPath, name) key = strings.Join(fullPath, ".") if display == "" { diff --git a/cmd/collectors/zapi/collector/zapi.go b/cmd/collectors/zapi/collector/zapi.go index af6a4c543..6436c01e4 100644 --- a/cmd/collectors/zapi/collector/zapi.go +++ b/cmd/collectors/zapi/collector/zapi.go @@ -275,10 +275,10 @@ func (z *Zapi) PollData() (map[string]*matrix.Matrix, error) { } fetch = func(instance *matrix.Instance, node *node.Node, path []string, isAppend bool) { - - newpath := append(path, node.GetNameS()) - key := strings.Join(newpath, ".") - z.Logger.Trace().Msgf(" > %s(%s)%s <%s%d%s> name=[%s%s%s%s] value=[%s%s%s]", color.Grey, newpath, color.End, color.Red, len(node.GetChildren()), color.End, color.Bold, color.Cyan, node.GetNameS(), color.End, color.Yellow, node.GetContentS(), color.End) + newPath := path + newPath = append(newPath, node.GetNameS()) + key := strings.Join(newPath, ".") + z.Logger.Trace().Msgf(" > %s(%s)%s <%s%d%s> name=[%s%s%s%s] value=[%s%s%s]", color.Grey, newPath, color.End, color.Red, len(node.GetChildren()), color.End, color.Bold, color.Cyan, node.GetNameS(), color.End, color.Yellow, node.GetContentS(), color.End) if value := node.GetContentS(); value != "" { if label, has := z.instanceLabelPaths[key]; has { @@ -312,9 +312,9 @@ func (z *Zapi) PollData() (map[string]*matrix.Matrix, error) { for _, child := range node.GetChildren() { if util.HasDuplicates(child.GetAllChildNamesS()) { z.Logger.Debug().Msgf("Array detected for %s", child.GetNameS()) - fetch(instance, child, newpath, true) + fetch(instance, child, newPath, true) } else { - fetch(instance, child, newpath, isAppend) + fetch(instance, child, newPath, isAppend) } } } @@ -483,13 +483,16 @@ func (z *Zapi) CollectAutoSupport(p *collector.Payload) { } if z.Object == "Node" { - nodeIds, err := z.getNodeUuids() + var ( + nodeIds []collector.ID + err error + ) + nodeIds, err = z.getNodeUuids() if err != nil { // log but don't return so the other info below is collected z.Logger.Error(). Err(err). Msg("Unable to get nodes.") - nodeIds = make([]collector.ID, 0) } info.Ids = nodeIds p.Nodes = &info diff --git a/cmd/collectors/zapi/plugins/sensor/sensor.go b/cmd/collectors/zapi/plugins/sensor/sensor.go index e715d8487..1b17dbaf3 100644 --- a/cmd/collectors/zapi/plugins/sensor/sensor.go +++ b/cmd/collectors/zapi/plugins/sensor/sensor.go @@ -249,31 +249,27 @@ func (my *Sensor) calculateEnvironmentMetrics(data *matrix.Matrix) ([]*matrix.Ma currentKey := currentKeys[i] voltageKey := voltageKeys[i] - //get values + // get values currentSensorValue := v.currentSensor[currentKey] voltageSensorValue := v.voltageSensor[voltageKey] // convert units if currentSensorValue.unit == "mA" { currentSensorValue.value = currentSensorValue.value / 1000 - } else if currentSensorValue.unit == "A" { - // do nothing - } else { + } else if currentSensorValue.unit != "A" { my.Logger.Warn().Str("node", key).Str("unit", currentSensorValue.unit).Float64("value", currentSensorValue.value).Msg("unknown current unit") } if voltageSensorValue.unit == "mV" { voltageSensorValue.value = voltageSensorValue.value / 1000 - } else if voltageSensorValue.unit == "V" { - // do nothing - } else { + } else if voltageSensorValue.unit != "V" { my.Logger.Warn().Str("node", key).Str("unit", voltageSensorValue.unit).Float64("value", voltageSensorValue.value).Msg("unknown voltage unit") } p := currentSensorValue.value * voltageSensorValue.value if !strings.EqualFold(voltageSensorValue.name, "in") && !strings.EqualFold(currentSensorValue.name, "in") { - p = p / 0.93 //If the sensor names to do NOT contain "IN" or "in", then we need to adjust the power to account for loss in the power supply. We will use 0.93 as the power supply efficiency factor for all systems. + p = p / 0.93 // If the sensor names to do NOT contain "IN" or "in", then we need to adjust the power to account for loss in the power supply. We will use 0.93 as the power supply efficiency factor for all systems. } sumPower += p diff --git a/cmd/collectors/zapi/plugins/sensor/sensor_test.go b/cmd/collectors/zapi/plugins/sensor/sensor_test.go index a4f7a3029..576585f9f 100644 --- a/cmd/collectors/zapi/plugins/sensor/sensor_test.go +++ b/cmd/collectors/zapi/plugins/sensor/sensor_test.go @@ -33,9 +33,9 @@ func init() { } fetch = func(instance *matrix.Instance, node *node.Node, path []string) { - - newpath := append(path, node.GetNameS()) - key := strings.Join(newpath, ".") + newPath := path + newPath = append(newPath, node.GetNameS()) + key := strings.Join(newPath, ".") if value := node.GetContentS(); value != "" { if label, has := instanceLabelPaths[key]; has { instance.SetLabel(label, value) @@ -45,7 +45,7 @@ func init() { } for _, child := range node.GetChildren() { - fetch(instance, child, newpath) + fetch(instance, child, newPath) } } diff --git a/cmd/collectors/zapi/plugins/snapmirror/snapmirror_test.go b/cmd/collectors/zapi/plugins/snapmirror/snapmirror_test.go index 00ef8967e..23254c7d2 100644 --- a/cmd/collectors/zapi/plugins/snapmirror/snapmirror_test.go +++ b/cmd/collectors/zapi/plugins/snapmirror/snapmirror_test.go @@ -34,9 +34,7 @@ func testWithoutGroupType(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "" && instance.GetLabel("protectionSourceType") == "" { - // OK - } else { + if instance.GetLabel("protectedBy") != "" || instance.GetLabel("protectionSourceType") != "" { t.Errorf("Labels protectedBy= %s, expected empty and protectionSourceType= %s, expected empty", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -47,9 +45,7 @@ func testSvmdr(t *testing.T, instance *matrix.Instance) { instance.SetLabel("source_volume", "") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "storage_vm" && instance.GetLabel("protectionSourceType") == "storage_vm" { - // OK - } else { + if instance.GetLabel("protectedBy") != "storage_vm" || instance.GetLabel("protectionSourceType") != "storage_vm" { t.Errorf("Labels protectedBy= %s, expected: storage_vm and protectionSourceType= %s, expected: storage_vm", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -61,9 +57,7 @@ func testConstituentVolumeWithinSvmdr(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test1") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "storage_vm" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "storage_vm" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: storage_vm and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -73,9 +67,7 @@ func testCg(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test123:/cg/") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "cg" && instance.GetLabel("protectionSourceType") == "cg" { - // OK - } else { + if instance.GetLabel("protectedBy") != "cg" || instance.GetLabel("protectionSourceType") != "cg" { t.Errorf("Labels protectedBy= %s, expected: cg and protectionSourceType= %s, expected: cg", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -85,9 +77,7 @@ func testConstituentVolumeWithinCg(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test123") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "cg" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "cg" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: cg and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -96,9 +86,7 @@ func testNegativeCase1(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "infinitevol") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "not_mapped" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "not_mapped" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: not_mapped", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -110,9 +98,7 @@ func testNegativeCase2(t *testing.T, instance *matrix.Instance) { instance.SetLabel("destination_location", "test123:") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "not_mapped" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "not_mapped" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: not_mapped", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -121,9 +107,7 @@ func testGroupTypeNone(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "none") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -132,9 +116,7 @@ func testGroupTypeFlexgroup(t *testing.T, instance *matrix.Instance) { instance.SetLabel("group_type", "flexgroup") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("protectedBy") == "volume" && instance.GetLabel("protectionSourceType") == "volume" { - // OK - } else { + if instance.GetLabel("protectedBy") != "volume" || instance.GetLabel("protectionSourceType") != "volume" { t.Errorf("Labels protectedBy= %s, expected: volume and protectionSourceType= %s, expected: volume", instance.GetLabel("protectedBy"), instance.GetLabel("protectionSourceType")) } } @@ -145,9 +127,7 @@ func testStrictSyncMirror(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "strict_sync_mirror") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "sync_mirror_strict" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "sync_mirror_strict" { t.Errorf("Labels derived_relationship_type= %s, expected: sync_mirror_strict", instance.GetLabel("derived_relationship_type")) } } @@ -157,9 +137,7 @@ func testSyncMirror(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "sync_mirror") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "sync_mirror" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "sync_mirror" { t.Errorf("Labels derived_relationship_type= %s, expected: sync_mirror", instance.GetLabel("derived_relationship_type")) } } @@ -169,9 +147,7 @@ func testMirrorVault(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "mirror_vault") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "mirror_vault" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "mirror_vault" { t.Errorf("Labels derived_relationship_type= %s, expected: mirror_vault", instance.GetLabel("derived_relationship_type")) } } @@ -181,9 +157,7 @@ func testAutomatedFailover(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "automated_failover") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "sync_mirror" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "sync_mirror" { t.Errorf("Labels derived_relationship_type= %s, expected: sync_mirror", instance.GetLabel("derived_relationship_type")) } } @@ -193,9 +167,7 @@ func testOtherPolicyType(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "vault") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "vault" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "vault" { t.Errorf("Labels derived_relationship_type= %s, expected: vault", instance.GetLabel("derived_relationship_type")) } } @@ -205,9 +177,7 @@ func testWithNoPolicyType(t *testing.T, instance *matrix.Instance) { instance.SetLabel("policy_type", "") collectors.UpdateProtectedFields(instance) - if instance.GetLabel("derived_relationship_type") == "extended_data_protection" { - // OK - } else { + if instance.GetLabel("derived_relationship_type") != "extended_data_protection" { t.Errorf("Labels derived_relationship_type= %s, expected: extended_data_protection", instance.GetLabel("derived_relationship_type")) } } diff --git a/cmd/collectors/zapi/plugins/svm/svm.go b/cmd/collectors/zapi/plugins/svm/svm.go index ad3d550c7..0214dc8ed 100644 --- a/cmd/collectors/zapi/plugins/svm/svm.go +++ b/cmd/collectors/zapi/plugins/svm/svm.go @@ -29,36 +29,36 @@ type SVM struct { batchSize string client *zapi.Client auditProtocols map[string]string - cifsProtocols map[string]cifsSecurity - nsswitchInfo map[string]nsswitch + cifsProtocols map[string]CifsSecurity + nsswitchInfo map[string]Nsswitch nisInfo map[string]string cifsEnabled map[string]bool nfsEnabled map[string]string - sshData map[string]sshInfo + sshData map[string]SSHInfo iscsiAuth map[string]string iscsiService map[string]string - fpolicyData map[string]fpolicy + fpolicyData map[string]Fpolicy ldapData map[string]string kerberosConfig map[string]string } -type nsswitch struct { +type Nsswitch struct { nsdb []string nssource []string } -type fpolicy struct { +type Fpolicy struct { name string enable string } -type cifsSecurity struct { +type CifsSecurity struct { cifsNtlmEnabled string smbEncryption string smbSigning string } -type sshInfo struct { +type SSHInfo struct { ciphers string isInsecure string } @@ -85,15 +85,15 @@ func (my *SVM) Init() error { } my.auditProtocols = make(map[string]string) - my.cifsProtocols = make(map[string]cifsSecurity) - my.nsswitchInfo = make(map[string]nsswitch) + my.cifsProtocols = make(map[string]CifsSecurity) + my.nsswitchInfo = make(map[string]Nsswitch) my.nisInfo = make(map[string]string) my.cifsEnabled = make(map[string]bool) my.nfsEnabled = make(map[string]string) - my.sshData = make(map[string]sshInfo) + my.sshData = make(map[string]SSHInfo) my.iscsiAuth = make(map[string]string) my.iscsiService = make(map[string]string) - my.fpolicyData = make(map[string]fpolicy) + my.fpolicyData = make(map[string]Fpolicy) my.ldapData = make(map[string]string) my.kerberosConfig = make(map[string]string) @@ -339,15 +339,15 @@ func (my *SVM) GetAuditProtocols() (map[string]string, error) { return vserverAuditEnableMap, nil } -func (my *SVM) GetCifsProtocols() (map[string]cifsSecurity, error) { +func (my *SVM) GetCifsProtocols() (map[string]CifsSecurity, error) { var ( result []*node.Node request *node.Node - vserverCifsDataMap map[string]cifsSecurity + vserverCifsDataMap map[string]CifsSecurity err error ) - vserverCifsDataMap = make(map[string]cifsSecurity) + vserverCifsDataMap = make(map[string]CifsSecurity) request = node.NewXMLS("cifs-security-get-iter") request.NewChildS("max-records", my.batchSize) @@ -365,22 +365,22 @@ func (my *SVM) GetCifsProtocols() (map[string]cifsSecurity, error) { smbSigning := cifsSecurityData.GetChildContentS("is-signing-required") smbEncryption := cifsSecurityData.GetChildContentS("is-smb-encryption-required") svmName := cifsSecurityData.GetChildContentS("vserver") - vserverCifsDataMap[svmName] = cifsSecurity{cifsNtlmEnabled: lmCompatibilityLevel, smbEncryption: smbEncryption, smbSigning: smbSigning} + vserverCifsDataMap[svmName] = CifsSecurity{cifsNtlmEnabled: lmCompatibilityLevel, smbEncryption: smbEncryption, smbSigning: smbSigning} } return vserverCifsDataMap, nil } -func (my *SVM) GetNSSwitchInfo() (map[string]nsswitch, error) { +func (my *SVM) GetNSSwitchInfo() (map[string]Nsswitch, error) { var ( result []*node.Node request *node.Node - vserverNsswitchMap map[string]nsswitch - ns nsswitch + vserverNsswitchMap map[string]Nsswitch + ns Nsswitch ok bool err error ) - vserverNsswitchMap = make(map[string]nsswitch) + vserverNsswitchMap = make(map[string]Nsswitch) request = node.NewXMLS("nameservice-nsswitch-get-iter") request.NewChildS("max-records", my.batchSize) @@ -403,7 +403,7 @@ func (my *SVM) GetNSSwitchInfo() (map[string]nsswitch, error) { ns.nsdb = append(ns.nsdb, nsdb) ns.nssource = append(ns.nssource, nssourcelist...) } else { - ns = nsswitch{nsdb: []string{nsdb}, nssource: nssourcelist} + ns = Nsswitch{nsdb: []string{nsdb}, nssource: nssourcelist} } vserverNsswitchMap[svmName] = ns } @@ -496,15 +496,15 @@ func (my *SVM) GetNfsEnabled() (map[string]string, error) { return vserverNfsMap, nil } -func (my *SVM) GetSSHData() (map[string]sshInfo, error) { +func (my *SVM) GetSSHData() (map[string]SSHInfo, error) { var ( result []*node.Node request *node.Node - sshMap map[string]sshInfo + sshMap map[string]SSHInfo err error ) - sshMap = make(map[string]sshInfo) + sshMap = make(map[string]SSHInfo) request = node.NewXMLS("security-ssh-get-iter") request.NewChildS("max-records", my.batchSize) @@ -523,7 +523,7 @@ func (my *SVM) GetSSHData() (map[string]sshInfo, error) { sort.Strings(sshList) ciphersVal := strings.Join(sshList, ",") insecured := weakCiphers.MatchString(ciphersVal) - sshMap[svmName] = sshInfo{ciphers: ciphersVal, isInsecure: strconv.FormatBool(insecured)} + sshMap[svmName] = SSHInfo{ciphers: ciphersVal, isInsecure: strconv.FormatBool(insecured)} } return sshMap, nil } @@ -598,15 +598,15 @@ func (my *SVM) GetIscsiService() (map[string]string, error) { return vserverIscsiServiceMap, nil } -func (my *SVM) GetFpolicy() (map[string]fpolicy, error) { +func (my *SVM) GetFpolicy() (map[string]Fpolicy, error) { var ( result []*node.Node request *node.Node - vserverFpolicyMap map[string]fpolicy + vserverFpolicyMap map[string]Fpolicy err error ) - vserverFpolicyMap = make(map[string]fpolicy) + vserverFpolicyMap = make(map[string]Fpolicy) request = node.NewXMLS("fpolicy-policy-status-get-iter") request.NewChildS("max-records", my.batchSize) @@ -624,11 +624,11 @@ func (my *SVM) GetFpolicy() (map[string]fpolicy, error) { enable := fpolicyData.GetChildContentS("status") svmName := fpolicyData.GetChildContentS("vserver") if _, ok := vserverFpolicyMap[svmName]; !ok { - vserverFpolicyMap[svmName] = fpolicy{name: name, enable: enable} + vserverFpolicyMap[svmName] = Fpolicy{name: name, enable: enable} } else { // If svm is already present, update the status value only if it is false if vserverFpolicyMap[svmName].enable == "false" { - vserverFpolicyMap[svmName] = fpolicy{name: name, enable: enable} + vserverFpolicyMap[svmName] = Fpolicy{name: name, enable: enable} } } } diff --git a/cmd/collectors/zapi/plugins/volume/volume.go b/cmd/collectors/zapi/plugins/volume/volume.go index a34cc33e8..66a5e5ec9 100644 --- a/cmd/collectors/zapi/plugins/volume/volume.go +++ b/cmd/collectors/zapi/plugins/volume/volume.go @@ -136,9 +136,8 @@ func (v *Volume) updateVolumeLabels(data *matrix.Matrix, volumeCloneMap map[stri if splitEstimateBytes, err = strconv.ParseFloat(vc.splitEstimate, 64); err != nil { v.Logger.Error().Err(err).Str("clone_split_estimate", vc.splitEstimate).Msg("parse clone_split_estimate") continue - } else { - splitEstimateBytes = splitEstimateBytes * 4 * 1024 } + splitEstimateBytes = splitEstimateBytes * 4 * 1024 if err = splitEstimate.SetValueFloat64(volume, splitEstimateBytes); err != nil { v.Logger.Error().Err(err).Str("clone_split_estimate", vc.splitEstimate).Msg("set clone_split_estimate") continue @@ -196,7 +195,7 @@ func (v *Volume) getEncryptedDisks() ([]string, error) { request := node.NewXMLS("disk-encrypt-get-iter") request.NewChildS("max-records", collectors.DefaultBatchSize) - //algorithm is -- Protection mode needs to be DATA or FULL + // algorithm is -- Protection mode needs to be DATA or FULL // Fetching rest of them and add as query := request.NewChildS("query", "") encryptInfoQuery := query.NewChildS("disk-encrypt-info", "") diff --git a/cmd/collectors/zapiperf/plugins/disk/disk.go b/cmd/collectors/zapiperf/plugins/disk/disk.go index e5dcd3d9f..7e4f27b39 100644 --- a/cmd/collectors/zapiperf/plugins/disk/disk.go +++ b/cmd/collectors/zapiperf/plugins/disk/disk.go @@ -235,13 +235,13 @@ func (d *Disk) initAggrPowerMatrix() { } func (d *Disk) initMaps() { - //reset shelf Power + // reset shelf Power d.ShelfMap = make(map[string]*shelf) - //reset diskmap + // reset diskmap d.diskMap = make(map[string]*disk) - //reset aggrmap + // reset aggrmap d.aggrMap = make(map[string]*aggregate) } @@ -356,7 +356,7 @@ func (d *Disk) calculateAggrPower(data *matrix.Matrix, output []*matrix.Matrix) for _, v1 := range v.disks { c := len(v1.aggregates) if c > 0 { - diskWithAggregateCount += 1 + diskWithAggregateCount++ } } if diskWithAggregateCount != 0 { diff --git a/cmd/collectors/zapiperf/plugins/externalserviceoperation/externalserviceoperation.go b/cmd/collectors/zapiperf/plugins/externalserviceoperation/externalserviceoperation.go index ef65ff41b..219602607 100644 --- a/cmd/collectors/zapiperf/plugins/externalserviceoperation/externalserviceoperation.go +++ b/cmd/collectors/zapiperf/plugins/externalserviceoperation/externalserviceoperation.go @@ -1,6 +1,5 @@ -/* - * Copyright NetApp Inc, 2023 All rights reserved - */ +// Copyright NetApp Inc, 2023 All rights reserved + package externalserviceoperation import ( diff --git a/cmd/collectors/zapiperf/plugins/fcvi/fcvi.go b/cmd/collectors/zapiperf/plugins/fcvi/fcvi.go index 6f7d8e882..46bfd2fa4 100644 --- a/cmd/collectors/zapiperf/plugins/fcvi/fcvi.go +++ b/cmd/collectors/zapiperf/plugins/fcvi/fcvi.go @@ -30,10 +30,7 @@ func (f *FCVI) Init() error { f.Logger.Error().Stack().Err(err).Msg("connecting") return err } - if err = f.client.Init(5); err != nil { - return err - } - return nil + return f.client.Init(5) } func (f *FCVI) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matrix, error) { diff --git a/cmd/collectors/zapiperf/plugins/headroom/headroom.go b/cmd/collectors/zapiperf/plugins/headroom/headroom.go index cefc0f14e..e4efee38b 100644 --- a/cmd/collectors/zapiperf/plugins/headroom/headroom.go +++ b/cmd/collectors/zapiperf/plugins/headroom/headroom.go @@ -1,6 +1,5 @@ -/* - * Copyright NetApp Inc, 2021 All rights reserved - */ +// Copyright NetApp Inc, 2021 All rights reserved + package headroom import ( diff --git a/cmd/collectors/zapiperf/plugins/volumetag/volumetag.go b/cmd/collectors/zapiperf/plugins/volumetag/volumetag.go index e7a4501e8..9dca02d91 100644 --- a/cmd/collectors/zapiperf/plugins/volumetag/volumetag.go +++ b/cmd/collectors/zapiperf/plugins/volumetag/volumetag.go @@ -29,10 +29,7 @@ func (v *VolumeTag) Init() error { v.Logger.Error().Stack().Err(err).Msg("connecting") return err } - if err = v.client.Init(5); err != nil { - return err - } - return nil + return v.client.Init(5) } func (v *VolumeTag) Run(dataMap map[string]*matrix.Matrix) ([]*matrix.Matrix, error) { diff --git a/cmd/collectors/zapiperf/zapiperf.go b/cmd/collectors/zapiperf/zapiperf.go index 35bf4926e..a2ef30bac 100644 --- a/cmd/collectors/zapiperf/zapiperf.go +++ b/cmd/collectors/zapiperf/zapiperf.go @@ -264,14 +264,14 @@ func (z *ZapiPerf) PollData() (map[string]*matrix.Matrix, error) { // list of instance keys (instance names or uuids) for which // we will request counter data if z.Query == objWorkloadDetail || z.Query == objWorkloadDetailVolume { - if resourceMap := z.Params.GetChildS("resource_map"); resourceMap == nil { + resourceMap := z.Params.GetChildS("resource_map") + if resourceMap == nil { return nil, errs.New(errs.ErrMissingParam, "resource_map") - } else { - instanceKeys = make([]string, 0) - for _, layer := range resourceMap.GetAllChildNamesS() { - for key := range prevMat.GetInstances() { - instanceKeys = append(instanceKeys, key+"."+layer) - } + } + instanceKeys = make([]string, 0) + for _, layer := range resourceMap.GetAllChildNamesS() { + for key := range prevMat.GetInstances() { + instanceKeys = append(instanceKeys, key+"."+layer) } } } else { @@ -337,8 +337,7 @@ func (z *ZapiPerf) PollData() (map[string]*matrix.Matrix, error) { if err != nil { // if ONTAP complains about batch size, use a smaller batch size if strings.Contains(err.Error(), "resource limit exceeded") && z.batchSize > 100 { - z.Logger.Error().Err(err) - z.Logger.Info(). + z.Logger.Error().Err(err). Int("oldBatchSize", z.batchSize). Int("newBatchSize", z.batchSize-100). Msg("Changed batch_size") @@ -1109,48 +1108,48 @@ func (z *ZapiPerf) PollCounter() (map[string]*matrix.Matrix, error) { wait.SetExportable(false) visits.SetExportable(false) - if resourceMap := z.Params.GetChildS("resource_map"); resourceMap == nil { + resourceMap := z.Params.GetChildS("resource_map") + if resourceMap == nil { return nil, errs.New(errs.ErrMissingParam, "resource_map") - } else { - for _, x := range resourceMap.GetChildren() { - for _, wm := range workloadDetailMetrics { - - name := x.GetNameS() + wm - resource := x.GetContentS() + } + for _, x := range resourceMap.GetChildren() { + for _, wm := range workloadDetailMetrics { - if m := mat.GetMetric(name); m != nil { - oldMetrics.Remove(name) - continue - } - if m, err := mat.NewMetricFloat64(name, wm); err != nil { - return nil, err - } else { - m.SetLabel("resource", resource) - m.SetProperty(service.GetProperty()) - // base counter is the ops of the same resource - m.SetComment("ops") + name := x.GetNameS() + wm + resource := x.GetContentS() - oldMetrics.Remove(name) - z.Logger.Debug().Msgf("+ [%s] (=> %s) added workload latency metric", name, resource) - } + if m := mat.GetMetric(name); m != nil { + oldMetrics.Remove(name) + continue } + m, err := mat.NewMetricFloat64(name, wm) + if err != nil { + return nil, err + } + m.SetLabel("resource", resource) + m.SetProperty(service.GetProperty()) + // base counter is the ops of the same resource + m.SetComment("ops") + + oldMetrics.Remove(name) + z.Logger.Debug().Msgf("+ [%s] (=> %s) added workload latency metric", name, resource) } } } - if qosLabels := z.Params.GetChildS("qos_labels"); qosLabels == nil { + qosLabels := z.Params.GetChildS("qos_labels") + if qosLabels == nil { return nil, errs.New(errs.ErrMissingParam, "qos_labels") - } else { - z.qosLabels = make(map[string]string) - for _, label := range qosLabels.GetAllChildContentS() { + } + z.qosLabels = make(map[string]string) + for _, label := range qosLabels.GetAllChildContentS() { - display := strings.ReplaceAll(label, "-", "_") - if x := strings.Split(label, "=>"); len(x) == 2 { - label = strings.TrimSpace(x[0]) - display = strings.TrimSpace(x[1]) - } - z.qosLabels[label] = display + display := strings.ReplaceAll(label, "-", "_") + if x := strings.Split(label, "=>"); len(x) == 2 { + label = strings.TrimSpace(x[0]) + display = strings.TrimSpace(x[1]) } + z.qosLabels[label] = display } } diff --git a/cmd/collectors/zapiperf/zapiperf_test.go b/cmd/collectors/zapiperf/zapiperf_test.go index adf83d9b5..f4f8efbf9 100644 --- a/cmd/collectors/zapiperf/zapiperf_test.go +++ b/cmd/collectors/zapiperf/zapiperf_test.go @@ -48,7 +48,7 @@ func NewZapiPerf(object, path string) *ZapiPerf { ac := collector.New("Zapiperf", object, &opts, params(object, path), nil) z := &ZapiPerf{} if err := z.Init(ac); err != nil { - log.Fatal().Err(err) + log.Fatal().Err(err).Send() } z.Object = object diff --git a/cmd/exporters/influxdb/influxdb.go b/cmd/exporters/influxdb/influxdb.go index b9b683e00..137261d75 100644 --- a/cmd/exporters/influxdb/influxdb.go +++ b/cmd/exporters/influxdb/influxdb.go @@ -217,11 +217,11 @@ func (e *InfluxDB) Emit(data [][]byte) error { //goland:noinspection GoUnhandledErrorResult defer response.Body.Close() if response.StatusCode != expectedResponseCode { - if body, err := io.ReadAll(response.Body); err != nil { + body, err := io.ReadAll(response.Body) + if err != nil { return errs.New(errs.ErrAPIResponse, err.Error()) - } else { - return fmt.Errorf("%w: %s", errs.ErrAPIRequestRejected, string(body)) } + return fmt.Errorf("%w: %s", errs.ErrAPIRequestRejected, string(body)) } return nil } @@ -340,7 +340,7 @@ func (e *InfluxDB) Render(data *matrix.Matrix) ([][]byte, error) { e.Logger.Debug().Msgf("skip instance (%s), no field set parsed", key) } else if r, err := m.Render(); err == nil { rendered = append(rendered, []byte(r)) - //logger.Debug(e.Prefix, "M= [%s%s%s]", color.Blue, r, color.End) + // logger.Debug(e.Prefix, "M= [%s%s%s]", color.Blue, r, color.End) count += countTmp } else { e.Logger.Debug().Msg(err.Error()) diff --git a/cmd/exporters/prometheus/httpd.go b/cmd/exporters/prometheus/httpd.go index 7ffba1aac..9325944b7 100644 --- a/cmd/exporters/prometheus/httpd.go +++ b/cmd/exporters/prometheus/httpd.go @@ -96,7 +96,7 @@ func (p *Prometheus) checkAddr(addr string) bool { func (p *Prometheus) denyAccess(w http.ResponseWriter, r *http.Request) { p.Logger.Debug().Msgf("(httpd) denied request [%s] (%s)", r.RequestURI, r.RemoteAddr) - w.WriteHeader(403) + w.WriteHeader(http.StatusForbidden) w.Header().Set("content-type", "text/plain") _, err := w.Write([]byte("403 Forbidden")) if err != nil { @@ -145,7 +145,7 @@ func (p *Prometheus) ServeMetrics(w http.ResponseWriter, r *http.Request) { data = filterMetaTags(data) } - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) w.Header().Set("content-type", "text/plain") _, err := w.Write(bytes.Join(data, []byte("\n"))) if err != nil { @@ -284,7 +284,7 @@ func (p *Prometheus) ServeInfo(w http.ResponseWriter, r *http.Request) { poller := p.Options.Poller bodyFlat := fmt.Sprintf(htmlTemplate, poller, poller, poller, numCollectors, numObjects, numMetrics, strings.Join(body, "\n\n")) - w.WriteHeader(200) + w.WriteHeader(http.StatusOK) w.Header().Set("content-type", "text/html") _, err := w.Write([]byte(bodyFlat)) if err != nil { diff --git a/cmd/exporters/prometheus/prometheus.go b/cmd/exporters/prometheus/prometheus.go index 55ac0b013..e09561ebc 100644 --- a/cmd/exporters/prometheus/prometheus.go +++ b/cmd/exporters/prometheus/prometheus.go @@ -585,7 +585,7 @@ func (p *Prometheus) normalizeHistogram(metric *matrix.Metric, ontap string, obj p.Logger.Trace().Str("num", num).Msg("Unable to convert to float64") return "" } - normal := 0.0 + var normal float64 switch unit { case "us": return num diff --git a/cmd/harvest/harvest.go b/cmd/harvest/harvest.go index 732dabeba..32945dfa7 100644 --- a/cmd/harvest/harvest.go +++ b/cmd/harvest/harvest.go @@ -1,5 +1,5 @@ /* - - Copyright NetApp Inc, 2021 All rights reserved +Copyright NetApp Inc, 2021 All rights reserved NetApp Harvest : the swiss-army-knife for datacenter monitoring diff --git a/cmd/harvest/version/version.go b/cmd/harvest/version/version.go index beecee9c6..041e54b75 100644 --- a/cmd/harvest/version/version.go +++ b/cmd/harvest/version/version.go @@ -90,9 +90,8 @@ func isNewerAvailable(current string, remote string) (bool, error) { } if currentVersion.GreaterThanOrEqual(remoteVersion) { return false, nil - } else { - return true, nil } + return true, nil } func latestRelease() (string, error) { diff --git a/cmd/poller/collector/asup.go b/cmd/poller/collector/asup.go index 9deeafa8f..9f55aa954 100644 --- a/cmd/poller/collector/asup.go +++ b/cmd/poller/collector/asup.go @@ -322,9 +322,8 @@ func attachMemory(msg *Payload) { cmdline, err := p.Cmdline() if err != nil { continue - } else { - pp.Cmdline = cmdline } + pp.Cmdline = cmdline if len(cmdline) == 0 { continue } diff --git a/cmd/poller/plugin/labelagent/label_agent.go b/cmd/poller/plugin/labelagent/label_agent.go index bd43e29a8..c5c83d6d1 100644 --- a/cmd/poller/plugin/labelagent/label_agent.go +++ b/cmd/poller/plugin/labelagent/label_agent.go @@ -311,9 +311,8 @@ func (a *LabelAgent) mapValueToNum(m *matrix.Matrix) error { if metric, err = m.NewMetricUint8(r.metric); err != nil { a.Logger.Error().Stack().Err(err).Msgf("valueToNumMapping: new metric [%s]:", r.metric) return err - } else { - metric.SetProperty("value_to_num mapping") } + metric.SetProperty("value_to_num mapping") } for key, instance := range m.GetInstances() { @@ -342,9 +341,8 @@ func (a *LabelAgent) mapValueToNumRegex(m *matrix.Matrix) error { if metric, err = m.NewMetricUint8(r.metric); err != nil { a.Logger.Error().Stack().Err(err).Msgf("valueToNumRegexMapping: new metric [%s]:", r.metric) return err - } else { - metric.SetProperty("value_to_num_regex mapping") } + metric.SetProperty("value_to_num_regex mapping") } for key, instance := range m.GetInstances() { diff --git a/cmd/poller/plugin/labelagent/label_agent_test.go b/cmd/poller/plugin/labelagent/label_agent_test.go index 14f10ec1d..27ec7998a 100644 --- a/cmd/poller/plugin/labelagent/label_agent_test.go +++ b/cmd/poller/plugin/labelagent/label_agent_test.go @@ -9,7 +9,7 @@ import ( "github.com/netapp/harvest/v2/pkg/matrix" "github.com/netapp/harvest/v2/pkg/tree/node" "testing" - //"github.com/netapp/harvest/v2/share/logger" + // "github.com/netapp/harvest/v2/share/logger" ) func newLabelAgent() *LabelAgent { @@ -83,9 +83,7 @@ func TestSplitSimpleRule(t *testing.T) { _ = p.splitSimple(m) t.Logf("after = [%s]\n", instance.GetLabels().String()) - if instance.GetLabel("C") == "c" && instance.GetLabel("D") == "d" { - // OK - } else { + if instance.GetLabel("C") != "c" || instance.GetLabel("D") != "d" { t.Error("Labels C and D don't have expected values") } } @@ -101,9 +99,7 @@ func TestSplitRegexRule(t *testing.T) { _ = p.splitRegex(m) t.Logf("after = [%s]\n", instance.GetLabels().String()) - if instance.GetLabel("A") == "A22" && instance.GetLabel("B") == "B333" { - // OK - } else { + if instance.GetLabel("A") != "A22" || instance.GetLabel("B") != "B333" { t.Error("Labels A and B don't have expected values") } } @@ -119,9 +115,7 @@ func TestSplitPairsRule(t *testing.T) { _ = p.splitPairs(m) t.Logf("after = [%s]\n", instance.GetLabels().String()) - if instance.GetLabel("owner") == "jack" && instance.GetLabel("contact") == "some@email" { - // OK - } else { + if instance.GetLabel("owner") != "jack" || instance.GetLabel("contact") != "some@email" { t.Error("Labels owner and contact don't have expected values") } } @@ -138,9 +132,7 @@ func TestJoinSimpleRule(t *testing.T) { _ = p.joinSimple(m) t.Logf("after = [%s]\n", instance.GetLabels().String()) - if instance.GetLabel("X") == "aaa_bbb" { - // OK - } else { + if instance.GetLabel("X") != "aaa_bbb" { t.Error("Label A does have expected value") } } @@ -156,9 +148,7 @@ func TestReplaceSimpleRule(t *testing.T) { _ = p.replaceSimple(m) t.Logf("after = [%s]\n", instance.GetLabels().String()) - if instance.GetLabel("A") == "X" && instance.GetLabel("B") == "bbb_X" { - // OK - } else { + if instance.GetLabel("A") != "X" || instance.GetLabel("B") != "bbb_X" { t.Error("Labels A and B don't have expected values") } } @@ -174,9 +164,7 @@ func TestReplaceRegexRule(t *testing.T) { _ = p.replaceRegex(m) t.Logf("after = [%s]\n", instance.GetLabels().String()) - if instance.GetLabel("B") == "abcDEF-12345-bbb" { - // OK - } else { + if instance.GetLabel("B") != "abcDEF-12345-bbb" { t.Error("Label B does not have expected value") } } diff --git a/cmd/poller/plugin/labelagent/parse_rules.go b/cmd/poller/plugin/labelagent/parse_rules.go index d085db17d..fbdb512fc 100644 --- a/cmd/poller/plugin/labelagent/parse_rules.go +++ b/cmd/poller/plugin/labelagent/parse_rules.go @@ -315,7 +315,7 @@ type replaceRegexRule struct { // example rule: //nolint:dupword -//node node `^(node)_(\d+)_.*$` `Node-$2` +// node node `^(node)_(\d+)_.*$` `Node-$2` // if node="node_10_dc2"; then: // node="Node-10" @@ -522,13 +522,13 @@ func (a *LabelAgent) parseValueToNumRule(rule string) { fields[4] = strings.TrimPrefix(strings.TrimSuffix(fields[4], "`"), "`") - if v, err := strconv.ParseUint(fields[4], 10, 8); err != nil { + v, err := strconv.ParseUint(fields[4], 10, 8) + if err != nil { a.Logger.Error().Stack().Err(err).Msgf("(value_to_num) parse default value (%s): ", fields[4]) return - } else { - r.hasDefault = true - r.defaultValue = uint8(v) } + r.hasDefault = true + r.defaultValue = uint8(v) } a.valueToNumRules = append(a.valueToNumRules, r) @@ -568,13 +568,13 @@ func (a *LabelAgent) parseValueToNumRegexRule(rule string) { if len(fields) == 5 { fields[4] = strings.TrimPrefix(strings.TrimSuffix(fields[4], "`"), "`") - if v, err := strconv.ParseUint(fields[4], 10, 8); err != nil { + v, err := strconv.ParseUint(fields[4], 10, 8) + if err != nil { a.Logger.Error().Stack().Err(err).Msgf("(value_to_num_regex) parse default value (%s): ", fields[4]) return - } else { - r.hasDefault = true - r.defaultValue = uint8(v) } + r.hasDefault = true + r.defaultValue = uint8(v) } a.valueToNumRegexRules = append(a.valueToNumRegexRules, r) diff --git a/cmd/poller/plugin/metricagent/metric_agent.go b/cmd/poller/plugin/metricagent/metric_agent.go index 7044c2694..8fa2c7060 100644 --- a/cmd/poller/plugin/metricagent/metric_agent.go +++ b/cmd/poller/plugin/metricagent/metric_agent.go @@ -68,9 +68,8 @@ func (a *MetricAgent) computeMetrics(m *matrix.Matrix) error { if metric, err = m.NewMetricFloat64(r.metric); err != nil { a.Logger.Error().Err(err).Str("metric", r.metric).Msg("Failed to create metric") return err - } else { - metric.SetProperty("compute_metric mapping") } + metric.SetProperty("compute_metric mapping") } for _, instance := range m.GetInstances() { diff --git a/cmd/poller/plugin/plugin.go b/cmd/poller/plugin/plugin.go index 9230cf7de..43d14a0a7 100644 --- a/cmd/poller/plugin/plugin.go +++ b/cmd/poller/plugin/plugin.go @@ -1,30 +1,28 @@ -//Copyright NetApp Inc, 2021 All rights reserved - -/* - Package plugin provides abstractions for plugins, as well as - a number of generic built-in plugins. Plugins allow to customize - and manipulate data from collectors and sometimes collect additional - data without changing the sourcecode of collectors. Multiple plugins - can be put in a pipeline, they are executed in the same order as they - are defined in the collector's config file. - Harvest architecture defines three types of plugins: - - **built-in** - Statically compiled, generic plugins. "Generic" means - the plugin is collector-agnostic. These plugins are - provided in this package. - - **generic** - These are generic plugins as well, but they are compiled - as shared objects and dynamically loaded. These plugins are - living in the directory src/plugins. - - **custom** - These plugins are collector-specific. Their source code should - reside inside the plugins/ subdirectory of the collector package. - Custom plugins have access to all the parameters of their parent - collector and should be therefore treated with great care. -*/ +// Copyright NetApp Inc, 2021 All rights reserved +// Package plugin provides abstractions for plugins, as well as +// a number of generic built-in plugins. Plugins allow customizing +// and manipulating data from collectors and sometimes collect additional +// data without changing the sourcecode of collectors. Multiple plugins +// can be put in a pipeline, they are executed in the same order as they +// are defined in the collector's config file. +// Harvest architecture defines three types of plugins: +// +// **built-in** +// Statically compiled, generic plugins. "Generic" means +// the plugin is collector-agnostic. These plugins are +// provided in this package. +// +// **generic** +// These are generic plugins as well, but they are compiled +// as shared objects and dynamically loaded. These plugins are +// living in the directory src/plugins. +// +// **custom** +// These plugins are collector-specific. Their source code should +// reside inside the plugins/ subdirectory of the collector package. +// Custom plugins have access to all the parameters of their parent +// collector and should be therefore treated with great care. + package plugin import ( diff --git a/cmd/poller/plugin/test/plugin_test.go b/cmd/poller/plugin/test/plugin_test.go index 51fa16926..c62c40613 100644 --- a/cmd/poller/plugin/test/plugin_test.go +++ b/cmd/poller/plugin/test/plugin_test.go @@ -90,7 +90,7 @@ func TestMultipleRule(t *testing.T) { instanceNo.SetLabel("B", "aaa bbb ccc") instanceNo.SetLabel("node", "nodeB") - results := make([]*matrix.Matrix, 0) + var results []*matrix.Matrix results = append(results, m) dataMap := map[string]*matrix.Matrix{ m.Object: m, diff --git a/cmd/poller/poller.go b/cmd/poller/poller.go index f6f937810..9f95d0cb6 100644 --- a/cmd/poller/poller.go +++ b/cmd/poller/poller.go @@ -135,7 +135,7 @@ func (p *Poller) Init() error { p.options = &args p.name = args.Poller - fileLoggingEnabled := false + var fileLoggingEnabled bool consoleLoggingEnabled := false zeroLogLevel := logging.GetZerologLevel(p.options.LogLevel) // if we are daemon, use file logging @@ -695,13 +695,13 @@ func (p *Poller) loadCollectorObject(ocs []objectCollector) error { // update metadata - if instance, err := p.metadata.NewInstance(name + "." + obj); err != nil { + instance, err := p.metadata.NewInstance(name + "." + obj) + if err != nil { return err - } else { - instance.SetLabel("type", "collector") - instance.SetLabel("name", name) - instance.SetLabel("target", obj) } + instance.SetLabel("type", "collector") + instance.SetLabel("name", name) + instance.SetLabel("target", obj) } return nil @@ -1031,7 +1031,7 @@ func (p *Poller) publishDetails() { return } p.client.CloseIdleConnections() - if resp.StatusCode != 200 { + if resp.StatusCode != http.StatusOK { txt := string(body) txt = txt[0:int(math.Min(float64(len(txt)), 48))] logger.Error(). @@ -1126,7 +1126,7 @@ func (p *Poller) negotiateAPI(c conf.Collector, checkZAPIs func() error) conf.Co switchToRest = true } - if he.StatusCode == 400 { + if he.StatusCode == http.StatusBadRequest { logger.Warn().Str("collector", c.Name).Msg("ZAPIs EOA. Use REST") switchToRest = true } @@ -1159,10 +1159,7 @@ func (p *Poller) doZAPIsExist() error { return err } - if err = connection.Init(2); err != nil { - return err - } - return nil + return connection.Init(2) } func startPoller(_ *cobra.Command, _ []string) { diff --git a/cmd/poller/schedule/schedule.go b/cmd/poller/schedule/schedule.go index 0cb546be6..bffdb9c7a 100644 --- a/cmd/poller/schedule/schedule.go +++ b/cmd/poller/schedule/schedule.go @@ -1,35 +1,34 @@ -/* - Copyright NetApp Inc, 2021 All rights reserved - - Package Schedule provides a mechanism to run tasks at fixed time interals. - It is intended to be used by collectors, but can be used by any other - package as well. Tasks can be dynamically pointed to the poll functions - of the collector. (This why poll functions of collectors are public and - have the same signature). - - At least one task should be added to Schedule before it can be used. - Tasks are yielded in the same order as added (FIFO). The intervals of tasks - can be safely changed any time. - - Create Schedule: - - Initialize empty Schedule with New(), - - Add tasks with NewTask() or NewTaskString(), - the task is marked as due immediately! - - Use Schedule (usually in a closed loop): - - iterate over all tasks with GetTasks() - - check if it's time to run the task with IsDue(task) - - run the task with task.Run() or run "manually" with task.Start() - - suspend the goroutine until another task is due Sleep()/Wait() - - The Schedule can enter standByMode when a critical task has failed. In this - scenario all tasks are stalled until the critical task has succeeded. This is - sometimes useful when a target system is unreachable and we have to wait - until it's up again. - - Schedule is meant to be used by at most one goroutine and is not - concurrent-safe. -*/ +// Copyright NetApp Inc, 2021 All rights reserved + +// Package Schedule provides a mechanism to run tasks at fixed time internals. +// It is intended to be used by collectors, but can be used by any other +// package as well. Tasks can be dynamically pointed to the poll functions +// of the collector. (This is why poll functions of collectors are public and +// have the same signature). +// +// At least one task should be added to Schedule before it can be used. +// Tasks are yielded in the same order as added (FIFO). The intervals of tasks +// can be safely changed any time. +// +// Create Schedule: +// - Initialize empty Schedule with New(), +// - Add tasks with NewTask() or NewTaskString(), +// the task is marked as due immediately! +// +// Use Schedule (usually in a closed loop): +// - iterate over all tasks with GetTasks() +// - check if it's time to run the task with IsDue(task) +// - run the task with task.Run() or run "manually" with task.Start() +// - suspend the goroutine until another task is due Sleep()/Wait() +// +// The Schedule can enter standByMode when a critical task has failed. In this +// scenario, all tasks are stalled until the critical task has succeeded. This is +// sometimes useful when a target system is unreachable, and we have to wait +// until it's up again. +// +// Schedule is meant to be used by at most one goroutine and is not +// concurrent-safe. + package schedule import ( @@ -39,7 +38,7 @@ import ( ) // Task represents a scheduled task -type task struct { +type Task struct { Name string // name of the task interval time.Duration // the schedule interval timer time.Time // last time task was executed @@ -51,49 +50,49 @@ type task struct { // Use this method if you are executing the task yourself and you need to register // when task started. If the task has a pointer to the executing function, use // Run() instead. -func (t *task) Start() { +func (t *Task) Start() { t.timer = time.Now() } // Run marks the task as started and executes it -func (t *task) Run() (map[string]*matrix.Matrix, error) { +func (t *Task) Run() (map[string]*matrix.Matrix, error) { t.Start() return t.foo() } // GetDuration tells duration of executing the task // it assumes that the task just completed -func (t *task) GetDuration() time.Duration { +func (t *Task) GetDuration() time.Duration { return time.Since(t.timer) } // GetInterval tells the scheduled interval of the task -func (t *task) GetInterval() time.Duration { +func (t *Task) GetInterval() time.Duration { return t.interval } // NextDue tells time until the task is due -func (t *task) NextDue() time.Duration { +func (t *Task) NextDue() time.Duration { return t.interval - time.Since(t.timer) } // IsDue tells whether it's time to run the task -func (t *task) IsDue() bool { +func (t *Task) IsDue() bool { return t.NextDue() <= 0 } // Schedule contains a collection of tasks and the current state of the schedule type Schedule struct { - tasks []*task // list of tasks that Schedule needs to run + tasks []*Task // list of tasks that Schedule needs to run standByMode bool // if true, Schedule waitsfor a stalled task - standByTask *task // stalled task in standByMode + standByTask *Task // stalled task in standByMode cachedInterval map[string]time.Duration // normal interval of the stalled tasks } // New creates and initializes an empty Schedule. func New() *Schedule { s := Schedule{} - s.tasks = make([]*task, 0) + s.tasks = make([]*Task, 0) s.standByMode = false s.cachedInterval = make(map[string]time.Duration) return &s @@ -106,14 +105,14 @@ func (s *Schedule) IsStandBy() bool { } // IsTaskStandBy tells if a task in schedule is in IsStandBy. -func (s *Schedule) IsTaskStandBy(t *task) bool { +func (s *Schedule) IsTaskStandBy(t *Task) bool { return t.Name == s.standByTask.Name } // SetStandByMode initializes StandbyMode: Schedule will suspend all tasks until // the critical task t has succeeded. The temporary interval i will be used for // the task until Schedule recovers to normal mode. -func (s *Schedule) SetStandByMode(t *task, i time.Duration) { +func (s *Schedule) SetStandByMode(t *Task, i time.Duration) { for _, x := range s.tasks { if x.Name == t.Name { s.standByTask = t @@ -142,7 +141,7 @@ func (s *Schedule) Recover() { t.timer = time.Now().Add(-t.interval) } } - //s.cachedInterval = nil + // s.cachedInterval = nil s.standByTask = nil s.standByMode = false return @@ -158,7 +157,7 @@ func (s *Schedule) Recover() { func (s *Schedule) NewTask(n string, i time.Duration, f func() (map[string]*matrix.Matrix, error), runNow bool, identifier string) error { if s.GetTask(n) == nil { if i > 0 { - t := &task{Name: n, interval: i, foo: f, identifier: identifier} + t := &Task{Name: n, interval: i, foo: f, identifier: identifier} s.cachedInterval[n] = t.interval // remember normal interval of task if runNow { t.timer = time.Now().Add(-i) // set to run immediately @@ -183,15 +182,15 @@ func (s *Schedule) NewTaskString(n, i string, f func() (map[string]*matrix.Matri } // GetTasks returns scheduled tasks -func (s *Schedule) GetTasks() []*task { +func (s *Schedule) GetTasks() []*Task { if !s.standByMode { return s.tasks } - return []*task{s.standByTask} + return []*Task{s.standByTask} } // GetTask returns the task named n or nil if it doesn't exist -func (s *Schedule) GetTask(n string) *task { +func (s *Schedule) GetTask(n string) *Task { for _, t := range s.tasks { if t.Name == n { return t diff --git a/cmd/tools/doctor/doctor.go b/cmd/tools/doctor/doctor.go index 19f6473c5..5ad102164 100644 --- a/cmd/tools/doctor/doctor.go +++ b/cmd/tools/doctor/doctor.go @@ -129,9 +129,8 @@ func checkAll(path string, contents []byte) { if anyFailed { os.Exit(1) - } else { - os.Exit(0) } + os.Exit(0) } // checkCollectorName checks if the collector names in the config struct are valid diff --git a/cmd/tools/doctor/restZapiDiff.go b/cmd/tools/doctor/restZapiDiff.go index 3e949fb8d..100911885 100644 --- a/cmd/tools/doctor/restZapiDiff.go +++ b/cmd/tools/doctor/restZapiDiff.go @@ -113,7 +113,7 @@ func metricPerfValueDiff(metricName string) { replacer := strings.NewReplacer("[", "", "]", "", "\"", "") zapiMetric := make(map[string]float64) restMetric := make(map[string]float64) - results := make([]gjson.Result, 0) + var results []gjson.Result keyIndexes := make([]int, 0) @@ -355,11 +355,10 @@ func metricValueDiff(metricName string) { replacer := strings.NewReplacer("[", "", "]", "", "\"", "") zapiMetric := make(map[string]float64) restMetric := make(map[string]float64) - results := make([]gjson.Result, 0) - - keyIndexes := make([]int, 0) + var results []gjson.Result + var keyIndexes []int - // These plugin generated metrics are node scoped. + // These plugin-generated metrics are node scoped. environmentSensorMetrics := strings.Join([]string{ "environment_sensor_average_ambient_temperature", "environment_sensor_average_fan_speed", diff --git a/cmd/tools/generate/counter.go b/cmd/tools/generate/counter.go index db892ec0f..45d5a478a 100644 --- a/cmd/tools/generate/counter.go +++ b/cmd/tools/generate/counter.go @@ -229,8 +229,8 @@ func handleZapiCounter(path []string, content string, object string) (string, st } name = strings.TrimSpace(strings.TrimLeft(name, "^")) - - fullPath = append(path, name) + fullPath = path + fullPath = append(fullPath, name) key = strings.Join(fullPath, ".") if display == "" { display = util.ParseZAPIDisplay(object, fullPath) diff --git a/cmd/tools/grafana/grafana.go b/cmd/tools/grafana/grafana.go index 75be7bbf8..fe5175649 100644 --- a/cmd/tools/grafana/grafana.go +++ b/cmd/tools/grafana/grafana.go @@ -217,7 +217,7 @@ func addLabel(content []byte, label string, labelMap map[string]string) []byte { // create a new list of vars and copy the existing ones into it, duplicate the first var since we're going to // overwrite it - newVars := make([]gjson.Result, 0) + var newVars []gjson.Result newVars = append(newVars, vars[0]) newVars = append(newVars, vars...) @@ -304,7 +304,7 @@ func toChainedVar(defStr string, label string) string { if firstParen == -1 { return "" } - if lastComma == -1 { + if lastComma == -1 { //nolint:revive // Case 1: There are not existing labels // label_values(datacenter) becomes label_values({foo=~"$Foo"}, datacenter) } else { diff --git a/cmd/tools/rest/client.go b/cmd/tools/rest/client.go index aa737db0c..13f6c019d 100644 --- a/cmd/tools/rest/client.go +++ b/cmd/tools/rest/client.go @@ -177,13 +177,13 @@ func (c *Client) invokeWithAuthRetry() ([]byte, error) { //goland:noinspection GoUnhandledErrorResult defer response.Body.Close() - if response.StatusCode != 200 { + if response.StatusCode != http.StatusOK { body, err2 := io.ReadAll(response.Body) if err2 != nil { return nil, errs.Rest(response.StatusCode, err2.Error(), 0, "") } - if response.StatusCode == 401 { + if response.StatusCode == http.StatusUnauthorized { return nil, errs.New(errs.ErrAuthFailed, response.Status) } @@ -271,7 +271,7 @@ func downloadSwagger(poller *conf.Poller, path string, url string, verbose bool) debugResp, _ := httputil.DumpResponse(response, false) fmt.Printf("RESPONSE: \n%s", debugResp) } - if response.StatusCode != 200 { + if response.StatusCode != http.StatusOK { return 0, fmt.Errorf("error making request. server response statusCode=[%d]", response.StatusCode) } n, err := io.Copy(out, response.Body) diff --git a/cmd/tools/rest/rest.go b/cmd/tools/rest/rest.go index 74e759e1d..34c7da99d 100644 --- a/cmd/tools/rest/rest.go +++ b/cmd/tools/rest/rest.go @@ -388,11 +388,11 @@ func Fetch(client *Client, href string) ([]gjson.Result, error) { return nil, err } if mr != "" { - if mri, err := strconv.Atoi(mr); err != nil { + mri, err := strconv.Atoi(mr) + if err != nil { return nil, err - } else { - maxRecords = mri } + maxRecords = mri downloadAll = maxRecords == 0 } } @@ -421,11 +421,11 @@ func FetchAnalytics(client *Client, href string) ([]gjson.Result, gjson.Result, return []gjson.Result{}, gjson.Result{}, err } if mr != "" { - if mri, err := strconv.Atoi(mr); err != nil { + mri, err := strconv.Atoi(mr) + if err != nil { return []gjson.Result{}, gjson.Result{}, err - } else { - maxRecords = mri } + maxRecords = mri } downloadAll = maxRecords == 0 } diff --git a/cmd/tools/template/template_test.go b/cmd/tools/template/template_test.go index 2181fb698..b87aa1a40 100644 --- a/cmd/tools/template/template_test.go +++ b/cmd/tools/template/template_test.go @@ -279,7 +279,8 @@ func TestExportLabelsExist(t *testing.T) { allLabelNames[m.right] = true } else { if isZapi { - zapiPaths := append(m.parents, m.left) + zapiPaths := m.parents + zapiPaths = append(zapiPaths, m.left) display := util.ParseZAPIDisplay(model.Object, zapiPaths) allLabelNames[display] = true } else { diff --git a/cmd/tools/zapi/export.go b/cmd/tools/zapi/export.go index ea53f9049..e01a93562 100644 --- a/cmd/tools/zapi/export.go +++ b/cmd/tools/zapi/export.go @@ -87,7 +87,7 @@ func exportCounters(item *node.Node, c *client.Client, args *Args) error { } fmt.Println("\n===========================================================================\n") */ - fp := make([]string, 0) + var fp []string harvestHomePath = conf.GetHarvestHomePath() fp = append(fp, harvestHomePath) diff --git a/pkg/api/ontapi/zapi/client.go b/pkg/api/ontapi/zapi/client.go index ba201f631..dbfb78ad4 100644 --- a/pkg/api/ontapi/zapi/client.go +++ b/pkg/api/ontapi/zapi/client.go @@ -311,11 +311,11 @@ func (c *Client) InvokeZapiCall(request *node.Node) ([]*node.Node, error) { // this method should only be called after building the request func (c *Client) Invoke(testFilePath string) (*node.Node, error) { if testFilePath != "" { - if testData, err := tree.ImportXML(testFilePath); err == nil { - return testData, nil - } else { + testData, err := tree.ImportXML(testFilePath) + if err != nil { return nil, err } + return testData, nil } result, _, _, err := c.invokeWithAuthRetry(false) return result, err @@ -328,11 +328,11 @@ func (c *Client) Invoke(testFilePath string) (*node.Node, error) { // Use the returned tag for subsequent calls to this method func (c *Client) InvokeBatchRequest(request *node.Node, tag string, testFilePath string) (*node.Node, string, error) { if testFilePath != "" && tag != "" { - if testData, err := tree.ImportXML(testFilePath); err == nil { - return testData, "", nil - } else { + testData, err := tree.ImportXML(testFilePath) + if err != nil { return nil, "", err } + return testData, "", nil } // wasteful of course, need to rewrite later @TODO results, tag, _, _, err := c.InvokeBatchWithTimers(request, tag) @@ -401,11 +401,11 @@ func (c *Client) InvokeRequest(request *node.Node) (*node.Node, error) { // This method should only be called after building the request func (c *Client) InvokeWithTimers(testFilePath string) (*node.Node, time.Duration, time.Duration, error) { if testFilePath != "" { - if testData, err := tree.ImportXML(testFilePath); err == nil { - return testData, 0, 0, nil - } else { + testData, err := tree.ImportXML(testFilePath) + if err != nil { return nil, 0, 0, err } + return testData, 0, 0, nil } return c.invokeWithAuthRetry(true) } @@ -489,8 +489,8 @@ func (c *Client) invoke(withTimers bool) (*node.Node, time.Duration, time.Durati responseT = time.Since(start) } - if response.StatusCode != 200 { - if response.StatusCode == 401 { + if response.StatusCode != http.StatusOK { + if response.StatusCode == http.StatusUnauthorized { return result, responseT, parseT, errs.New(errs.ErrAuthFailed, response.Status, errs.WithStatus(response.StatusCode)) } return result, responseT, parseT, errs.New(errs.ErrAPIResponse, response.Status, errs.WithStatus(response.StatusCode)) diff --git a/pkg/conf/conf.go b/pkg/conf/conf.go index a95f810fb..116d655f3 100644 --- a/pkg/conf/conf.go +++ b/pkg/conf/conf.go @@ -175,9 +175,8 @@ func GetDefaultHarvestConfigPath() string { configPath := os.Getenv("HARVEST_CONF") if configPath == "" { return "./" + HarvestYML - } else { - return path.Join(configPath, HarvestYML) } + return path.Join(configPath, HarvestYML) } // GetHarvestHomePath returns the value of the env var HARVEST_CONF or ./ diff --git a/pkg/logging/logger.go b/pkg/logging/logger.go index 33a400b80..94fe3ddea 100644 --- a/pkg/logging/logger.go +++ b/pkg/logging/logger.go @@ -107,7 +107,7 @@ func Configure(config LogConfig) *Logger { multiWriters := zerolog.MultiLevelWriter(writers...) zerolog.SetGlobalLevel(config.LogLevel) - zerolog.ErrorStackMarshaler = MarshalStack + zerolog.ErrorStackMarshaler = MarshalStack //nolint:reassign zerolog.CallerMarshalFunc = ShortFile zeroLogger := zerolog.New(multiWriters).With().Caller().Str(config.PrefixKey, config.PrefixValue).Timestamp().Logger() diff --git a/pkg/test/node_test.go b/pkg/test/node_test.go index ebe08c8e8..98aebb9be 100644 --- a/pkg/test/node_test.go +++ b/pkg/test/node_test.go @@ -70,7 +70,7 @@ func TestNode_MergeCollector(t *testing.T) { // object name overwrite want := "customLun" - got := "" + var got string if name := defaultTemplate.GetChildS("name"); name != nil { got = name.GetContentS() if got != want { diff --git a/pkg/tree/node/node.go b/pkg/tree/node/node.go index 16ac91ebb..96893f82b 100644 --- a/pkg/tree/node/node.go +++ b/pkg/tree/node/node.go @@ -402,20 +402,18 @@ func (n *Node) printN(depth int, b *strings.Builder) { } func (n *Node) SearchContent(prefix []string, paths [][]string) ([]string, bool) { - - //fmt.Printf("SearchContent: prefix=%v \t paths=%v\n", prefix, paths) - - var search func(*Node, []string) - - matches := make([]string, 0) + var ( + search func(*Node, []string) + matches []string + ) search = func(node *Node, currentPath []string) { var newPath []string if len(currentPath) > 0 || prefix[0] == node.GetNameS() { - newPath = append(currentPath, node.GetNameS()) + newPath = currentPath + newPath = append(newPath, node.GetNameS()) } else { - newPath = make([]string, len(currentPath)) - copy(newPath, currentPath) + newPath = slices.Clone(currentPath) } //fmt.Printf(" -> current_path=%v \t new_path=%v\n", currentPath, newPath) for _, path := range paths { @@ -440,17 +438,18 @@ func (n *Node) SearchContent(prefix []string, paths [][]string) ([]string, bool) func (n *Node) SearchChildren(path []string) []*Node { - var search func(*Node, []string) - - matches := make([]*Node, 0) + var ( + search func(*Node, []string) + matches []*Node + ) search = func(node *Node, currentPath []string) { var newPath []string if len(currentPath) > 0 || path[0] == node.GetNameS() { - newPath = append(currentPath, node.GetNameS()) + newPath = currentPath + newPath = append(newPath, node.GetNameS()) } else { - newPath = make([]string, len(currentPath)) - copy(newPath, currentPath) + newPath = slices.Clone(currentPath) } if slices.Equal(newPath, path) { matches = append(matches, node) diff --git a/pkg/tree/node/node_test.go b/pkg/tree/node/node_test.go index 3f406506c..7c4616bb7 100644 --- a/pkg/tree/node/node_test.go +++ b/pkg/tree/node/node_test.go @@ -40,7 +40,7 @@ func TestNode_FlatList(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - list := make([]string, 0) + var list []string tt.tree.FlatList(&list, "") if len(list) != tt.count { t.Errorf("flat list has size= %v, want %v", len(list), tt.count) diff --git a/pkg/util/util.go b/pkg/util/util.go index 8c63b2fcb..5d51f30e2 100644 --- a/pkg/util/util.go +++ b/pkg/util/util.go @@ -388,9 +388,8 @@ func HasDuplicates(slice []string) bool { for _, v := range slice { if encountered[v] { return true - } else { - encountered[v] = true } + encountered[v] = true } return false From 9c00fb8f8f2cb643336635d95e7c3fae16c25516 Mon Sep 17 00:00:00 2001 From: Chris Grindstaff Date: Mon, 21 Aug 2023 14:23:27 -0400 Subject: [PATCH 2/2] feat: enable more golanglint linters --- .golangci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.golangci.yml b/.golangci.yml index 8a848b94f..22bab4fd3 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -30,7 +30,7 @@ linters: - staticcheck - stylecheck - tenv - - tenv + - thelper - testableexamples - typecheck - unconvert