diff --git a/.golangci.yml b/.golangci.yml index 16bec0de7f..4cb6899c98 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -3,6 +3,7 @@ linters: enable: - depguard - misspell + - modernize - revive settings: depguard: @@ -17,11 +18,6 @@ linters: # Used in HTTP handlers, any error is handled by the server itself. exclude-functions: - (net/http.ResponseWriter).Write - revive: - rules: - - name: unused-parameter - severity: warning - disabled: true exclusions: generated: lax presets: diff --git a/collector/collector.go b/collector/collector.go index 18ff7388ca..167af5d741 100644 --- a/collector/collector.go +++ b/collector/collector.go @@ -96,7 +96,7 @@ func DisableDefaultCollectors() { // does not contain information about which flag called the action. // See: https://github.com/alecthomas/kingpin/issues/294 func collectorFlagAction(collector string) func(ctx *kingpin.ParseContext) error { - return func(ctx *kingpin.ParseContext) error { + return func(_ *kingpin.ParseContext) error { forcedCollectors[collector] = true return nil } @@ -199,7 +199,7 @@ func IsNoDataError(err error) bool { } // pushMetric helps construct and convert a variety of value types into Prometheus float64 metrics. -func pushMetric(ch chan<- prometheus.Metric, fieldDesc *prometheus.Desc, name string, value any, valueType prometheus.ValueType, labelValues ...string) { +func pushMetric(ch chan<- prometheus.Metric, fieldDesc *prometheus.Desc, value any, valueType prometheus.ValueType, labelValues ...string) { var fVal float64 switch val := value.(type) { case uint8: diff --git a/collector/cpu_linux.go b/collector/cpu_linux.go index 30fe305ac0..f7b0c3ef1f 100644 --- a/collector/cpu_linux.go +++ b/collector/cpu_linux.go @@ -488,7 +488,7 @@ func (c *cpuCollector) updateCPUStats(newStats map[int64]procfs.CPUStat) { // Remove offline CPUs. if len(newStats) != len(c.cpuStats) { onlineCPUIds := slices.Collect(maps.Keys(newStats)) - maps.DeleteFunc(c.cpuStats, func(key int64, item procfs.CPUStat) bool { + maps.DeleteFunc(c.cpuStats, func(key int64, _ procfs.CPUStat) bool { return !slices.Contains(onlineCPUIds, key) }) } diff --git a/collector/cpu_vulnerabilities_linux.go b/collector/cpu_vulnerabilities_linux.go index a41d5b17a5..155253b5f4 100644 --- a/collector/cpu_vulnerabilities_linux.go +++ b/collector/cpu_vulnerabilities_linux.go @@ -40,7 +40,7 @@ func init() { registerCollector(cpuVulnerabilitiesCollectorSubsystem, defaultDisabled, NewVulnerabilitySysfsCollector) } -func NewVulnerabilitySysfsCollector(logger *slog.Logger) (Collector, error) { +func NewVulnerabilitySysfsCollector(_ *slog.Logger) (Collector, error) { return &cpuVulnerabilitiesCollector{}, nil } diff --git a/collector/diskstats_common.go b/collector/diskstats_common.go index 9d4158c0a7..c0737462f5 100644 --- a/collector/diskstats_common.go +++ b/collector/diskstats_common.go @@ -34,7 +34,7 @@ var ( diskstatsDeviceExclude = kingpin.Flag( "collector.diskstats.device-exclude", "Regexp of diskstats devices to exclude (mutually exclusive to device-include).", - ).Default(diskstatsDefaultIgnoredDevices).PreAction(func(c *kingpin.ParseContext) error { + ).Default(diskstatsDefaultIgnoredDevices).PreAction(func(_ *kingpin.ParseContext) error { diskstatsDeviceExcludeSet = true return nil }).String() diff --git a/collector/fibrechannel_linux.go b/collector/fibrechannel_linux.go index a0528d168a..f56ef48288 100644 --- a/collector/fibrechannel_linux.go +++ b/collector/fibrechannel_linux.go @@ -22,8 +22,6 @@ import ( "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/procfs/sysfs" - - "github.com/prometheus/node_exporter/collector/utils" ) const maxUint64 = ^uint64(0) @@ -114,7 +112,7 @@ func (c *fibrechannelCollector) Update(ch chan<- prometheus.Metric) error { infoValue := 1.0 // First push the Host values - ch <- prometheus.MustNewConstMetric(infoDesc, prometheus.GaugeValue, infoValue, utils.SafeDereference( + ch <- prometheus.MustNewConstMetric(infoDesc, prometheus.GaugeValue, infoValue, SafeDereference( host.Name, host.Speed, host.PortState, diff --git a/collector/filesystem_common.go b/collector/filesystem_common.go index 1676492b97..1cd4f3dc71 100644 --- a/collector/filesystem_common.go +++ b/collector/filesystem_common.go @@ -35,7 +35,7 @@ var ( mountPointsExclude = kingpin.Flag( "collector.filesystem.mount-points-exclude", "Regexp of mount points to exclude for filesystem collector. (mutually exclusive to mount-points-include)", - ).Default(defMountPointsExcluded).PreAction(func(c *kingpin.ParseContext) error { + ).Default(defMountPointsExcluded).PreAction(func(_ *kingpin.ParseContext) error { mountPointsExcludeSet = true return nil }).String() @@ -52,7 +52,7 @@ var ( fsTypesExclude = kingpin.Flag( "collector.filesystem.fs-types-exclude", "Regexp of filesystem types to exclude for filesystem collector. (mutually exclusive to fs-types-include)", - ).Default(defFSTypesExcluded).PreAction(func(c *kingpin.ParseContext) error { + ).Default(defFSTypesExcluded).PreAction(func(_ *kingpin.ParseContext) error { fsTypesExcludeSet = true return nil }).String() diff --git a/collector/filesystem_linux.go b/collector/filesystem_linux.go index 31e784cb07..038ff7970b 100644 --- a/collector/filesystem_linux.go +++ b/collector/filesystem_linux.go @@ -59,14 +59,12 @@ func (c *filesystemCollector) GetStats() ([]filesystemStats, error) { workerCount := max(*statWorkerCount, 1) - for i := 0; i < workerCount; i++ { - wg.Add(1) - go func() { - defer wg.Done() + for range workerCount { + wg.Go(func() { for labels := range labelChan { statChan <- c.processStat(labels) } - }() + }) } go func() { diff --git a/collector/hwmon_linux_test.go b/collector/hwmon_linux_test.go index 2603a4c095..3206b0e09d 100644 --- a/collector/hwmon_linux_test.go +++ b/collector/hwmon_linux_test.go @@ -20,6 +20,7 @@ import ( "log/slog" "os" "path/filepath" + "slices" "testing" "github.com/prometheus/client_golang/prometheus" @@ -133,15 +134,6 @@ func newTestHwmonCollector() *hwMonCollector { return &hwMonCollector{logger: slog.New(slog.NewTextHandler(io.Discard, nil))} } -func contains(haystack []string, needle string) bool { - for _, h := range haystack { - if h == needle { - return true - } - } - return false -} - // Two hwmon entries sharing the same parent device — the configuration // that triggered #3637 on ASUS WMI laptops — must produce distinct chip // labels and not error during gather. @@ -177,10 +169,10 @@ func TestHwmonDuplicateChipNamesAreDisambiguated(t *testing.T) { t.Fatalf("gather: %v", err) } - if !contains(chips, "platform_asus_nb_wmi_asus") { + if !slices.Contains(chips, "platform_asus_nb_wmi_asus") { t.Errorf("expected disambiguated chip 'platform_asus_nb_wmi_asus', got %v", uniq(chips)) } - if !contains(chips, "platform_asus_nb_wmi_asus_wmi_sensors") { + if !slices.Contains(chips, "platform_asus_nb_wmi_asus_wmi_sensors") { t.Errorf("expected disambiguated chip 'platform_asus_nb_wmi_asus_wmi_sensors', got %v", uniq(chips)) } for _, chip := range chips { @@ -217,10 +209,10 @@ func TestHwmonUniqueChipNamesAreUnchanged(t *testing.T) { if err != nil { t.Fatalf("gather: %v", err) } - if !contains(chips, "platform_coretemp_0") { + if !slices.Contains(chips, "platform_coretemp_0") { t.Errorf("expected platform_coretemp_0, got %v", uniq(chips)) } - if !contains(chips, "platform_coretemp_1") { + if !slices.Contains(chips, "platform_coretemp_1") { t.Errorf("expected platform_coretemp_1, got %v", uniq(chips)) } } @@ -253,10 +245,10 @@ func TestHwmonDuplicateChipNamesWithSameNameFile(t *testing.T) { if err != nil { t.Fatalf("gather: %v", err) } - if !contains(chips, "platform_asus_nb_wmi_hwmon3") { + if !slices.Contains(chips, "platform_asus_nb_wmi_hwmon3") { t.Errorf("expected platform_asus_nb_wmi_hwmon3, got %v", uniq(chips)) } - if !contains(chips, "platform_asus_nb_wmi_hwmon4") { + if !slices.Contains(chips, "platform_asus_nb_wmi_hwmon4") { t.Errorf("expected platform_asus_nb_wmi_hwmon4, got %v", uniq(chips)) } } diff --git a/collector/interrupts_openbsd_amd64.go b/collector/interrupts_openbsd_amd64.go index 5f40449696..fae7905d60 100644 --- a/collector/interrupts_openbsd_amd64.go +++ b/collector/interrupts_openbsd_amd64.go @@ -20,8 +20,6 @@ import ( "strconv" "unsafe" - "github.com/prometheus/node_exporter/collector/utils" - "github.com/prometheus/client_golang/prometheus" "golang.org/x/sys/unix" ) @@ -50,7 +48,7 @@ func intr(idx _C_int) (itr interrupt, err error) { return } dev := *(*[128]byte)(unsafe.Pointer(&buf[0])) - itr.device = utils.SafeBytesToString(dev[:]) + itr.device = SafeBytesToString(dev[:]) mib[2] = KERN_INTRCNT_VECTOR buf, err = sysctl(mib[:]) diff --git a/collector/netclass_linux.go b/collector/netclass_linux.go index 7f8373dfb3..4fe40b9881 100644 --- a/collector/netclass_linux.go +++ b/collector/netclass_linux.go @@ -104,31 +104,31 @@ func (c *netClassCollector) netClassSysfsUpdate(ch chan<- prometheus.Metric) err ch <- prometheus.MustNewConstMetric(infoDesc, prometheus.GaugeValue, infoValue, ifaceInfo.Name, ifaceInfo.Address, ifaceInfo.Broadcast, ifaceInfo.Duplex, ifaceInfo.OperState, getAdminState(ifaceInfo.Flags), ifaceInfo.IfAlias) - pushMetric(ch, c.getFieldDesc("address_assign_type"), "address_assign_type", ifaceInfo.AddrAssignType, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("carrier"), "carrier", ifaceInfo.Carrier, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("carrier_changes_total"), "carrier_changes_total", ifaceInfo.CarrierChanges, prometheus.CounterValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("carrier_up_changes_total"), "carrier_up_changes_total", ifaceInfo.CarrierUpCount, prometheus.CounterValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("carrier_down_changes_total"), "carrier_down_changes_total", ifaceInfo.CarrierDownCount, prometheus.CounterValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("device_id"), "device_id", ifaceInfo.DevID, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("dormant"), "dormant", ifaceInfo.Dormant, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("flags"), "flags", ifaceInfo.Flags, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("iface_id"), "iface_id", ifaceInfo.IfIndex, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("iface_link"), "iface_link", ifaceInfo.IfLink, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("iface_link_mode"), "iface_link_mode", ifaceInfo.LinkMode, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("mtu_bytes"), "mtu_bytes", ifaceInfo.MTU, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("name_assign_type"), "name_assign_type", ifaceInfo.NameAssignType, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("net_dev_group"), "net_dev_group", ifaceInfo.NetDevGroup, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("address_assign_type"), ifaceInfo.AddrAssignType, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("carrier"), ifaceInfo.Carrier, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("carrier_changes_total"), ifaceInfo.CarrierChanges, prometheus.CounterValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("carrier_up_changes_total"), ifaceInfo.CarrierUpCount, prometheus.CounterValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("carrier_down_changes_total"), ifaceInfo.CarrierDownCount, prometheus.CounterValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("device_id"), ifaceInfo.DevID, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("dormant"), ifaceInfo.Dormant, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("flags"), ifaceInfo.Flags, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("iface_id"), ifaceInfo.IfIndex, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("iface_link"), ifaceInfo.IfLink, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("iface_link_mode"), ifaceInfo.LinkMode, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("mtu_bytes"), ifaceInfo.MTU, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("name_assign_type"), ifaceInfo.NameAssignType, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("net_dev_group"), ifaceInfo.NetDevGroup, prometheus.GaugeValue, ifaceInfo.Name) if ifaceInfo.Speed != nil { // Some devices return -1 if the speed is unknown. if *ifaceInfo.Speed >= 0 || !*netclassInvalidSpeed { speedBytes := int64(*ifaceInfo.Speed * 1000 * 1000 / 8) - pushMetric(ch, c.getFieldDesc("speed_bytes"), "speed_bytes", speedBytes, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("speed_bytes"), speedBytes, prometheus.GaugeValue, ifaceInfo.Name) } } - pushMetric(ch, c.getFieldDesc("transmit_queue_length"), "transmit_queue_length", ifaceInfo.TxQueueLen, prometheus.GaugeValue, ifaceInfo.Name) - pushMetric(ch, c.getFieldDesc("protocol_type"), "protocol_type", ifaceInfo.Type, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("transmit_queue_length"), ifaceInfo.TxQueueLen, prometheus.GaugeValue, ifaceInfo.Name) + pushMetric(ch, c.getFieldDesc("protocol_type"), ifaceInfo.Type, prometheus.GaugeValue, ifaceInfo.Name) } diff --git a/collector/netclass_rtnl_linux.go b/collector/netclass_rtnl_linux.go index d3dde4c034..c71957cc29 100644 --- a/collector/netclass_rtnl_linux.go +++ b/collector/netclass_rtnl_linux.go @@ -52,7 +52,7 @@ func (c *netClassCollector) netClassRTNLUpdate(ch chan<- prometheus.Metric) erro } if lm.SpeedMegabits >= 0 { speedBytes := uint64(lm.SpeedMegabits * 1000 * 1000 / 8) - pushMetric(ch, c.getFieldDesc("speed_bytes"), "speed_bytes", speedBytes, prometheus.GaugeValue, lm.Interface.Name) + pushMetric(ch, c.getFieldDesc("speed_bytes"), speedBytes, prometheus.GaugeValue, lm.Interface.Name) } linkModes[lm.Interface.Name] = lm } @@ -128,67 +128,67 @@ func (c *netClassCollector) netClassRTNLUpdate(ch chan<- prometheus.Metric) erro ch <- prometheus.MustNewConstMetric(altnameDesc, prometheus.GaugeValue, infoValue, strings.ToValidUTF8(altname, "\uFFFD"), msg.Attributes.Name) } } - pushMetric(ch, c.getFieldDesc("address_assign_type"), "address_assign_type", ifaceInfo.AddrAssignType, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("carrier"), "carrier", msg.Attributes.Carrier, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("carrier_changes_total"), "carrier_changes_total", msg.Attributes.CarrierChanges, prometheus.CounterValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("carrier_up_changes_total"), "carrier_up_changes_total", msg.Attributes.CarrierUpCount, prometheus.CounterValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("carrier_down_changes_total"), "carrier_down_changes_total", msg.Attributes.CarrierDownCount, prometheus.CounterValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("device_id"), "device_id", ifaceInfo.DevID, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("flags"), "flags", msg.Flags, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("iface_id"), "iface_id", msg.Index, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("iface_link_mode"), "iface_link_mode", msg.Attributes.LinkMode, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("dormant"), "dormant", msg.Attributes.LinkMode, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("address_assign_type"), ifaceInfo.AddrAssignType, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("carrier"), msg.Attributes.Carrier, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("carrier_changes_total"), msg.Attributes.CarrierChanges, prometheus.CounterValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("carrier_up_changes_total"), msg.Attributes.CarrierUpCount, prometheus.CounterValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("carrier_down_changes_total"), msg.Attributes.CarrierDownCount, prometheus.CounterValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("device_id"), ifaceInfo.DevID, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("flags"), msg.Flags, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("iface_id"), msg.Index, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("iface_link_mode"), msg.Attributes.LinkMode, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("dormant"), msg.Attributes.LinkMode, prometheus.GaugeValue, msg.Attributes.Name) // kernel logic: IFLA_LINK attribute will be ignore when ifindex is the same as iflink // (dev->ifindex != dev_get_iflink(dev) && nla_put_u32(skb, IFLA_LINK, dev_get_iflink(dev))) // As interface ID is never 0, we assume msg.Attributes.Type 0 means iflink is omitted in RTM_GETLINK response. if msg.Attributes.Type > 0 { - pushMetric(ch, c.getFieldDesc("iface_link"), "iface_link", msg.Attributes.Type, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("iface_link"), msg.Attributes.Type, prometheus.GaugeValue, msg.Attributes.Name) } else { - pushMetric(ch, c.getFieldDesc("iface_link"), "iface_link", msg.Index, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("iface_link"), msg.Index, prometheus.GaugeValue, msg.Attributes.Name) } - pushMetric(ch, c.getFieldDesc("mtu_bytes"), "mtu_bytes", msg.Attributes.MTU, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("name_assign_type"), "name_assign_type", ifaceInfo.NameAssignType, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("net_dev_group"), "net_dev_group", msg.Attributes.NetDevGroup, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_queue_length"), "transmit_queue_length", msg.Attributes.TxQueueLen, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("protocol_type"), "protocol_type", msg.Type, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("mtu_bytes"), msg.Attributes.MTU, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("name_assign_type"), ifaceInfo.NameAssignType, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("net_dev_group"), msg.Attributes.NetDevGroup, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_queue_length"), msg.Attributes.TxQueueLen, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("protocol_type"), msg.Type, prometheus.GaugeValue, msg.Attributes.Name) // Skip statistics if argument collector.netclass_rtnl.with-stats is false or statistics are unavailable. if netclassRTNLWithStats == nil || !*netclassRTNLWithStats || msg.Attributes.Stats64 == nil { continue } - pushMetric(ch, c.getFieldDesc("receive_packets_total"), "receive_packets_total", msg.Attributes.Stats64.RXPackets, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_packets_total"), "transmit_packets_total", msg.Attributes.Stats64.TXPackets, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_bytes_total"), "receive_bytes_total", msg.Attributes.Stats64.RXBytes, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_bytes_total"), "transmit_bytes_total", msg.Attributes.Stats64.TXBytes, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_errors_total"), "receive_errors_total", msg.Attributes.Stats64.RXErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_errors_total"), "transmit_errors_total", msg.Attributes.Stats64.TXErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_dropped_total"), "receive_dropped_total", msg.Attributes.Stats64.RXDropped, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_dropped_total"), "transmit_dropped_total", msg.Attributes.Stats64.TXDropped, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("multicast_total"), "multicast_total", msg.Attributes.Stats64.Multicast, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("collisions_total"), "collisions_total", msg.Attributes.Stats64.Collisions, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_packets_total"), msg.Attributes.Stats64.RXPackets, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_packets_total"), msg.Attributes.Stats64.TXPackets, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_bytes_total"), msg.Attributes.Stats64.RXBytes, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_bytes_total"), msg.Attributes.Stats64.TXBytes, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_errors_total"), msg.Attributes.Stats64.RXErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_errors_total"), msg.Attributes.Stats64.TXErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_dropped_total"), msg.Attributes.Stats64.RXDropped, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_dropped_total"), msg.Attributes.Stats64.TXDropped, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("multicast_total"), msg.Attributes.Stats64.Multicast, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("collisions_total"), msg.Attributes.Stats64.Collisions, prometheus.GaugeValue, msg.Attributes.Name) // Detailed rx_errors. - pushMetric(ch, c.getFieldDesc("receive_length_errors_total"), "receive_length_errors_total", msg.Attributes.Stats64.RXLengthErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_over_errors_total"), "receive_over_errors_total", msg.Attributes.Stats64.RXOverErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_crc_errors_total"), "receive_crc_errors_total", msg.Attributes.Stats64.RXCRCErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_frame_errors_total"), "receive_frame_errors_total", msg.Attributes.Stats64.RXFrameErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_fifo_errors_total"), "receive_fifo_errors_total", msg.Attributes.Stats64.RXFIFOErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_missed_errors_total"), "receive_missed_errors_total", msg.Attributes.Stats64.RXMissedErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_length_errors_total"), msg.Attributes.Stats64.RXLengthErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_over_errors_total"), msg.Attributes.Stats64.RXOverErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_crc_errors_total"), msg.Attributes.Stats64.RXCRCErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_frame_errors_total"), msg.Attributes.Stats64.RXFrameErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_fifo_errors_total"), msg.Attributes.Stats64.RXFIFOErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_missed_errors_total"), msg.Attributes.Stats64.RXMissedErrors, prometheus.GaugeValue, msg.Attributes.Name) // Detailed tx_errors. - pushMetric(ch, c.getFieldDesc("transmit_aborted_errors_total"), "transmit_aborted_errors_total", msg.Attributes.Stats64.TXAbortedErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_carrier_errors_total"), "transmit_carrier_errors_total", msg.Attributes.Stats64.TXCarrierErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_fifo_errors_total"), "transmit_fifo_errors_total", msg.Attributes.Stats64.TXFIFOErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_heartbeat_errors_total"), "transmit_heartbeat_errors_total", msg.Attributes.Stats64.TXHeartbeatErrors, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_window_errors_total"), "transmit_window_errors_total", msg.Attributes.Stats64.TXWindowErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_aborted_errors_total"), msg.Attributes.Stats64.TXAbortedErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_carrier_errors_total"), msg.Attributes.Stats64.TXCarrierErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_fifo_errors_total"), msg.Attributes.Stats64.TXFIFOErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_heartbeat_errors_total"), msg.Attributes.Stats64.TXHeartbeatErrors, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_window_errors_total"), msg.Attributes.Stats64.TXWindowErrors, prometheus.GaugeValue, msg.Attributes.Name) // For cslip, etc. - pushMetric(ch, c.getFieldDesc("receive_compressed_total"), "receive_compressed_total", msg.Attributes.Stats64.RXCompressed, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("transmit_compressed_total"), "transmit_compressed_total", msg.Attributes.Stats64.TXCompressed, prometheus.GaugeValue, msg.Attributes.Name) - pushMetric(ch, c.getFieldDesc("receive_nohandler_total"), "receive_nohandler_total", msg.Attributes.Stats64.RXNoHandler, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_compressed_total"), msg.Attributes.Stats64.RXCompressed, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("transmit_compressed_total"), msg.Attributes.Stats64.TXCompressed, prometheus.GaugeValue, msg.Attributes.Name) + pushMetric(ch, c.getFieldDesc("receive_nohandler_total"), msg.Attributes.Stats64.RXNoHandler, prometheus.GaugeValue, msg.Attributes.Name) } diff --git a/collector/network_route_linux.go b/collector/network_route_linux.go index d290b202d3..075695eebf 100644 --- a/collector/network_route_linux.go +++ b/collector/network_route_linux.go @@ -131,8 +131,8 @@ func (n networkRouteCollector) Update(ch chan<- prometheus.Metric) error { return nil } -func networkRouteIPWithPrefixToString(ip net.IP, len uint8) string { - if len == 0 { +func networkRouteIPWithPrefixToString(ip net.IP, length uint8) string { + if length == 0 { return "default" } iplen := net.IPv4len @@ -141,7 +141,7 @@ func networkRouteIPWithPrefixToString(ip net.IP, len uint8) string { } network := &net.IPNet{ IP: ip, - Mask: net.CIDRMask(int(len), iplen*8), + Mask: net.CIDRMask(int(length), iplen*8), } return network.String() } diff --git a/collector/pcidevice_linux.go b/collector/pcidevice_linux.go index 6f33db938f..0d1baab2f5 100644 --- a/collector/pcidevice_linux.go +++ b/collector/pcidevice_linux.go @@ -33,11 +33,11 @@ const ( ) var ( - pciIdsPaths = []string{ + pciIDsPaths = []string{ "/usr/share/misc/pci.ids", "/usr/share/hwdata/pci.ids", } - pciIdsFile = kingpin.Flag("collector.pcidevice.idsfile", "Path to pci.ids file to use for PCI device identification.").String() + pciIDsFile = kingpin.Flag("collector.pcidevice.idsfile", "Path to pci.ids file to use for PCI device identification.").String() pciNames = kingpin.Flag("collector.pcidevice.names", "Enable PCI device name resolution (requires pci.ids file).").Default("false").Bool() pcideviceLabelNames = []string{"segment", "bus", "device", "function"} @@ -366,16 +366,16 @@ func (c *pcideviceCollector) loadPCIIds() { c.pciProgIfs = make(map[string]string) // Use custom pci.ids file if specified - if *pciIdsFile != "" { - file, err = os.Open(*pciIdsFile) + if *pciIDsFile != "" { + file, err = os.Open(*pciIDsFile) if err != nil { - c.logger.Debug("Failed to open PCI IDs file", "file", *pciIdsFile, "error", err) + c.logger.Debug("Failed to open PCI IDs file", "file", *pciIDsFile, "error", err) return } - c.logger.Debug("Loading PCI IDs from", "file", *pciIdsFile) + c.logger.Debug("Loading PCI IDs from", "file", *pciIDsFile) } else { // Try each possible default path - for _, path := range pciIdsPaths { + for _, path := range pciIDsPaths { file, err = os.Open(path) if err == nil { c.logger.Debug("Loading PCI IDs from default path", "path", path) @@ -468,8 +468,8 @@ func (c *pcideviceCollector) loadPCIIds() { } // Handle subsystem lines (double tab) - if strings.HasPrefix(line, "\t\t") { - line = strings.TrimPrefix(line, "\t\t") + if after, ok := strings.CutPrefix(line, "\t\t"); ok { + line = after parts := strings.SplitN(line, " ", 2) if len(parts) >= 2 && currentVendor != "" && currentDevice != "" { subsysID := strings.TrimSpace(parts[0]) diff --git a/collector/pcidevice_linux_test.go b/collector/pcidevice_linux_test.go index aedc7c5f01..b8b9d4c4fe 100644 --- a/collector/pcidevice_linux_test.go +++ b/collector/pcidevice_linux_test.go @@ -83,6 +83,6 @@ func (tc *testPCICollector) Collect(ch chan<- prometheus.Metric) { } } -func (tc *testPCICollector) Describe(ch chan<- *prometheus.Desc) { +func (tc *testPCICollector) Describe(_ chan<- *prometheus.Desc) { // No-op for testing } diff --git a/collector/systemd_linux.go b/collector/systemd_linux.go index 51b82c0186..0464f23d2b 100644 --- a/collector/systemd_linux.go +++ b/collector/systemd_linux.go @@ -41,13 +41,13 @@ const ( var ( systemdUnitIncludeSet bool - systemdUnitInclude = kingpin.Flag("collector.systemd.unit-include", "Regexp of systemd units to include. Units must both match include and not match exclude to be included.").Default(".+").PreAction(func(c *kingpin.ParseContext) error { + systemdUnitInclude = kingpin.Flag("collector.systemd.unit-include", "Regexp of systemd units to include. Units must both match include and not match exclude to be included.").Default(".+").PreAction(func(_ *kingpin.ParseContext) error { systemdUnitIncludeSet = true return nil }).String() oldSystemdUnitInclude = kingpin.Flag("collector.systemd.unit-whitelist", "DEPRECATED: Use --collector.systemd.unit-include").Hidden().String() systemdUnitExcludeSet bool - systemdUnitExclude = kingpin.Flag("collector.systemd.unit-exclude", "Regexp of systemd units to exclude. Units must both match include and not match exclude to be included.").Default(".+\\.(automount|device|mount|scope|slice)").PreAction(func(c *kingpin.ParseContext) error { + systemdUnitExclude = kingpin.Flag("collector.systemd.unit-exclude", "Regexp of systemd units to exclude. Units must both match include and not match exclude to be included.").Default(".+\\.(automount|device|mount|scope|slice)").PreAction(func(_ *kingpin.ParseContext) error { systemdUnitExcludeSet = true return nil }).String() @@ -224,51 +224,41 @@ func (c *systemdCollector) Update(ch chan<- prometheus.Metric) error { var wg sync.WaitGroup defer wg.Wait() - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { begin := time.Now() c.collectUnitStatusMetrics(conn, ch, units) c.logger.Debug("collectUnitStatusMetrics took", "duration_seconds", time.Since(begin).Seconds()) - }() + }) if *enableStartTimeMetrics { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { begin := time.Now() c.collectUnitStartTimeMetrics(conn, ch, units) c.logger.Debug("collectUnitStartTimeMetrics took", "duration_seconds", time.Since(begin).Seconds()) - }() + }) } if *enableTaskMetrics { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { begin := time.Now() c.collectUnitTasksMetrics(conn, ch, units) c.logger.Debug("collectUnitTasksMetrics took", "duration_seconds", time.Since(begin).Seconds()) - }() + }) } if systemdVersion >= minSystemdVersionSystemState { - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { begin := time.Now() c.collectTimers(conn, ch, units) c.logger.Debug("collectTimers took", "duration_seconds", time.Since(begin).Seconds()) - }() + }) } - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { begin := time.Now() c.collectSockets(conn, ch, units) c.logger.Debug("collectSockets took", "duration_seconds", time.Since(begin).Seconds()) - }() + }) if systemdVersion >= minSystemdVersionSystemState { begin := time.Now() diff --git a/collector/textfile.go b/collector/textfile.go index 17e4a60de2..5b39609d73 100644 --- a/collector/textfile.go +++ b/collector/textfile.go @@ -213,7 +213,7 @@ func (c *textFileCollector) Update(ch chan<- prometheus.Metric) error { continue } - mtime, families, err := c.processFile(path, f.Name(), ch) + mtime, families, err := c.processFile(path, f.Name()) for _, mf := range families { // Check for metrics with inconsistent help texts and take the first help text occurrence. @@ -285,7 +285,7 @@ func (c *textFileCollector) Update(ch chan<- prometheus.Metric) error { } // processFile processes a single file, returning its modification time on success. -func (c *textFileCollector) processFile(dir, name string, ch chan<- prometheus.Metric) (*time.Time, map[string]*dto.MetricFamily, error) { +func (c *textFileCollector) processFile(dir, name string) (*time.Time, map[string]*dto.MetricFamily, error) { path := filepath.Join(dir, name) f, err := os.Open(path) if err != nil { diff --git a/collector/thermal_darwin.go b/collector/thermal_darwin.go index 75be7c4217..c55b9b2845 100644 --- a/collector/thermal_darwin.go +++ b/collector/thermal_darwin.go @@ -49,8 +49,6 @@ import ( "log/slog" "unsafe" - "github.com/prometheus/node_exporter/collector/utils" - "github.com/prometheus/client_golang/prometheus" ) @@ -188,7 +186,7 @@ func mappingCFStringToString(s C.CFStringRef) string { buf := make([]byte, maxBufLen) var usedBufLen C.CFIndex _ = C.CFStringGetBytes(s, C.CFRange{0, length}, C.kCFStringEncodingUTF8, C.UInt8(0), C.false, (*C.UInt8)(&buf[0]), maxBufLen, &usedBufLen) - return utils.SafeBytesToString(buf[:usedBufLen]) + return SafeBytesToString(buf[:usedBufLen]) } func mappingCFNumberLongToInt(n C.CFNumberRef) int { diff --git a/collector/thermal_darwin_arm64.go b/collector/thermal_darwin_arm64.go index 5f9461a898..24558a1c9d 100644 --- a/collector/thermal_darwin_arm64.go +++ b/collector/thermal_darwin_arm64.go @@ -46,7 +46,6 @@ import ( "unsafe" "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/node_exporter/collector/utils" ) const absoluteZeroCelsius = -273.15 @@ -150,5 +149,5 @@ func cfStringToString(s C.CFStringRef) string { buf := make([]byte, maxBufLen) var usedBufLen C.CFIndex _ = C.CFStringGetBytes(s, C.CFRange{0, length}, C.kCFStringEncodingUTF8, C.UInt8(0), C.false, (*C.UInt8)(&buf[0]), maxBufLen, &usedBufLen) - return utils.SafeBytesToString(buf[:usedBufLen]) + return SafeBytesToString(buf[:usedBufLen]) } diff --git a/collector/utils/utils.go b/collector/utils.go similarity index 88% rename from collector/utils/utils.go rename to collector/utils.go index 9bcaf4c8ea..6dea8f828a 100644 --- a/collector/utils/utils.go +++ b/collector/utils.go @@ -1,4 +1,4 @@ -// Copyright 2024 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package utils +package collector import ( "bytes" @@ -37,11 +37,11 @@ func SafeDereference[T any](s ...*T) []T { // * Convert any invalid UTF-8 to "�". func SafeBytesToString(b []byte) string { var s string - zeroIndex := bytes.IndexByte(b, 0) - if zeroIndex == -1 { + before, _, ok := bytes.Cut(b, []byte{0}) + if !ok { s = string(b) } else { - s = string(b[:zeroIndex]) + s = string(before) } return strings.ToValidUTF8(s, "�") } diff --git a/collector/utils/utils_test.go b/collector/utils_test.go similarity index 94% rename from collector/utils/utils_test.go rename to collector/utils_test.go index 3246ebc31f..ac36f6a0b1 100644 --- a/collector/utils/utils_test.go +++ b/collector/utils_test.go @@ -1,4 +1,4 @@ -// Copyright 2025 The Prometheus Authors +// Copyright The Prometheus Authors // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file ewcept in compliance with the License. // You may obtain a copy of the License at @@ -11,7 +11,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -package utils +package collector import ( "testing" diff --git a/collector/zfs_linux_test.go b/collector/zfs_linux_test.go index 182a324083..29b9ede2d3 100644 --- a/collector/zfs_linux_test.go +++ b/collector/zfs_linux_test.go @@ -292,7 +292,7 @@ func TestZpoolParsing(t *testing.T) { t.Fatal(err) } - err = c.parsePoolProcfsFile(file, zpoolPath, func(poolName string, s zfsSysctl, v uint64) { + err = c.parsePoolProcfsFile(file, zpoolPath, func(_ string, s zfsSysctl, v uint64) { if s != zfsSysctl("kstat.zfs.misc.io.nread") { return } @@ -347,7 +347,7 @@ func TestZpoolObjsetParsingWithSpace(t *testing.T) { } handlerCalled = false - err = c.parsePoolObjsetFile(file, test.path, func(poolName string, datasetName string, s zfsSysctl, v uint64) { + err = c.parsePoolObjsetFile(file, test.path, func(_ string, datasetName string, _ zfsSysctl, _ uint64) { handlerCalled = true if test.expectedDataset != datasetName { t.Fatalf("Incorrectly parsed dataset name: expected: '%s', got: '%s'", test.expectedDataset, datasetName) @@ -381,7 +381,7 @@ func TestZpoolObjsetParsing(t *testing.T) { t.Fatal(err) } - err = c.parsePoolObjsetFile(file, zpoolPath, func(poolName string, datasetName string, s zfsSysctl, v uint64) { + err = c.parsePoolObjsetFile(file, zpoolPath, func(_ string, _ string, s zfsSysctl, v uint64) { if s != zfsSysctl("kstat.zfs.misc.objset.writes") { return } diff --git a/node_exporter.go b/node_exporter.go index 2c0e12ccc1..17c372eb31 100644 --- a/node_exporter.go +++ b/node_exporter.go @@ -67,11 +67,11 @@ func newHandler(includeExporterMetrics bool, maxRequests int, logger *slog.Logge promcollectors.NewGoCollector(), ) } - if innerHandler, err := h.innerHandler(); err != nil { + innerHandler, err := h.innerHandler() + if err != nil { panic(fmt.Sprintf("Couldn't create metrics handler: %s", err)) - } else { - h.unfilteredHandler = innerHandler } + h.unfilteredHandler = innerHandler return h }