chore: modernize some code

This commit is contained in:
Vincent Bernat
2025-11-14 23:11:53 +01:00
parent 625387a617
commit abca5e983d
21 changed files with 42 additions and 63 deletions

View File

@@ -274,14 +274,7 @@ func orchestratorWatch(r *reporter.Reporter, daemonComponent daemon.Component, p
if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) { if event.Has(fsnotify.Create) || event.Has(fsnotify.Write) {
// Check if we have one of the monitored path matching // Check if we have one of the monitored path matching
r.Debug().Str("name", event.Name).Msg("detected potential configuration change") r.Debug().Str("name", event.Name).Msg("detected potential configuration change")
found := false if !slices.Contains(paths, filepath.Clean(event.Name)) {
for _, path := range paths {
if filepath.Clean(event.Name) == path {
found = true
break
}
}
if !found {
continue continue
} }
@@ -309,7 +302,7 @@ func orchestratorWatch(r *reporter.Reporter, daemonComponent daemon.Component, p
// component to clickhouse component // component to clickhouse component
func orchestratorGeoIPMigrationHook() mapstructure.DecodeHookFunc { func orchestratorGeoIPMigrationHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }
@@ -382,7 +375,7 @@ func orchestratorGeoIPMigrationHook() mapstructure.DecodeHookFunc {
// configuration from clickhouse component to clickhousedb component // configuration from clickhouse component to clickhousedb component
func orchestratorClickHouseMigrationHook() mapstructure.DecodeHookFunc { func orchestratorClickHouseMigrationHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }
@@ -449,7 +442,7 @@ func orchestratorClickHouseMigrationHook() mapstructure.DecodeHookFunc {
// there is only one inlet configuration. // there is only one inlet configuration.
func orchestratorInletToOutletMigrationHook() mapstructure.DecodeHookFunc { func orchestratorInletToOutletMigrationHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }

View File

@@ -69,7 +69,7 @@ func TestOrchestratorConfig(t *testing.T) {
var got any var got any
got = gotYAML got = gotYAML
i := 0 i := 0
for _, component := range strings.Split(path, ".") { for component := range strings.SplitSeq(path, ".") {
var ok bool var ok bool
i++ i++
switch gotConcrete := got.(type) { switch gotConcrete := got.(type) {

View File

@@ -189,7 +189,7 @@ func outletStart(r *reporter.Reporter, config OutletConfiguration, checkOnly boo
// BMP configuration to routing. // BMP configuration to routing.
func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }
@@ -231,7 +231,7 @@ func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
if helpers.MapStructureMatchName(k.String(), "Workers") { if helpers.MapStructureMatchName(k.String(), "Workers") {
continue continue
} }
metadataConfig := reflect.TypeOf(metadata.Configuration{}) metadataConfig := reflect.TypeFor[metadata.Configuration]()
for j := range metadataConfig.NumField() { for j := range metadataConfig.NumField() {
if helpers.MapStructureMatchName(k.String(), metadataConfig.Field(j).Name) { if helpers.MapStructureMatchName(k.String(), metadataConfig.Field(j).Name) {
metadataValue[k.String()] = snmpMap.MapIndex(snmpKeys[i]).Interface() metadataValue[k.String()] = snmpMap.MapIndex(snmpKeys[i]).Interface()
@@ -280,7 +280,7 @@ func OutletConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
if k.Kind() != reflect.String { if k.Kind() != reflect.String {
continue continue
} }
routingConfig := reflect.TypeOf(routing.Configuration{}) routingConfig := reflect.TypeFor[routing.Configuration]()
for j := range routingConfig.NumField() { for j := range routingConfig.NumField() {
if helpers.MapStructureMatchName(k.String(), routingConfig.Field(j).Name) { if helpers.MapStructureMatchName(k.String(), routingConfig.Field(j).Name) {
routingValue[k.String()] = bmpMap.MapIndex(bmpKeys[i]).Interface() routingValue[k.String()] = bmpMap.MapIndex(bmpKeys[i]).Interface()

View File

@@ -70,7 +70,7 @@ func TestUnmapPrefix(t *testing.T) {
func TestNetIPAddrStructure(t *testing.T) { func TestNetIPAddrStructure(t *testing.T) {
var addr netip.Addr 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) // Test total size: 24 bytes (16 for uint128 + 8 for unique.Handle)
if unsafe.Sizeof(addr) != 24 { if unsafe.Sizeof(addr) != 24 {

View File

@@ -223,7 +223,7 @@ func ParametrizedConfigurationUnmarshallerHook[OuterConfiguration any, InnerConf
return from.Interface(), nil return from.Interface(), nil
} }
configField := to.FieldByName("Config") 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. // Find "type" key in map to get input type. Keep existing fields as is.
// Move everything else in "config". // Move everything else in "config".

View File

@@ -173,10 +173,10 @@ func LooksLikeSubnetMap(v reflect.Value) bool {
// an intermediate map. // an intermediate map.
func SubnetMapUnmarshallerHook[V any]() mapstructure.DecodeHookFunc { func SubnetMapUnmarshallerHook[V any]() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }
if from.Type() == reflect.TypeOf(&SubnetMap[V]{}) { if from.Type() == reflect.PtrTo(reflect.TypeFor[SubnetMap[V]]()) {
return from.Interface(), nil return from.Interface(), nil
} }
output := gin.H{} output := gin.H{}

View File

@@ -66,9 +66,8 @@ func (config TLSConfiguration) MakeTLSConfig() (*tls.Config, error) {
// RenameKeyUnmarshallerHook move a configuration setting from one place to another. // RenameKeyUnmarshallerHook move a configuration setting from one place to another.
func tlsUnmarshallerHook() mapstructure.DecodeHookFunc { func tlsUnmarshallerHook() mapstructure.DecodeHookFunc {
var zeroConfiguration TLSConfiguration
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }

View File

@@ -132,7 +132,7 @@ func NewConfig(r *reporter.Reporter, config Configuration) ([]kgo.Opt, error) {
// - move SASL related parameters from TLS section to SASL section // - move SASL related parameters from TLS section to SASL section
func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }

View File

@@ -623,7 +623,7 @@ func (schema Schema) finalize() Schema {
// Update disabledGroups // Update disabledGroups
schema.disabledGroups = *bitset.New(uint(ColumnGroupLast)) schema.disabledGroups = *bitset.New(uint(ColumnGroupLast))
for group := ColumnGroup(0); group < ColumnGroupLast; group++ { for group := range ColumnGroupLast {
schema.disabledGroups.Set(uint(group)) schema.disabledGroups.Set(uint(group))
for _, column := range schema.columns { for _, column := range schema.columns {
if !column.Disabled && column.Group == group { if !column.Disabled && column.Group == group {

View File

@@ -139,7 +139,7 @@ func (r *internalLinkTransformer) Transform(node *ast.Document, _ text.Reader, _
case *ast.Link: case *ast.Link:
matches := internalLinkRegexp.FindStringSubmatch(string(node.Destination)) matches := internalLinkRegexp.FindStringSubmatch(string(node.Destination))
if matches != nil { 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 return ast.WalkContinue, nil
@@ -160,7 +160,7 @@ func (r *imageLinkTransformer) Transform(node *ast.Document, _ text.Reader, _ pa
case *ast.Image: case *ast.Image:
path := string(node.Destination) path := string(node.Destination)
if !strings.Contains(path, "/") { 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 return ast.WalkContinue, nil

View File

@@ -106,7 +106,7 @@ func (c *Component) filterCompleteHandlerFunc(gc *gin.Context) {
} }
case "operator": case "operator":
_, err := filter.Parse("", _, err := filter.Parse("",
[]byte(fmt.Sprintf("%s ", input.Column)), fmt.Appendf(nil, "%s ", input.Column),
filter.Entrypoint("ConditionExpr"), filter.Entrypoint("ConditionExpr"),
filter.GlobalStore("meta", &filter.Meta{Schema: c.d.Schema})) filter.GlobalStore("meta", &filter.Meta{Schema: c.d.Schema}))
if err != nil { if err != nil {

View File

@@ -8,6 +8,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"net/netip" "net/netip"
"slices"
"strings" "strings"
"akvorado/common/schema" "akvorado/common/schema"
@@ -116,19 +117,14 @@ func (c *current) acceptColumn() (schema.Column, error) {
// should be used in predicate code blocks. // should be used in predicate code blocks.
func (c *current) columnIsOfType(name any, types ...string) (bool, error) { func (c *current) columnIsOfType(name any, types ...string) (bool, error) {
nameSl := name.([]any) nameSl := name.([]any)
var columnName string var columnName strings.Builder
for _, s := range nameSl { for _, s := range nameSl {
columnName += string(s.([]byte)) columnName.Write(s.([]byte))
} }
sch := c.globalStore["meta"].(*Meta).Schema sch := c.globalStore["meta"].(*Meta).Schema
for _, column := range sch.Columns() { for _, column := range sch.Columns() {
if strings.EqualFold(columnName, column.Name) { if strings.EqualFold(columnName.String(), column.Name) {
for _, t := range types { return slices.Contains(types, column.ParserType), nil
if column.ParserType == t {
return true, nil
}
}
return false, nil
} }
} }
return false, nil return false, nil

View File

@@ -49,13 +49,13 @@ LIMIT 1`).
colInIfName := mocks.NewMockColumnType(ctrl) colInIfName := mocks.NewMockColumnType(ctrl)
colInIfBoundary := mocks.NewMockColumnType(ctrl) colInIfBoundary := mocks.NewMockColumnType(ctrl)
colInIfSpeed := mocks.NewMockColumnType(ctrl) colInIfSpeed := mocks.NewMockColumnType(ctrl)
colTimeReceived.EXPECT().ScanType().Return(reflect.TypeOf(time.Time{})) colTimeReceived.EXPECT().ScanType().Return(reflect.TypeFor[time.Time]())
colSamplingRate.EXPECT().ScanType().Return(reflect.TypeOf(uint64(0))) colSamplingRate.EXPECT().ScanType().Return(reflect.TypeFor[uint64]())
colSrcAddr.EXPECT().ScanType().Return(reflect.TypeOf(net.IP{})) colSrcAddr.EXPECT().ScanType().Return(reflect.TypeFor[net.IP]())
colSrcCountry.EXPECT().ScanType().Return(reflect.TypeOf("")) colSrcCountry.EXPECT().ScanType().Return(reflect.TypeFor[string]())
colInIfName.EXPECT().ScanType().Return(reflect.TypeOf("")) colInIfName.EXPECT().ScanType().Return(reflect.TypeFor[string]())
colInIfBoundary.EXPECT().ScanType().Return(reflect.TypeOf("")) colInIfBoundary.EXPECT().ScanType().Return(reflect.TypeFor[string]())
colInIfSpeed.EXPECT().ScanType().Return(reflect.TypeOf(uint32(0))) colInIfSpeed.EXPECT().ScanType().Return(reflect.TypeFor[uint32]())
mockRows.EXPECT().ColumnTypes().Return([]driver.ColumnType{ mockRows.EXPECT().ColumnTypes().Return([]driver.ColumnType{
colTimeReceived, colTimeReceived,
colSamplingRate, colSamplingRate,

View File

@@ -8,6 +8,7 @@ import (
"math" "math"
"math/rand/v2" "math/rand/v2"
"net/netip" "net/netip"
"slices"
"testing" "testing"
"time" "time"
@@ -102,14 +103,7 @@ func TestChooseRandom(t *testing.T) {
} }
break break
} }
found := false if !slices.Contains(tc, result) {
for _, v := range tc {
if v == result {
found = true
break
}
}
if !found {
t.Fatalf("chooseRandom() returned %d, not in slice", t.Fatalf("chooseRandom() returned %d, not in slice",
result) result)
} }

View File

@@ -33,10 +33,7 @@ func getNetFlowData(ctx context.Context, flows []generatedFlow, sequenceNumber u
flows := ipFlows[etype] flows := ipFlows[etype]
settings := flowSettings[etype] settings := flowSettings[etype]
for i := 0; i < len(flows); i += settings.MaxFlowsPerPacket { for i := 0; i < len(flows); i += settings.MaxFlowsPerPacket {
upper := i + settings.MaxFlowsPerPacket upper := min(i+settings.MaxFlowsPerPacket, len(flows))
if upper > len(flows) {
upper = len(flows)
}
fls := flows[i:upper] fls := flows[i:upper]
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
if err := binary.Write(buf, binary.BigEndian, nfv9Header{ if err := binary.Write(buf, binary.BigEndian, nfv9Header{

View File

@@ -108,7 +108,7 @@ func NetworkAttributesUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { return func(from, to reflect.Value) (any, error) {
from = helpers.ElemOrIdentity(from) from = helpers.ElemOrIdentity(from)
to = helpers.ElemOrIdentity(to) to = helpers.ElemOrIdentity(to)
if to.Type() != reflect.TypeOf(NetworkAttributes{}) { if to.Type() != reflect.TypeFor[NetworkAttributes]() {
return from.Interface(), nil return from.Interface(), nil
} }
if from.Kind() == reflect.String { if from.Kind() == reflect.String {

View File

@@ -74,7 +74,7 @@ const (
// - map bmp to routing // - map bmp to routing
func ASNProviderUnmarshallerHook() mapstructure.DecodeHookFunc { func ASNProviderUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }
if strings.ToLower(from.String()) == "bmp" { if strings.ToLower(from.String()) == "bmp" {
@@ -91,7 +91,7 @@ func ASNProviderUnmarshallerHook() mapstructure.DecodeHookFunc {
// - map bmp to routing // - map bmp to routing
func NetProviderUnmarshallerHook() mapstructure.DecodeHookFunc { func NetProviderUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }
if strings.ToLower(from.String()) == "bmp" { if strings.ToLower(from.String()) == "bmp" {
@@ -105,7 +105,7 @@ func NetProviderUnmarshallerHook() mapstructure.DecodeHookFunc {
// - replace ignore-asn-from-flow by asn-providers // - replace ignore-asn-from-flow by asn-providers
func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }

View File

@@ -109,7 +109,7 @@ outer2:
// Set name // Set name
if iface.Name == "" && len(model.IfNameKeys) > 0 { if iface.Name == "" && len(model.IfNameKeys) > 0 {
inner3: inner3:
for _, key := range strings.Split(keys, ",") { for key := range strings.SplitSeq(keys, ",") {
for _, name := range model.IfNameKeys { for _, name := range model.IfNameKeys {
pfx := fmt.Sprintf("%s=", name) pfx := fmt.Sprintf("%s=", name)
if strings.HasPrefix(key, pfx) { if strings.HasPrefix(key, pfx) {

View File

@@ -168,7 +168,7 @@ func DefaultModels() []Model {
// - If no Insecure field is present, TLS.Enable defaults to true // - If no Insecure field is present, TLS.Enable defaults to true
func AuthenticationParameterUnmarshallerHook() mapstructure.DecodeHookFunc { func AuthenticationParameterUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 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. // - replace an occurrence of "default" in the list of models with the list of default models.
func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }

View File

@@ -156,7 +156,7 @@ commit now
// gNMI setup // gNMI setup
srLinuxGNMI := helpers.CheckExternalService(t, "SR Linux gNMI", srLinuxGNMI := helpers.CheckExternalService(t, "SR Linux gNMI",
[]string{"srlinux:57400", "127.0.0.1:57400"}) []string{"srlinux:57400", "127.0.0.1:57400"})
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(t.Context())
defer cancel() defer cancel()
tg, err := api.NewTarget( tg, err := api.NewTarget(
api.Address(srLinuxGNMI), api.Address(srLinuxGNMI),

View File

@@ -67,7 +67,7 @@ func DefaultConfiguration() provider.Configuration {
// - merge security parameters and communities into credentials // - merge security parameters and communities into credentials
func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc { func ConfigurationUnmarshallerHook() mapstructure.DecodeHookFunc {
return func(from, to reflect.Value) (any, error) { 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 return from.Interface(), nil
} }