From abca5e983db4bfdd2fe3c8daf60a7517b750463f Mon Sep 17 00:00:00 2001 From: Vincent Bernat Date: Fri, 14 Nov 2025 23:11:53 +0100 Subject: [PATCH] chore: modernize some code --- cmd/orchestrator.go | 15 ++++----------- cmd/orchestrator_test.go | 2 +- cmd/outlet.go | 6 +++--- common/helpers/ipv6_test.go | 2 +- common/helpers/mapstructure.go | 2 +- common/helpers/subnetmap.go | 4 ++-- common/helpers/tls.go | 3 +-- common/kafka/config.go | 2 +- common/schema/definition.go | 2 +- console/docs.go | 4 ++-- console/filter.go | 2 +- console/filter/helpers.go | 14 +++++--------- console/widgets_test.go | 14 +++++++------- demoexporter/flows/generate_test.go | 10 ++-------- demoexporter/flows/nfdata.go | 5 +---- orchestrator/clickhouse/config.go | 2 +- outlet/core/config.go | 6 +++--- outlet/metadata/provider/gnmi/collector.go | 2 +- outlet/metadata/provider/gnmi/config.go | 4 ++-- outlet/metadata/provider/gnmi/srlinux_test.go | 2 +- outlet/metadata/provider/snmp/config.go | 2 +- 21 files changed, 42 insertions(+), 63 deletions(-) diff --git a/cmd/orchestrator.go b/cmd/orchestrator.go index 84ad810b..ef61a744 100644 --- a/cmd/orchestrator.go +++ b/cmd/orchestrator.go @@ -274,14 +274,7 @@ func orchestratorWatch(r *reporter.Reporter, daemonComponent daemon.Component, p if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) { // Check if we have one of the monitored path matching r.Debug().Str("name", event.Name).Msg("detected potential configuration change") - found := false - for _, path := range paths { - if filepath.Clean(event.Name) == path { - found = true - break - } - } - if !found { + if !slices.Contains(paths, filepath.Clean(event.Name)) { continue } @@ -309,7 +302,7 @@ func orchestratorWatch(r *reporter.Reporter, daemonComponent daemon.Component, p // component to clickhouse component func orchestratorGeoIPMigrationHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(OrchestratorConfiguration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[OrchestratorConfiguration]() { return from.Interface(), nil } @@ -382,7 +375,7 @@ func orchestratorGeoIPMigrationHook() mapstructure.DecodeHookFunc { // configuration from clickhouse component to clickhousedb component func orchestratorClickHouseMigrationHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(OrchestratorConfiguration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[OrchestratorConfiguration]() { return from.Interface(), nil } @@ -449,7 +442,7 @@ func orchestratorClickHouseMigrationHook() mapstructure.DecodeHookFunc { // there is only one inlet configuration. func orchestratorInletToOutletMigrationHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(OrchestratorConfiguration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[OrchestratorConfiguration]() { return from.Interface(), nil } diff --git a/cmd/orchestrator_test.go b/cmd/orchestrator_test.go index 4ef2274c..8b614dbb 100644 --- a/cmd/orchestrator_test.go +++ b/cmd/orchestrator_test.go @@ -69,7 +69,7 @@ func TestOrchestratorConfig(t *testing.T) { var got any got = gotYAML i := 0 - for _, component := range strings.Split(path, ".") { + for component := range strings.SplitSeq(path, ".") { var ok bool i++ switch gotConcrete := got.(type) { diff --git a/cmd/outlet.go b/cmd/outlet.go index 79f46ef6..b8ee94f2 100644 --- a/cmd/outlet.go +++ b/cmd/outlet.go @@ -189,7 +189,7 @@ func outletStart(r *reporter.Reporter, config OutletConfiguration, checkOnly boo // BMP configuration to routing. func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(OutletConfiguration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[OutletConfiguration]() { return from.Interface(), nil } @@ -231,7 +231,7 @@ func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { if helpers.MapStructureMatchName(k.String(), "Workers") { continue } - metadataConfig := reflect.TypeOf(metadata.Configuration{}) + metadataConfig := reflect.TypeFor[metadata.Configuration]() for j := range metadataConfig.NumField() { if helpers.MapStructureMatchName(k.String(), metadataConfig.Field(j).Name) { metadataValue[k.String()] = snmpMap.MapIndex(snmpKeys[i]).Interface() @@ -280,7 +280,7 @@ func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { if k.Kind() != reflect.String { continue } - routingConfig := reflect.TypeOf(routing.Configuration{}) + routingConfig := reflect.TypeFor[routing.Configuration]() for j := range routingConfig.NumField() { if helpers.MapStructureMatchName(k.String(), routingConfig.Field(j).Name) { routingValue[k.String()] = bmpMap.MapIndex(bmpKeys[i]).Interface() diff --git a/common/helpers/ipv6_test.go b/common/helpers/ipv6_test.go index 84efbfde..f35cc027 100644 --- a/common/helpers/ipv6_test.go +++ b/common/helpers/ipv6_test.go @@ -70,7 +70,7 @@ func TestUnmapPrefix(t *testing.T) { func TestNetIPAddrStructure(t *testing.T) { var addr netip.Addr - addrType := reflect.TypeOf(addr) + addrType := reflect.TypeFor[netip.Addr]() // Test total size: 24 bytes (16 for uint128 + 8 for unique.Handle) if unsafe.Sizeof(addr) != 24 { diff --git a/common/helpers/mapstructure.go b/common/helpers/mapstructure.go index b725f900..fbac2e03 100644 --- a/common/helpers/mapstructure.go +++ b/common/helpers/mapstructure.go @@ -223,7 +223,7 @@ func ParametrizedConfigurationUnmarshallerHook[OuterConfiguration any, InnerConf return from.Interface(), nil } configField := to.FieldByName("Config") - fromConfig := reflect.MakeMap(reflect.TypeOf(gin.H{})) + fromConfig := reflect.MakeMap(reflect.TypeFor[gin.H]()) // Find "type" key in map to get input type. Keep existing fields as is. // Move everything else in "config". diff --git a/common/helpers/subnetmap.go b/common/helpers/subnetmap.go index e71841ff..cee0bd33 100644 --- a/common/helpers/subnetmap.go +++ b/common/helpers/subnetmap.go @@ -173,10 +173,10 @@ func LooksLikeSubnetMap(v reflect.Value) bool { // an intermediate map. func SubnetMapUnmarshallerHook[V any]() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if to.Type() != reflect.TypeOf(SubnetMap[V]{}) { + if to.Type() != reflect.TypeFor[SubnetMap[V]]() { return from.Interface(), nil } - if from.Type() == reflect.TypeOf(&SubnetMap[V]{}) { + if from.Type() == reflect.PtrTo(reflect.TypeFor[SubnetMap[V]]()) { return from.Interface(), nil } output := gin.H{} diff --git a/common/helpers/tls.go b/common/helpers/tls.go index 9e1e8c06..34a1b07d 100644 --- a/common/helpers/tls.go +++ b/common/helpers/tls.go @@ -66,9 +66,8 @@ func (config TLSConfiguration) MakeTLSConfig() (*tls.Config, error) { // RenameKeyUnmarshallerHook move a configuration setting from one place to another. func tlsUnmarshallerHook() mapstructure.DecodeHookFunc { - var zeroConfiguration TLSConfiguration return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(zeroConfiguration) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[TLSConfiguration]() { return from.Interface(), nil } diff --git a/common/kafka/config.go b/common/kafka/config.go index e28856a1..ec0d1401 100644 --- a/common/kafka/config.go +++ b/common/kafka/config.go @@ -132,7 +132,7 @@ func NewConfig(r *reporter.Reporter, config Configuration) ([]kgo.Opt, error) { // - move SASL related parameters from TLS section to SASL section func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || !helpers.SameTypeOrSuperset(to.Type(), reflect.TypeOf(Configuration{})) { + if from.Kind() != reflect.Map || from.IsNil() || !helpers.SameTypeOrSuperset(to.Type(), reflect.TypeFor[Configuration]()) { return from.Interface(), nil } diff --git a/common/schema/definition.go b/common/schema/definition.go index afc419e6..5422bdf9 100644 --- a/common/schema/definition.go +++ b/common/schema/definition.go @@ -623,7 +623,7 @@ func (schema Schema) finalize() Schema { // Update disabledGroups schema.disabledGroups = *bitset.New(uint(ColumnGroupLast)) - for group := ColumnGroup(0); group < ColumnGroupLast; group++ { + for group := range ColumnGroupLast { schema.disabledGroups.Set(uint(group)) for _, column := range schema.columns { if !column.Disabled && column.Group == group { diff --git a/console/docs.go b/console/docs.go index ca47adf4..24a39328 100644 --- a/console/docs.go +++ b/console/docs.go @@ -139,7 +139,7 @@ func (r *internalLinkTransformer) Transform(node *ast.Document, _ text.Reader, _ case *ast.Link: matches := internalLinkRegexp.FindStringSubmatch(string(node.Destination)) if matches != nil { - node.Destination = []byte(fmt.Sprintf("%s%s", matches[3], matches[4])) + node.Destination = fmt.Appendf(nil, "%s%s", matches[3], matches[4]) } } return ast.WalkContinue, nil @@ -160,7 +160,7 @@ func (r *imageLinkTransformer) Transform(node *ast.Document, _ text.Reader, _ pa case *ast.Image: path := string(node.Destination) if !strings.Contains(path, "/") { - node.Destination = []byte(fmt.Sprintf("../assets/docs/%s", path)) + node.Destination = fmt.Appendf(nil, "../assets/docs/%s", path) } } return ast.WalkContinue, nil diff --git a/console/filter.go b/console/filter.go index 0e965ac2..cf0d5620 100644 --- a/console/filter.go +++ b/console/filter.go @@ -106,7 +106,7 @@ func (c *Component) filterCompleteHandlerFunc(gc *gin.Context) { } case "operator": _, err := filter.Parse("", - []byte(fmt.Sprintf("%s ", input.Column)), + fmt.Appendf(nil, "%s ", input.Column), filter.Entrypoint("ConditionExpr"), filter.GlobalStore("meta", &filter.Meta{Schema: c.d.Schema})) if err != nil { diff --git a/console/filter/helpers.go b/console/filter/helpers.go index 3ac586c2..c3aec5ce 100644 --- a/console/filter/helpers.go +++ b/console/filter/helpers.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "net/netip" + "slices" "strings" "akvorado/common/schema" @@ -116,19 +117,14 @@ func (c *current) acceptColumn() (schema.Column, error) { // should be used in predicate code blocks. func (c *current) columnIsOfType(name any, types ...string) (bool, error) { nameSl := name.([]any) - var columnName string + var columnName strings.Builder for _, s := range nameSl { - columnName += string(s.([]byte)) + columnName.Write(s.([]byte)) } sch := c.globalStore["meta"].(*Meta).Schema for _, column := range sch.Columns() { - if strings.EqualFold(columnName, column.Name) { - for _, t := range types { - if column.ParserType == t { - return true, nil - } - } - return false, nil + if strings.EqualFold(columnName.String(), column.Name) { + return slices.Contains(types, column.ParserType), nil } } return false, nil diff --git a/console/widgets_test.go b/console/widgets_test.go index 6259a1d4..674f252b 100644 --- a/console/widgets_test.go +++ b/console/widgets_test.go @@ -49,13 +49,13 @@ LIMIT 1`). colInIfName := mocks.NewMockColumnType(ctrl) colInIfBoundary := mocks.NewMockColumnType(ctrl) colInIfSpeed := mocks.NewMockColumnType(ctrl) - colTimeReceived.EXPECT().ScanType().Return(reflect.TypeOf(time.Time{})) - colSamplingRate.EXPECT().ScanType().Return(reflect.TypeOf(uint64(0))) - colSrcAddr.EXPECT().ScanType().Return(reflect.TypeOf(net.IP{})) - colSrcCountry.EXPECT().ScanType().Return(reflect.TypeOf("")) - colInIfName.EXPECT().ScanType().Return(reflect.TypeOf("")) - colInIfBoundary.EXPECT().ScanType().Return(reflect.TypeOf("")) - colInIfSpeed.EXPECT().ScanType().Return(reflect.TypeOf(uint32(0))) + colTimeReceived.EXPECT().ScanType().Return(reflect.TypeFor[time.Time]()) + colSamplingRate.EXPECT().ScanType().Return(reflect.TypeFor[uint64]()) + colSrcAddr.EXPECT().ScanType().Return(reflect.TypeFor[net.IP]()) + colSrcCountry.EXPECT().ScanType().Return(reflect.TypeFor[string]()) + colInIfName.EXPECT().ScanType().Return(reflect.TypeFor[string]()) + colInIfBoundary.EXPECT().ScanType().Return(reflect.TypeFor[string]()) + colInIfSpeed.EXPECT().ScanType().Return(reflect.TypeFor[uint32]()) mockRows.EXPECT().ColumnTypes().Return([]driver.ColumnType{ colTimeReceived, colSamplingRate, diff --git a/demoexporter/flows/generate_test.go b/demoexporter/flows/generate_test.go index f2964477..5095892a 100644 --- a/demoexporter/flows/generate_test.go +++ b/demoexporter/flows/generate_test.go @@ -8,6 +8,7 @@ import ( "math" "math/rand/v2" "net/netip" + "slices" "testing" "time" @@ -102,14 +103,7 @@ func TestChooseRandom(t *testing.T) { } break } - found := false - for _, v := range tc { - if v == result { - found = true - break - } - } - if !found { + if !slices.Contains(tc, result) { t.Fatalf("chooseRandom() returned %d, not in slice", result) } diff --git a/demoexporter/flows/nfdata.go b/demoexporter/flows/nfdata.go index c47a2b81..fb32cc6f 100644 --- a/demoexporter/flows/nfdata.go +++ b/demoexporter/flows/nfdata.go @@ -33,10 +33,7 @@ func getNetFlowData(ctx context.Context, flows []generatedFlow, sequenceNumber u flows := ipFlows[etype] settings := flowSettings[etype] for i := 0; i < len(flows); i += settings.MaxFlowsPerPacket { - upper := i + settings.MaxFlowsPerPacket - if upper > len(flows) { - upper = len(flows) - } + upper := min(i+settings.MaxFlowsPerPacket, len(flows)) fls := flows[i:upper] buf := new(bytes.Buffer) if err := binary.Write(buf, binary.BigEndian, nfv9Header{ diff --git a/orchestrator/clickhouse/config.go b/orchestrator/clickhouse/config.go index f9d7828a..ed38eae1 100644 --- a/orchestrator/clickhouse/config.go +++ b/orchestrator/clickhouse/config.go @@ -108,7 +108,7 @@ func NetworkAttributesUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { from = helpers.ElemOrIdentity(from) to = helpers.ElemOrIdentity(to) - if to.Type() != reflect.TypeOf(NetworkAttributes{}) { + if to.Type() != reflect.TypeFor[NetworkAttributes]() { return from.Interface(), nil } if from.Kind() == reflect.String { diff --git a/outlet/core/config.go b/outlet/core/config.go index c2cc5fb4..7a5336a3 100644 --- a/outlet/core/config.go +++ b/outlet/core/config.go @@ -74,7 +74,7 @@ const ( // - map bmp to routing func ASNProviderUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.String || to.Type() != reflect.TypeOf(ASNProvider(0)) { + if from.Kind() != reflect.String || to.Type() != reflect.TypeFor[ASNProvider]() { return from.Interface(), nil } if strings.ToLower(from.String()) == "bmp" { @@ -91,7 +91,7 @@ func ASNProviderUnmarshallerHook() mapstructure.DecodeHookFunc { // - map bmp to routing func NetProviderUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.String || to.Type() != reflect.TypeOf(NetProvider(0)) { + if from.Kind() != reflect.String || to.Type() != reflect.TypeFor[NetProvider]() { return from.Interface(), nil } if strings.ToLower(from.String()) == "bmp" { @@ -105,7 +105,7 @@ func NetProviderUnmarshallerHook() mapstructure.DecodeHookFunc { // - replace ignore-asn-from-flow by asn-providers func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(Configuration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[Configuration]() { return from.Interface(), nil } diff --git a/outlet/metadata/provider/gnmi/collector.go b/outlet/metadata/provider/gnmi/collector.go index 891ec2b1..82e96d0d 100644 --- a/outlet/metadata/provider/gnmi/collector.go +++ b/outlet/metadata/provider/gnmi/collector.go @@ -109,7 +109,7 @@ outer2: // Set name if iface.Name == "" && len(model.IfNameKeys) > 0 { inner3: - for _, key := range strings.Split(keys, ",") { + for key := range strings.SplitSeq(keys, ",") { for _, name := range model.IfNameKeys { pfx := fmt.Sprintf("%s=", name) if strings.HasPrefix(key, pfx) { diff --git a/outlet/metadata/provider/gnmi/config.go b/outlet/metadata/provider/gnmi/config.go index 0c7dec1b..cb83600b 100644 --- a/outlet/metadata/provider/gnmi/config.go +++ b/outlet/metadata/provider/gnmi/config.go @@ -168,7 +168,7 @@ func DefaultModels() []Model { // - If no Insecure field is present, TLS.Enable defaults to true func AuthenticationParameterUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(AuthenticationParameter{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[AuthenticationParameter]() { return from.Interface(), nil } @@ -283,7 +283,7 @@ func AuthenticationParameterUnmarshallerHook() mapstructure.DecodeHookFunc { // - replace an occurrence of "default" in the list of models with the list of default models. func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(Configuration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[Configuration]() { return from.Interface(), nil } diff --git a/outlet/metadata/provider/gnmi/srlinux_test.go b/outlet/metadata/provider/gnmi/srlinux_test.go index 31ecb025..2217c290 100644 --- a/outlet/metadata/provider/gnmi/srlinux_test.go +++ b/outlet/metadata/provider/gnmi/srlinux_test.go @@ -156,7 +156,7 @@ commit now // gNMI setup srLinuxGNMI := helpers.CheckExternalService(t, "SR Linux gNMI", []string{"srlinux:57400", "127.0.0.1:57400"}) - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(t.Context()) defer cancel() tg, err := api.NewTarget( api.Address(srLinuxGNMI), diff --git a/outlet/metadata/provider/snmp/config.go b/outlet/metadata/provider/snmp/config.go index d098e017..ea291858 100644 --- a/outlet/metadata/provider/snmp/config.go +++ b/outlet/metadata/provider/snmp/config.go @@ -67,7 +67,7 @@ func DefaultConfiguration() provider.Configuration { // - merge security parameters and communities into credentials func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { return func(from, to reflect.Value) (any, error) { - if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeOf(Configuration{}) { + if from.Kind() != reflect.Map || from.IsNil() || to.Type() != reflect.TypeFor[Configuration]() { return from.Interface(), nil }