diff --git a/internal/pkg/api/apiVersion.go b/internal/pkg/api/apiVersion.go index e54566b7ae..18797503d1 100644 --- a/internal/pkg/api/apiVersion.go +++ b/internal/pkg/api/apiVersion.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "regexp" + "slices" "strings" ) @@ -47,12 +48,7 @@ func (a *apiVersion) validateVersionFormat(version string) error { } func (a *apiVersion) isVersionSupported(version string) bool { - for _, vers := range a.supportedVersions { - if vers == version { - return true - } - } - return false + return slices.Contains(a.supportedVersions, version) } func (a *apiVersion) middleware(next http.Handler) http.Handler { diff --git a/internal/pkg/api/error_test.go b/internal/pkg/api/error_test.go index c1b604dba0..45705905c4 100644 --- a/internal/pkg/api/error_test.go +++ b/internal/pkg/api/error_test.go @@ -22,20 +22,20 @@ func Test_ErrorResp(t *testing.T) { tests := []struct { name string err error - expectedTags map[string]interface{} + expectedTags map[string]any }{{ name: "generic error", err: fmt.Errorf("generic error"), }, { name: "elastic error", err: &es.ErrElastic{}, - expectedTags: map[string]interface{}{ + expectedTags: map[string]any{ "error_type": "ErrElastic", }, }, { name: "wrapped elastic error", err: fmt.Errorf("wrapped error: %w", &es.ErrElastic{}), - expectedTags: map[string]interface{}{ + expectedTags: map[string]any{ "error_type": "ErrElastic", }, }} @@ -64,7 +64,7 @@ func Test_ErrorResp(t *testing.T) { require.Len(t, payloads.Transactions, 1) require.Len(t, payloads.Errors, 1) - tags := make(map[string]interface{}) + tags := make(map[string]any) for _, tag := range payloads.Transactions[0].Context.Tags { tags[tag.Key] = tag.Value } diff --git a/internal/pkg/api/handleAck_test.go b/internal/pkg/api/handleAck_test.go index 67bb6b2b14..8307568c14 100644 --- a/internal/pkg/api/handleAck_test.go +++ b/internal/pkg/api/handleAck_test.go @@ -48,7 +48,7 @@ func TestMakeUpdatePolicyBody(t *testing.T) { data := makeUpdatePolicyBody(policyID, newRev) - var i interface{} + var i any err := json.Unmarshal(data, &i) if err != nil { @@ -706,7 +706,7 @@ func TestAckHandleUpgrade(t *testing.T) { bulker: func(t *testing.T) *ftesting.MockBulk { m := ftesting.NewMockBulk() m.On("Update", mock.Anything, mock.Anything, mock.Anything, mock.MatchedBy(func(p []byte) bool { - var body map[string]map[string]interface{} + var body map[string]map[string]any if err := json.Unmarshal(p, &body); err != nil { t.Fatal(err) } @@ -725,7 +725,7 @@ func TestAckHandleUpgrade(t *testing.T) { bulker: func(t *testing.T) *ftesting.MockBulk { m := ftesting.NewMockBulk() m.On("Update", mock.Anything, mock.Anything, mock.Anything, mock.MatchedBy(func(p []byte) bool { - var body map[string]map[string]interface{} + var body map[string]map[string]any if err := json.Unmarshal(p, &body); err != nil { t.Fatal(err) } diff --git a/internal/pkg/api/handleCheckin.go b/internal/pkg/api/handleCheckin.go index eeda1ca1ac..dc50333200 100644 --- a/internal/pkg/api/handleCheckin.go +++ b/internal/pkg/api/handleCheckin.go @@ -217,13 +217,7 @@ func (ct *CheckinT) validateRequest(zlog zerolog.Logger, w http.ResponseWriter, // sets timeout is set to max(1m, min(pDur-2m, max poll time)) // sets the response write timeout to max(2m, timeout+1m) if pDur != time.Duration(0) { - pollDuration = pDur - (2 * time.Minute) - if pollDuration > ct.cfg.Timeouts.CheckinMaxPoll { - pollDuration = ct.cfg.Timeouts.CheckinMaxPoll - } - if pollDuration < time.Minute { - pollDuration = time.Minute - } + pollDuration = max(min(pDur-(2*time.Minute), ct.cfg.Timeouts.CheckinMaxPoll), time.Minute) wTime := pollDuration + time.Minute rc := http.NewResponseController(w) @@ -678,12 +672,7 @@ func (ct *CheckinT) writeResponse(zlog zerolog.Logger, w http.ResponseWriter, r } func acceptsEncoding(r *http.Request, encoding string) bool { - for _, v := range r.Header.Values("Accept-Encoding") { - if v == encoding { - return true - } - } - return false + return slices.Contains(r.Header.Values("Accept-Encoding"), encoding) } // Resolve AckToken from request, fallback on the agent record @@ -1044,7 +1033,7 @@ func parseMeta(zlog zerolog.Logger, agent *model.Agent, req *CheckinRequest) ([] } // Deserialize the request metadata - var reqLocalMeta interface{} + var reqLocalMeta any if err := json.Unmarshal(req.LocalMetadata, &reqLocalMeta); err != nil { return nil, fmt.Errorf("parseMeta request: %w", err) } @@ -1056,7 +1045,7 @@ func parseMeta(zlog zerolog.Logger, agent *model.Agent, req *CheckinRequest) ([] // Deserialize the agent's metadata copy. If it fails, it's ignored as it will just // be replaced with the correct contents from the clients checkin. - var agentLocalMeta interface{} + var agentLocalMeta any if err := json.Unmarshal(agent.LocalMetadata, &agentLocalMeta); err != nil { zlog.Warn().Err(err).Msg("local_metadata in document invalid; ignoring it") } diff --git a/internal/pkg/api/handleCheckin_test.go b/internal/pkg/api/handleCheckin_test.go index cbbad177a1..109b23fb63 100644 --- a/internal/pkg/api/handleCheckin_test.go +++ b/internal/pkg/api/handleCheckin_test.go @@ -356,8 +356,7 @@ func TestResolveSeqNo(t *testing.T) { t.Run(tc.name, func(t *testing.T) { // setup mock CheckinT logger := testlog.SetLogger(t) - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() verCon := mustBuildConstraints("8.0.0") cfg := &config.Server{} c, _ := cache.New(config.Cache{NumCounters: 100, MaxCost: 100000}) @@ -413,7 +412,7 @@ func TestProcessUpgradeDetails(t *testing.T) { mBulk := ftesting.NewMockBulk() mBulk.On("Update", mock.Anything, dl.FleetAgents, "doc-ID", mock.MatchedBy(func(p []byte) bool { doc := struct { - Doc map[string]interface{} `json:"doc"` + Doc map[string]any `json:"doc"` }{} if err := json.Unmarshal(p, &doc); err != nil { t.Logf("bulk match unmarshal error: %v", err) @@ -1090,7 +1089,7 @@ func TestParseComponents(t *testing.T) { } } -func requireMarshalJSON(t *testing.T, obj interface{}) json.RawMessage { +func requireMarshalJSON(t *testing.T, obj any) json.RawMessage { data, err := json.Marshal(obj) require.NoError(t, err) return data diff --git a/internal/pkg/api/handleEnroll.go b/internal/pkg/api/handleEnroll.go index 01ea555d45..4e9ab2e33b 100644 --- a/internal/pkg/api/handleEnroll.go +++ b/internal/pkg/api/handleEnroll.go @@ -607,16 +607,16 @@ func updateLocalMetaAgentID(data []byte, agentID string) ([]byte, error) { return data, nil } - var m map[string]interface{} + var m map[string]any err := json.Unmarshal(data, &m) if err != nil { return nil, err } if v, ok := m["elastic"]; ok { - if sm, ok := v.(map[string]interface{}); ok { + if sm, ok := v.(map[string]any); ok { if v, ok = sm["agent"]; ok { - if sm, ok = v.(map[string]interface{}); ok { + if sm, ok = v.(map[string]any); ok { if _, ok = sm["id"]; ok { sm["id"] = agentID data, err = json.Marshal(m) diff --git a/internal/pkg/api/handleEnroll_test.go b/internal/pkg/api/handleEnroll_test.go index d960983eca..213eec7a7d 100644 --- a/internal/pkg/api/handleEnroll_test.go +++ b/internal/pkg/api/handleEnroll_test.go @@ -63,8 +63,7 @@ func TestRemoveDuplicateStr(t *testing.T) { } func TestEnroll(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} enrollmentID := "1234" @@ -102,8 +101,7 @@ func TestEnroll(t *testing.T) { } func TestEnrollWithAgentID(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" @@ -144,8 +142,7 @@ func TestEnrollWithAgentID(t *testing.T) { } func TestEnrollWithAgentIDExistingNonActive(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" @@ -191,8 +188,7 @@ func TestEnrollWithAgentIDExistingNonActive(t *testing.T) { } func TestEnrollWithAgentIDExistingActive_NotReplaceable(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" @@ -226,8 +222,7 @@ func TestEnrollWithAgentIDExistingActive_NotReplaceable(t *testing.T) { } func TestEnrollWithAgentIDExistingActive_InvalidReplaceToken_Missing(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" @@ -269,8 +264,7 @@ func TestEnrollWithAgentIDExistingActive_InvalidReplaceToken_Missing(t *testing. } func TestEnrollWithAgentIDExistingActive_InvalidReplaceToken_Mismatch(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" @@ -314,8 +308,7 @@ func TestEnrollWithAgentIDExistingActive_InvalidReplaceToken_Mismatch(t *testing } func TestEnrollWithAgentIDExistingActive_WrongPolicy(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" @@ -359,8 +352,7 @@ func TestEnrollWithAgentIDExistingActive_WrongPolicy(t *testing.T) { } func TestEnrollWithAgentIDExistingActive(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() rb := &rollback.Rollback{} zlog := zerolog.Logger{} agentID := "1234" diff --git a/internal/pkg/api/handleFileDelivery_test.go b/internal/pkg/api/handleFileDelivery_test.go index 1ffa1506b9..fdd559392f 100644 --- a/internal/pkg/api/handleFileDelivery_test.go +++ b/internal/pkg/api/handleFileDelivery_test.go @@ -162,9 +162,9 @@ func TestFileDelivery(t *testing.T) { SeqNo: 1, Version: 1, Index: fmt.Sprintf(delivery.FileDataIndexPattern, "endpoint"), - Fields: map[string]interface{}{ - file.FieldBaseID: []interface{}{"X"}, - file.FieldLast: []interface{}{true}, + Fields: map[string]any{ + file.FieldBaseID: []any{"X"}, + file.FieldLast: []any{true}, }, }, }, @@ -222,8 +222,8 @@ func TestFileDeliveryMultipleChunks(t *testing.T) { SeqNo: 1, Version: 1, Index: fmt.Sprintf(delivery.FileDataIndexPattern, "endpoint"), - Fields: map[string]interface{}{ - file.FieldBaseID: []interface{}{"X"}, + Fields: map[string]any{ + file.FieldBaseID: []any{"X"}, }, }, { @@ -231,9 +231,9 @@ func TestFileDeliveryMultipleChunks(t *testing.T) { SeqNo: 1, Version: 1, Index: fmt.Sprintf(delivery.FileDataIndexPattern, "endpoint"), - Fields: map[string]interface{}{ - file.FieldBaseID: []interface{}{"X"}, - file.FieldLast: []interface{}{true}, + Fields: map[string]any{ + file.FieldBaseID: []any{"X"}, + file.FieldLast: []any{true}, }, }, }, @@ -301,9 +301,9 @@ func TestFileDeliverySetsHeaders(t *testing.T) { SeqNo: 1, Version: 1, Index: fmt.Sprintf(delivery.FileDataIndexPattern, "endpoint"), - Fields: map[string]interface{}{ - file.FieldBaseID: []interface{}{"X"}, - file.FieldLast: []interface{}{true}, + Fields: map[string]any{ + file.FieldBaseID: []any{"X"}, + file.FieldLast: []any{true}, }, }, }, @@ -362,9 +362,9 @@ func TestFileDeliverySetsHashWhenPresent(t *testing.T) { SeqNo: 1, Version: 1, Index: fmt.Sprintf(delivery.FileDataIndexPattern, "endpoint"), - Fields: map[string]interface{}{ - file.FieldBaseID: []interface{}{"X"}, - file.FieldLast: []interface{}{true}, + Fields: map[string]any{ + file.FieldBaseID: []any{"X"}, + file.FieldLast: []any{true}, }, }, }, diff --git a/internal/pkg/api/handleOpAMP.go b/internal/pkg/api/handleOpAMP.go index e50c37e4a4..f4eddf6e44 100644 --- a/internal/pkg/api/handleOpAMP.go +++ b/internal/pkg/api/handleOpAMP.go @@ -380,15 +380,15 @@ type localMetadata struct { ID string `json:"id,omitempty"` Version string `json:"version,omitempty"` Name string `json:"name,omitempty"` - } `json:"agent,omitempty"` - } `json:"elastic,omitempty"` + } `json:"agent"` + } `json:"elastic"` Host struct { Hostname string `json:"hostname,omitempty"` Name string `json:"name,omitempty"` - } `json:"host,omitempty"` + } `json:"host"` Os struct { Platform string `json:"platform,omitempty"` - } `json:"os,omitempty"` + } `json:"os"` } func ParseEffectiveConfig(effectiveConfig *protobufs.EffectiveConfig) ([]byte, error) { @@ -398,7 +398,7 @@ func ParseEffectiveConfig(effectiveConfig *protobufs.EffectiveConfig) ([]byte, e if len(configMap.Body) != 0 { bodyBytes := configMap.Body - obj := make(map[string]interface{}) + obj := make(map[string]any) if err := yaml.Unmarshal(bodyBytes, &obj); err != nil { return nil, fmt.Errorf("unmarshal effective config failure: %w", err) } @@ -413,10 +413,10 @@ func ParseEffectiveConfig(effectiveConfig *protobufs.EffectiveConfig) ([]byte, e return nil, nil } -func redactSensitive(v interface{}) { +func redactSensitive(v any) { const redacted = "[REDACTED]" switch typed := v.(type) { - case map[string]interface{}: + case map[string]any: for key, val := range typed { if redactKey(key) { typed[key] = redacted @@ -424,7 +424,7 @@ func redactSensitive(v interface{}) { } redactSensitive(val) } - case map[interface{}]interface{}: + case map[any]any: for rawKey, val := range typed { key, ok := rawKey.(string) if ok && redactKey(key) { @@ -433,7 +433,7 @@ func redactSensitive(v interface{}) { } redactSensitive(val) } - case []interface{}: + case []any: for i := range typed { redactSensitive(typed[i]) } @@ -459,7 +459,7 @@ func redactKey(k string) bool { } // anyValueToInterface recursively converts protobufs.AnyValue to Go interface{} for JSON marshalling -func anyValueToInterface(zlog zerolog.Logger, av *protobufs.AnyValue) interface{} { +func anyValueToInterface(zlog zerolog.Logger, av *protobufs.AnyValue) any { switch v := av.GetValue().(type) { case *protobufs.AnyValue_StringValue: return v.StringValue @@ -472,13 +472,13 @@ func anyValueToInterface(zlog zerolog.Logger, av *protobufs.AnyValue) interface{ case *protobufs.AnyValue_BytesValue: return v.BytesValue case *protobufs.AnyValue_ArrayValue: - arr := make([]interface{}, 0, len(v.ArrayValue.Values)) + arr := make([]any, 0, len(v.ArrayValue.Values)) for _, av2 := range v.ArrayValue.Values { arr = append(arr, anyValueToInterface(zlog, av2)) } return arr case *protobufs.AnyValue_KvlistValue: - m := make(map[string]interface{}, len(v.KvlistValue.Values)) + m := make(map[string]any, len(v.KvlistValue.Values)) for _, kv := range v.KvlistValue.Values { if kv.Value != nil { m[kv.Key] = anyValueToInterface(zlog, kv.Value) @@ -493,7 +493,7 @@ func anyValueToInterface(zlog zerolog.Logger, av *protobufs.AnyValue) interface{ func ProtobufKVToRawMessage(zlog zerolog.Logger, kv []*protobufs.KeyValue) (json.RawMessage, error) { // 1. Build an intermediate map to represent the JSON object - data := make(map[string]interface{}, len(kv)) + data := make(map[string]any, len(kv)) for _, item := range kv { if item.Value == nil { continue diff --git a/internal/pkg/api/handleOpAMP_test.go b/internal/pkg/api/handleOpAMP_test.go index f18995f128..b991d18c45 100644 --- a/internal/pkg/api/handleOpAMP_test.go +++ b/internal/pkg/api/handleOpAMP_test.go @@ -123,7 +123,7 @@ func TestProtobufKVToRawMessage(t *testing.T) { raw, err := ProtobufKVToRawMessage(zlog, input) require.NoError(t, err) - var got map[string]interface{} + var got map[string]any require.NoError(t, json.Unmarshal(raw, &got)) require.Equal(t, "hello", got["string_key"]) @@ -131,8 +131,8 @@ func TestProtobufKVToRawMessage(t *testing.T) { require.Equal(t, 3.14, got["double_key"]) require.Equal(t, true, got["bool_key"]) require.Equal(t, base64.StdEncoding.EncodeToString([]byte("bin")), got["bytes_key"]) - require.Equal(t, []interface{}{"elem1", float64(2)}, got["array_key"]) - require.Equal(t, map[string]interface{}{"nested_string_key": "nested", "nested_int_key": float64(99)}, got["kvlist_key"]) + require.Equal(t, []any{"elem1", float64(2)}, got["array_key"]) + require.Equal(t, map[string]any{"nested_string_key": "nested", "nested_int_key": float64(99)}, got["kvlist_key"]) } func TestEnrollAgentWithAgentToServerMessage(t *testing.T) { @@ -269,7 +269,7 @@ func TestUpdateAgentWithAgentToServerMessage(t *testing.T) { require.Equal(t, "StatusRecoverableError", health.Status) configBytes := getUnexportedField(extraVal, "effectiveConfig").Bytes() - var config map[string]interface{} + var config map[string]any require.NoError(t, json.Unmarshal(configBytes, &config)) require.Equal(t, "[REDACTED]", config["password"]) require.Equal(t, float64(2), config["num"]) @@ -290,8 +290,8 @@ func pendingFromOptions(t *testing.T, opts []checkin.Option) reflect.Value { t.Helper() require.NotEmpty(t, opts) - sampleOpt := checkin.WithStatus("") - argType := reflect.TypeOf(sampleOpt).In(0) + _ = checkin.WithStatus("") + argType := reflect.TypeFor[checkin.Option]().In(0) pendingPtr := reflect.New(argType.Elem()) for _, opt := range opts { reflect.ValueOf(opt).Call([]reflect.Value{pendingPtr}) diff --git a/internal/pkg/api/handleUpload_test.go b/internal/pkg/api/handleUpload_test.go index d44b8e3ffb..b8c58d2bc9 100644 --- a/internal/pkg/api/handleUpload_test.go +++ b/internal/pkg/api/handleUpload_test.go @@ -299,7 +299,7 @@ func TestUploadBeginWritesTimestampToMeta(t *testing.T) { mock.MatchedBy(func(idx string) bool { return strings.HasPrefix(idx, ".fleet-fileds-fromhost-meta") }), // index mock.Anything, // file document ID -- generated, so can be any value mock.MatchedBy(func(body []byte) bool { - doc := make(map[string]interface{}) + doc := make(map[string]any) err := json.Unmarshal(body, &doc) require.NoError(t, err) @@ -1175,11 +1175,11 @@ func mockStartBodyWithAgent(agent string) string { func mockUploadInfoResult(bulker *itesting.MockBulk, info file.Info) { // convert info into how it's stored/returned in ES - out, _ := json.Marshal(map[string]interface{}{ + out, _ := json.Marshal(map[string]any{ "action_id": info.ActionID, "agent_id": info.AgentID, "src": info.Source, - "file": map[string]interface{}{ + "file": map[string]any{ "size": info.Total, "ChunkSize": info.ChunkSize, "Status": info.Status, @@ -1213,11 +1213,11 @@ func mockChunkResult(bulker *itesting.MockBulk, chunks []file.ChunkInfo) string for i, chunk := range chunks { results[i] = es.HitT{ ID: chunk.BID + "." + strconv.Itoa(chunk.Pos), - Fields: map[string]interface{}{ - file.FieldBaseID: []interface{}{chunk.BID}, - file.FieldSHA2: []interface{}{chunk.SHA2}, - file.FieldLast: []interface{}{chunk.Last}, - "size": []interface{}{chunk.Size}, + Fields: map[string]any{ + file.FieldBaseID: []any{chunk.BID}, + file.FieldSHA2: []any{chunk.SHA2}, + file.FieldLast: []any{chunk.Last}, + "size": []any{chunk.Size}, }, } } diff --git a/internal/pkg/api/metrics_integration_test.go b/internal/pkg/api/metrics_integration_test.go index df090d9b16..8e0e8d2982 100644 --- a/internal/pkg/api/metrics_integration_test.go +++ b/internal/pkg/api/metrics_integration_test.go @@ -7,7 +7,6 @@ package api import ( - "context" "net/http" "testing" @@ -29,8 +28,7 @@ func TestMetricsEndpoints(t *testing.T) { Port: 8080, }, } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) srv, err := InitMetrics(ctx, cfg, bi, nil) diff --git a/internal/pkg/api/openapi_spec_test.go b/internal/pkg/api/openapi_spec_test.go index 9f74b69cae..90196fe7a8 100644 --- a/internal/pkg/api/openapi_spec_test.go +++ b/internal/pkg/api/openapi_spec_test.go @@ -75,7 +75,7 @@ func TestAckRequest(t *testing.T) { assert.NotNil(t, inputEvent.Error) // Sanity check embedded *json.RawMessage here - var obj map[string]interface{} + var obj map[string]any err = json.Unmarshal(inputEvent.ActionData, &obj) require.NoError(t, err) v, ok := obj["key1"] @@ -162,7 +162,7 @@ func validateSerialization(t *testing.T, action Action) { b, err := json.Marshal(action) assert.NoError(t, err) - var m map[string]interface{} + var m map[string]any err = json.Unmarshal(b, &m) assert.NoError(t, err) @@ -175,7 +175,7 @@ func validateSerialization(t *testing.T, action Action) { if action.Signed == nil { assert.False(t, ok) } else { - sm, ok := signed.(map[string]interface{}) + sm, ok := signed.(map[string]any) assert.True(t, ok) assert.Equal(t, action.Signed.Data, sm["data"]) assert.Equal(t, action.Signed.Signature, sm["signature"]) @@ -228,7 +228,6 @@ func Test_UpgradeDetailsMetadata_Downloading(t *testing.T) { }} for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { meta, err := tc.md.AsUpgradeMetadataDownloading() if tc.err == nil { @@ -286,7 +285,6 @@ func Test_UpgradeDetailsMetadata_Failed(t *testing.T) { }} for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { meta, err := tc.md.AsUpgradeMetadataFailed() if tc.err == nil { @@ -342,7 +340,6 @@ func Test_UpgradeDetailsMetadata_Scheduled(t *testing.T) { }} for _, tc := range tests { - tc := tc t.Run(tc.name, func(t *testing.T) { meta, err := tc.md.AsUpgradeMetadataScheduled() if tc.err == nil { @@ -385,7 +382,6 @@ func TestUpgradeDetailsSerialization(t *testing.T) { TargetVersion: "1.2.3", }} for _, d := range details { - d := d t.Run(string(d.State), func(t *testing.T) { p, err := json.Marshal(d) require.NoError(t, err) diff --git a/internal/pkg/api/server_test.go b/internal/pkg/api/server_test.go index 80767317b7..939dde47e0 100644 --- a/internal/pkg/api/server_test.go +++ b/internal/pkg/api/server_test.go @@ -48,14 +48,12 @@ func Test_server_Run(t *testing.T) { started := make(chan struct{}, 1) errCh := make(chan error, 1) var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { started <- struct{}{} if err := srv.Run(ctx); err != nil && !errors.Is(err, context.Canceled) { errCh <- err } - wg.Done() - }() + }) select { // if the goroutine has started within 500ms something is wrong, test has timed out case <-started: @@ -140,14 +138,12 @@ func Test_server_ClientCert(t *testing.T) { started := make(chan struct{}, 1) errCh := make(chan error, 1) var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { started <- struct{}{} if err := srv.Run(ctx); err != nil && !errors.Is(err, context.Canceled) { errCh <- err } - wg.Done() - }() + }) select { // make sure goroutine starts within 500ms case <-started: @@ -212,14 +208,12 @@ func Test_server_ClientCert(t *testing.T) { started := make(chan struct{}, 1) errCh := make(chan error, 1) var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { started <- struct{}{} if err := srv.Run(ctx); err != nil && !errors.Is(err, context.Canceled) { errCh <- err } - wg.Done() - }() + }) select { case <-started: @@ -285,14 +279,12 @@ func Test_server_ClientCert(t *testing.T) { started := make(chan struct{}, 1) errCh := make(chan error, 1) var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { started <- struct{}{} if err := srv.Run(ctx); err != nil && !errors.Is(err, context.Canceled) { errCh <- err } - wg.Done() - }() + }) select { case <-started: @@ -367,14 +359,12 @@ key: %s`, started := make(chan struct{}, 1) errCh := make(chan error, 1) var wg sync.WaitGroup - wg.Add(1) - go func() { + wg.Go(func() { started <- struct{}{} if err := srv.Run(ctx); err != nil && !errors.Is(err, context.Canceled) { errCh <- err } - wg.Done() - }() + }) select { case <-started: diff --git a/internal/pkg/apikey/create.go b/internal/pkg/apikey/create.go index 5238c27924..9b502b5926 100644 --- a/internal/pkg/apikey/create.go +++ b/internal/pkg/apikey/create.go @@ -17,12 +17,12 @@ import ( ) // Create generates a new APIKey in Elasticsearch using the given client. -func Create(ctx context.Context, client *elasticsearch.Client, name, ttl, refresh string, roles []byte, meta interface{}) (*APIKey, error) { +func Create(ctx context.Context, client *elasticsearch.Client, name, ttl, refresh string, roles []byte, meta any) (*APIKey, error) { payload := struct { Name string `json:"name,omitempty"` Expiration string `json:"expiration,omitempty"` Roles json.RawMessage `json:"role_descriptors,omitempty"` - Metadata interface{} `json:"metadata"` + Metadata any `json:"metadata"` }{ Name: name, Expiration: ttl, diff --git a/internal/pkg/bulk/block.go b/internal/pkg/bulk/block.go index 2650e513d7..139a6dcb98 100644 --- a/internal/pkg/bulk/block.go +++ b/internal/pkg/bulk/block.go @@ -79,5 +79,5 @@ func (blk *bulkT) reset() { type respT struct { err error idx int32 - data interface{} + data any } diff --git a/internal/pkg/bulk/bulk_integration_test.go b/internal/pkg/bulk/bulk_integration_test.go index f6ab18d16c..0934619ed2 100644 --- a/internal/pkg/bulk/bulk_integration_test.go +++ b/internal/pkg/bulk/bulk_integration_test.go @@ -22,8 +22,7 @@ import ( ) func TestBulkCreate(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() index, bulker := SetupIndexWithBulk(ctx, t, testPolicy, WithFlushThresholdCount(1)) @@ -124,8 +123,7 @@ func TestBulkCreate(t *testing.T) { } func TestBulkCreateBody(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() index, bulker := SetupIndexWithBulk(ctx, t, testPolicy, WithFlushThresholdCount(1)) @@ -177,8 +175,7 @@ func TestBulkCreateBody(t *testing.T) { } func TestBulkIndex(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker := SetupIndexWithBulk(ctx, t, testPolicy, WithFlushThresholdCount(1)) @@ -201,8 +198,7 @@ func TestBulkIndex(t *testing.T) { } func TestBulkUpdate(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker := SetupIndexWithBulk(ctx, t, testPolicy) @@ -240,8 +236,7 @@ func TestBulkUpdate(t *testing.T) { } func TestBulkSearch(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker := SetupIndexWithBulk(ctx, t, testPolicy) @@ -283,8 +278,7 @@ func TestBulkSearch(t *testing.T) { } func TestBulkSearchWithIgnoreUnavailable(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) _, bulker := SetupIndexWithBulk(ctx, t, testPolicy) @@ -306,8 +300,7 @@ func TestBulkSearchWithIgnoreUnavailable(t *testing.T) { } func TestBulkDelete(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker := SetupIndexWithBulk(ctx, t, testPolicy) @@ -353,7 +346,7 @@ func benchmarkCreate(n int, b *testing.B) { ch := make(chan error, n) var wait sync.WaitGroup wait.Add(n) - for i := 0; i < n; i++ { + for range n { go func() { defer wait.Done() @@ -415,7 +408,7 @@ func benchmarkCRUD(n int, b *testing.B) { b.ResetTimer() b.ReportAllocs() - for i := 0; i < n; i++ { + for range n { go func() { defer wait.Done() diff --git a/internal/pkg/bulk/bulk_remote_output_test.go b/internal/pkg/bulk/bulk_remote_output_test.go index 2a6c34a0d9..cc92ea2483 100644 --- a/internal/pkg/bulk/bulk_remote_output_test.go +++ b/internal/pkg/bulk/bulk_remote_output_test.go @@ -7,7 +7,6 @@ package bulk import ( - "context" "testing" "github.com/rs/zerolog" @@ -19,14 +18,14 @@ import ( func Test_hasChangedAndUpdateRemoteOutputConfig(t *testing.T) { testcases := []struct { name string - cfg map[string]interface{} - newCfg map[string]interface{} + cfg map[string]any + newCfg map[string]any changed bool }{ { name: "initial nil", cfg: nil, - newCfg: map[string]interface{}{ + newCfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token1", @@ -35,12 +34,12 @@ func Test_hasChangedAndUpdateRemoteOutputConfig(t *testing.T) { }, { name: "no changes", - cfg: map[string]interface{}{ + cfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token1", }, - newCfg: map[string]interface{}{ + newCfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token1", @@ -49,12 +48,12 @@ func Test_hasChangedAndUpdateRemoteOutputConfig(t *testing.T) { }, { name: "change to service token", - cfg: map[string]interface{}{ + cfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token1", }, - newCfg: map[string]interface{}{ + newCfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token2", @@ -63,13 +62,13 @@ func Test_hasChangedAndUpdateRemoteOutputConfig(t *testing.T) { }, { name: "change to advanced config", - cfg: map[string]interface{}{ + cfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token1", "server.memory_limit": "4", }, - newCfg: map[string]interface{}{ + newCfg: map[string]any{ "type": "remote_elasticsearch", "hosts": []string{"https://remote-es:443"}, "service_token": "token1", @@ -91,13 +90,12 @@ func Test_hasChangedAndUpdateRemoteOutputConfig(t *testing.T) { } func Test_CreateAndGetBulkerNew(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() bulker := NewBulker(nil, nil) - outputMap := make(map[string]map[string]interface{}) - outputMap["remote1"] = map[string]interface{}{ + outputMap := make(map[string]map[string]any) + outputMap["remote1"] = map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "token1", } newBulker, hasChanged, err := bulker.CreateAndGetBulker(ctx, zerolog.Nop(), "remote1", outputMap) @@ -107,15 +105,14 @@ func Test_CreateAndGetBulkerNew(t *testing.T) { } func Test_CreateAndGetBulkerExisting(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() bulker := NewBulker(nil, nil) outputBulker := NewBulker(nil, nil) bulker.bulkerMap["remote1"] = outputBulker - outputMap := make(map[string]map[string]interface{}) - cfg := map[string]interface{}{ + outputMap := make(map[string]map[string]any) + cfg := map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "token1", } bulker.remoteOutputConfigMap["remote1"] = cfg @@ -127,20 +124,19 @@ func Test_CreateAndGetBulkerExisting(t *testing.T) { } func Test_CreateAndGetBulkerChanged(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() bulker := NewBulker(nil, nil) outputBulker := NewBulker(nil, nil) bulker.bulkerMap["remote1"] = outputBulker - outputMap := make(map[string]map[string]interface{}) - bulker.remoteOutputConfigMap["remote1"] = map[string]interface{}{ + outputMap := make(map[string]map[string]any) + bulker.remoteOutputConfigMap["remote1"] = map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "token1", } - outputMap["remote1"] = map[string]interface{}{ + outputMap["remote1"] = map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "token2", } cancelFnCalled := false @@ -154,13 +150,12 @@ func Test_CreateAndGetBulkerChanged(t *testing.T) { func Benchmark_CreateAndGetBulker(b *testing.B) { b.Skip("Crashes on remote runner") - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := b.Context() log := zerolog.Nop() outputMap := map[string]map[string]any{ "remote1": map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "token1", }, } @@ -196,7 +191,7 @@ func Benchmark_CreateAndGetBulker(b *testing.B) { bulker.bulkerMap["remote1"] = outputBulker bulker.remoteOutputConfigMap["remote1"] = map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "wrong token", } b.StartTimer() diff --git a/internal/pkg/bulk/bulk_test.go b/internal/pkg/bulk/bulk_test.go index 5e07226354..37aa0658c1 100644 --- a/internal/pkg/bulk/bulk_test.go +++ b/internal/pkg/bulk/bulk_test.go @@ -257,12 +257,10 @@ func TestCancelCtx(t *testing.T) { cancelF() var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { test.test(t, ctx) - }() + }) wg.Wait() }) @@ -275,10 +273,10 @@ func TestCancelCtxChildBulker(t *testing.T) { ctx, cancelF := context.WithCancel(context.Background()) - outputMap := make(map[string]map[string]interface{}) - outputMap["remote"] = map[string]interface{}{ + outputMap := make(map[string]map[string]any) + outputMap["remote"] = map[string]any{ "type": "remote_elasticsearch", - "hosts": []interface{}{"https://remote-es:443"}, + "hosts": []any{"https://remote-es:443"}, "service_token": "token1", } @@ -289,16 +287,14 @@ func TestCancelCtxChildBulker(t *testing.T) { } var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { _, err := childBulker.APIKeyAuth(ctx, apikey.APIKey{}) if !errors.Is(err, context.Canceled) { t.Error("Expected context cancel err: ", err) } - }() + }) wg.Wait() } @@ -313,13 +309,11 @@ func benchmarkMockBulk(b *testing.B, samples [][]byte) { bulker := NewBulker(mock, nil, WithFlushThresholdCount(n)) var waitBulker sync.WaitGroup - waitBulker.Add(1) - go func() { - defer waitBulker.Done() + waitBulker.Go(func() { if err := bulker.Run(ctx); !errors.Is(err, context.Canceled) { b.Error(err) } - }() + }) fieldUpdate := UpdateFields{"kwval": "funkycoldmedina"} fieldData, err := fieldUpdate.Marshal() @@ -334,7 +328,7 @@ func benchmarkMockBulk(b *testing.B, samples [][]byte) { b.ResetTimer() b.ReportAllocs() - for i := 0; i < n; i++ { + for i := range n { go func(sampleData []byte) { defer wait.Done() diff --git a/internal/pkg/bulk/engine.go b/internal/pkg/bulk/engine.go index c999ffe453..e0fd248168 100644 --- a/internal/pkg/bulk/engine.go +++ b/internal/pkg/bulk/engine.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "reflect" "strings" "sync" @@ -64,7 +65,7 @@ type Bulk interface { MDelete(ctx context.Context, ops []MultiOp, opts ...Opt) ([]BulkIndexerResponseItem, error) // APIKey operations - APIKeyCreate(ctx context.Context, name, ttl string, roles []byte, meta interface{}) (*APIKey, error) + APIKeyCreate(ctx context.Context, name, ttl string, roles []byte, meta any) (*APIKey, error) APIKeyRead(ctx context.Context, id string, withOwner bool) (*APIKeyMetadata, error) APIKeyAuth(ctx context.Context, key APIKey) (*SecurityInfo, error) APIKeyInvalidate(ctx context.Context, ids ...string) error @@ -73,11 +74,11 @@ type Bulk interface { // Accessor used to talk to elastic search direcly bypassing bulk engine Client() *elasticsearch.Client - CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, outputName string, outputMap map[string]map[string]interface{}) (Bulk, bool, error) + CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, outputName string, outputMap map[string]map[string]any) (Bulk, bool, error) GetBulker(outputName string) Bulk GetBulkerMap() map[string]Bulk CancelFn() context.CancelFunc - RemoteOutputConfigChanged(zlog zerolog.Logger, name string, newCfg map[string]interface{}) bool + RemoteOutputConfigChanged(zlog zerolog.Logger, name string, newCfg map[string]any) bool ReadSecrets(ctx context.Context, secretIds []string) (map[string]string, error) } @@ -93,7 +94,7 @@ type Bulker struct { tracer *apm.Tracer cancelFn context.CancelFunc - remoteOutputConfigMap map[string]map[string]interface{} + remoteOutputConfigMap map[string]map[string]any bulkerMap map[string]Bulk remoteOutputMutex sync.RWMutex } @@ -113,7 +114,7 @@ func NewBulker(es esapi.Transport, tracer *apm.Tracer, opts ...BulkOpt) *Bulker bopts := parseBulkOpts(opts...) - poolFunc := func() interface{} { + poolFunc := func() any { return &bulkT{ch: make(chan respT, 1)} } @@ -124,7 +125,7 @@ func NewBulker(es esapi.Transport, tracer *apm.Tracer, opts ...BulkOpt) *Bulker blkPool: sync.Pool{New: poolFunc}, apikeyLimit: semaphore.NewWeighted(int64(bopts.apikeyMaxParallel)), tracer: tracer, - remoteOutputConfigMap: make(map[string]map[string]interface{}), + remoteOutputConfigMap: make(map[string]map[string]any), // remote ES bulkers bulkerMap: make(map[string]Bulk), } @@ -140,9 +141,7 @@ func (b *Bulker) GetBulker(outputName string) Bulk { func (b *Bulker) GetBulkerMap() map[string]Bulk { mp := make(map[string]Bulk) b.remoteOutputMutex.RLock() - for k, v := range b.bulkerMap { - mp[k] = v - } + maps.Copy(mp, b.bulkerMap) b.remoteOutputMutex.RUnlock() return mp } @@ -163,7 +162,7 @@ func (b *Bulker) updateBulkerMap(outputName string, newBulker *Bulker) { // if bulker exists for output, check if config changed // if not changed, return the existing bulker // if changed, stop the existing bulker and create a new one -func (b *Bulker) CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, outputName string, outputMap map[string]map[string]interface{}) (Bulk, bool, error) { +func (b *Bulker) CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, outputName string, outputMap map[string]map[string]any) (Bulk, bool, error) { hasConfigChanged := b.hasChangedAndUpdateRemoteOutputConfig(zlog, outputName, outputMap[outputName]) b.remoteOutputMutex.RLock() bulker := b.bulkerMap[outputName] @@ -213,7 +212,7 @@ func (b *Bulker) CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, ou var newESClient = es.NewClient -func (b *Bulker) createRemoteEsClient(ctx context.Context, outputName string, outputMap map[string]map[string]interface{}) (*elasticsearch.Client, error) { +func (b *Bulker) createRemoteEsClient(ctx context.Context, outputName string, outputMap map[string]map[string]any) (*elasticsearch.Client, error) { var esOutput config.Elasticsearch esConfig, err := ucfg.NewFrom(outputMap[outputName], config.DefaultOptions...) if err != nil { @@ -259,7 +258,7 @@ func (b *Bulker) Client() *elasticsearch.Client { return client } -func (b *Bulker) RemoteOutputConfigChanged(zlog zerolog.Logger, name string, newCfg map[string]interface{}) bool { +func (b *Bulker) RemoteOutputConfigChanged(zlog zerolog.Logger, name string, newCfg map[string]any) bool { b.remoteOutputMutex.RLock() defer b.remoteOutputMutex.RUnlock() curCfg := b.remoteOutputConfigMap[name] @@ -274,16 +273,14 @@ func (b *Bulker) RemoteOutputConfigChanged(zlog zerolog.Logger, name string, new } // check if remote output cfg changed -func (b *Bulker) hasChangedAndUpdateRemoteOutputConfig(zlog zerolog.Logger, name string, newCfg map[string]interface{}) bool { +func (b *Bulker) hasChangedAndUpdateRemoteOutputConfig(zlog zerolog.Logger, name string, newCfg map[string]any) bool { hasChanged := b.RemoteOutputConfigChanged(zlog, name, newCfg) if hasChanged { zlog.Debug().Str("name", name).Msg("remote output configuration has changed") } - newCfgCopy := make(map[string]interface{}) - for k, v := range newCfg { - newCfgCopy[k] = v - } + newCfgCopy := make(map[string]any) + maps.Copy(newCfgCopy, newCfg) b.remoteOutputMutex.Lock() b.remoteOutputConfigMap[name] = newCfgCopy b.remoteOutputMutex.Unlock() diff --git a/internal/pkg/bulk/helpers.go b/internal/pkg/bulk/helpers.go index 89a9e6c46b..0681087c5e 100644 --- a/internal/pkg/bulk/helpers.go +++ b/internal/pkg/bulk/helpers.go @@ -14,11 +14,11 @@ import ( "github.com/rs/zerolog" ) -type UpdateFields map[string]interface{} +type UpdateFields map[string]any func (u UpdateFields) Marshal() ([]byte, error) { doc := struct { - Doc map[string]interface{} `json:"doc"` + Doc map[string]any `json:"doc"` }{ u, } diff --git a/internal/pkg/bulk/opApiKey.go b/internal/pkg/bulk/opApiKey.go index ca3a50d16e..431adef8c4 100644 --- a/internal/pkg/bulk/opApiKey.go +++ b/internal/pkg/bulk/opApiKey.go @@ -51,7 +51,7 @@ func (b *Bulker) APIKeyAuth(ctx context.Context, key APIKey) (*SecurityInfo, err return key.Authenticate(ctx, b.Client()) } -func (b *Bulker) APIKeyCreate(ctx context.Context, name, ttl string, roles []byte, meta interface{}) (*APIKey, error) { +func (b *Bulker) APIKeyCreate(ctx context.Context, name, ttl string, roles []byte, meta any) (*APIKey, error) { span, ctx := apm.StartSpan(ctx, "createAPIKey", "auth") defer span.End() if err := b.apikeyLimit.Acquire(ctx, 1); err != nil { @@ -122,7 +122,7 @@ func (b *Bulker) flushUpdateAPIKey(ctx context.Context, queue queueT) error { // merge ids for n := queue.head; n != nil; n = n.next { content := n.buf.Bytes() - metaMap := make(map[string]interface{}) + metaMap := make(map[string]any) dec := json.NewDecoder(bytes.NewReader(content)) if err := dec.Decode(&metaMap); err != nil { zerolog.Ctx(ctx).Error(). @@ -190,12 +190,9 @@ func (b *Bulker) flushUpdateAPIKey(ctx context.Context, queue queueT) error { batches := int(math.Ceil(float64(len(ids)) / float64(idsPerBatch))) // batch ids into batches of meaningful size - for batch := 0; batch < batches; batch++ { + for batch := range batches { // guard against indexing out of range - to := (batch + 1) * idsPerBatch - if to > len(ids) { - to = len(ids) - } + to := min((batch+1)*idsPerBatch, len(ids)) // handle ids in batch, we put them into single request // and assign response index to the id so we can notify caller diff --git a/internal/pkg/bulk/opBulk.go b/internal/pkg/bulk/opBulk.go index 9f28d51037..52c9617aef 100644 --- a/internal/pkg/bulk/opBulk.go +++ b/internal/pkg/bulk/opBulk.go @@ -170,10 +170,7 @@ func (b *Bulker) flushBulk(ctx context.Context, queue queueT) error { const kRoughEstimatePerItem = 200 - bufSz := queue.cnt * kRoughEstimatePerItem - if bufSz < queue.pending { - bufSz = queue.pending - } + bufSz := max(queue.cnt*kRoughEstimatePerItem, queue.pending) var buf bytes.Buffer buf.Grow(bufSz) diff --git a/internal/pkg/bulk/opMulti.go b/internal/pkg/bulk/opMulti.go index 53ada5db49..6a02fc8880 100644 --- a/internal/pkg/bulk/opMulti.go +++ b/internal/pkg/bulk/opMulti.go @@ -96,7 +96,7 @@ func (b *Bulker) multiWaitBulkOp(ctx context.Context, action actionT, ops []Mult var lastErr error items := make([]BulkIndexerResponseItem, len(ops)) - for i := 0; i < len(ops); i++ { + for range ops { select { case r := <-ch: if r.err != nil { diff --git a/internal/pkg/bulk/opMulti_integration_test.go b/internal/pkg/bulk/opMulti_integration_test.go index 33e7ae3ee9..a6d6bf0d1c 100644 --- a/internal/pkg/bulk/opMulti_integration_test.go +++ b/internal/pkg/bulk/opMulti_integration_test.go @@ -26,7 +26,7 @@ func benchmarkMultiUpdate(n int, b *testing.B) { // Create N samples var ops []MultiOp - for i := 0; i < n; i++ { + for range n { sample := NewRandomSample() ops = append(ops, MultiOp{ Index: index, diff --git a/internal/pkg/bulk/opRead.go b/internal/pkg/bulk/opRead.go index 657e7f0855..82c7f4f7da 100644 --- a/internal/pkg/bulk/opRead.go +++ b/internal/pkg/bulk/opRead.go @@ -68,10 +68,7 @@ func (b *Bulker) flushRead(ctx context.Context, queue queueT) error { const kRoughEstimatePerItem = 256 - bufSz := queue.cnt * kRoughEstimatePerItem - if bufSz < queue.pending+len(rSuffix) { - bufSz = queue.pending + len(rSuffix) - } + bufSz := max(queue.cnt*kRoughEstimatePerItem, queue.pending+len(rSuffix)) buf := bytes.NewBufferString(rPrefix) buf.Grow(bufSz) diff --git a/internal/pkg/bulk/opSearch.go b/internal/pkg/bulk/opSearch.go index 14d5252e99..e1f42d3cb6 100644 --- a/internal/pkg/bulk/opSearch.go +++ b/internal/pkg/bulk/opSearch.go @@ -125,10 +125,7 @@ func (b *Bulker) flushSearch(ctx context.Context, queue queueT) error { const kRoughEstimatePerItem = 256 - bufSz := queue.cnt * kRoughEstimatePerItem - if bufSz < queue.pending { - bufSz = queue.pending - } + bufSz := max(queue.cnt*kRoughEstimatePerItem, queue.pending) var buf bytes.Buffer buf.Grow(bufSz) diff --git a/internal/pkg/cache/impl.go b/internal/pkg/cache/impl.go index ef7a70d8a6..70eaeb4bf2 100644 --- a/internal/pkg/cache/impl.go +++ b/internal/pkg/cache/impl.go @@ -9,8 +9,8 @@ import ( ) type Cacher interface { - Get(key interface{}) (interface{}, bool) - Set(key, value interface{}, cost int64) bool - SetWithTTL(key, value interface{}, cost int64, ttl time.Duration) bool + Get(key any) (any, bool) + Set(key, value any, cost int64) bool + SetWithTTL(key, value any, cost int64, ttl time.Duration) bool Close() } diff --git a/internal/pkg/cache/impl_integration.go b/internal/pkg/cache/impl_integration.go index 6e778b9de5..2491b9d002 100644 --- a/internal/pkg/cache/impl_integration.go +++ b/internal/pkg/cache/impl_integration.go @@ -18,15 +18,15 @@ func newCache(_ config.Cache) (Cacher, error) { type NoCache struct{} -func (c *NoCache) Get(_ interface{}) (interface{}, bool) { +func (c *NoCache) Get(_ any) (any, bool) { return nil, false } -func (c *NoCache) Set(_ interface{}, _ interface{}, _ int64) bool { +func (c *NoCache) Set(_ any, _ any, _ int64) bool { return true } -func (c *NoCache) SetWithTTL(_, _ interface{}, _ int64, _ time.Duration) bool { +func (c *NoCache) SetWithTTL(_, _ any, _ int64, _ time.Duration) bool { return true } diff --git a/internal/pkg/checkin/bulk.go b/internal/pkg/checkin/bulk.go index d5a4a67f58..d995aabfe9 100644 --- a/internal/pkg/checkin/bulk.go +++ b/internal/pkg/checkin/bulk.go @@ -384,7 +384,7 @@ func toUpdateBody(now string, pending pendingT) ([]byte, error) { // If the agent version is not empty it needs to be updated // Assuming the agent can by upgraded keeping the same id, but incrementing the version if pending.extra.ver != "" { - fields[dl.FieldAgent] = map[string]interface{}{ + fields[dl.FieldAgent] = map[string]any{ dl.FieldAgentVersion: pending.extra.ver, } } diff --git a/internal/pkg/checkin/bulk_test.go b/internal/pkg/checkin/bulk_test.go index d0cb344d54..46fec3a6f0 100644 --- a/internal/pkg/checkin/bulk_test.go +++ b/internal/pkg/checkin/bulk_test.go @@ -212,7 +212,7 @@ func benchmarkBulk(n int, b *testing.B) { bc := NewBulk(mockBulk) ids := make([]string, 0, n) - for i := 0; i < n; i++ { + for range n { id := xid.New().String() ids = append(ids, id) } @@ -236,7 +236,7 @@ func benchmarkFlush(n int, b *testing.B) { bc := NewBulk(mockBulk) ids := make([]string, 0, n) - for i := 0; i < n; i++ { + for range n { id := xid.New().String() ids = append(ids, id) } diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index bd50d02c4b..f93d6b6884 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -308,7 +308,7 @@ func (f *Flag) Set(s string) error { } // Get returns the Config object used to store values. -func (f *Flag) Get() interface{} { +func (f *Flag) Get() any { return f.Config() } diff --git a/internal/pkg/config/output.go b/internal/pkg/config/output.go index 99726904bb..d10c9eff17 100644 --- a/internal/pkg/config/output.go +++ b/internal/pkg/config/output.go @@ -35,8 +35,8 @@ var hasScheme = regexp.MustCompile(`^([a-z][a-z0-9+\-.]*)://`) // Output is the output configuration to elasticsearch. type Output struct { - Elasticsearch Elasticsearch `config:"elasticsearch"` - Extra map[string]interface{} `config:",inline"` + Elasticsearch Elasticsearch `config:"elasticsearch"` + Extra map[string]any `config:",inline"` } // Elasticsearch is the configuration for elasticsearch. diff --git a/internal/pkg/config/output_test.go b/internal/pkg/config/output_test.go index 26c31701fa..3881eda28e 100644 --- a/internal/pkg/config/output_test.go +++ b/internal/pkg/config/output_test.go @@ -8,7 +8,6 @@ package config import ( - "context" "crypto/tls" "net" "net/http" @@ -392,8 +391,7 @@ func Test_Elasticsearch_DiagRequests(t *testing.T) { w.WriteHeader(http.StatusOK) })) defer srv.Close() - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() t.Run("scheme included", func(t *testing.T) { es := &Elasticsearch{} diff --git a/internal/pkg/danger/buf_test.go b/internal/pkg/danger/buf_test.go index d0618aea12..7c96b853b1 100644 --- a/internal/pkg/danger/buf_test.go +++ b/internal/pkg/danger/buf_test.go @@ -23,7 +23,7 @@ func TestBufGrowWhileWrite(t *testing.T) { ptrs := make([][]byte, 0, nBytes) var dst Buf - for i := 0; i < nBytes; i++ { + for i := range nBytes { if err = dst.WriteByte(src[i]); err != nil { t.Fatal(err) diff --git a/internal/pkg/dl/action_results_integration_test.go b/internal/pkg/dl/action_results_integration_test.go index f1dd732f03..f79ce69d09 100644 --- a/internal/pkg/dl/action_results_integration_test.go +++ b/internal/pkg/dl/action_results_integration_test.go @@ -31,8 +31,8 @@ func createRandomActionResults() ([]model.ActionResult, error) { results := make([]model.ActionResult, sz) - for i := 0; i < sz; i++ { - payload := map[string]interface{}{ + for i := range sz { + payload := map[string]any{ uuid.Must(uuid.NewV4()).String(): uuid.Must(uuid.NewV4()).String(), } diff --git a/internal/pkg/dl/actions.go b/internal/pkg/dl/actions.go index b1752f1b66..fa632aaefd 100644 --- a/internal/pkg/dl/actions.go +++ b/internal/pkg/dl/actions.go @@ -104,14 +104,14 @@ func createBaseActionsQuery() (tmpl *dsl.Tmpl, root, filter *dsl.Node) { func FindAction(ctx context.Context, bulker bulk.Bulk, id string, opts ...Option) ([]model.Action, error) { o := newOption(FleetActions, opts...) - return findActions(ctx, bulker, QueryAction, o.indexName, map[string]interface{}{ + return findActions(ctx, bulker, QueryAction, o.indexName, map[string]any{ FieldActionID: id, }, nil) } func FindAgentActions(ctx context.Context, bulker bulk.Bulk, minSeqNo, maxSeqNo sqn.SeqNo, agentID string) ([]model.Action, error) { const index = FleetActions - params := map[string]interface{}{ + params := map[string]any{ FieldSeqNo: minSeqNo.Value(), FieldMaxSeqNo: maxSeqNo.Value(), FieldExpiration: time.Now().UTC().Format(time.RFC3339), @@ -127,7 +127,7 @@ func FindAgentActions(ctx context.Context, bulker bulk.Bulk, minSeqNo, maxSeqNo } func DeleteExpiredForIndex(ctx context.Context, index string, bulker bulk.Bulk, cleanupIntervalAfterExpired string) (int64, error) { - params := map[string]interface{}{ + params := map[string]any{ FieldExpiration: "now-" + cleanupIntervalAfterExpired, } @@ -166,7 +166,7 @@ func DeleteExpiredForIndex(ctx context.Context, index string, bulker bulk.Bulk, } func FindExpiredActionsHitsForIndex(ctx context.Context, index string, bulker bulk.Bulk, expiredBefore time.Time, size int) ([]es.HitT, error) { - params := map[string]interface{}{ + params := map[string]any{ FieldExpiration: expiredBefore.UTC().Format(time.RFC3339), FieldSize: size, } @@ -181,7 +181,7 @@ func FindExpiredActionsHitsForIndex(ctx context.Context, index string, bulker bu return nil, nil } -func findActionsHits(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, params map[string]interface{}, seqNos []int64) (*es.HitsT, error) { +func findActionsHits(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, params map[string]any, seqNos []int64) (*es.HitsT, error) { var ops []bulk.Opt if len(seqNos) > 0 { ops = append(ops, bulk.WithWaitForCheckpoints(seqNos)) @@ -197,7 +197,7 @@ func findActionsHits(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, inde return res, nil } -func findActions(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, params map[string]interface{}, seqNos []int64) ([]model.Action, error) { +func findActions(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, params map[string]any, seqNos []int64) ([]model.Action, error) { res, err := findActionsHits(ctx, bulker, tmpl, index, params, seqNos) if err != nil || res == nil { return nil, err diff --git a/internal/pkg/dl/actions_integration_test.go b/internal/pkg/dl/actions_integration_test.go index 11bb1587dc..aed5f2e9aa 100644 --- a/internal/pkg/dl/actions_integration_test.go +++ b/internal/pkg/dl/actions_integration_test.go @@ -7,7 +7,6 @@ package dl import ( - "context" "testing" "time" @@ -19,8 +18,7 @@ import ( ) func TestSearchActionsQuery(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) now := time.Now().UTC() @@ -37,7 +35,7 @@ func TestSearchActionsQuery(t *testing.T) { t.Run("all agents actions", func(t *testing.T) { - foundActions, err := findActions(ctx, bulker, QueryAllAgentActions, index, map[string]interface{}{ + foundActions, err := findActions(ctx, bulker, QueryAllAgentActions, index, map[string]any{ FieldSeqNo: minSeqNo, FieldMaxSeqNo: maxSeqNo, FieldExpiration: now, diff --git a/internal/pkg/dl/agent.go b/internal/pkg/dl/agent.go index 04487ff3a7..c14d682d55 100644 --- a/internal/pkg/dl/agent.go +++ b/internal/pkg/dl/agent.go @@ -39,7 +39,7 @@ func prepareAgentFindByEnrollmentID() *dsl.Tmpl { } func prepareAgentFindByField(field string) *dsl.Tmpl { - return prepareFindByField(field, map[string]interface{}{"version": true}) + return prepareFindByField(field, map[string]any{"version": true}) } func GetAgent(ctx context.Context, bulker bulk.Bulk, agentID string, opt ...Option) (model.Agent, error) { @@ -65,7 +65,7 @@ func GetAgent(ctx context.Context, bulker bulk.Bulk, agentID string, opt ...Opti return agent, err } -func FindAgent(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, name string, v interface{}, opt ...Option) (model.Agent, error) { +func FindAgent(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, name string, v any, opt ...Option) (model.Agent, error) { o := newOption(FleetAgents, opt...) res, err := SearchWithOneParam(ctx, bulker, tmpl, o.indexName, name, v) if err != nil { diff --git a/internal/pkg/dl/artifact.go b/internal/pkg/dl/artifact.go index abb1729a37..9dca5f3e14 100644 --- a/internal/pkg/dl/artifact.go +++ b/internal/pkg/dl/artifact.go @@ -31,7 +31,7 @@ func prepareQueryArtifact() *dsl.Tmpl { func FindArtifact(ctx context.Context, bulker bulk.Bulk, ident, sha2 string) (*model.Artifact, error) { - params := map[string]interface{}{ + params := map[string]any{ FieldDecodedSha256: sha2, FieldIdentifier: ident, } diff --git a/internal/pkg/dl/enrollment_api_key_integration_test.go b/internal/pkg/dl/enrollment_api_key_integration_test.go index 6f3331fba0..6e7edec69f 100644 --- a/internal/pkg/dl/enrollment_api_key_integration_test.go +++ b/internal/pkg/dl/enrollment_api_key_integration_test.go @@ -123,7 +123,7 @@ func TestSearchEnrollmentAPIKeyByPolicyIDWithInactiveIDs(t *testing.T) { if err != nil { t.Fatalf("unable to store enrollment key: %v", err) } - for i := 0; i < 10; i++ { + for range 10 { _, err = storeRandomEnrollmentAPIKey(ctx, bulker, index, uuid.Must(uuid.NewV4()).String(), false) if err != nil { t.Fatalf("unable to store enrollment key: %v", err) diff --git a/internal/pkg/dl/migration.go b/internal/pkg/dl/migration.go index 4930691482..86e7dd0aa5 100644 --- a/internal/pkg/dl/migration.go +++ b/internal/pkg/dl/migration.go @@ -222,7 +222,7 @@ func migrateAgentOutputs() (string, string, []byte, error) { query := dsl.NewRoot() query.Query().Bool().Must().Exists(fieldDefaultAPIKeyID) - fields := map[string]interface{}{fieldRetiredAt: timeNow().UTC().Format(time.RFC3339)} + fields := map[string]any{fieldRetiredAt: timeNow().UTC().Format(time.RFC3339)} painless := ` // set up the new fields ctx._source['` + fieldOutputs + `']=new HashMap(); @@ -254,7 +254,7 @@ ctx._source.default_api_key=null; ctx._source.default_api_key_id=null; ctx._source.policy_output_permissions_hash=null; ` - query.Param("script", map[string]interface{}{ + query.Param("script", map[string]any{ "lang": "painless", "source": painless, "params": fields, diff --git a/internal/pkg/dl/migration_integration_test.go b/internal/pkg/dl/migration_integration_test.go index 25d0445ab0..b6b2ea894f 100644 --- a/internal/pkg/dl/migration_integration_test.go +++ b/internal/pkg/dl/migration_integration_test.go @@ -31,7 +31,7 @@ func createSomeAgents(ctx context.Context, t *testing.T, n int, apiKey bulk.APIK var createdAgents []string - for i := 0; i < n; i++ { + for i := range n { outputAPIKey := bulk.APIKey{ ID: fmt.Sprint(apiKey.ID, i), Key: fmt.Sprint(apiKey.Key, i), diff --git a/internal/pkg/dl/policies.go b/internal/pkg/dl/policies.go index 0bbaf7d57f..ed42cfa181 100644 --- a/internal/pkg/dl/policies.go +++ b/internal/pkg/dl/policies.go @@ -91,7 +91,7 @@ func prepareQueryPolicies() *dsl.Tmpl { // can't filter on output in ES as the field is not mapped func QueryOutputFromPolicy(ctx context.Context, bulker bulk.Bulk, outputName string, opt ...Option) (*model.Policy, error) { o := newOption(FleetPolicies, opt...) - params := map[string]interface{}{} + params := map[string]any{} res, err := Search(ctx, bulker, tmplQueryPolicies, o.indexName, params) if err != nil { if errors.Is(err, es.ErrIndexNotFound) { diff --git a/internal/pkg/dl/policies_integration_test.go b/internal/pkg/dl/policies_integration_test.go index b2ca869f2b..e5d2fc5493 100644 --- a/internal/pkg/dl/policies_integration_test.go +++ b/internal/pkg/dl/policies_integration_test.go @@ -24,13 +24,13 @@ import ( func createRandomPolicy(id string, revisionIdx int) model.Policy { now := time.Now().UTC() var policyData = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, }, OutputPermissions: json.RawMessage(`{"default": {}}`), - Inputs: []map[string]interface{}{}, + Inputs: []map[string]any{}, } return model.Policy{ PolicyID: id, @@ -175,13 +175,13 @@ func TestQueryOutputFromPolicy(t *testing.T) { now := time.Now().UTC() var policyData = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "remote": { "type": "remote_elasticsearch", }, }, OutputPermissions: json.RawMessage(`{"default": {}}`), - Inputs: []map[string]interface{}{}, + Inputs: []map[string]any{}, } rec := model.Policy{ PolicyID: "policy1", @@ -200,5 +200,5 @@ func TestQueryOutputFromPolicy(t *testing.T) { if err != nil { t.Fatal(err) } - require.Equal(t, map[string]interface{}{"type": "remote_elasticsearch"}, policy.Data.Outputs["remote"]) + require.Equal(t, map[string]any{"type": "remote_elasticsearch"}, policy.Data.Outputs["remote"]) } diff --git a/internal/pkg/dl/prepare.go b/internal/pkg/dl/prepare.go index 6b9c9b5edf..d21327cf62 100644 --- a/internal/pkg/dl/prepare.go +++ b/internal/pkg/dl/prepare.go @@ -6,7 +6,7 @@ package dl import "github.com/elastic/fleet-server/v7/internal/pkg/dsl" -func prepareFindByField(field string, params map[string]interface{}) *dsl.Tmpl { +func prepareFindByField(field string, params map[string]any) *dsl.Tmpl { tmpl := dsl.NewTmpl() root := dsl.NewRoot() diff --git a/internal/pkg/dl/search.go b/internal/pkg/dl/search.go index 9cd708f3f9..459513675e 100644 --- a/internal/pkg/dl/search.go +++ b/internal/pkg/dl/search.go @@ -12,7 +12,7 @@ import ( "github.com/elastic/fleet-server/v7/internal/pkg/es" ) -func Search(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, params map[string]interface{}, opts ...bulk.Opt) (*es.HitsT, error) { +func Search(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, params map[string]any, opts ...bulk.Opt) (*es.HitsT, error) { query, err := tmpl.Render(params) if err != nil { return nil, err @@ -26,7 +26,7 @@ func Search(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, return &res.HitsT, nil } -func SearchWithOneParam(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, name string, v interface{}) (*es.HitsT, error) { +func SearchWithOneParam(ctx context.Context, bulker bulk.Bulk, tmpl *dsl.Tmpl, index string, name string, v any) (*es.HitsT, error) { query, err := tmpl.RenderOne(name, v) if err != nil { return nil, err diff --git a/internal/pkg/dsl/field.go b/internal/pkg/dsl/field.go index ba9009afd3..44ff3e200d 100644 --- a/internal/pkg/dsl/field.go +++ b/internal/pkg/dsl/field.go @@ -4,7 +4,7 @@ package dsl -func (n *Node) Field(fieldName interface{}) *Node { +func (n *Node) Field(fieldName any) *Node { n.Param(kKeywordField, fieldName) return n } diff --git a/internal/pkg/dsl/node.go b/internal/pkg/dsl/node.go index 9e7e0b0494..f91716ff46 100644 --- a/internal/pkg/dsl/node.go +++ b/internal/pkg/dsl/node.go @@ -14,7 +14,7 @@ type nodeMapT map[string]*Node type nodeListT []*Node type Node struct { - leaf interface{} + leaf any nodeMap nodeMapT nodeList nodeListT preventNull bool diff --git a/internal/pkg/dsl/param.go b/internal/pkg/dsl/param.go index 4766aaf4b5..12d242480e 100644 --- a/internal/pkg/dsl/param.go +++ b/internal/pkg/dsl/param.go @@ -4,7 +4,7 @@ package dsl -func (n *Node) Param(name string, val interface{}) { +func (n *Node) Param(name string, val any) { childNode := n.findOrCreateChildByName(name) childNode.leaf = val } diff --git a/internal/pkg/dsl/range.go b/internal/pkg/dsl/range.go index 3e53af1e6e..ac0d39eaa1 100644 --- a/internal/pkg/dsl/range.go +++ b/internal/pkg/dsl/range.go @@ -6,13 +6,13 @@ package dsl type RangeOpt func(nodeMapT) -func WithRangeGT(v interface{}) RangeOpt { +func WithRangeGT(v any) RangeOpt { return func(nmap nodeMapT) { nmap[kKeywordGreaterThan] = &Node{leaf: v} } } -func WithRangeLTE(v interface{}) RangeOpt { +func WithRangeLTE(v any) RangeOpt { return func(nmap nodeMapT) { nmap[kKeywordLessThanEq] = &Node{leaf: v} } diff --git a/internal/pkg/dsl/size.go b/internal/pkg/dsl/size.go index 27555943ed..520e9a104f 100644 --- a/internal/pkg/dsl/size.go +++ b/internal/pkg/dsl/size.go @@ -10,6 +10,6 @@ func (n *Node) Size(sz uint64) { } // WithSize allows to parameterize the size -func (n *Node) WithSize(v interface{}) { +func (n *Node) WithSize(v any) { n.nodeMap[kKeywordSize] = &Node{leaf: v} } diff --git a/internal/pkg/dsl/term.go b/internal/pkg/dsl/term.go index 7da88b08a8..0dd57195f7 100644 --- a/internal/pkg/dsl/term.go +++ b/internal/pkg/dsl/term.go @@ -4,15 +4,15 @@ package dsl -func (n *Node) Term(field string, value interface{}, boost *float64) *Node { +func (n *Node) Term(field string, value any, boost *float64) *Node { childNode := n.appendOrSetChildNode(kKeywordTerm) leaf := value if boost != nil { leaf = &struct { - Value interface{} `json:"value"` - Boost *float64 `json:"boost,omitempty"` + Value any `json:"value"` + Boost *float64 `json:"boost,omitempty"` }{ value, boost, @@ -25,7 +25,7 @@ func (n *Node) Term(field string, value interface{}, boost *float64) *Node { return childNode } -func (n *Node) Terms(field string, value interface{}, boost *float64) *Node { +func (n *Node) Terms(field string, value any, boost *float64) *Node { childNode := n.appendOrSetChildNode(kKeywordTerms) childNode.nodeMap = nodeMapT{ diff --git a/internal/pkg/dsl/tmpl.go b/internal/pkg/dsl/tmpl.go index 0e8cccba02..4a363a0086 100644 --- a/internal/pkg/dsl/tmpl.go +++ b/internal/pkg/dsl/tmpl.go @@ -129,7 +129,7 @@ func (t *Tmpl) MustResolve(n *Node) *Tmpl { } // RenderOne is a convenience function to avoid map when only one token -func (t *Tmpl) RenderOne(name string, v interface{}) ([]byte, error) { +func (t *Tmpl) RenderOne(name string, v any) ([]byte, error) { d, err := json.Marshal(v) if err != nil { return nil, err @@ -139,7 +139,7 @@ func (t *Tmpl) RenderOne(name string, v interface{}) ([]byte, error) { return t.render(m, len(d)) } -func (t *Tmpl) Render(m map[string]interface{}) ([]byte, error) { +func (t *Tmpl) Render(m map[string]any) ([]byte, error) { // Marshal all targets, get byte count marshalMap := make(map[string][]byte, len(m)) @@ -157,7 +157,7 @@ func (t *Tmpl) Render(m map[string]interface{}) ([]byte, error) { return t.render(marshalMap, sum) } -func (t *Tmpl) MustRender(m map[string]interface{}) []byte { +func (t *Tmpl) MustRender(m map[string]any) []byte { b, err := t.Render(m) if err != nil { panic(err) diff --git a/internal/pkg/dsl/tmpl_test.go b/internal/pkg/dsl/tmpl_test.go index 928dd358ef..e2e9370790 100644 --- a/internal/pkg/dsl/tmpl_test.go +++ b/internal/pkg/dsl/tmpl_test.go @@ -11,7 +11,7 @@ import ( ) // Emulate agent_id saved object query -func makeQuery(leaf interface{}) *Node { +func makeQuery(leaf any) *Node { const ty = "fleet-agents" root := NewRoot() @@ -21,7 +21,7 @@ func makeQuery(leaf interface{}) *Node { return root } -func makeQuery2(leaf1 interface{}, leaf2 interface{}) *Node { +func makeQuery2(leaf1 any, leaf2 any) *Node { const ty = "fleet-agent-actions" root := NewRoot() @@ -71,7 +71,7 @@ func BenchmarkRender(b *testing.B) { b.ResetTimer() // run the RenderOne function b.N times for n := 0; n < b.N; n++ { - if _, err := tmpl.Render(map[string]interface{}{ + if _, err := tmpl.Render(map[string]any{ kName: v, }); err != nil { b.Error(err) @@ -142,7 +142,7 @@ func BenchmarkRender2(b *testing.B) { // run the RenderOne function b.N times b.ResetTimer() for n := 0; n < b.N; n++ { - if _, err := tmpl.Render(map[string]interface{}{ + if _, err := tmpl.Render(map[string]any{ kName1: "27e58fc0-09a2-11eb-a8cd-57e98f140de5", kName2: 3, }); err != nil { diff --git a/internal/pkg/es/client.go b/internal/pkg/es/client.go index d808cb9ccd..08bdd3ffe9 100644 --- a/internal/pkg/es/client.go +++ b/internal/pkg/es/client.go @@ -10,6 +10,7 @@ import ( "fmt" "net/http" "runtime" + "slices" "syscall" "time" @@ -129,11 +130,8 @@ func WithMaxRetries(retries int) ConfigOption { func WithRetryOnStatus(status int) ConfigOption { return func(config *elasticsearch.Config) { - for _, s := range config.RetryOnStatus { - // check for duplicities - if s == status { - return - } + if slices.Contains(config.RetryOnStatus, status) { + return } config.RetryOnStatus = append(config.RetryOnStatus, status) diff --git a/internal/pkg/es/result.go b/internal/pkg/es/result.go index bcd7ef6bc8..cf5d28a95c 100644 --- a/internal/pkg/es/result.go +++ b/internal/pkg/es/result.go @@ -27,16 +27,16 @@ type AckResponse struct { } type HitT struct { - ID string `json:"_id"` - SeqNo int64 `json:"_seq_no"` - Version int64 `json:"version"` - Index string `json:"_index"` - Source json.RawMessage `json:"_source"` - Score *float64 `json:"_score"` - Fields map[string]interface{} `json:"fields"` + ID string `json:"_id"` + SeqNo int64 `json:"_seq_no"` + Version int64 `json:"version"` + Index string `json:"_index"` + Source json.RawMessage `json:"_source"` + Score *float64 `json:"_score"` + Fields map[string]any `json:"fields"` } -func (hit *HitT) Unmarshal(v interface{}) error { +func (hit *HitT) Unmarshal(v any) error { err := json.Unmarshal(hit.Source, v) if err != nil { return err @@ -72,7 +72,7 @@ func (b *Bucket) UnmarshalJSON(data []byte) error { if err != nil { return err } - var aggs map[string]interface{} + var aggs map[string]any err = json.Unmarshal(data, &aggs) if err != nil { return err @@ -84,7 +84,7 @@ func (b *Bucket) UnmarshalJSON(data []byte) error { delete(aggs, "doc_count") b2.Aggregations = make(map[string]HitsT) for name, value := range aggs { - vMap, ok := value.(map[string]interface{}) + vMap, ok := value.(map[string]any) if !ok { continue } diff --git a/internal/pkg/file/delivery/delivery_test.go b/internal/pkg/file/delivery/delivery_test.go index 62d544ab3f..98f6100014 100644 --- a/internal/pkg/file/delivery/delivery_test.go +++ b/internal/pkg/file/delivery/delivery_test.go @@ -115,17 +115,17 @@ func TestLocateChunks(t *testing.T) { ID: baseID + ".0", Index: "", Source: []byte(""), - Fields: map[string]interface{}{ - "bid": []interface{}{baseID}, + Fields: map[string]any{ + "bid": []any{baseID}, }, }, { ID: baseID + ".1", Index: "", Source: []byte(""), - Fields: map[string]interface{}{ - "bid": []interface{}{baseID}, - "last": []interface{}{true}, + Fields: map[string]any{ + "bid": []any{baseID}, + "last": []any{true}, }, }, }, diff --git a/internal/pkg/file/delivery/es.go b/internal/pkg/file/delivery/es.go index 174fec85f9..98b446933e 100644 --- a/internal/pkg/file/delivery/es.go +++ b/internal/pkg/file/delivery/es.go @@ -45,7 +45,7 @@ func prepareQueryMetaByIDAndAgent() *dsl.Tmpl { } func findFileForAgent(ctx context.Context, bulker bulk.Bulk, fileID string, agentID string) (*es.ResultT, error) { - q, err := MetaByIDAndAgent.Render(map[string]interface{}{ + q, err := MetaByIDAndAgent.Render(map[string]any{ FieldDocID: fileID, "target_agents": agentID, }) diff --git a/internal/pkg/file/es.go b/internal/pkg/file/es.go index ec8f0a0562..4cd3b30f67 100644 --- a/internal/pkg/file/es.go +++ b/internal/pkg/file/es.go @@ -39,9 +39,9 @@ func prepareChunkInfo(size bool) *dsl.Tmpl { root.Query().Term(FieldBaseID, tmpl.Bind(FieldBaseID), nil) root.Param("fields", []string{FieldSHA2, FieldLast, FieldBaseID}) if size { - root.Param("script_fields", map[string]interface{}{ - "size": map[string]interface{}{ - "script": map[string]interface{}{ + root.Param("script_fields", map[string]any{ + "size": map[string]any{ + "script": map[string]any{ "lang": "painless", "source": "params._source.data.length", }, @@ -64,7 +64,7 @@ func prepareFindMetaByUploadID() *dsl.Tmpl { func GetMetadata(ctx context.Context, bulker bulk.Bulk, indexPattern string, uploadID string) ([]es.HitT, error) { span, ctx := apm.StartSpan(ctx, "getFileInfo", "search") defer span.End() - query, err := QueryUploadID.Render(map[string]interface{}{ + query, err := QueryUploadID.Render(map[string]any{ FieldUploadID: uploadID, }) if err != nil { @@ -144,7 +144,7 @@ func GetChunkInfos(ctx context.Context, bulker bulk.Bulk, indexPattern string, b if opt.IncludeSize { tpl = QueryChunkInfoWithSize } - query, err := tpl.Render(map[string]interface{}{ + query, err := tpl.Render(map[string]any{ FieldBaseID: baseID, }) if err != nil { @@ -206,8 +206,8 @@ func GetChunkInfos(ctx context.Context, bulker bulk.Bulk, indexPattern string, b // convenience function for translating the elasticsearch "field" response format // of "field": { "a": [value], "b": [value] } -func getResultField(fields map[string]interface{}, key string) (interface{}, bool) { - array, ok := fields[key].([]interface{}) +func getResultField(fields map[string]any, key string) (any, bool) { + array, ok := fields[key].([]any) if !ok { return nil, false } @@ -217,7 +217,7 @@ func getResultField(fields map[string]interface{}, key string) (interface{}, boo return array[0], true } -func getResultsFieldString(fields map[string]interface{}, key string) (string, bool) { +func getResultsFieldString(fields map[string]any, key string) (string, bool) { val, ok := getResultField(fields, key) if !ok { return "", false @@ -225,7 +225,7 @@ func getResultsFieldString(fields map[string]interface{}, key string) (string, b str, ok := val.(string) return str, ok } -func getResultsFieldBool(fields map[string]interface{}, key string) (bool, bool) { +func getResultsFieldBool(fields map[string]any, key string) (bool, bool) { val, ok := getResultField(fields, key) if !ok { return false, false @@ -233,7 +233,7 @@ func getResultsFieldBool(fields map[string]interface{}, key string) (bool, bool) b, ok := val.(bool) return b, ok } -func getResultsFieldInt(fields map[string]interface{}, key string) (int, bool) { +func getResultsFieldInt(fields map[string]any, key string) (int, bool) { val, ok := getResultField(fields, key) if !ok { return 0, false diff --git a/internal/pkg/file/es_test.go b/internal/pkg/file/es_test.go index d98932b132..f076c31192 100644 --- a/internal/pkg/file/es_test.go +++ b/internal/pkg/file/es_test.go @@ -28,22 +28,22 @@ func TestChunkInfoResultsParseCorrectly(t *testing.T) { ID: baseID + ".0", Index: "", Source: []byte(""), - Fields: map[string]interface{}{ - "bid": []interface{}{baseID}, - "last": []interface{}{false}, - "sha2": []interface{}{sha2}, - "size": []interface{}{float64(size)}, + Fields: map[string]any{ + "bid": []any{baseID}, + "last": []any{false}, + "sha2": []any{sha2}, + "size": []any{float64(size)}, }, }, { ID: baseID + ".1", Index: "", Source: []byte(""), - Fields: map[string]interface{}{ - "bid": []interface{}{baseID}, - "last": []interface{}{true}, - "sha2": []interface{}{sha2}, - "size": []interface{}{float64(size)}, + Fields: map[string]any{ + "bid": []any{baseID}, + "last": []any{true}, + "sha2": []any{sha2}, + "size": []any{float64(size)}, }, }, }, diff --git a/internal/pkg/file/uploader/es.go b/internal/pkg/file/uploader/es.go index 20526ee5f0..74ecc25700 100644 --- a/internal/pkg/file/uploader/es.go +++ b/internal/pkg/file/uploader/es.go @@ -80,7 +80,7 @@ func UpdateFileDoc(ctx context.Context, bulker bulk.Bulk, source string, fileID defer span.End() client := bulker.Client() - q, err := UpdateMetaDocByID.Render(map[string]interface{}{ + q, err := UpdateMetaDocByID.Render(map[string]any{ "_id": fileID, "status": string(status), "hash": hash, @@ -165,7 +165,7 @@ type ChunkUploadResponse struct { func DeleteChunk(ctx context.Context, bulker bulk.Bulk, source string, fileID string, chunkNum int) error { span, ctx := apm.StartSpan(ctx, "deleteChunk", "delete_by_query") defer span.End() - q, err := MatchChunkByDocument.Render(map[string]interface{}{ + q, err := MatchChunkByDocument.Render(map[string]any{ "_id": fmt.Sprintf("%s.%d", fileID, chunkNum), }) if err != nil { @@ -177,7 +177,7 @@ func DeleteChunk(ctx context.Context, bulker bulk.Bulk, source string, fileID st } func DeleteAllChunksForFile(ctx context.Context, bulker bulk.Bulk, source string, baseID string) error { - q, err := MatchChunkByBID.Render(map[string]interface{}{ + q, err := MatchChunkByBID.Render(map[string]any{ file.FieldBaseID: baseID, }) if err != nil { diff --git a/internal/pkg/file/uploader/finalize_test.go b/internal/pkg/file/uploader/finalize_test.go index 051581b290..9c1e437ba3 100644 --- a/internal/pkg/file/uploader/finalize_test.go +++ b/internal/pkg/file/uploader/finalize_test.go @@ -57,7 +57,7 @@ func TestUploadCompletePerformsRefreshBeforeChunkSearch(t *testing.T) { "action_id": "actionID", "agent_id": "agentID", "src": fakeIntegrationSrc, - "file": map[string]interface{}{ + "file": map[string]any{ "size": size, "ChunkSize": file.MaxChunkSize, "Status": file.StatusProgress, diff --git a/internal/pkg/file/uploader/jsdict.go b/internal/pkg/file/uploader/jsdict.go index b563974dd4..3a6c7c9936 100644 --- a/internal/pkg/file/uploader/jsdict.go +++ b/internal/pkg/file/uploader/jsdict.go @@ -22,16 +22,16 @@ func ReadDict(r io.Reader) (JSDict, error) { // helper for accessing nested properties without panics // it allows for a safe way to do things like // js["foo"].(map[string]interface{})["bar"].(map[string]interface{})["baz"].(string) -type JSDict map[string]interface{} +type JSDict map[string]any // for a given path, retrieves the raw value in the json structure // safely, such that if any key is missing, or if any non-leaf key // is not an object, returns false instead of panicking -func (j JSDict) Val(keys ...string) (interface{}, bool) { +func (j JSDict) Val(keys ...string) (any, bool) { if len(keys) == 0 { return nil, false } - var m map[string]interface{} = j + var m map[string]any = j for i, k := range keys { value, ok := m[k] if !ok { @@ -40,7 +40,7 @@ func (j JSDict) Val(keys ...string) (interface{}, bool) { if i == len(keys)-1 { return value, true } - m, ok = value.(map[string]interface{}) + m, ok = value.(map[string]any) if !ok { return nil, false } @@ -78,7 +78,7 @@ func (j JSDict) Int64(keys ...string) (int64, bool) { } // write values to possibly nested locations -func (j JSDict) Put(value interface{}, keys ...string) error { +func (j JSDict) Put(value any, keys ...string) error { if len(keys) == 0 { return errors.New("path not provided") } @@ -87,14 +87,14 @@ func (j JSDict) Put(value interface{}, keys ...string) error { j[keys[0]] = value return nil } - var m map[string]interface{} = j + var m map[string]any = j for i, k := range keys { if i == len(keys)-1 { m[k] = value return nil } // otherwise, we have more to nest. Make sure this level is an object - x, ok := m[k].(map[string]interface{}) + x, ok := m[k].(map[string]any) if !ok { return fmt.Errorf("unable to write to %s, missing property at %s", strings.Join(keys, "."), k) } diff --git a/internal/pkg/file/uploader/upload_test.go b/internal/pkg/file/uploader/upload_test.go index c09103b8d0..61d53498ac 100644 --- a/internal/pkg/file/uploader/upload_test.go +++ b/internal/pkg/file/uploader/upload_test.go @@ -24,10 +24,10 @@ import ( // convenience function for making a typical file request structure // with defaults when specific values are not checked or required -func makeUploadRequestDict(input map[string]interface{}) JSDict { +func makeUploadRequestDict(input map[string]any) JSDict { // defaults d := JSDict{ - "file": map[string]interface{}{ + "file": map[string]any{ "name": "foo.png", "mime_type": "image/png", "size": 1024, @@ -43,11 +43,11 @@ func makeUploadRequestDict(input map[string]interface{}) JSDict { // fill in any provided values, e.g. "file.name": "test.zip" for k, v := range input { - dict := map[string]interface{}(d) + dict := map[string]any(d) keys := strings.Split(k, ".") for i, key := range keys { if i < len(keys)-1 { - dict, _ = dict[key].(map[string]interface{}) + dict, _ = dict[key].(map[string]any) continue } dict[key] = v @@ -63,7 +63,7 @@ func TestUploadBeginReturnsCorrectInfo(t *testing.T) { src := "mysource" action := "abc" agent := "XYZ" - data := makeUploadRequestDict(map[string]interface{}{ + data := makeUploadRequestDict(map[string]any{ "action_id": action, "agent_id": agent, "src": src, @@ -106,7 +106,7 @@ func TestUploadBeginWritesDocumentFromInputs(t *testing.T) { agent := "xyz-123" name := "test.zip" - data := makeUploadRequestDict(map[string]interface{}{ + data := makeUploadRequestDict(map[string]any{ "action_id": action, "agent_id": agent, "src": src, @@ -168,7 +168,7 @@ func TestUploadBeginCalculatesCorrectChunkCount(t *testing.T) { for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { - data := makeUploadRequestDict(map[string]interface{}{ + data := makeUploadRequestDict(map[string]any{ "file.size": tc.FileSize, }) info, err := u.Begin(t.Context(), []string{}, data) @@ -211,7 +211,7 @@ func TestUploadBeginMaxFileSize(t *testing.T) { for _, tc := range tests { t.Run(tc.Name, func(t *testing.T) { u := New(nil, fakeBulk, c, tc.UploadSizeLimit, time.Hour) - data := makeUploadRequestDict(map[string]interface{}{ + data := makeUploadRequestDict(map[string]any{ "file.size": tc.FileSize, }) _, err := u.Begin(t.Context(), []string{}, data) @@ -261,13 +261,13 @@ func TestUploadRejectsMissingRequiredFields(t *testing.T) { data := makeUploadRequestDict(nil) // now delete this field and expect failure below - d := map[string]interface{}(data) + d := map[string]any(data) parts := strings.Split(field, ".") for i, part := range parts { if i == len(parts)-1 { // leaf of an object tree delete(d, part) } else { - d, ok = d[part].(map[string]interface{}) + d, ok = d[part].(map[string]any) assert.Truef(t, ok, "incorrect key path '%s' when testing required fields", field) } } @@ -283,11 +283,11 @@ func TestUploadRejectsMissingRequiredFields(t *testing.T) { func mockUploadInfoResult(bulker *itesting.MockBulk, info file.Info) { // convert info into how it's stored/returned in ES - out, _ := json.Marshal(map[string]interface{}{ + out, _ := json.Marshal(map[string]any{ "action_id": info.ActionID, "agent_id": info.AgentID, "src": info.Source, - "file": map[string]interface{}{ + "file": map[string]any{ "size": info.Total, "ChunkSize": info.ChunkSize, "Status": info.Status, @@ -346,7 +346,7 @@ func TestChunkMarksFinal(t *testing.T) { u := New(nil, fakeBulk, c, size_ptr(8388608000), time.Hour) - data := makeUploadRequestDict(map[string]interface{}{ + data := makeUploadRequestDict(map[string]any{ "file.size": tc.FileSize, }) diff --git a/internal/pkg/logger/http_test.go b/internal/pkg/logger/http_test.go index b634c3e637..21b72a4635 100644 --- a/internal/pkg/logger/http_test.go +++ b/internal/pkg/logger/http_test.go @@ -40,8 +40,7 @@ func TestMiddleware(t *testing.T) { } srv.Start() defer srv.Close() - reqCtx, cancel := context.WithCancel(context.Background()) - defer cancel() + reqCtx := t.Context() req, err := http.NewRequestWithContext(reqCtx, "GET", srv.URL, nil) require.NoError(t, err) diff --git a/internal/pkg/logger/zap/zapStub.go b/internal/pkg/logger/zap/zapStub.go index 56fa3faad4..5e27acb8a8 100644 --- a/internal/pkg/logger/zap/zapStub.go +++ b/internal/pkg/logger/zap/zapStub.go @@ -62,7 +62,7 @@ func (z zapStub) Sync() error { func (z zapStub) Write(p []byte) (n int, err error) { // Unwrap the zap object for logging - m := make(map[string]interface{}) + m := make(map[string]any) if err := json.Unmarshal(p, &m); err != nil { return 0, err } diff --git a/internal/pkg/model/ext.go b/internal/pkg/model/ext.go index e33f1e4338..03222822a8 100644 --- a/internal/pkg/model/ext.go +++ b/internal/pkg/model/ext.go @@ -89,7 +89,7 @@ func ClonePolicyData(d *PolicyData) *PolicyData { Agent: d.Agent, Fleet: d.Fleet, ID: d.ID, - Inputs: make([]map[string]interface{}, 0, len(d.Inputs)), + Inputs: make([]map[string]any, 0, len(d.Inputs)), OutputPermissions: d.OutputPermissions, Outputs: cloneMap(d.Outputs), Revision: d.Revision, @@ -135,11 +135,11 @@ func cloneOTelService(s *Service) *Service { // cloneMap does a deep copy on a map of objects // TODO generics? -func cloneMap(m map[string]map[string]interface{}) map[string]map[string]interface{} { +func cloneMap(m map[string]map[string]any) map[string]map[string]any { if m == nil { return nil } - r := make(map[string]map[string]interface{}) + r := make(map[string]map[string]any) for k, v := range m { r[k] = maps.Clone(v) } diff --git a/internal/pkg/model/schema_test.go b/internal/pkg/model/schema_test.go index 7ee8fb44b4..fb1289a253 100644 --- a/internal/pkg/model/schema_test.go +++ b/internal/pkg/model/schema_test.go @@ -40,7 +40,7 @@ func validateSerialization(t *testing.T, action Action) { b, err := json.Marshal(action) assert.NoError(t, err) - var m map[string]interface{} + var m map[string]any err = json.Unmarshal(b, &m) assert.NoError(t, err) @@ -56,7 +56,7 @@ func validateSerialization(t *testing.T, action Action) { if action.Signed == nil { assert.False(t, ok) } else { - sm, ok := signed.(map[string]interface{}) + sm, ok := signed.(map[string]any) assert.True(t, ok) assert.Equal(t, action.Signed.Data, sm["data"]) assert.Equal(t, action.Signed.Signature, sm["signature"]) diff --git a/internal/pkg/monitor/monitor.go b/internal/pkg/monitor/monitor.go index e01eeee5e9..1e39502280 100644 --- a/internal/pkg/monitor/monitor.go +++ b/internal/pkg/monitor/monitor.go @@ -392,7 +392,7 @@ func (m *simpleMonitorT) fetch(ctx context.Context, checkpoint, maxCheckpoint sq now := time.Now().UTC().Format(time.RFC3339) // Run check query that detects that there are new documents available - params := map[string]interface{}{ + params := map[string]any{ dl.FieldSeqNo: checkpoint.Value(), dl.FieldMaxSeqNo: maxCheckpoint.Value(), } @@ -408,7 +408,7 @@ func (m *simpleMonitorT) fetch(ctx context.Context, checkpoint, maxCheckpoint sq return hits, nil } -func (m *simpleMonitorT) search(ctx context.Context, tmpl *dsl.Tmpl, params map[string]interface{}, seqNos sqn.SeqNo) ([]es.HitT, error) { +func (m *simpleMonitorT) search(ctx context.Context, tmpl *dsl.Tmpl, params map[string]any, seqNos sqn.SeqNo) ([]es.HitT, error) { span, ctx := apm.StartSpan(ctx, "action", "fleet_search") defer span.End() query, err := tmpl.Render(params) diff --git a/internal/pkg/monitor/monitor_integration_test.go b/internal/pkg/monitor/monitor_integration_test.go index 2256c84d29..87b0f7e8e3 100644 --- a/internal/pkg/monitor/monitor_integration_test.go +++ b/internal/pkg/monitor/monitor_integration_test.go @@ -29,8 +29,7 @@ import ( ) func TestSimpleMonitorEmptyIndex(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker := ftesting.SetupCleanIndex(ctx, t, dl.FleetActions) @@ -39,8 +38,7 @@ func TestSimpleMonitorEmptyIndex(t *testing.T) { } func TestSimpleMonitorNonEmptyIndex(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker, _ := ftesting.SetupActions(ctx, t, 1, 12) diff --git a/internal/pkg/monitor/subscription_monitor_integration_test.go b/internal/pkg/monitor/subscription_monitor_integration_test.go index 220e62b2fe..6de9c2b1ea 100644 --- a/internal/pkg/monitor/subscription_monitor_integration_test.go +++ b/internal/pkg/monitor/subscription_monitor_integration_test.go @@ -23,8 +23,7 @@ import ( ) func TestMonitorEmptyIndex(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker := ftesting.SetupCleanIndex(ctx, t, dl.FleetActions) @@ -32,8 +31,7 @@ func TestMonitorEmptyIndex(t *testing.T) { } func TestMonitorNonEmptyIndex(t *testing.T) { - ctx, cn := context.WithCancel(context.Background()) - defer cn() + ctx := t.Context() ctx = testlog.SetLogger(t).WithContext(ctx) index, bulker, _ := ftesting.SetupActions(ctx, t, 1, 12) @@ -51,14 +49,12 @@ func runMonitorTest(t *testing.T, ctx context.Context, index string, bulker bulk var wg sync.WaitGroup mctx, mcn := context.WithCancel(ctx) var merr error - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { merr = mon.Run(mctx) if errors.Is(merr, context.Canceled) { merr = nil } - }() + }) // Wait until monitor is running err = <-readyCh @@ -79,7 +75,7 @@ func runMonitorTest(t *testing.T, ctx context.Context, index string, bulker bulk // Listen monitor updates var mwg sync.WaitGroup mwg.Add(2) - for i := 0; i < 2; i++ { + for i := range 2 { go func(i int, s Subscription) { defer mwg.Done() defer mon.Unsubscribe(s) diff --git a/internal/pkg/policy/monitor_integration_test.go b/internal/pkg/policy/monitor_integration_test.go index 70a6e29788..cfc70174df 100644 --- a/internal/pkg/policy/monitor_integration_test.go +++ b/internal/pkg/policy/monitor_integration_test.go @@ -26,7 +26,7 @@ import ( ) var intPolData = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, @@ -48,14 +48,12 @@ func TestMonitor_Integration(t *testing.T) { // Start index monitor var imerr error var imwg sync.WaitGroup - imwg.Add(1) - go func() { - defer imwg.Done() + imwg.Go(func() { imerr = im.Run(ctx) if errors.Is(imerr, context.Canceled) { imerr = nil } - }() + }) m := NewMonitor(bulker, im, config.ServerLimits{}) pm, ok := m.(*monitorT) @@ -66,14 +64,12 @@ func TestMonitor_Integration(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = m.Run(ctx) if errors.Is(merr, context.Canceled) { merr = nil } - }() + }) err = pm.waitStart(ctx) require.NoError(t, err) @@ -144,14 +140,12 @@ func TestMonitor_Debounce_Integration(t *testing.T) { // Start index monitor var imerr error var imwg sync.WaitGroup - imwg.Add(1) - go func() { - defer imwg.Done() + imwg.Go(func() { imerr = im.Run(ctx) if errors.Is(imerr, context.Canceled) { imerr = nil } - }() + }) m := NewMonitor(bulker, im, config.ServerLimits{}) pm, ok := m.(*monitorT) @@ -162,14 +156,12 @@ func TestMonitor_Debounce_Integration(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = m.Run(ctx) if errors.Is(merr, context.Canceled) { merr = nil } - }() + }) err = pm.waitStart(ctx) require.NoError(t, err) @@ -335,14 +327,12 @@ func TestMonitor_Revisions(t *testing.T) { // Start index monitor var imerr error var imwg sync.WaitGroup - imwg.Add(1) - go func() { - defer imwg.Done() + imwg.Go(func() { imerr = im.Run(ctx) if errors.Is(imerr, context.Canceled) { imerr = nil } - }() + }) m := NewMonitor(bulker, im, config.ServerLimits{}) pm, ok := m.(*monitorT) @@ -353,14 +343,12 @@ func TestMonitor_Revisions(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = m.Run(ctx) if errors.Is(merr, context.Canceled) { merr = nil } - }() + }) err = pm.waitStart(ctx) require.NoError(t, err) @@ -457,14 +445,12 @@ func TestMonitor_KickDeploy(t *testing.T) { // Start index monitor var imerr error var imwg sync.WaitGroup - imwg.Add(1) - go func() { - defer imwg.Done() + imwg.Go(func() { imerr = im.Run(ctx) if errors.Is(imerr, context.Canceled) { imerr = nil } - }() + }) m := NewMonitor(bulker, im, config.ServerLimits{}) pm, ok := m.(*monitorT) @@ -475,14 +461,12 @@ func TestMonitor_KickDeploy(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = m.Run(ctx) if errors.Is(merr, context.Canceled) { merr = nil } - }() + }) err = pm.waitStart(ctx) require.NoError(t, err) diff --git a/internal/pkg/policy/monitor_test.go b/internal/pkg/policy/monitor_test.go index 44f9141297..2588417402 100644 --- a/internal/pkg/policy/monitor_test.go +++ b/internal/pkg/policy/monitor_test.go @@ -33,8 +33,8 @@ import ( ) var policyDataDefault = &model.PolicyData{ - Outputs: map[string]map[string]interface{}{ - "default": map[string]interface{}{ + Outputs: map[string]map[string]any{ + "default": map[string]any{ "type": "elasticsearch", }, }, @@ -92,11 +92,9 @@ func TestMonitor_NewPolicy(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) err := monitor.(*monitorT).waitStart(ctx) require.NoError(t, err) @@ -171,11 +169,9 @@ func TestMonitor_SamePolicy(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) err := monitor.(*monitorT).waitStart(ctx) require.NoError(t, err) @@ -337,11 +333,9 @@ func Test_Monitor_Limit_Delay(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) err := monitor.(*monitorT).waitStart(ctx) require.NoError(t, err) @@ -510,11 +504,9 @@ func Test_Monitor_cancel_pending(t *testing.T) { // start monitor var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) err = monitor.(*monitorT).waitStart(ctx) require.NoError(t, err) diff --git a/internal/pkg/policy/parsed_policy.go b/internal/pkg/policy/parsed_policy.go index 8b817a2be1..0f55e8dde1 100644 --- a/internal/pkg/policy/parsed_policy.go +++ b/internal/pkg/policy/parsed_policy.go @@ -49,9 +49,9 @@ type ParsedPolicy struct { Roles RoleMapT Outputs map[string]Output Default ParsedPolicyDefaults - Inputs []map[string]interface{} - Agent map[string]interface{} - Fleet map[string]interface{} + Inputs []map[string]any + Agent map[string]any + Fleet map[string]any SecretKeys []string Links apm.SpanLink } @@ -94,7 +94,7 @@ func NewParsedPolicy(ctx context.Context, bulker bulk.Bulk, p model.Policy) (*Pa // Replace secrets in 'agent.download' section of policy if agentDownload, exists := p.Data.Agent["download"]; exists { - if section, ok := agentDownload.(map[string]interface{}); ok { + if section, ok := agentDownload.(map[string]any); ok { agentDownloadSecretKeys, err := secret.ProcessMapSecrets(section, secretValues) if err != nil { return nil, fmt.Errorf("failed to replace secrets in agent.download section of policy: %w", err) @@ -170,7 +170,7 @@ func NewParsedPolicy(ctx context.Context, bulker bulk.Bulk, p model.Policy) (*Pa return pp, nil } -func constructPolicyOutputs(outputs map[string]map[string]interface{}, roles map[string]RoleT) (map[string]Output, error) { +func constructPolicyOutputs(outputs map[string]map[string]any, roles map[string]RoleT) (map[string]Output, error) { result := make(map[string]Output, len(outputs)) for k, v := range outputs { @@ -227,7 +227,7 @@ func parsePerms(permsRaw json.RawMessage) (RoleMapT, error) { // findDefaultName returns the name of the 1st output with the "elasticsearch" type or falls back to behaviour that relies on deprecated fields. // // Previous fleet-server and elastic-agent released had a default output which was removed Sept 2021. -func findDefaultOutputName(outputs map[string]map[string]interface{}) (string, error) { +func findDefaultOutputName(outputs map[string]map[string]any) (string, error) { // iterate across the keys finding the defaults var defaults []string var ESdefaults []string @@ -244,7 +244,7 @@ func findDefaultOutputName(outputs map[string]map[string]interface{}) (string, e defaults = append(defaults, k) continue } - fsMap, ok := fleetServer.(map[string]interface{}) + fsMap, ok := fleetServer.(map[string]any) if ok { str, ok := fsMap[FieldOutputServiceToken].(string) if ok && str == "" { diff --git a/internal/pkg/policy/parsed_policy_test.go b/internal/pkg/policy/parsed_policy_test.go index 394f92b91a..614240f5d4 100644 --- a/internal/pkg/policy/parsed_policy_test.go +++ b/internal/pkg/policy/parsed_policy_test.go @@ -145,11 +145,11 @@ func TestParsedPolicyMixedSecretsReplacement(t *testing.T) { require.Equal(t, "0Mx2UZoBTAyw4gQKSaao_value", firstInputFirstStream["auth.basic.password"]) require.Equal(t, "0Mx2UZoBTAyw4gQKSaao_value", firstInputSecondStream["auth.basic.password"]) require.Equal(t, "abcdef123_value", pp.Policy.Data.Outputs["fs-output"]["type"]) - require.Equal(t, "w8yELZoBTAyw4gQK9KZ7_value", pp.Policy.Data.Outputs["fs-output"]["ssl"].(map[string]interface{})["key"]) - require.Equal(t, "bcdefg234_value", pp.Policy.Data.Agent["download"].(map[string]interface{})["sourceURI"]) - require.Equal(t, "rwXzUJoBxE9I-QCxFt9m_value", pp.Policy.Data.Agent["download"].(map[string]interface{})["ssl"].(map[string]interface{})["key"]) - require.Equal(t, "abcdef123_value", pp.Policy.Data.Fleet["hosts"].([]interface{})[0]) - require.Equal(t, "w8yELZoBTAyw4gQK9KZ7_value", pp.Policy.Data.Fleet["ssl"].(map[string]interface{})["key"]) + require.Equal(t, "w8yELZoBTAyw4gQK9KZ7_value", pp.Policy.Data.Outputs["fs-output"]["ssl"].(map[string]any)["key"]) + require.Equal(t, "bcdefg234_value", pp.Policy.Data.Agent["download"].(map[string]any)["sourceURI"]) + require.Equal(t, "rwXzUJoBxE9I-QCxFt9m_value", pp.Policy.Data.Agent["download"].(map[string]any)["ssl"].(map[string]any)["key"]) + require.Equal(t, "abcdef123_value", pp.Policy.Data.Fleet["hosts"].([]any)[0]) + require.Equal(t, "w8yELZoBTAyw4gQK9KZ7_value", pp.Policy.Data.Fleet["ssl"].(map[string]any)["key"]) } // TestParsedPolicyOTELSecretsReplacement tests that secrets in OTEL sections of a policy diff --git a/internal/pkg/policy/policy_output.go b/internal/pkg/policy/policy_output.go index 0f6e5064eb..ec2e949e56 100644 --- a/internal/pkg/policy/policy_output.go +++ b/internal/pkg/policy/policy_output.go @@ -9,6 +9,7 @@ import ( "encoding/json" "errors" "fmt" + "maps" "strings" "time" @@ -47,7 +48,7 @@ type Output struct { // Prepare prepares the output p to be sent to the elastic-agent // The agent might be mutated for an elasticsearch output -func (p *Output) Prepare(ctx context.Context, zlog zerolog.Logger, bulker bulk.Bulk, agent *model.Agent, outputMap map[string]map[string]interface{}) error { +func (p *Output) Prepare(ctx context.Context, zlog zerolog.Logger, bulker bulk.Bulk, agent *model.Agent, outputMap map[string]map[string]any) error { span, ctx := apm.StartSpan(ctx, "prepareOutput", "process") defer span.End() span.Context.SetLabel("output_type", p.Type) @@ -90,7 +91,7 @@ func (p *Output) prepareElasticsearch( bulker bulk.Bulk, outputBulker bulk.Bulk, agent *model.Agent, - outputMap map[string]map[string]interface{}, + outputMap map[string]map[string]any, hasConfigChanged bool) error { // The role is required to do api key management if p.Role == nil { @@ -141,7 +142,7 @@ func (p *Output) prepareElasticsearch( if toRetireAPIKeys != nil { // adding remote API key to new output toRetireAPIKeys - fields := map[string]interface{}{ + fields := map[string]any{ dl.FieldPolicyOutputToRetireAPIKeyIDs: *toRetireAPIKeys, } @@ -157,8 +158,8 @@ func (p *Output) prepareElasticsearch( } // remove output from agent doc - body, err = json.Marshal(map[string]interface{}{ - "script": map[string]interface{}{ + body, err = json.Marshal(map[string]any{ + "script": map[string]any{ "lang": "painless", "source": fmt.Sprintf("ctx._source['outputs'].remove(\"%s\")", removedOutputName), }, @@ -238,7 +239,7 @@ func (p *Output) prepareElasticsearch( Str("roles", string(p.Role.Raw)). Msg("Updating agent record to pick up most recent roles.") - fields := map[string]interface{}{ + fields := map[string]any{ dl.FieldPolicyOutputPermissionsHash: p.Role.Sha2, } @@ -306,7 +307,7 @@ func (p *Output) prepareElasticsearch( Str(ecs.DefaultOutputAPIKeyID, outputAPIKey.ID). Msg("Updating agent record to pick up default output key.") - fields := map[string]interface{}{ + fields := map[string]any{ dl.FieldPolicyOutputAPIKey: outputAPIKey.Agent(), dl.FieldPolicyOutputAPIKeyID: outputAPIKey.ID, dl.FieldPolicyOutputPermissionsHash: p.Role.Sha2, @@ -421,13 +422,11 @@ func mergeRoles(zlog zerolog.Logger, old, new *RoleT) (*RoleT, error) { destMap := smap.Map{} // copy all from new - for k, v := range newMap { - destMap[k] = v - } + maps.Copy(destMap, newMap) findNewKey := func(m smap.Map, candidate string) string { - if strings.HasSuffix(candidate, "-rdstale") { - candidate = strings.TrimSuffix(candidate, "-rdstale") + if before, ok := strings.CutSuffix(candidate, "-rdstale"); ok { + candidate = before dashIdx := strings.LastIndex(candidate, "-") if dashIdx >= 0 { candidate = candidate[:dashIdx] @@ -436,7 +435,7 @@ func mergeRoles(zlog zerolog.Logger, old, new *RoleT) (*RoleT, error) { } // 1 should be enough, 100 is just to have some space - for i := 0; i < 100; i++ { + for i := range 100 { c := fmt.Sprintf("%s-%d-rdstale", candidate, i) if _, exists := m[c]; !exists { @@ -473,7 +472,7 @@ func mergeRoles(zlog zerolog.Logger, old, new *RoleT) (*RoleT, error) { return r, nil } -func renderUpdatePainlessScript(outputName string, fields map[string]interface{}) ([]byte, error) { +func renderUpdatePainlessScript(outputName string, fields map[string]any) ([]byte, error) { var source strings.Builder // prepare agent.elasticsearch_outputs[OUTPUT_NAME] @@ -503,8 +502,8 @@ ctx._source['outputs']['%s'].%s=params.%s;`, } } - body, err := json.Marshal(map[string]interface{}{ - "script": map[string]interface{}{ + body, err := json.Marshal(map[string]any{ + "script": map[string]any{ "lang": "painless", "source": source.String(), "params": fields, diff --git a/internal/pkg/policy/policy_output_integration_test.go b/internal/pkg/policy/policy_output_integration_test.go index 41cf6a22e5..0142046158 100644 --- a/internal/pkg/policy/policy_output_integration_test.go +++ b/internal/pkg/policy/policy_output_integration_test.go @@ -102,7 +102,7 @@ func TestRenderUpdatePainlessScript(t *testing.T) { ctx, index, agentID, body, bulk.WithRefresh()) require.NoError(t, err) - fields := map[string]interface{}{ + fields := map[string]any{ dl.FieldPolicyOutputAPIKey: outputAPIKey.Agent(), dl.FieldPolicyOutputAPIKeyID: outputAPIKey.ID, dl.FieldPolicyOutputPermissionsHash: outputPermissionSha, @@ -150,8 +150,8 @@ func TestPolicyOutputESPrepareRealES(t *testing.T) { Raw: TestPayload, }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{}, } err = output.prepareElasticsearch( @@ -224,9 +224,9 @@ func TestPolicyOutputESPrepareRemoteES(t *testing.T) { Raw: TestPayload, }, } - policyMap := map[string]map[string]interface{}{ - "test remote output": map[string]interface{}{ - "hosts": []interface{}{"http://localhost:9200"}, + policyMap := map[string]map[string]any{ + "test remote output": map[string]any{ + "hosts": []any{"http://localhost:9200"}, }, } @@ -278,8 +278,8 @@ func TestPolicyOutputESPrepareESRetireRemoteAPIKeys(t *testing.T) { Raw: TestPayload, }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{}, } err = output.prepareElasticsearch( diff --git a/internal/pkg/policy/policy_output_test.go b/internal/pkg/policy/policy_output_test.go index 8f167b4b8a..3efefcc0a7 100644 --- a/internal/pkg/policy/policy_output_test.go +++ b/internal/pkg/policy/policy_output_test.go @@ -38,7 +38,7 @@ func TestPolicyLogstashOutputPrepare(t *testing.T) { }, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) } @@ -51,7 +51,7 @@ func TestPolicyLogstashOutputPrepareNoRole(t *testing.T) { Role: nil, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) // No permissions are required by logstash currently require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) @@ -69,7 +69,7 @@ func TestPolicyDefaultLogstashOutputPrepare(t *testing.T) { }, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) } @@ -86,7 +86,7 @@ func TestPolicyKafkaOutputPrepare(t *testing.T) { }, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) } @@ -99,7 +99,7 @@ func TestPolicyKafkaOutputPrepareNoRole(t *testing.T) { Role: nil, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) // No permissions are required by kafka currently require.Nil(t, err, "expected prepare to pass") bulker.AssertExpectations(t) @@ -114,7 +114,7 @@ func TestPolicyESOutputPrepareNoRole(t *testing.T) { Role: nil, } - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) require.NotNil(t, err, "expected prepare to error") bulker.AssertExpectations(t) } @@ -136,8 +136,8 @@ func TestPolicyOutputESPrepare(t *testing.T) { }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{}, } testAgent := &model.Agent{ @@ -207,8 +207,8 @@ func TestPolicyOutputESPrepare(t *testing.T) { }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{}, } testAgent := &model.Agent{ @@ -269,8 +269,8 @@ func TestPolicyOutputESPrepare(t *testing.T) { }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{}, } testAgent := &model.Agent{Outputs: map[string]*model.PolicyOutput{}} @@ -311,7 +311,7 @@ func TestPolicyRemoteESOutputPrepareNoRole(t *testing.T) { outputBulker := ftesting.NewMockBulk() bulker.On("CreateAndGetBulker", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(outputBulker, false).Once() - err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]interface{}{}) + err := po.Prepare(context.Background(), logger, bulker, &model.Agent{}, map[string]map[string]any{}) require.Error(t, err, "expected prepare to error") bulker.AssertExpectations(t) } @@ -336,9 +336,9 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { outputBulker := ftesting.NewMockBulk() bulker.On("CreateAndGetBulker", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(outputBulker, false).Once() - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{ - "hosts": []interface{}{"http://localhost"}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{ + "hosts": []any{"http://localhost"}, "service_token": "serviceToken1", "type": OutputTypeRemoteElasticsearch, }, @@ -412,9 +412,9 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{ - "hosts": []interface{}{"http://localhost"}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{ + "hosts": []any{"http://localhost"}, "service_token": "serviceToken1", "type": OutputTypeRemoteElasticsearch, }, @@ -484,9 +484,9 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{ - "hosts": []interface{}{"http://localhost"}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{ + "hosts": []any{"http://localhost"}, "service_token": "serviceToken1", "type": OutputTypeRemoteElasticsearch, }, @@ -542,9 +542,9 @@ func TestPolicyRemoteESOutputPrepare(t *testing.T) { }, } - policyMap := map[string]map[string]interface{}{ - "test output": map[string]interface{}{ - "hosts": []interface{}{"http://localhost"}, + policyMap := map[string]map[string]any{ + "test output": map[string]any{ + "hosts": []any{"http://localhost"}, "service_token": "serviceToken1", "type": OutputTypeRemoteElasticsearch, }, diff --git a/internal/pkg/policy/self.go b/internal/pkg/policy/self.go index 79df146fab..212d8a47bb 100644 --- a/internal/pkg/policy/self.go +++ b/internal/pkg/policy/self.go @@ -217,7 +217,7 @@ func (m *selfMonitorT) updateState(ctx context.Context) (client.UnitState, error state := client.UnitStateHealthy extendMsg := "" - var payload map[string]interface{} + var payload map[string]any if m.fleet.Agent.ID == "" { state = client.UnitStateDegraded extendMsg = "; missing config fleet.agent.id (expected during bootstrap process)" @@ -237,7 +237,7 @@ func (m *selfMonitorT) updateState(ctx context.Context) (client.UnitState, error } return client.UnitStateStarting, nil } - payload = map[string]interface{}{ + payload = map[string]any{ "enrollment_token": tokens[0].APIKey, } } @@ -288,7 +288,7 @@ func reportOutputHealth(ctx context.Context, bulker bulk.Bulk, zlog zerolog.Logg } } -func HasFleetServerInput(inputs []map[string]interface{}) bool { +func HasFleetServerInput(inputs []map[string]any) bool { for _, input := range inputs { attr, ok := input["type"].(string) if !ok { diff --git a/internal/pkg/policy/self_test.go b/internal/pkg/policy/self_test.go index b678a77964..c4adb0e8d1 100644 --- a/internal/pkg/policy/self_test.go +++ b/internal/pkg/policy/self_test.go @@ -62,11 +62,9 @@ func TestSelfMonitor_DefaultPolicy(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) if err := monitor.(*selfMonitorT).waitStart(ctx); err != nil { t.Fatal(err) @@ -86,7 +84,7 @@ func TestSelfMonitor_DefaultPolicy(t *testing.T) { policyID := uuid.Must(uuid.NewV4()).String() rId := xid.New().String() - pData := model.PolicyData{Inputs: []map[string]interface{}{}} + pData := model.PolicyData{Inputs: []map[string]any{}} policy := model.Policy{ ESDocument: model.ESDocument{ Id: rId, @@ -122,7 +120,7 @@ func TestSelfMonitor_DefaultPolicy(t *testing.T) { }) rId = xid.New().String() - pData = model.PolicyData{Inputs: []map[string]interface{}{ + pData = model.PolicyData{Inputs: []map[string]any{ { "type": "fleet-server", }, @@ -213,11 +211,9 @@ func TestSelfMonitor_DefaultPolicy_Degraded(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) if err := monitor.(*selfMonitorT).waitStart(ctx); err != nil { t.Fatal(err) @@ -237,7 +233,7 @@ func TestSelfMonitor_DefaultPolicy_Degraded(t *testing.T) { policyID := uuid.Must(uuid.NewV4()).String() rId := xid.New().String() - pData := model.PolicyData{Inputs: []map[string]interface{}{ + pData := model.PolicyData{Inputs: []map[string]any{ { "type": "fleet-server", }, @@ -357,11 +353,9 @@ func TestSelfMonitor_SpecificPolicy(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) if err := monitor.(*selfMonitorT).waitStart(ctx); err != nil { t.Fatal(err) @@ -380,7 +374,7 @@ func TestSelfMonitor_SpecificPolicy(t *testing.T) { }, ftesting.RetrySleep(1*time.Second)) rId := xid.New().String() - pData := model.PolicyData{Inputs: []map[string]interface{}{}} + pData := model.PolicyData{Inputs: []map[string]any{}} policy := model.Policy{ ESDocument: model.ESDocument{ Id: rId, @@ -416,7 +410,7 @@ func TestSelfMonitor_SpecificPolicy(t *testing.T) { }, ftesting.RetrySleep(1*time.Second)) rId = xid.New().String() - pData = model.PolicyData{Inputs: []map[string]interface{}{ + pData = model.PolicyData{Inputs: []map[string]any{ { "type": "fleet-server", }, @@ -507,11 +501,9 @@ func TestSelfMonitor_SpecificPolicy_Degraded(t *testing.T) { var merr error var mwg sync.WaitGroup - mwg.Add(1) - go func() { - defer mwg.Done() + mwg.Go(func() { merr = monitor.Run(ctx) - }() + }) if err := monitor.(*selfMonitorT).waitStart(ctx); err != nil { t.Fatal(err) @@ -530,7 +522,7 @@ func TestSelfMonitor_SpecificPolicy_Degraded(t *testing.T) { }, ftesting.RetrySleep(1*time.Second)) rId := xid.New().String() - pData := model.PolicyData{Inputs: []map[string]interface{}{ + pData := model.PolicyData{Inputs: []map[string]any{ { "type": "fleet-server", }, @@ -623,10 +615,10 @@ type FakeReporter struct { lock sync.Mutex state client.UnitState msg string - payload map[string]interface{} + payload map[string]any } -func (r *FakeReporter) UpdateState(state client.UnitState, message string, payload map[string]interface{}) error { +func (r *FakeReporter) UpdateState(state client.UnitState, message string, payload map[string]any) error { r.lock.Lock() defer r.lock.Unlock() r.state = state @@ -635,15 +627,14 @@ func (r *FakeReporter) UpdateState(state client.UnitState, message string, paylo return nil } -func (r *FakeReporter) Current() (client.UnitState, string, map[string]interface{}) { +func (r *FakeReporter) Current() (client.UnitState, string, map[string]any) { r.lock.Lock() defer r.lock.Unlock() return r.state, r.msg, r.payload } func TestSelfMonitor_reportOutputHealthyState(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() @@ -677,8 +668,7 @@ func TestSelfMonitor_reportOutputHealthyState(t *testing.T) { } func TestSelfMonitor_reportOutputDegradedState(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() @@ -714,8 +704,7 @@ func TestSelfMonitor_reportOutputDegradedState(t *testing.T) { } func TestSelfMonitor_reportOutputSkipIfOutdated(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() @@ -739,8 +728,7 @@ func TestSelfMonitor_reportOutputSkipIfOutdated(t *testing.T) { } func TestSelfMonitor_reportOutputSkipIfNotFound(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + ctx := t.Context() logger := testlog.SetLogger(t) bulker := ftesting.NewMockBulk() diff --git a/internal/pkg/policy/sub_test.go b/internal/pkg/policy/sub_test.go index 0244327808..d352884d5f 100644 --- a/internal/pkg/policy/sub_test.go +++ b/internal/pkg/policy/sub_test.go @@ -124,7 +124,7 @@ func TestSub_PushRandom(t *testing.T) { N := rand.Intn(4096) + 1 nodes := make([]*subT, 0, N) - for i := 0; i < N; i++ { + for i := range N { name := fmt.Sprintf("policy%d", i) nn := NewSub(name, "", 0) @@ -160,7 +160,7 @@ func TestSub_UnlinkRandomN(t *testing.T) { N := rand.Intn(4096) + 1 nodes := make([]*subT, 0, N) - for i := 0; i < N; i++ { + for i := range N { name := fmt.Sprintf("policy%d", i) nn := NewSub(name, "", 0) head.pushBack(nn) @@ -171,7 +171,7 @@ func TestSub_UnlinkRandomN(t *testing.T) { t.Error("head should not be empty after push") } - for i := 0; i < N; i++ { + for range N { idx := rand.Intn(len(nodes)) sub := nodes[idx] sub.unlink() @@ -216,7 +216,7 @@ func BenchmarkSubs(b *testing.B) { b.Run(fmt.Sprintf("%d", bm), func(b *testing.B) { b.StopTimer() subs := make([]*subT, 0, bm) - for i := 0; i < bm; i++ { + for i := range bm { name := fmt.Sprintf("policy%d", i) nn := NewSub(name, "", 0) subs = append(subs, nn) @@ -226,11 +226,11 @@ func BenchmarkSubs(b *testing.B) { b.StartTimer() for i := 0; i < b.N; i++ { - for j := 0; j < bm; j++ { + for j := range bm { head.pushBack(subs[j]) } - for j := 0; j < bm; j++ { + for j := range bm { subs[j].unlink() } } diff --git a/internal/pkg/profile/profile_test.go b/internal/pkg/profile/profile_test.go index 45b9005288..ba5e64df47 100644 --- a/internal/pkg/profile/profile_test.go +++ b/internal/pkg/profile/profile_test.go @@ -34,7 +34,7 @@ func TestRunProfiler(t *testing.T) { require.NoError(t, err) var resp *http.Response - for i := 0; i < 10; i++ { + for i := range 10 { resp, err = http.DefaultClient.Do(req) //nolint:bodyclose // closed outside the loop if err == nil { break diff --git a/internal/pkg/secret/secret.go b/internal/pkg/secret/secret.go index 90bdb7baef..585cc222c9 100644 --- a/internal/pkg/secret/secret.go +++ b/internal/pkg/secret/secret.go @@ -46,7 +46,7 @@ func GetSecretValues(ctx context.Context, secretRefs []model.SecretReferencesIte // read inputs and secret_references from agent policy // replace values of secret refs in inputs and input streams properties -func ProcessInputsSecrets(data *model.PolicyData, secretValues map[string]string) ([]map[string]interface{}, []string) { +func ProcessInputsSecrets(data *model.PolicyData, secretValues map[string]string) ([]map[string]any, []string) { if len(data.Inputs) == 0 { // No inputs, so no secret references in them to replace. return nil, nil @@ -75,8 +75,8 @@ func ProcessInputsSecrets(data *model.PolicyData, secretValues map[string]string // processInputsWithInlineSecrets reads inputs and secret_references from agent policy and replaces // the values of secret refs in inputs and input streams properties using the old format // for specifying secrets: : $co.elastic.secret{} -func processInputsWithInlineSecrets(data *model.PolicyData, secretValues map[string]string) ([]map[string]interface{}, []string) { - result := make([]map[string]interface{}, 0) +func processInputsWithInlineSecrets(data *model.PolicyData, secretValues map[string]string) ([]map[string]any, []string) { + result := make([]map[string]any, 0) keys := make([]string, 0) for i, input := range data.Inputs { replacedInput, ks := replaceInlineSecretRefsInMap(input, secretValues) @@ -91,8 +91,8 @@ func processInputsWithInlineSecrets(data *model.PolicyData, secretValues map[str // processInputsWithPathSecrets reads inputs and secret_references from agent policy and replaces // the values of secret refs in inputs and input streams properties using the new format // for specifying secrets: secrets...id: -func processInputsWithPathSecrets(data *model.PolicyData, secretValues map[string]string) ([]map[string]interface{}, []string) { - result := make([]map[string]interface{}, 0) +func processInputsWithPathSecrets(data *model.PolicyData, secretValues map[string]string) ([]map[string]any, []string) { + result := make([]map[string]any, 0) keys := make([]string, 0) for i, inp := range data.Inputs { @@ -317,7 +317,7 @@ func setSecretPath(section smap.Map, secretValue string, secretPaths []string) { path, secretPaths := secretPaths[0], secretPaths[1:] if section.GetMap(path) == nil { - section[path] = make(map[string]interface{}) + section[path] = make(map[string]any) } setSecretPath(section.GetMap(path), secretValue, secretPaths) diff --git a/internal/pkg/secret/secret_test.go b/internal/pkg/secret/secret_test.go index 988ebcc273..2ab43c843f 100644 --- a/internal/pkg/secret/secret_test.go +++ b/internal/pkg/secret/secret_test.go @@ -102,10 +102,10 @@ func TestGetActionDataWithSecrets(t *testing.T) { {ID: "ref2"}, } // Input JSON with secret references - input := map[string]interface{}{ + input := map[string]any{ "username": "user1", "password": "$co.elastic.secret{ref1}", - "nested": map[string]interface{}{ + "nested": map[string]any{ "token": "$co.elastic.secret{ref2}", }, } @@ -116,14 +116,14 @@ func TestGetActionDataWithSecrets(t *testing.T) { result, err := GetActionDataWithSecrets(t.Context(), b, refs, bulker) require.NoError(t, err) - var out map[string]interface{} + var out map[string]any err = json.Unmarshal(result, &out) require.NoError(t, err) assert.Equal(t, "user1", out["username"]) assert.Equal(t, "ref1_value", out["password"]) - nestedMap, ok := out["nested"].(map[string]interface{}) + nestedMap, ok := out["nested"].(map[string]any) assert.True(t, ok) require.NoError(t, err) @@ -132,11 +132,11 @@ func TestGetActionDataWithSecrets(t *testing.T) { func TestGetPolicyInputsWithSecretsAndStreams(t *testing.T) { refs := []model.SecretReferencesItems{{ID: "ref1"}, {ID: "ref2"}, {ID: "ref3"}} - inputs := []map[string]interface{}{ + inputs := []map[string]any{ {"id": "input1", "package_var_secret": "$co.elastic.secret{ref1}", "input_var_secret": "$co.elastic.secret{ref2}"}, - {"id": "input2", "streams": []interface{}{ - map[string]interface{}{ + {"id": "input2", "streams": []any{ + map[string]any{ "id": "stream1", "package_var_secret": "$co.elastic.secret{ref1}", "input_var_secret": "$co.elastic.secret{ref2}", @@ -148,16 +148,16 @@ func TestGetPolicyInputsWithSecretsAndStreams(t *testing.T) { SecretReferences: refs, Inputs: inputs, } - expectedStream := map[string]interface{}{ + expectedStream := map[string]any{ "id": "stream1", "package_var_secret": "ref1_value", "input_var_secret": "ref2_value", "stream_var_secret": "ref3_value", } - expectedResult := []map[string]interface{}{ + expectedResult := []map[string]any{ {"id": "input1", "package_var_secret": "ref1_value", "input_var_secret": "ref2_value"}, - {"id": "input2", "streams": []interface{}{expectedStream}}, + {"id": "input2", "streams": []any{expectedStream}}, } secretValues := map[string]string{ @@ -173,15 +173,15 @@ func TestGetPolicyInputsWithSecretsAndStreams(t *testing.T) { func TestPolicyInputSteamsEmbedded(t *testing.T) { refs := []model.SecretReferencesItems{{ID: "ref1"}} - inputs := []map[string]interface{}{ - {"id": "input1", "streams": []interface{}{ - map[string]interface{}{ + inputs := []map[string]any{ + {"id": "input1", "streams": []any{ + map[string]any{ "id": "stream1", "key": "val", - "embedded": map[string]interface{}{ + "embedded": map[string]any{ "embedded-key": "embedded-val", - "embedded-arr": []interface{}{ - map[string]interface{}{ + "embedded-arr": []any{ + map[string]any{ "embedded-secret": "$co.elastic.secret{ref1}", }, }}, @@ -193,16 +193,16 @@ func TestPolicyInputSteamsEmbedded(t *testing.T) { SecretReferences: refs, Inputs: inputs, } - expected := []map[string]interface{}{{ + expected := []map[string]any{{ "id": "input1", - "streams": []interface{}{ - map[string]interface{}{ + "streams": []any{ + map[string]any{ "id": "stream1", "key": "val", - "embedded": map[string]interface{}{ + "embedded": map[string]any{ "embedded-key": "embedded-val", - "embedded-arr": []interface{}{ - map[string]interface{}{ + "embedded-arr": []any{ + map[string]any{ "embedded-secret": "ref1_value", }, }}, @@ -220,10 +220,10 @@ func TestPolicyInputSteamsEmbedded(t *testing.T) { } func TestGetPolicyInputsNoopWhenNoSecrets(t *testing.T) { - inputs := []map[string]interface{}{ + inputs := []map[string]any{ {"id": "input1"}, - {"id": "input2", "streams": []interface{}{ - map[string]interface{}{ + {"id": "input2", "streams": []any{ + map[string]any{ "id": "stream1", }, }}, @@ -231,12 +231,12 @@ func TestGetPolicyInputsNoopWhenNoSecrets(t *testing.T) { pData := model.PolicyData{ Inputs: inputs, } - expectedStream := map[string]interface{}{ + expectedStream := map[string]any{ "id": "stream1", } - expectedResult := []map[string]interface{}{ + expectedResult := []map[string]any{ {"id": "input1"}, - {"id": "input2", "streams": []interface{}{expectedStream}}, + {"id": "input2", "streams": []any{expectedStream}}, } result, keys := ProcessInputsSecrets(&pData, nil) diff --git a/internal/pkg/server/agent.go b/internal/pkg/server/agent.go index 740bc1c1c1..1f6595b087 100644 --- a/internal/pkg/server/agent.go +++ b/internal/pkg/server/agent.go @@ -47,7 +47,7 @@ const ( type clientUnit interface { Expected() client.Expected - UpdateState(state client.UnitState, message string, payload map[string]interface{}) error + UpdateState(state client.UnitState, message string, payload map[string]any) error } // Agent is a fleet-server that runs under the elastic-agent. @@ -223,7 +223,7 @@ func (a *Agent) Run(ctx context.Context) error { } // UpdateState updates the state of the message and payload. -func (a *Agent) UpdateState(state client.UnitState, message string, payload map[string]interface{}) error { +func (a *Agent) UpdateState(state client.UnitState, message string, payload map[string]any) error { if a.inputUnit != nil { _ = a.inputUnit.UpdateState(state, message, payload) } @@ -440,14 +440,11 @@ func (a *Agent) configFromUnits(ctx context.Context) (*config.Config, error) { } expInput := a.inputUnit.Expected() expOutput := a.outputUnit.Expected() - logLevel := expInput.LogLevel - if expOutput.LogLevel > logLevel { - logLevel = expOutput.LogLevel - } + logLevel := max(expOutput.LogLevel, expInput.LogLevel) // pass inputs from policy through go-ucfg in order to flatten keys // if inputCfg.Source.AsMap() is passed directly, any additional server.* settings will be missed - var input map[string]interface{} + var input map[string]any inputsConfig, err := ucfg.NewFrom(expInput.Config.Source.AsMap(), config.DefaultOptions...) if err != nil { return nil, err @@ -465,7 +462,7 @@ func (a *Agent) configFromUnits(ctx context.Context) (*config.Config, error) { a.outputCheckCanceller = nil } - bootstrap, ok := bootstrapCfg.(map[string]interface{}) + bootstrap, ok := bootstrapCfg.(map[string]any) if !ok { return nil, fmt.Errorf("output bootstrap attribute is not an object, detected type: %T", bootstrapCfg) } @@ -491,20 +488,20 @@ func (a *Agent) configFromUnits(ctx context.Context) (*config.Config, error) { } } - cfgData, err := ucfg.NewFrom(map[string]interface{}{ - "fleet": map[string]interface{}{ - "agent": map[string]interface{}{ + cfgData, err := ucfg.NewFrom(map[string]any{ + "fleet": map[string]any{ + "agent": map[string]any{ "id": agentID, "version": agentVersion, }, }, - "output": map[string]interface{}{ + "output": map[string]any{ "elasticsearch": outMap, }, - "inputs": []interface{}{ + "inputs": []any{ input, }, - "logging": map[string]interface{}{ + "logging": map[string]any{ "level": logLevel.String(), }, }) @@ -517,9 +514,9 @@ func (a *Agent) configFromUnits(ctx context.Context) (*config.Config, error) { if err != nil { zerolog.Ctx(ctx).Warn().Err(err).Msg("Unable to parse expected APM config as instrumentation config") } else { - obj := map[string]interface{}{ - "inputs": []interface{}{map[string]interface{}{ - "server": map[string]interface{}{ + obj := map[string]any{ + "inputs": []any{map[string]any{ + "server": map[string]any{ "instrumentation": instrumentationCfg, }, }, @@ -573,7 +570,7 @@ func apmConfigToInstrumentation(src *proto.APMConfig) (config.Instrumentation, e // injectMissingOutputAttributes will inject an explicit set of keys that may be present in bootstrap into outMap. // If outmap has a certificate_authorities or a fingerprint, verification_mode: none will not be injected if it is part of bootstrap. // Note that we avoiding a more generic injection here (iterating over all keys in bootstrap recursively) in order to avoid injecting any unnecessary/deprecated attributes. -func injectMissingOutputAttributes(ctx context.Context, outMap, bootstrap map[string]interface{}) { +func injectMissingOutputAttributes(ctx context.Context, outMap, bootstrap map[string]any) { bootstrapKeys := []string{ "protocol", "hosts", @@ -600,9 +597,9 @@ func injectMissingOutputAttributes(ctx context.Context, outMap, bootstrap map[st outputSSLUsesCA := false injectVerificationNone := false // handle nested structs in bootstrap, currently we just support some ssl config - var bootstrapSSL map[string]interface{} + var bootstrapSSL map[string]any if mp, ok := bootstrap["ssl"]; ok { - bootstrapSSL, ok = mp.(map[string]interface{}) + bootstrapSSL, ok = mp.(map[string]any) if !ok { zerolog.Ctx(ctx).Warn().Interface("ssl_attribute", mp).Msg("Bootstrap ssl attribute is not an object.") // ssl is not a map @@ -619,9 +616,9 @@ func injectMissingOutputAttributes(ctx context.Context, outMap, bootstrap map[st return } - outputSSL := map[string]interface{}{} + outputSSL := map[string]any{} if mp, ok := outMap["ssl"]; ok { - outputSSL, ok = mp.(map[string]interface{}) + outputSSL, ok = mp.(map[string]any) if !ok { zerolog.Ctx(ctx).Warn().Interface("ssl_attribute", mp).Msg("Policy ssl attribute is not an object.") // output.ssl is not a map @@ -639,7 +636,7 @@ func injectMissingOutputAttributes(ctx context.Context, outMap, bootstrap map[st } // injectKeys will inject any key in the passed list that exists in src but is missing from dst. -func injectKeys(keys []string, dst, src map[string]interface{}) { +func injectKeys(keys []string, dst, src map[string]any) { for _, key := range keys { // dst contains the key if _, ok := dst[key]; ok { @@ -654,7 +651,7 @@ func injectKeys(keys []string, dst, src map[string]interface{}) { } // checkForCA checks to see if the passed cfg contains a certificate_authorities list with one item or a non-empty ca_trusted_fingerprint value. -func checkForCA(cfg map[string]interface{}) bool { +func checkForCA(cfg map[string]any) bool { // if the cfg contains verificaton_mode none return false if tmp, ok := cfg["verification_mode"]; ok { if verificationMode, ok := tmp.(string); ok && verificationMode == verifyNone { @@ -662,7 +659,7 @@ func checkForCA(cfg map[string]interface{}) bool { } } if tmp, ok := cfg["certificate_authorities"]; ok { - if cas, ok := tmp.([]interface{}); ok && len(cas) > 0 { + if cas, ok := tmp.([]any); ok && len(cas) > 0 { return true } } @@ -674,7 +671,7 @@ func checkForCA(cfg map[string]interface{}) bool { return false } -func toOutput(data map[string]interface{}) (config.Output, error) { +func toOutput(data map[string]any) (config.Output, error) { var esOut config.Elasticsearch temp, err := ucfg.NewFrom(data, config.DefaultOptions...) if err != nil { @@ -700,7 +697,7 @@ func toOutput(data map[string]interface{}) (config.Output, error) { }, nil } -func (a *Agent) esOutputCheck(ctx context.Context, cfg map[string]interface{}) error { +func (a *Agent) esOutputCheck(ctx context.Context, cfg map[string]any) error { outCfg, err := toOutput(cfg) if err != nil { return fmt.Errorf("unable to convert map into output object: %w", err) @@ -721,7 +718,7 @@ func (a *Agent) esOutputCheck(ctx context.Context, cfg map[string]interface{}) e // esOutputCheckLoop will periodically retest the passed (output) config and signal chReconfigure if it succeeds then return. // If the context ic canceled, or an ErrElasticVersionConflict is returned (by the test) it will return -func (a *Agent) esOutputCheckLoop(ctx context.Context, delay time.Duration, cfg map[string]interface{}) { +func (a *Agent) esOutputCheckLoop(ctx context.Context, delay time.Duration, cfg map[string]any) { for { if err := sleep.WithContext(ctx, delay); err != nil { return // context cancelled diff --git a/internal/pkg/server/agent_integration_test.go b/internal/pkg/server/agent_integration_test.go index e6552a753f..2a95236627 100644 --- a/internal/pkg/server/agent_integration_test.go +++ b/internal/pkg/server/agent_integration_test.go @@ -49,13 +49,13 @@ var biInfo = build.Info{ } var policyData = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, }, OutputPermissions: json.RawMessage(`{"default": {}}`), - Inputs: []map[string]interface{}{{ + Inputs: []map[string]any{{ "type": "fleet-server", }}, } @@ -94,20 +94,20 @@ func TestAgent(t *testing.T) { }) require.NoError(t, err) - inputSource, err := structpb.NewStruct(map[string]interface{}{ + inputSource, err := structpb.NewStruct(map[string]any{ "id": "fleet-server", "type": "fleet-server", "name": "fleet-server", "revision": 1, }) require.NoError(t, err) - outputSource, err := structpb.NewStruct(map[string]interface{}{ + outputSource, err := structpb.NewStruct(map[string]any{ "id": "default", "type": "elasticsearch", "name": "elasticsearch", "revision": 1, "hosts": getESHosts(), - "bootstrap": map[string]interface{}{ + "bootstrap": map[string]any{ // check to make sure the service_token is injected into the output "service_token": getESServiceToken(), }, @@ -118,9 +118,7 @@ func TestAgent(t *testing.T) { defer control.Stop() var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() + wg.Go(func() { a := &Agent{ cliCfg: ucfg.New(), @@ -133,7 +131,7 @@ func TestAgent(t *testing.T) { }, client.WithGRPCDialOptions(grpc.WithTransportCredentials(insecure.NewCredentials()))) err = a.Run(ctx) assert.NoError(t, err) - }() + }) t.Log("'bootstrap' fleet-server test") // wait for fleet-server to report as degraded (starting mode without agent.id) @@ -164,12 +162,12 @@ func TestAgent(t *testing.T) { t.Log("Test bad configuration can recover") // trigger update with bad configuration - badSource, err := structpb.NewStruct(map[string]interface{}{ + badSource, err := structpb.NewStruct(map[string]any{ "id": "default", "type": "elasticsearch", "name": "elasticsearch", "revision": 1, - "hosts": []interface{}{"localhost:63542"}, + "hosts": []any{"localhost:63542"}, "service_token": getESServiceToken(), }) require.NoError(t, err) @@ -187,14 +185,14 @@ func TestAgent(t *testing.T) { // reconfigure to good config with debug log level // the good config in this case is the bootstrap config. - goodSource, err := structpb.NewStruct(map[string]interface{}{ + goodSource, err := structpb.NewStruct(map[string]any{ "id": "default", "type": "elasticsearch", "name": "elasticsearch", "revision": 1, - "hosts": []interface{}{"localhost:63542"}, + "hosts": []any{"localhost:63542"}, "service_token": getESServiceToken(), - "bootstrap": map[string]interface{}{ + "bootstrap": map[string]any{ "id": "default", "type": "elasticsearch", "name": "elasticsearch", @@ -254,15 +252,15 @@ func TestAgentAPM(t *testing.T) { bulker := ftesting.SetupBulk(ctx, t) policyWithInstrumentation := model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, }, OutputPermissions: json.RawMessage(`{"default": {}}`), - Inputs: []map[string]interface{}{{ + Inputs: []map[string]any{{ "type": "fleet-server", - "instrumentation": map[string]interface{}{ // expect this config to not send traces + "instrumentation": map[string]any{ // expect this config to not send traces "enabled": true, "hosts": []string{"example"}, }, @@ -289,20 +287,20 @@ func TestAgentAPM(t *testing.T) { }) require.NoError(t, err) - inputSource, err := structpb.NewStruct(map[string]interface{}{ + inputSource, err := structpb.NewStruct(map[string]any{ "id": "fleet-server", "type": "fleet-server", "name": "fleet-server", "revision": 1, }) require.NoError(t, err) - outputSource, err := structpb.NewStruct(map[string]interface{}{ + outputSource, err := structpb.NewStruct(map[string]any{ "id": "default", "type": "elasticsearch", "name": "elasticsearch", "revision": 1, "hosts": getESHosts(), - "bootstrap": map[string]interface{}{ + "bootstrap": map[string]any{ // check to make sure the service_token is injected into the output "service_token": getESServiceToken(), }, @@ -553,13 +551,13 @@ func (s *StubV2Control) Actions(server proto.ElasticAgent_ActionsServer) error { return nil } -func getESHosts() []interface{} { +func getESHosts() []any { hosts := os.Getenv("ELASTICSEARCH_HOSTS") if hosts == "" { - return []interface{}{"localhost:9200"} + return []any{"localhost:9200"} } hostsSplit := strings.Split(hosts, ",") - rawHosts := make([]interface{}, 0, len(hostsSplit)) + rawHosts := make([]any, 0, len(hostsSplit)) for _, host := range hostsSplit { rawHosts = append(rawHosts, host) } diff --git a/internal/pkg/server/agent_test.go b/internal/pkg/server/agent_test.go index aff7bd9a41..cfbc44701f 100644 --- a/internal/pkg/server/agent_test.go +++ b/internal/pkg/server/agent_test.go @@ -30,28 +30,28 @@ func TestCLIOverrides(t *testing.T) { loggingFilesNameExpected := "fleet-server-logging" serviceToken := "token-test" - cliConfig, err := ucfg.NewFrom(map[string]interface{}{ - "http": map[string]interface{}{ + cliConfig, err := ucfg.NewFrom(map[string]any{ + "http": map[string]any{ "enabled": httpEnabledExpected, "host": httpHostExpected, }, - "logging": map[string]interface{}{ - "files": map[string]interface{}{ + "logging": map[string]any{ + "files": map[string]any{ "name": loggingFilesNameExpected, }, }, - "output": map[string]interface{}{ - "elasticsearch": map[string]interface{}{ + "output": map[string]any{ + "elasticsearch": map[string]any{ "service_token": serviceToken, }, }, }) require.NoError(t, err, "failed creating CLI config") - sampleInputConfig, err := structpb.NewStruct(map[string]interface{}{}) + sampleInputConfig, err := structpb.NewStruct(map[string]any{}) require.NoError(t, err) - sampleOutputConfig, err := structpb.NewStruct(map[string]interface{}{}) + sampleOutputConfig, err := structpb.NewStruct(map[string]any{}) require.NoError(t, err) clientMock := &mockClientV2{} @@ -144,7 +144,7 @@ func (u *mockClientUnit) Expected() client.Expected { return args.Get(0).(client.Expected) //nolint:errcheck // testing mock } -func (u *mockClientUnit) UpdateState(state client.UnitState, message string, payload map[string]interface{}) error { +func (u *mockClientUnit) UpdateState(state client.UnitState, message string, payload map[string]any) error { args := u.Called() return args.Get(0).(error) //nolint:errcheck // testing mock } @@ -156,7 +156,7 @@ func Test_Agent_configFromUnits(t *testing.T) { Version: "test-version", }) t.Run("input has additional server keys", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -168,11 +168,11 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", - "timeouts": map[string]interface{}{ + "timeouts": map[string]any{ "write": "29m", }, }, @@ -206,9 +206,9 @@ func Test_Agent_configFromUnits(t *testing.T) { assert.Equal(t, "test-token", cfg.Output.Elasticsearch.ServiceToken) }) t.Run("output has multiple hosts", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", - "hosts": []interface{}{"https://localhost:9200", "https://127.0.0.1:9200"}, + "hosts": []any{"https://localhost:9200", "https://127.0.0.1:9200"}, }) require.NoError(t, err) mockOutClient := &mockClientUnit{} @@ -218,7 +218,7 @@ func Test_Agent_configFromUnits(t *testing.T) { LogLevel: client.UnitLogLevelInfo, Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{"type": "fleet-server"}) + inStruct, err := structpb.NewStruct(map[string]any{"type": "fleet-server"}) require.NoError(t, err) mockInClient := &mockClientUnit{} mockInClient.On("Expected").Return( @@ -241,7 +241,7 @@ func Test_Agent_configFromUnits(t *testing.T) { require.Len(t, cfg.Output.Elasticsearch.Hosts, 2) }) t.Run("Minimal APM config is specified", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -253,12 +253,12 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", }, - "policy": map[string]interface{}{ + "policy": map[string]any{ "id": "test-policy", }, }) @@ -279,10 +279,10 @@ func Test_Agent_configFromUnits(t *testing.T) { }, }) - cliCfg, err := ucfg.NewFrom(map[string]interface{}{ - "inputs": []interface{}{ - map[string]interface{}{ - "policy": map[string]interface{}{ + cliCfg, err := ucfg.NewFrom(map[string]any{ + "inputs": []any{ + map[string]any{ + "policy": map[string]any{ "id": "test-policy", }, }, @@ -313,7 +313,7 @@ func Test_Agent_configFromUnits(t *testing.T) { assert.Equal(t, "test-token", cfg.Output.Elasticsearch.ServiceToken) }) t.Run("APM config is specified", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -325,12 +325,12 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", }, - "policy": map[string]interface{}{ + "policy": map[string]any{ "id": "test-policy", }, }) @@ -359,10 +359,10 @@ func Test_Agent_configFromUnits(t *testing.T) { }, }) - cliCfg, err := ucfg.NewFrom(map[string]interface{}{ - "inputs": []interface{}{ - map[string]interface{}{ - "policy": map[string]interface{}{ + cliCfg, err := ucfg.NewFrom(map[string]any{ + "inputs": []any{ + map[string]any{ + "policy": map[string]any{ "id": "test-policy", }, }, @@ -394,7 +394,7 @@ func Test_Agent_configFromUnits(t *testing.T) { assert.Equal(t, "0.5", cfg.Inputs[0].Server.Instrumentation.TransactionSampleRate) }) t.Run("APM config no tls", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -406,9 +406,9 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", }, }) @@ -457,7 +457,7 @@ func Test_Agent_configFromUnits(t *testing.T) { assert.Equal(t, "0.01", cfg.Inputs[0].Server.Instrumentation.TransactionSampleRate) }) t.Run("APM config and instrumentation is specified", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -469,20 +469,20 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", - "instrumentation": map[string]interface{}{ + "instrumentation": map[string]any{ "enabled": false, - "tls": map[string]interface{}{ + "tls": map[string]any{ "skip_verify": true, "server_certificate": "/path/to/cert.crt", }, "environment": "replace", "api_key": "replace", "secret_token": "replace", - "hosts": []interface{}{"replace"}, + "hosts": []any{"replace"}, "transaction_sample_rate": "0.75", }, }, @@ -537,7 +537,7 @@ func Test_Agent_configFromUnits(t *testing.T) { assert.Equal(t, "0.01", cfg.Inputs[0].Server.Instrumentation.TransactionSampleRate) }) t.Run("APM config error", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -549,9 +549,9 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", }, }) @@ -581,7 +581,7 @@ func Test_Agent_configFromUnits(t *testing.T) { assert.Equal(t, "test-token", cfg.Output.Elasticsearch.ServiceToken) }) t.Run("no APMConfig has instrumentation config", func(t *testing.T) { - outStruct, err := structpb.NewStruct(map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ "service_token": "test-token", }) require.NoError(t, err) @@ -594,19 +594,19 @@ func Test_Agent_configFromUnits(t *testing.T) { Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{ + inStruct, err := structpb.NewStruct(map[string]any{ "type": "fleet-server", - "server": map[string]interface{}{ + "server": map[string]any{ "host": "0.0.0.0", - "instrumentation": map[string]interface{}{ + "instrumentation": map[string]any{ "enabled": true, - "tls": map[string]interface{}{ + "tls": map[string]any{ "skip_verify": false, "server_certificate": "/path/to/cert.crt", }, "environment": "test", "secret_token": "testToken", - "hosts": []interface{}{"localhost:8080"}, + "hosts": []any{"localhost:8080"}, }, }, }) @@ -651,12 +651,12 @@ func Test_Agent_configFromUnits(t *testing.T) { })) defer srv.Close() - outStruct, err := structpb.NewStruct(map[string]interface{}{ - "bootstrap": map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ + "bootstrap": map[string]any{ "service_token": "test-token", - "hosts": []interface{}{"https://127.0.0.1:9200"}, + "hosts": []any{"https://127.0.0.1:9200"}, }, - "hosts": []interface{}{srv.URL, "https://127.0.0.1:9200"}, + "hosts": []any{srv.URL, "https://127.0.0.1:9200"}, }) require.NoError(t, err) mockOutClient := &mockClientUnit{} @@ -666,7 +666,7 @@ func Test_Agent_configFromUnits(t *testing.T) { LogLevel: client.UnitLogLevelInfo, Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{"type": "fleet-server"}) + inStruct, err := structpb.NewStruct(map[string]any{"type": "fleet-server"}) require.NoError(t, err) mockInClient := &mockClientUnit{} mockInClient.On("Expected").Return( @@ -701,12 +701,12 @@ func Test_Agent_configFromUnits(t *testing.T) { })) defer srv.Close() - outStruct, err := structpb.NewStruct(map[string]interface{}{ - "bootstrap": map[string]interface{}{ + outStruct, err := structpb.NewStruct(map[string]any{ + "bootstrap": map[string]any{ "service_token": "test-token", - "hosts": []interface{}{"https://127.0.0.1:9200"}, + "hosts": []any{"https://127.0.0.1:9200"}, }, - "hosts": []interface{}{srv.URL, "https://127.0.0.1:9200"}, + "hosts": []any{srv.URL, "https://127.0.0.1:9200"}, }) require.NoError(t, err) mockOutClient := &mockClientUnit{} @@ -716,7 +716,7 @@ func Test_Agent_configFromUnits(t *testing.T) { LogLevel: client.UnitLogLevelInfo, Config: &proto.UnitExpectedConfig{Source: outStruct}, }) - inStruct, err := structpb.NewStruct(map[string]interface{}{"type": "fleet-server"}) + inStruct, err := structpb.NewStruct(map[string]any{"type": "fleet-server"}) require.NoError(t, err) mockInClient := &mockClientUnit{} mockInClient.On("Expected").Return( @@ -746,95 +746,95 @@ func Test_Agent_configFromUnits(t *testing.T) { func TestInjectMissingOutputAttributes(t *testing.T) { tests := []struct { name string - input map[string]interface{} - expect map[string]interface{} + input map[string]any + expect map[string]any }{{ name: "empty input", - input: map[string]interface{}{}, - expect: map[string]interface{}{ + input: map[string]any{}, + expect: map[string]any{ "protocol": "https", - "hosts": []interface{}{"localhost:9200"}, + "hosts": []any{"localhost:9200"}, "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "verification_mode": "full", }, }, }, { name: "all keys differ", - input: map[string]interface{}{ + input: map[string]any{ "NewSetting": 4, - "NewMap": map[string]interface{}{ + "NewMap": map[string]any{ "key": "val", }, }, - expect: map[string]interface{}{ + expect: map[string]any{ "NewSetting": 4, - "NewMap": map[string]interface{}{ + "NewMap": map[string]any{ "key": "val", }, "protocol": "https", - "hosts": []interface{}{"localhost:9200"}, + "hosts": []any{"localhost:9200"}, "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "verification_mode": "full", }, }, }, { name: "input has same key", - input: map[string]interface{}{ - "hosts": []interface{}{"localhost:9200", "elasticsearch:9200"}, + input: map[string]any{ + "hosts": []any{"localhost:9200", "elasticsearch:9200"}, }, - expect: map[string]interface{}{ + expect: map[string]any{ "protocol": "https", - "hosts": []interface{}{"localhost:9200", "elasticsearch:9200"}, + "hosts": []any{"localhost:9200", "elasticsearch:9200"}, "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "verification_mode": "full", }, }, }, { name: "input has empty ssl object", - input: map[string]interface{}{ - "ssl": map[string]interface{}{}, + input: map[string]any{ + "ssl": map[string]any{}, }, - expect: map[string]interface{}{ + expect: map[string]any{ "protocol": "https", - "hosts": []interface{}{"localhost:9200"}, + "hosts": []any{"localhost:9200"}, "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "verification_mode": "full", }, }, }, { name: "input has ssl object with same key", - input: map[string]interface{}{ - "ssl": map[string]interface{}{ + input: map[string]any{ + "ssl": map[string]any{ "certificate": "cert", "key": "key", "verification_mode": "none", }, }, - expect: map[string]interface{}{ + expect: map[string]any{ "protocol": "https", - "hosts": []interface{}{"localhost:9200"}, + "hosts": []any{"localhost:9200"}, "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "certificate": "cert", "key": "key", "verification_mode": "none", }, }, }} - bootstrap := map[string]interface{}{ + bootstrap := map[string]any{ "protocol": "https", - "hosts": []interface{}{"localhost:9200"}, + "hosts": []any{"localhost:9200"}, "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "verification_mode": "full", }, "ignoredKey": "badValue", - "ignoredMap": map[string]interface{}{ + "ignoredMap": map[string]any{ "key": "value", }, } @@ -846,68 +846,68 @@ func TestInjectMissingOutputAttributes(t *testing.T) { }) } - bootstrapVerifyNone := map[string]interface{}{ + bootstrapVerifyNone := map[string]any{ "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "verification_mode": "none", }, } sslTests := []struct { name string - input map[string]interface{} - expect map[string]interface{} + input map[string]any + expect map[string]any }{{ name: "no cas none is injected", - input: map[string]interface{}{ - "ssl": map[string]interface{}{ + input: map[string]any{ + "ssl": map[string]any{ "certificate": "value", }, }, - expect: map[string]interface{}{ + expect: map[string]any{ "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "certificate": "value", "verification_mode": "none", }, }, }, { name: "certificate_authority provided", - input: map[string]interface{}{ - "ssl": map[string]interface{}{ - "certificate_authorities": []interface{}{"value"}, + input: map[string]any{ + "ssl": map[string]any{ + "certificate_authorities": []any{"value"}, }, }, - expect: map[string]interface{}{ + expect: map[string]any{ "service_token": "token", - "ssl": map[string]interface{}{ - "certificate_authorities": []interface{}{"value"}, + "ssl": map[string]any{ + "certificate_authorities": []any{"value"}, }, }, }, { name: "fingerprint provided", - input: map[string]interface{}{ - "ssl": map[string]interface{}{ + input: map[string]any{ + "ssl": map[string]any{ "ca_trusted_fingerprint": "value", }, }, - expect: map[string]interface{}{ + expect: map[string]any{ "service_token": "token", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "ca_trusted_fingerprint": "value", }, }, }, { name: "output has CA and verification_mode: none", - input: map[string]interface{}{ - "ssl": map[string]interface{}{ - "certificate_authorities": []interface{}{"value"}, + input: map[string]any{ + "ssl": map[string]any{ + "certificate_authorities": []any{"value"}, "verification_mode": "none", }, }, - expect: map[string]interface{}{ + expect: map[string]any{ "service_token": "token", - "ssl": map[string]interface{}{ - "certificate_authorities": []interface{}{"value"}, + "ssl": map[string]any{ + "certificate_authorities": []any{"value"}, "verification_mode": "none", }, }, @@ -931,7 +931,7 @@ func Test_Agent_esOutputCheckLoop(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) cancel() - a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]interface{}{}) + a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]any{}) assert.Empty(t, a.chReconfigure) }) t.Run("test fails version check", func(t *testing.T) { @@ -951,9 +951,9 @@ func Test_Agent_esOutputCheckLoop(t *testing.T) { } ctx, cancel := context.WithCancel(t.Context()) defer cancel() - a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]interface{}{ + a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]any{ "service_token": "test-token", - "hosts": []interface{}{srv.URL}, + "hosts": []any{srv.URL}, }) assert.Empty(t, a.chReconfigure) }) @@ -980,9 +980,9 @@ func Test_Agent_esOutputCheckLoop(t *testing.T) { } ctx, cancel := context.WithCancel(t.Context()) defer cancel() - a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]interface{}{ + a.esOutputCheckLoop(ctx, time.Millisecond*10, map[string]any{ "service_token": "test-token", - "hosts": []interface{}{srv.URL}, + "hosts": []any{srv.URL}, }) assert.NotEmpty(t, a.chReconfigure) }) diff --git a/internal/pkg/server/fleet_integration_test.go b/internal/pkg/server/fleet_integration_test.go index 7bac90de52..6ab93fb9bb 100644 --- a/internal/pkg/server/fleet_integration_test.go +++ b/internal/pkg/server/fleet_integration_test.go @@ -175,7 +175,7 @@ func startTestServer(t *testing.T, ctx context.Context, policyD model.PolicyData "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", @@ -306,7 +306,7 @@ type MockReporter struct { mock.Mock } -func (m *MockReporter) UpdateState(state client.UnitState, message string, payload map[string]interface{}) error { +func (m *MockReporter) UpdateState(state client.UnitState, message string, payload map[string]any) error { args := m.Called(state, message, payload) return args.Error(0) } @@ -352,7 +352,7 @@ func TestServerConfigErrorReload(t *testing.T) { "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", @@ -629,13 +629,13 @@ func Test_SmokeTest_Agent_Calls(t *testing.T) { t.Log("Agent enrollment successful, verify body") p, _ := io.ReadAll(res.Body) res.Body.Close() - var obj map[string]interface{} // NOTE Should we use response objects? + var obj map[string]any // NOTE Should we use response objects? err = json.Unmarshal(p, &obj) require.NoError(t, err) item, ok := obj["item"] require.True(t, ok, "expected attribute item is missing") - mm, ok := item.(map[string]interface{}) + mm, ok := item.(map[string]any) require.True(t, ok, "expected attribute item to be an object") id, ok := mm["id"] @@ -674,10 +674,10 @@ func Test_SmokeTest_Agent_Calls(t *testing.T) { actionsRaw, ok := obj["actions"] require.True(t, ok, "expected actions is missing") - actions, ok := actionsRaw.([]interface{}) + actions, ok := actionsRaw.([]any) require.True(t, ok, "expected actions to be an array") require.Greater(t, len(actions), 0, "expected at least 1 action") - action, ok := actions[0].(map[string]interface{}) + action, ok := actions[0].(map[string]any) require.True(t, ok, "expected action to be an object") aIDRaw, ok := action["id"] require.True(t, ok, "expected action id attribute missing") @@ -710,7 +710,7 @@ func Test_SmokeTest_Agent_Calls(t *testing.T) { t.Log("Ack successful, verify body") p, _ = io.ReadAll(res.Body) res.Body.Close() - var ackObj map[string]interface{} + var ackObj map[string]any err = json.Unmarshal(p, &ackObj) require.NoError(t, err) @@ -1016,13 +1016,13 @@ func Test_Agent_Auth_errors(t *testing.T) { require.Equal(t, http.StatusOK, res.StatusCode) p, _ := io.ReadAll(res.Body) res.Body.Close() - var obj map[string]interface{} // NOTE Should we use response objects? + var obj map[string]any // NOTE Should we use response objects? err = json.Unmarshal(p, &obj) require.NoError(t, err) item, ok := obj["item"] require.True(t, ok, "expected attribute item is missing") - mm, ok := item.(map[string]interface{}) + mm, ok := item.(map[string]any) require.True(t, ok, "expected attribute item to be an object") keyRaw, ok := mm["access_api_key"] require.True(t, ok, "expected attribute access_api_key is missing") @@ -1076,13 +1076,13 @@ func Test_Agent_Auth_errors(t *testing.T) { t.Log("Agent enrollment successful, verify body") p, _ := io.ReadAll(res.Body) res.Body.Close() - var obj map[string]interface{} // NOTE Should we use response objects? + var obj map[string]any // NOTE Should we use response objects? err = json.Unmarshal(p, &obj) require.NoError(t, err) item, ok := obj["item"] require.True(t, ok, "expected attribute item is missing") - mm, ok := item.(map[string]interface{}) + mm, ok := item.(map[string]any) require.True(t, ok, "expected attribute item to be an object") idRaw, ok := mm["id"] @@ -1475,7 +1475,7 @@ func Test_SmokeTest_Verify_v85Migrate(t *testing.T) { t.Log("Checkin successful, verify body") p, _ := io.ReadAll(res.Body) res.Body.Close() - var obj map[string]interface{} + var obj map[string]any err = json.Unmarshal(p, &obj) require.NoError(t, err) @@ -1486,10 +1486,10 @@ func Test_SmokeTest_Verify_v85Migrate(t *testing.T) { actionsRaw, ok := obj["actions"] require.True(t, ok, "expected actions is missing") - actions, ok := actionsRaw.([]interface{}) + actions, ok := actionsRaw.([]any) require.True(t, ok, "expected actions to be an array") require.Greater(t, len(actions), 0, "expected at least 1 action") - action, ok := actions[0].(map[string]interface{}) + action, ok := actions[0].(map[string]any) require.True(t, ok, "expected action to be an object") aIDRaw, ok := action["id"] require.True(t, ok, "expected action id attribute missing") @@ -1522,7 +1522,7 @@ func Test_SmokeTest_Verify_v85Migrate(t *testing.T) { t.Log("Ack successful, verify body") p, _ = io.ReadAll(res.Body) res.Body.Close() - var ackObj map[string]interface{} + var ackObj map[string]any err = json.Unmarshal(p, &ackObj) require.NoError(t, err) @@ -1539,7 +1539,7 @@ func Test_SmokeTest_Verify_v85Migrate(t *testing.T) { outputNames = append(outputNames, name) } require.Len(t, outputNames, 1) - p = []byte(fmt.Sprintf(`{"script":{"lang": "painless", "source": "ctx._source['outputs'][params.output].api_key = ''; ctx._source['outputs'][params.output].api_key_id = '';", "params": {"output": "%s"}}}`, outputNames[0])) + p = fmt.Appendf(nil, `{"script":{"lang": "painless", "source": "ctx._source['outputs'][params.output].api_key = ''; ctx._source['outputs'][params.output].api_key_id = '';", "params": {"output": "%s"}}}`, outputNames[0]) t.Logf("Attempting to remove api_key attribute from: %s, body: %s", resp.Item.Id, string(p)) err = srv.bulker.Update( ctx, @@ -1574,7 +1574,7 @@ func Test_SmokeTest_Verify_v85Migrate(t *testing.T) { actionsRaw, ok = obj["actions"] require.True(t, ok, "expected actions is missing") - actions, ok = actionsRaw.([]interface{}) + actions, ok = actionsRaw.([]any) require.True(t, ok, "expected actions to be an array") require.Greater(t, len(actions), 0, "expected at least 1 action") @@ -1659,7 +1659,7 @@ func Test_SmokeTest_AuditUnenroll(t *testing.T) { t.Log("Checkin successful, verify body") p, _ := io.ReadAll(res.Body) res.Body.Close() - var obj map[string]interface{} + var obj map[string]any err = json.Unmarshal(p, &obj) require.NoError(t, err) @@ -1675,12 +1675,12 @@ func Test_SmokeTest_AuditUnenroll(t *testing.T) { } p, err := io.ReadAll(res.Body) require.NoError(t, err) - var tmp map[string]interface{} + var tmp map[string]any err = json.Unmarshal(p, &tmp) require.NoError(t, err) o, ok := tmp["_source"] require.Truef(t, ok, "expected to find _source in: %v", tmp) - obj, ok := o.(map[string]interface{}) + obj, ok := o.(map[string]any) require.Truef(t, ok, "expected _source to be an object, was: %T", o) _, ok = obj["audit_unenrolled_reason"] _, ok2 := obj["unenrolled_at"] @@ -1698,7 +1698,7 @@ func TestCheckinOTelColPolicy(t *testing.T) { return fmt.Sprintf("%s/%s", id, idSuffix) } policyData := model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, diff --git a/internal/pkg/server/fleet_secrets_integration_test.go b/internal/pkg/server/fleet_secrets_integration_test.go index 477d837ec3..7a85b2de6c 100644 --- a/internal/pkg/server/fleet_secrets_integration_test.go +++ b/internal/pkg/server/fleet_secrets_integration_test.go @@ -85,36 +85,36 @@ func createSecret(t *testing.T, ctx context.Context, bulker bulk.Bulk, value str func createAgentPolicyWithSecrets(t *testing.T, ctx context.Context, bulker bulk.Bulk, inlineSecretID, inlineSecretRef, pathSecretID string) string { policyID := uuid.Must(uuid.NewV4()).String() var policyData = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", - "secrets": map[string]interface{}{ - "secret-key": map[string]interface{}{"id": pathSecretID}, + "secrets": map[string]any{ + "secret-key": map[string]any{"id": pathSecretID}, }, }, }, OutputPermissions: json.RawMessage(`{"default":{}}`), - Inputs: []map[string]interface{}{{ + Inputs: []map[string]any{{ "type": "fleet-server", "package_var_secret": inlineSecretRef, }}, - Agent: map[string]interface{}{ - "download": map[string]interface{}{ + Agent: map[string]any{ + "download": map[string]any{ "sourceURI": inlineSecretRef, - "secrets": map[string]interface{}{ - "ssl": map[string]interface{}{ - "key": map[string]interface{}{ + "secrets": map[string]any{ + "ssl": map[string]any{ + "key": map[string]any{ "id": pathSecretID, }, }, }, }, }, - Fleet: map[string]interface{}{ + Fleet: map[string]any{ "hosts": []string{inlineSecretRef}, - "secrets": map[string]interface{}{ - "ssl": map[string]interface{}{ - "key": map[string]interface{}{ + "secrets": map[string]any{ + "ssl": map[string]any{ + "key": map[string]any{ "id": pathSecretID, }, }, @@ -156,7 +156,7 @@ func createAgentPolicyWithSecrets(t *testing.T, ctx context.Context, bulker bulk "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", @@ -211,12 +211,12 @@ func Test_Agent_Policy_Secrets(t *testing.T) { t.Log("Agent enrollment successful") p, _ := io.ReadAll(res.Body) res.Body.Close() - var obj map[string]interface{} + var obj map[string]any err = json.Unmarshal(p, &obj) require.NoError(t, err) item := obj["item"] - mm, ok := item.(map[string]interface{}) + mm, ok := item.(map[string]any) require.True(t, ok, "expected attribute item to be an object") id := mm["id"] str, ok := id.(string) @@ -255,7 +255,7 @@ func Test_Agent_Policy_Secrets(t *testing.T) { input := actionData.Policy.Inputs[0] // expect secret reference replaced with secret value - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "package_var_secret": "inline_secret_value", "type": "fleet-server", }, input) @@ -263,7 +263,7 @@ func Test_Agent_Policy_Secrets(t *testing.T) { // expect output secret to be replaced output := actionData.Policy.Outputs["default"] assert.Conditionf(t, func() bool { - mp, ok := output.(map[string]interface{}) + mp, ok := output.(map[string]any) if !ok { return false } @@ -279,17 +279,17 @@ func Test_Agent_Policy_Secrets(t *testing.T) { }, "expected output to contain secret-key: output_secret_value, got %v", output) // expect agent.download secrets to be replaced - assert.Equal(t, map[string]interface{}{ + assert.Equal(t, map[string]any{ "sourceURI": "inline_secret_value", - "ssl": map[string]interface{}{ + "ssl": map[string]any{ "key": "path_secret_value", }, }, actionData.Policy.Agent["download"]) // expect fleet secrets to be replaced - assert.Equal(t, map[string]interface{}{ - "hosts": []interface{}{"inline_secret_value"}, - "ssl": map[string]interface{}{ + assert.Equal(t, map[string]any{ + "hosts": []any{"inline_secret_value"}, + "ssl": map[string]any{ "key": "path_secret_value", }, }, actionData.Policy.Fleet) diff --git a/internal/pkg/server/namespaces_integration_test.go b/internal/pkg/server/namespaces_integration_test.go index 22534077f8..e22e552837 100644 --- a/internal/pkg/server/namespaces_integration_test.go +++ b/internal/pkg/server/namespaces_integration_test.go @@ -28,7 +28,7 @@ import ( func AgentCheckin(t *testing.T, ctx context.Context, srv *tserver, agentID, key string) string { cli := cleanhttp.DefaultClient() - var obj map[string]interface{} + var obj map[string]any t.Logf("Fake a checkin for agent %s", agentID) req, err := http.NewRequestWithContext(ctx, "POST", srv.baseURL()+"/api/fleet/agents/"+agentID+"/checkin", strings.NewReader(checkinBody)) @@ -48,10 +48,10 @@ func AgentCheckin(t *testing.T, ctx context.Context, srv *tserver, agentID, key actionsRaw, ok := obj["actions"] require.True(t, ok, "expected actions is missing") - actions, ok := actionsRaw.([]interface{}) + actions, ok := actionsRaw.([]any) require.True(t, ok, "expected actions to be an array") require.Equal(t, len(actions), 1, "expected 1 action") - action, ok := actions[0].(map[string]interface{}) + action, ok := actions[0].(map[string]any) require.True(t, ok, "expected action to be an object") aIDRaw, ok := action["id"] @@ -164,14 +164,14 @@ func Test_Agent_Namespace_test1(t *testing.T) { t.Log("Create policy with namespace test1") var policyRemoteID = uuid.Must(uuid.NewV4()).String() var policyDataNamespaceTest = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, }, OutputPermissions: json.RawMessage(`{"default": {} }`), - Inputs: []map[string]interface{}{}, - Agent: map[string]interface{}{"monitoring": map[string]string{"use_output": "default"}}, + Inputs: []map[string]any{}, + Agent: map[string]any{"monitoring": map[string]string{"use_output": "default"}}, } _, err = dl.CreatePolicy(ctx, srv.bulker, model.Policy{ @@ -196,7 +196,7 @@ func Test_Agent_Namespace_test1(t *testing.T) { "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", diff --git a/internal/pkg/server/remote_es_output_integration_test.go b/internal/pkg/server/remote_es_output_integration_test.go index 00d6b733f6..550d2d8f38 100644 --- a/internal/pkg/server/remote_es_output_integration_test.go +++ b/internal/pkg/server/remote_es_output_integration_test.go @@ -35,7 +35,7 @@ const ( func Checkin(t *testing.T, ctx context.Context, srv *tserver, agentID, key string, shouldHaveRemoteES bool, actionType string) (string, string) { cli := cleanhttp.DefaultClient() - var obj map[string]interface{} + var obj map[string]any t.Logf("Fake a checkin for agent %s", agentID) req, err := http.NewRequestWithContext(ctx, "POST", srv.baseURL()+"/api/fleet/agents/"+agentID+"/checkin", strings.NewReader(checkinBody)) @@ -55,10 +55,10 @@ func Checkin(t *testing.T, ctx context.Context, srv *tserver, agentID, key strin actionsRaw, ok := obj["actions"] require.True(t, ok, "expected actions is missing") - actions, ok := actionsRaw.([]interface{}) + actions, ok := actionsRaw.([]any) require.True(t, ok, "expected actions to be an array") require.Equal(t, len(actions), 1, "expected 1 action") - action, ok := actions[0].(map[string]interface{}) + action, ok := actions[0].(map[string]any) require.True(t, ok, "expected action to be an object") aIDRaw, ok := action["id"] @@ -72,15 +72,15 @@ func Checkin(t *testing.T, ctx context.Context, srv *tserver, agentID, key strin return "", actionID } dataRaw := action["data"] - data, ok := dataRaw.(map[string]interface{}) + data, ok := dataRaw.(map[string]any) require.True(t, ok, "expected data to be map") - policy, ok := data["policy"].(map[string]interface{}) + policy, ok := data["policy"].(map[string]any) require.True(t, ok, "expected policy to be map") - outputs, ok := policy["outputs"].(map[string]interface{}) + outputs, ok := policy["outputs"].(map[string]any) require.True(t, ok, "expected outputs to be map") var remoteAPIKey string if shouldHaveRemoteES { - remoteES, ok := outputs["remoteES"].(map[string]interface{}) + remoteES, ok := outputs["remoteES"].(map[string]any) require.True(t, ok, "expected remoteES to be map") oType, ok := remoteES["type"].(string) require.True(t, ok, "expected type to be string") @@ -90,7 +90,7 @@ func Checkin(t *testing.T, ctx context.Context, srv *tserver, agentID, key strin remoteAPIKey, ok = remoteES["api_key"].(string) require.True(t, ok, "expected remoteAPIKey to be string") } - defaultOutput, ok := outputs["default"].(map[string]interface{}) + defaultOutput, ok := outputs["default"].(map[string]any) require.True(t, ok, "expected default to be map") defaultAPIKey, ok := defaultOutput["api_key"].(string) require.True(t, ok, "expected defaultAPIKey to be string") @@ -129,7 +129,7 @@ func Ack(t *testing.T, ctx context.Context, srv *tserver, actionID, agentID, key t.Log("Ack successful, verify body") p, _ := io.ReadAll(res.Body) res.Body.Close() - var ackObj map[string]interface{} + var ackObj map[string]any err = json.Unmarshal(p, &ackObj) require.NoError(t, err) @@ -151,7 +151,7 @@ func Test_Agent_Remote_ES_Output(t *testing.T) { var policyRemoteID = uuid.Must(uuid.NewV4()).String() var policyDataRemoteES = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, @@ -164,8 +164,8 @@ func Test_Agent_Remote_ES_Output(t *testing.T) { }, }, OutputPermissions: json.RawMessage(`{"default": {}, "remoteES": {}}`), - Inputs: []map[string]interface{}{}, - Agent: map[string]interface{}{"monitoring": map[string]string{"use_output": "remoteES"}}, + Inputs: []map[string]any{}, + Agent: map[string]any{"monitoring": map[string]string{"use_output": "remoteES"}}, } _, err = dl.CreatePolicy(ctx, srv.bulker, model.Policy{ @@ -190,7 +190,7 @@ func Test_Agent_Remote_ES_Output(t *testing.T) { "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", @@ -234,13 +234,13 @@ func Test_Agent_Remote_ES_Output(t *testing.T) { t.Log("Update policy to remove remote ES output") var policyData = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, }, OutputPermissions: json.RawMessage(`{"default": {}}`), - Inputs: []map[string]interface{}{}, + Inputs: []map[string]any{}, } _, err = dl.CreatePolicy(ctx, srv.bulker, model.Policy{ @@ -305,7 +305,7 @@ func Test_Agent_Remote_ES_Output_ForceUnenroll(t *testing.T) { var policyRemoteID = uuid.Must(uuid.NewV4()).String() var policyDataRemoteES = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, @@ -318,8 +318,8 @@ func Test_Agent_Remote_ES_Output_ForceUnenroll(t *testing.T) { }, }, OutputPermissions: json.RawMessage(`{"default": {}, "remoteES": {}}`), - Inputs: []map[string]interface{}{}, - Agent: map[string]interface{}{"monitoring": map[string]string{"use_output": "remoteES"}}, + Inputs: []map[string]any{}, + Agent: map[string]any{"monitoring": map[string]string{"use_output": "remoteES"}}, } _, err = dl.CreatePolicy(ctx, srv.bulker, model.Policy{ @@ -344,7 +344,7 @@ func Test_Agent_Remote_ES_Output_ForceUnenroll(t *testing.T) { "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", @@ -426,7 +426,7 @@ func Test_Agent_Remote_ES_Output_Unenroll(t *testing.T) { var policyRemoteID = uuid.Must(uuid.NewV4()).String() var policyDataRemoteES = model.PolicyData{ - Outputs: map[string]map[string]interface{}{ + Outputs: map[string]map[string]any{ "default": { "type": "elasticsearch", }, @@ -439,8 +439,8 @@ func Test_Agent_Remote_ES_Output_Unenroll(t *testing.T) { }, }, OutputPermissions: json.RawMessage(`{"default": {}, "remoteES": {}}`), - Inputs: []map[string]interface{}{}, - Agent: map[string]interface{}{"monitoring": map[string]string{"use_output": "remoteES"}}, + Inputs: []map[string]any{}, + Agent: map[string]any{"monitoring": map[string]string{"use_output": "remoteES"}}, } _, err = dl.CreatePolicy(ctx, srv.bulker, model.Policy{ @@ -465,7 +465,7 @@ func Test_Agent_Remote_ES_Output_Unenroll(t *testing.T) { "resources": ["*"] }] } - }`), map[string]interface{}{ + }`), map[string]any{ "managed_by": "fleet", "managed": true, "type": "enroll", diff --git a/internal/pkg/smap/smap.go b/internal/pkg/smap/smap.go index 7cd9ae0b31..7e71fd2a2d 100644 --- a/internal/pkg/smap/smap.go +++ b/internal/pkg/smap/smap.go @@ -16,7 +16,7 @@ import ( "strings" ) -type Map map[string]interface{} +type Map map[string]any // GetMap will return the value for k as a Map or a nil. func (m Map) GetMap(k string) Map { @@ -26,7 +26,7 @@ func (m Map) GetMap(k string) Map { v := m[k] if v != nil { - if m, ok := v.(map[string]interface{}); ok { + if m, ok := v.(map[string]any); ok { return m } } @@ -87,8 +87,8 @@ func (m Map) Get(keyPath string) any { var index uint var isIndex bool - parts := strings.Split(keyPath, ".") - for _, part := range parts { + parts := strings.SplitSeq(keyPath, ".") + for part := range parts { key = part // Check if part is an index diff --git a/internal/pkg/state/reporter.go b/internal/pkg/state/reporter.go index 9f06cf7a65..5d8bf8f8c5 100644 --- a/internal/pkg/state/reporter.go +++ b/internal/pkg/state/reporter.go @@ -14,7 +14,7 @@ import ( // Reporter is interface that reports updated state on. type Reporter interface { // UpdateState triggers updating the state. - UpdateState(state client.UnitState, message string, payload map[string]interface{}) error + UpdateState(state client.UnitState, message string, payload map[string]any) error } // Log will write state' to log. @@ -30,7 +30,7 @@ func NewLog(l *zerolog.Logger) *Log { } // UpdateState triggers updating the state. -func (l *Log) UpdateState(state client.UnitState, message string, _ map[string]interface{}) error { +func (l *Log) UpdateState(state client.UnitState, message string, _ map[string]any) error { l.Info().Str("state", state.String()).Msg(message) return nil } @@ -46,7 +46,7 @@ func NewChained(reporters ...Reporter) *Chained { } // UpdateState triggers updating the state. -func (l *Chained) UpdateState(state client.UnitState, message string, payload map[string]interface{}) error { +func (l *Chained) UpdateState(state client.UnitState, message string, payload map[string]any) error { for _, reporter := range l.reporters { if err := reporter.UpdateState(state, message, payload); err != nil { return err diff --git a/internal/pkg/testing/actions.go b/internal/pkg/testing/actions.go index b7b39160cf..c0f1b0c6ec 100644 --- a/internal/pkg/testing/actions.go +++ b/internal/pkg/testing/actions.go @@ -98,7 +98,7 @@ func CreateRandomActions(opts ...CreateActionsOpt) ([]model.Action, error) { start := r.Int(0, len(agentIds)) end := start + r.Int(0, len(agentIds)-start) - payload := map[string]interface{}{ + payload := map[string]any{ uuid.Must(uuid.NewV4()).String(): uuid.Must(uuid.NewV4()).String(), } diff --git a/internal/pkg/testing/bulk.go b/internal/pkg/testing/bulk.go index b951179aaf..59b8c86b18 100644 --- a/internal/pkg/testing/bulk.go +++ b/internal/pkg/testing/bulk.go @@ -98,7 +98,7 @@ func (m *MockBulk) GetBulkerMap() map[string]bulk.Bulk { return args.Get(0).(map[string]bulk.Bulk) } -func (m *MockBulk) CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, outputName string, outputMap map[string]map[string]interface{}) (bulk.Bulk, bool, error) { +func (m *MockBulk) CreateAndGetBulker(ctx context.Context, zlog zerolog.Logger, outputName string, outputMap map[string]map[string]any) (bulk.Bulk, bool, error) { args := m.Called(ctx, zlog, outputName, outputMap) return args.Get(0).(bulk.Bulk), args.Get(1).(bool), nil } @@ -116,7 +116,7 @@ func (m *MockBulk) ReadSecrets(ctx context.Context, secretIds []string) (map[str return result, nil } -func (m *MockBulk) APIKeyCreate(ctx context.Context, name, ttl string, roles []byte, meta interface{}) (*bulk.APIKey, error) { +func (m *MockBulk) APIKeyCreate(ctx context.Context, name, ttl string, roles []byte, meta any) (*bulk.APIKey, error) { args := m.Called(ctx, name, ttl, roles, meta) return args.Get(0).(*bulk.APIKey), args.Error(1) } @@ -153,7 +153,7 @@ func (m *MockBulk) StartTransactionOptions(name, transactionType string, opts ap return nil } -func (m *MockBulk) RemoteOutputConfigChanged(zlog zerolog.Logger, name string, newCfg map[string]interface{}) bool { +func (m *MockBulk) RemoteOutputConfigChanged(zlog zerolog.Logger, name string, newCfg map[string]any) bool { return name == "outdated" } diff --git a/internal/pkg/testing/esutil/esutil.go b/internal/pkg/testing/esutil/esutil.go index 9b2bb0c2b9..d1da1a901c 100644 --- a/internal/pkg/testing/esutil/esutil.go +++ b/internal/pkg/testing/esutil/esutil.go @@ -48,7 +48,7 @@ type errorResponse struct { Error struct { Type string `json:"type"` Reason string `json:"reason"` - } `json:"error,omitempty"` + } `json:"error"` Status int `json:"status,omitempty"` } diff --git a/internal/pkg/testing/esutil/strmap.go b/internal/pkg/testing/esutil/strmap.go index 3e0950ff1e..bf3de2c933 100644 --- a/internal/pkg/testing/esutil/strmap.go +++ b/internal/pkg/testing/esutil/strmap.go @@ -4,7 +4,7 @@ package esutil -type stringMap map[string]interface{} +type stringMap map[string]any func (m stringMap) GetMap(k string) stringMap { if m == nil { @@ -13,7 +13,7 @@ func (m stringMap) GetMap(k string) stringMap { v := m[k] if v != nil { - if m, ok := v.(map[string]interface{}); ok { + if m, ok := v.(map[string]any); ok { return m } } diff --git a/internal/pkg/testing/esutil/template.go b/internal/pkg/testing/esutil/template.go index 3a19e59cf4..2888bf4158 100644 --- a/internal/pkg/testing/esutil/template.go +++ b/internal/pkg/testing/esutil/template.go @@ -41,8 +41,8 @@ const ( ) type Template struct { - Version int `json:"version"` - Settings map[string]interface{} `json:"settings"` + Version int `json:"version"` + Settings map[string]any `json:"settings"` } type AckResponse struct { diff --git a/internal/pkg/testing/setup.go b/internal/pkg/testing/setup.go index 702b7b7515..95bbfcd22a 100644 --- a/internal/pkg/testing/setup.go +++ b/internal/pkg/testing/setup.go @@ -102,7 +102,7 @@ func CleanIndex(ctx context.Context, t *testing.T, bulker bulk.Bulk, index strin root.Query().MatchAll() q := tmpl.MustResolve(root) - query, err := q.Render(make(map[string]interface{})) + query, err := q.Render(make(map[string]any)) if err != nil { t.Fatalf("could not clean index: failed to render query template: %v", err) } diff --git a/internal/pkg/throttle/throttle_test.go b/internal/pkg/throttle/throttle_test.go index 293f51eacd..0894bb695b 100644 --- a/internal/pkg/throttle/throttle_test.go +++ b/internal/pkg/throttle/throttle_test.go @@ -26,7 +26,7 @@ func TestThrottleZero(t *testing.T) { N := rand.Intn(64) + 10 //nolint:gosec // random number is used for testing var tokens []*Token - for i := 0; i < N; i++ { + for i := range N { key := strconv.Itoa(i) @@ -46,7 +46,7 @@ func TestThrottleZero(t *testing.T) { } // Validate again that all tokens are blocked after allocating N - for i := 0; i < N; i++ { + for i := range N { key := strconv.Itoa(i) @@ -115,7 +115,7 @@ func TestThrottleN(t *testing.T) { // Any subsequent request should fail because at max try := rand.Intn(64) + 1 //nolint:gosec // random number is used for testing - for i := 0; i < try; i++ { + for i := range try { key := strconv.Itoa(N + i) diff --git a/magefile.go b/magefile.go index 06aecf9878..e8c65a116c 100644 --- a/magefile.go +++ b/magefile.go @@ -636,9 +636,9 @@ func (Check) Imports() error { return sh.Run("go", "tool", "-modfile", filepath.Join("dev-tools", "go.mod"), "golang.org/x/tools/cmd/goimports", "-w", ".") } -// Ci runs CI related checks - runs generate, imports, checkHeaders, notice, checkNoChanges. +// Ci runs CI related checks - runs generate, imports, fix, checkHeaders, notice, checkNoChanges. func (Check) Ci() { - mg.SerialDeps(Generate, Check.Imports, Check.Headers, Check.Notice, Check.NoChanges) + mg.SerialDeps(Generate, Check.Imports, Check.Fix, Check.Headers, Check.Notice, Check.NoChanges) } // Go installs and runs golangci-lint. @@ -651,6 +651,25 @@ func (Check) Go() error { return sh.RunV("golangci-lint", "run", "-v") } +// Fix runs go fix ./... with all build tags used in the repo root, and testing dir. +func (Check) Fix() error { + err := sh.RunV("go", "fix", "./...") + for _, tag := range []string{"snapshot", "integration", "requirefips", "requirefips,snapshot", "requirefips,integration"} { + if e := sh.RunV("go", "fix", "-tags", tag, "./..."); e != nil { + err = errors.Join(err, e) + } + } + for _, tag := range []string{"e2e", "cloude2e", "requirefips,e2e", "requirefips,cloude2e"} { + log.Printf("Running in testing with tags: %s", tag) + cmd := exec.Command("go", "fix", "-tags", tag, "./...") + cmd.Dir = "testing" + if out, e := cmd.CombinedOutput(); e != nil { + err = errors.Join(err, fmt.Errorf("%w: %s", e, string(out))) + } + } + return err +} + // getLinter ensures that the linter of the correct version is installed to GOPATH. func getLinter() error { // exit early if linter exists with same version. diff --git a/testing/e2e/agent_install_test.go b/testing/e2e/agent_install_test.go index ee07c7114b..51ad6068b9 100644 --- a/testing/e2e/agent_install_test.go +++ b/testing/e2e/agent_install_test.go @@ -405,16 +405,16 @@ func (suite *AgentInstallSuite) TestAPMInstrumentationPolicy() { ctx, cancel := context.WithTimeout(context.Background(), time.Minute*5) defer cancel() - suite.AddPolicyOverrides(ctx, "fleet-server-apm", map[string]interface{}{ + suite.AddPolicyOverrides(ctx, "fleet-server-apm", map[string]any{ // NOTE: if the following key is specified as agent.monitoring the kibana ui will not merge it correctly in the policy. - "agent": map[string]interface{}{ - "monitoring": map[string]interface{}{ + "agent": map[string]any{ + "monitoring": map[string]any{ "traces": true, - "apm": map[string]interface{}{ - "hosts": []interface{}{"http://localhost:8200"}, + "apm": map[string]any{ + "hosts": []any{"http://localhost:8200"}, "environment": "test-AgentInstallAPMInstrumentationPolicy", "secret_token": "b!gS3cret", - "global_labels": map[string]interface{}{ + "global_labels": map[string]any{ "testName": "AgentInstallAPMInstrumentationPolicy", }, }, diff --git a/testing/e2e/api_version/client_api_2023_06_01.go b/testing/e2e/api_version/client_api_2023_06_01.go index cdbe133162..36fee6703c 100644 --- a/testing/e2e/api_version/client_api_2023_06_01.go +++ b/testing/e2e/api_version/client_api_2023_06_01.go @@ -204,7 +204,7 @@ func (tester *ClientAPITester20230601) FullFileUpload(ctx context.Context, apiKe chunkCount := int(math.Ceil(float64(size) / float64(chunkSize))) tHash := sha256.New() - for i := 0; i < chunkCount; i++ { + for i := range chunkCount { var body bytes.Buffer n := int64(math.Min(float64(chunkSize), float64(size))) size = size - n diff --git a/testing/e2e/api_version/client_api_current.go b/testing/e2e/api_version/client_api_current.go index 7ed80cccdf..34782220c4 100644 --- a/testing/e2e/api_version/client_api_current.go +++ b/testing/e2e/api_version/client_api_current.go @@ -239,7 +239,7 @@ func (tester *ClientAPITester) FullFileUpload(ctx context.Context, apiKey, agent chunkCount := int(math.Ceil(float64(size) / float64(chunkSize))) tHash := sha256.New() - for i := 0; i < chunkCount; i++ { + for i := range chunkCount { var body bytes.Buffer n := int64(math.Min(float64(chunkSize), float64(size))) size = size - n @@ -459,7 +459,7 @@ func (tester *ClientAPITester) TestEnrollAuditUnenroll() { return false } var obj struct { - Source map[string]interface{} `json:"_source"` + Source map[string]any `json:"_source"` } err = json.NewDecoder(res.Body).Decode(&obj) tester.Require().NoError(err) diff --git a/testing/e2e/e2e_test.go b/testing/e2e/e2e_test.go index 57e3fa80e3..604e9b2bf1 100644 --- a/testing/e2e/e2e_test.go +++ b/testing/e2e/e2e_test.go @@ -20,7 +20,7 @@ type logger struct { *testing.T } -func (l *logger) Printf(format string, v ...interface{}) { +func (l *logger) Printf(format string, v ...any) { l.Helper() l.Logf(format, v...) } diff --git a/testing/e2e/scaffold/scaffold.go b/testing/e2e/scaffold/scaffold.go index 2998d97fe6..86c0a966d8 100644 --- a/testing/e2e/scaffold/scaffold.go +++ b/testing/e2e/scaffold/scaffold.go @@ -137,7 +137,7 @@ func (s *Scaffold) SetupKibana() { // If it is in use it will poll every second for up to 30s for any change. func (s *Scaffold) IsFleetServerPortFree() bool { portFree := false - for i := 0; i < 30; i++ { + for range 30 { ln, err := net.Listen("tcp", ":8220") if err == nil { ln.Close() @@ -596,7 +596,7 @@ type logger struct { *testing.T } -func (l *logger) Printf(format string, v ...interface{}) { +func (l *logger) Printf(format string, v ...any) { l.Helper() l.Logf(format, v...) } @@ -696,11 +696,11 @@ func (s *Scaffold) HasTestStatusTrace(ctx context.Context, name string, retry fu } } -func (s *Scaffold) AddPolicyOverrides(ctx context.Context, id string, overrides map[string]interface{}) { +func (s *Scaffold) AddPolicyOverrides(ctx context.Context, id string, overrides map[string]any) { body := struct { - Name string `json:"name"` - Namespace string `json:"namespace"` - Overrides map[string]interface{} `json:"overrides"` + Name string `json:"name"` + Namespace string `json:"namespace"` + Overrides map[string]any `json:"overrides"` }{ Name: id, Namespace: "default", diff --git a/testing/e2e/stand_alone_test.go b/testing/e2e/stand_alone_test.go index ce1e3c4934..a3b51ab06a 100644 --- a/testing/e2e/stand_alone_test.go +++ b/testing/e2e/stand_alone_test.go @@ -265,7 +265,7 @@ func (suite *StandAloneSuite) TestStaticTokenAuthentication() { suite.Require().NoError(err) f, err := os.Create(filepath.Join(dir, "config.yml")) suite.Require().NoError(err) - err = tpl.Execute(f, map[string]interface{}{ + err = tpl.Execute(f, map[string]any{ "Hosts": suite.ESHosts, "ServiceToken": suite.ServiceToken, "CertPath": filepath.Join(suite.CertPath, "fleet-server.crt"), @@ -592,7 +592,7 @@ func (suite *StandAloneSuite) TestOpAMP() { suite.Require().NoError(err) f, err := os.Create(filepath.Join(dir, "config.yml")) suite.Require().NoError(err) - err = tpl.Execute(f, map[string]interface{}{ + err = tpl.Execute(f, map[string]any{ "Hosts": suite.ESHosts, "ServiceToken": suite.ServiceToken, "StaticTokenKey": "opamp-e2e-test-key", @@ -671,7 +671,7 @@ func (suite *StandAloneSuite) TestOpAMP() { suite.Require().NoError(err) f, err = os.Create(filepath.Join(dir, "otelcol.yml")) suite.Require().NoError(err) - err = tpl.Execute(f, map[string]interface{}{ + err = tpl.Execute(f, map[string]any{ "OpAMP": map[string]string{ "InstanceUID": instanceUID, "APIKey": apiKey,