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) {
// 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
}

View File

@@ -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) {

View File

@@ -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()

View File

@@ -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 {

View File

@@ -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".

View File

@@ -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{}

View File

@@ -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
}

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
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
}

View File

@@ -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 {

View File

@@ -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

View File

@@ -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 {

View File

@@ -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

View File

@@ -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,

View File

@@ -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)
}

View File

@@ -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{

View File

@@ -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 {

View File

@@ -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
}

View File

@@ -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) {

View File

@@ -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
}

View File

@@ -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),

View File

@@ -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
}