diff --git a/x-pack/elastic-agent/pkg/agent/application/config_test.go b/x-pack/elastic-agent/pkg/agent/application/config_test.go index 1a0287e2502..c79edd0adf7 100644 --- a/x-pack/elastic-agent/pkg/agent/application/config_test.go +++ b/x-pack/elastic-agent/pkg/agent/application/config_test.go @@ -5,12 +5,9 @@ package application import ( - "io/ioutil" "testing" "time" - "gopkg.in/yaml.v2" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -77,9 +74,3 @@ func mustWithConfigMode(standalone bool) *config.Config { }, ) } - -func dumpToYAML(t *testing.T, out string, in interface{}) { - b, err := yaml.Marshal(in) - require.NoError(t, err) - ioutil.WriteFile(out, b, 0600) -} diff --git a/x-pack/elastic-agent/pkg/agent/application/filters/stream_checker_test.go b/x-pack/elastic-agent/pkg/agent/application/filters/stream_checker_test.go index 5750734c477..893398fd6ea 100644 --- a/x-pack/elastic-agent/pkg/agent/application/filters/stream_checker_test.go +++ b/x-pack/elastic-agent/pkg/agent/application/filters/stream_checker_test.go @@ -16,8 +16,6 @@ import ( "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/logger" ) -const semiLongString = "" - func TestStreamCheck(t *testing.T) { type testCase struct { name string diff --git a/x-pack/elastic-agent/pkg/agent/application/gateway/fleet/fleet_gateway_test.go b/x-pack/elastic-agent/pkg/agent/application/gateway/fleet/fleet_gateway_test.go index 8fef5f49e33..aa68c0a715d 100644 --- a/x-pack/elastic-agent/pkg/agent/application/gateway/fleet/fleet_gateway_test.go +++ b/x-pack/elastic-agent/pkg/agent/application/gateway/fleet/fleet_gateway_test.go @@ -164,7 +164,7 @@ func wrapStrToResp(code int, body string) *http.Response { ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(body)), ContentLength: int64(len(body)), - Header: make(http.Header, 0), + Header: make(http.Header), } } diff --git a/x-pack/elastic-agent/pkg/agent/application/managed_mode.go b/x-pack/elastic-agent/pkg/agent/application/managed_mode.go index e0d72a38fc5..16ef8e1710f 100644 --- a/x-pack/elastic-agent/pkg/agent/application/managed_mode.go +++ b/x-pack/elastic-agent/pkg/agent/application/managed_mode.go @@ -7,9 +7,6 @@ package application import ( "context" "fmt" - "io" - "net/http" - "net/url" "github.com/elastic/go-sysinfo" @@ -48,16 +45,6 @@ import ( logreporter "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/reporter/log" ) -type apiClient interface { - Send( - method string, - path string, - params url.Values, - headers http.Header, - body io.Reader, - ) (*http.Response, error) -} - type stateStore interface { Add(fleetapi.Action) AckToken() string @@ -73,7 +60,6 @@ type Managed struct { cancelCtxFn context.CancelFunc log *logger.Logger Config configuration.FleetAgentConfig - api apiClient agentInfo *info.AgentInfo gateway gateway.FleetGateway router pipeline.Router diff --git a/x-pack/elastic-agent/pkg/agent/application/pipeline/dispatcher/dispatcher_test.go b/x-pack/elastic-agent/pkg/agent/application/pipeline/dispatcher/dispatcher_test.go index 0bd1d00408c..504778ad804 100644 --- a/x-pack/elastic-agent/pkg/agent/application/pipeline/dispatcher/dispatcher_test.go +++ b/x-pack/elastic-agent/pkg/agent/application/pipeline/dispatcher/dispatcher_test.go @@ -84,6 +84,7 @@ func TestActionDispatcher(t *testing.T) { action := &mockActionUnknown{} err = d.Dispatch(ack, action) + require.NoError(t, err) require.True(t, def.called) require.Equal(t, action, def.received) }) diff --git a/x-pack/elastic-agent/pkg/agent/application/pipeline/emitter/modifiers/monitoring_decorator.go b/x-pack/elastic-agent/pkg/agent/application/pipeline/emitter/modifiers/monitoring_decorator.go index 82b26f4f5e8..5c1d2d037fd 100644 --- a/x-pack/elastic-agent/pkg/agent/application/pipeline/emitter/modifiers/monitoring_decorator.go +++ b/x-pack/elastic-agent/pkg/agent/application/pipeline/emitter/modifiers/monitoring_decorator.go @@ -42,7 +42,6 @@ func InjectMonitoring(agentInfo *info.AgentInfo, outputGroup string, rootAst *tr }, } - config := make(map[string]interface{}) // if monitoring is not specified use default one where everything is enabled if _, found := transpiler.Lookup(rootAst, monitoringKey); !found { monitoringNode := transpiler.NewDict([]transpiler.Node{ @@ -72,7 +71,7 @@ func InjectMonitoring(agentInfo *info.AgentInfo, outputGroup string, rootAst *tr return programsToRun, err } - config, err = ast.Map() + config, err := ast.Map() if err != nil { return programsToRun, err } diff --git a/x-pack/elastic-agent/pkg/agent/application/pipeline/stream/operator_stream.go b/x-pack/elastic-agent/pkg/agent/application/pipeline/stream/operator_stream.go index ad513133e1e..519a7b6bb52 100644 --- a/x-pack/elastic-agent/pkg/agent/application/pipeline/stream/operator_stream.go +++ b/x-pack/elastic-agent/pkg/agent/application/pipeline/stream/operator_stream.go @@ -8,13 +8,11 @@ import ( "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/agent/application/pipeline" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/agent/configrequest" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/logger" - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/monitoring" ) type operatorStream struct { configHandler pipeline.ConfigHandler log *logger.Logger - monitor monitoring.Monitor } func (b *operatorStream) Close() error { diff --git a/x-pack/elastic-agent/pkg/agent/cmd/enroll.go b/x-pack/elastic-agent/pkg/agent/cmd/enroll.go index 3f0ff56f1eb..4606f363f94 100644 --- a/x-pack/elastic-agent/pkg/agent/cmd/enroll.go +++ b/x-pack/elastic-agent/pkg/agent/cmd/enroll.go @@ -181,7 +181,7 @@ func enroll(streams *cli.IOStreams, cmd *cobra.Command, flags *globalFlags, args } // prompt only when it is not forced and is already enrolled - if !force && (cfg.Fleet != nil && cfg.Fleet.Enabled == true) { + if !force && (cfg.Fleet != nil && cfg.Fleet.Enabled) { confirm, err := c.Confirm("This will replace your current settings. Do you want to continue?", true) if err != nil { return errors.New(err, "problem reading prompt response") diff --git a/x-pack/elastic-agent/pkg/agent/cmd/enroll_cmd.go b/x-pack/elastic-agent/pkg/agent/cmd/enroll_cmd.go index f8c97fc253b..87facba4db6 100644 --- a/x-pack/elastic-agent/pkg/agent/cmd/enroll_cmd.go +++ b/x-pack/elastic-agent/pkg/agent/cmd/enroll_cmd.go @@ -53,11 +53,6 @@ type saver interface { Save(io.Reader) error } -type storeLoad interface { - saver - Load() (io.ReadCloser, error) -} - // enrollCmd is an enroll subcommand that interacts between the Kibana API and the Agent. type enrollCmd struct { log *logger.Logger @@ -218,6 +213,10 @@ func (c *enrollCmd) fleetServerBootstrap(ctx context.Context) error { c.options.FleetServer.ConnStr, c.options.FleetServer.PolicyID, c.options.FleetServer.Host, c.options.FleetServer.Port, c.options.FleetServer.Cert, c.options.FleetServer.CertKey, c.options.FleetServer.ElasticsearchCA) + if err != nil { + return err + } + configToStore := map[string]interface{}{ "fleet": fleetConfig, } diff --git a/x-pack/elastic-agent/pkg/agent/cmd/run.go b/x-pack/elastic-agent/pkg/agent/cmd/run.go index cfc2a2898b3..6daac21342a 100644 --- a/x-pack/elastic-agent/pkg/agent/cmd/run.go +++ b/x-pack/elastic-agent/pkg/agent/cmd/run.go @@ -329,7 +329,7 @@ func exposeMetricsEndpoint(log *logger.Logger, config *common.Config, ns func(st } else { content = string(bytes) } - fmt.Fprintf(w, content) + fmt.Fprint(w, content) } } diff --git a/x-pack/elastic-agent/pkg/agent/cmd/watch.go b/x-pack/elastic-agent/pkg/agent/cmd/watch.go index d7707053dc3..75ad178eb27 100644 --- a/x-pack/elastic-agent/pkg/agent/cmd/watch.go +++ b/x-pack/elastic-agent/pkg/agent/cmd/watch.go @@ -81,7 +81,7 @@ func watchCmd(streams *cli.IOStreams, cmd *cobra.Command, flags *globalFlags, ar isWithinGrace, tilGrace := gracePeriod(marker) if !isWithinGrace { - log.Debugf("not within grace [updatedOn %v] %v", marker.UpdatedOn.String(), time.Now().Sub(marker.UpdatedOn).String()) + log.Debugf("not within grace [updatedOn %v] %v", marker.UpdatedOn.String(), time.Since(marker.UpdatedOn).String()) // if it is started outside of upgrade loop // if we're not within grace and marker is still there it might mean // that cleanup was not performed ok, cleanup everything except current version @@ -172,7 +172,7 @@ WATCHLOOP: // gracePeriod returns true if it is within grace period and time until grace period ends. // otherwise it returns false and 0 func gracePeriod(marker *upgrade.UpdateMarker) (bool, time.Duration) { - sinceUpdate := time.Now().Sub(marker.UpdatedOn) + sinceUpdate := time.Since(marker.UpdatedOn) if 0 < sinceUpdate && sinceUpdate < gracePeriodDuration { return true, gracePeriodDuration - sinceUpdate diff --git a/x-pack/elastic-agent/pkg/agent/control/client/client.go b/x-pack/elastic-agent/pkg/agent/control/client/client.go index 5e55fce9349..3709a834a77 100644 --- a/x-pack/elastic-agent/pkg/agent/control/client/client.go +++ b/x-pack/elastic-agent/pkg/agent/control/client/client.go @@ -78,12 +78,10 @@ type Client interface { // client manages the state and communication to the Elastic Agent. type client struct { - ctx context.Context - cancel context.CancelFunc - wg sync.WaitGroup - client proto.ElasticAgentControlClient - cfgLock sync.RWMutex - obsLock sync.RWMutex + ctx context.Context + cancel context.CancelFunc + wg sync.WaitGroup + client proto.ElasticAgentControlClient } // New creates a client connection to Elastic Agent. diff --git a/x-pack/elastic-agent/pkg/agent/install/uninstall.go b/x-pack/elastic-agent/pkg/agent/install/uninstall.go index 978a6965403..38b0e62dd24 100644 --- a/x-pack/elastic-agent/pkg/agent/install/uninstall.go +++ b/x-pack/elastic-agent/pkg/agent/install/uninstall.go @@ -176,6 +176,9 @@ func programsFromConfig(cfg *config.Config) ([]program.Program, error) { } ppMap, err := program.Programs(agentInfo, ast) + if err != nil { + return nil, errors.New("failed to get programs from config", err) + } var pp []program.Program check := make(map[string]bool) @@ -196,6 +199,10 @@ func programsFromConfig(cfg *config.Config) ([]program.Program, error) { func applyDynamics(ctx context.Context, log *logger.Logger, cfg *config.Config) (*config.Config, error) { cfgMap, err := cfg.ToMapStr() + if err != nil { + return nil, err + } + ast, err := transpiler.NewAST(cfgMap) if err != nil { return nil, err @@ -204,7 +211,7 @@ func applyDynamics(ctx context.Context, log *logger.Logger, cfg *config.Config) // apply dynamic inputs inputs, ok := transpiler.Lookup(ast, "inputs") if ok { - varsArray := make([]*transpiler.Vars, 0, 0) + varsArray := make([]*transpiler.Vars, 0) var wg sync.WaitGroup wg.Add(1) varsCallback := func(vv []*transpiler.Vars) { @@ -246,5 +253,9 @@ func applyDynamics(ctx context.Context, log *logger.Logger, cfg *config.Config) } finalConfig, err := newAst.Map() + if err != nil { + return nil, err + } + return config.NewConfigFrom(finalConfig) } diff --git a/x-pack/elastic-agent/pkg/agent/operation/common_test.go b/x-pack/elastic-agent/pkg/agent/operation/common_test.go index 2ec6b531456..12e20e9b0ff 100644 --- a/x-pack/elastic-agent/pkg/agent/operation/common_test.go +++ b/x-pack/elastic-agent/pkg/agent/operation/common_test.go @@ -129,7 +129,7 @@ func waitFor(t *testing.T, check func() error) { if err == nil { return } - if time.Now().Sub(started) >= 15*time.Second { + if time.Since(started) >= 15*time.Second { t.Fatalf("check timed out after 15 second: %s", err) } time.Sleep(10 * time.Millisecond) diff --git a/x-pack/elastic-agent/pkg/agent/operation/operation_remove.go b/x-pack/elastic-agent/pkg/agent/operation/operation_remove.go deleted file mode 100644 index f2254293446..00000000000 --- a/x-pack/elastic-agent/pkg/agent/operation/operation_remove.go +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one -// or more contributor license agreements. Licensed under the Elastic License; -// you may not use this file except in compliance with the Elastic License. - -package operation - -import ( - "context" - - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/state" -) - -// operationRemove uninstall and removes all the bits related to the artifact -type operationRemove struct { -} - -func newOperationRemove() *operationRemove { - return &operationRemove{} -} - -// Name is human readable name identifying an operation -func (o *operationRemove) Name() string { - return "operation-remove" -} - -// Check checks whether remove needs to run. -// -// Always returns false. -func (o *operationRemove) Check(_ context.Context, _ Application) (bool, error) { - return false, nil -} - -// Run runs the operation -func (o *operationRemove) Run(ctx context.Context, application Application) (err error) { - defer func() { - if err != nil { - application.SetState(state.Failed, err.Error(), nil) - } - }() - - return nil -} diff --git a/x-pack/elastic-agent/pkg/agent/operation/operator.go b/x-pack/elastic-agent/pkg/agent/operation/operator.go index a0416545b11..35b9a6731b1 100644 --- a/x-pack/elastic-agent/pkg/agent/operation/operator.go +++ b/x-pack/elastic-agent/pkg/agent/operation/operator.go @@ -152,7 +152,7 @@ func (o *Operator) HandleConfig(cfg configrequest.Request) error { o.statusController.UpdateStateID(stateID) for _, step := range steps { - if strings.ToLower(step.ProgramSpec.Cmd) != strings.ToLower(monitoringName) { + if !strings.EqualFold(step.ProgramSpec.Cmd, monitoringName) { if _, isSupported := program.SupportedMap[strings.ToLower(step.ProgramSpec.Cmd)]; !isSupported { // mark failed, new config cannot be run msg := fmt.Sprintf("program '%s' is not supported", step.ProgramSpec.Cmd) @@ -344,8 +344,3 @@ func (o *Operator) deleteApp(p Descriptor) { o.logger.Debugf("operator is removing %s from app collection: %v", p.ID(), o.apps) delete(o.apps, id) } - -func isMonitorable(descriptor Descriptor) bool { - isSidecar := app.IsSidecar(descriptor) - return !isSidecar // everything is monitorable except sidecar -} diff --git a/x-pack/elastic-agent/pkg/agent/stateresolver/resolve.go b/x-pack/elastic-agent/pkg/agent/stateresolver/resolve.go index 2491a66d4a0..93f01d89ec8 100644 --- a/x-pack/elastic-agent/pkg/agent/stateresolver/resolve.go +++ b/x-pack/elastic-agent/pkg/agent/stateresolver/resolve.go @@ -27,8 +27,6 @@ const ( unchangedState // UNCHANGED ) -type id string - // state represent the SHOULD state of the system, contains a reference to the actual bundle of // configuration received by the upstream call and keep track of the last change executed on a program. // diff --git a/x-pack/elastic-agent/pkg/agent/stateresolver/stateresolver_test.go b/x-pack/elastic-agent/pkg/agent/stateresolver/stateresolver_test.go index e1c83c7409d..3bc4a1ac547 100644 --- a/x-pack/elastic-agent/pkg/agent/stateresolver/stateresolver_test.go +++ b/x-pack/elastic-agent/pkg/agent/stateresolver/stateresolver_test.go @@ -38,7 +38,7 @@ func TestStateResolverAcking(t *testing.T) { ack() // Current sate is not empty lets try to resolve the same configuration. - _, _, steps, ack, err = r.Resolve(submit) + _, _, steps, _, err = r.Resolve(submit) require.NoError(t, err) require.Equal(t, 0, len(steps)) }) diff --git a/x-pack/elastic-agent/pkg/agent/storage/storage.go b/x-pack/elastic-agent/pkg/agent/storage/storage.go index 2ff2d7250f1..a578edb1dfd 100644 --- a/x-pack/elastic-agent/pkg/agent/storage/storage.go +++ b/x-pack/elastic-agent/pkg/agent/storage/storage.go @@ -26,10 +26,6 @@ type Store interface { Save(io.Reader) error } -type load interface { - Load() (io.ReadCloser, error) -} - // NullStore this is only use to split the work into multiples PRs. type NullStore struct{} diff --git a/x-pack/elastic-agent/pkg/agent/transpiler/ast.go b/x-pack/elastic-agent/pkg/agent/transpiler/ast.go index cfb02d1660a..f2f600e5646 100644 --- a/x-pack/elastic-agent/pkg/agent/transpiler/ast.go +++ b/x-pack/elastic-agent/pkg/agent/transpiler/ast.go @@ -611,7 +611,7 @@ func (s *BoolVal) Find(key string) (Node, bool) { } func (s *BoolVal) String() string { - if s.value == true { + if s.value { return "true" } return "false" @@ -1077,7 +1077,7 @@ func Insert(a *AST, node Node, to Selector) error { // to create 2 different sub AST and want to merge them together again. func Combine(a, b *AST) (*AST, error) { newAST := &AST{} - if reflect.TypeOf(b.root) != reflect.TypeOf(b.root) { + if reflect.TypeOf(a.root) != reflect.TypeOf(b.root) { return nil, fmt.Errorf("incompatible node type to combine, received %T and %T", a, b) } diff --git a/x-pack/elastic-agent/pkg/agent/transpiler/rules.go b/x-pack/elastic-agent/pkg/agent/transpiler/rules.go index 42acd53d21a..4fec7c78032 100644 --- a/x-pack/elastic-agent/pkg/agent/transpiler/rules.go +++ b/x-pack/elastic-agent/pkg/agent/transpiler/rules.go @@ -953,7 +953,7 @@ func (r *TranslateWithRegexpRule) Apply(_ AgentInfo, ast *AST) error { return fmt.Errorf("cannot rename, invalid type expected 'Key' received '%T'", node) } - candidate, ok := n.value.(Node).Value().(string) + candidate, ok := n.value.Value().(string) if !ok { return fmt.Errorf("cannot filter on value expected 'string' and received %T", candidate) } @@ -1170,7 +1170,7 @@ func (r *FilterValuesRule) Apply(_ AgentInfo, ast *AST) error { } for _, v := range r.Values { - if v == n.value.(Node).Value() { + if v == n.value.Value() { newNodes = append(newNodes, item) break } @@ -1282,7 +1282,7 @@ func (r *FilterValuesWithRegexpRule) Apply(_ AgentInfo, ast *AST) error { continue } - candidate, ok := n.value.(Node).Value().(string) + candidate, ok := n.value.Value().(string) if !ok { return fmt.Errorf("cannot filter on value expected 'string' and received %T", candidate) } diff --git a/x-pack/elastic-agent/pkg/agent/transpiler/vars.go b/x-pack/elastic-agent/pkg/agent/transpiler/vars.go index 698847edd16..811c5ee9577 100644 --- a/x-pack/elastic-agent/pkg/agent/transpiler/vars.go +++ b/x-pack/elastic-agent/pkg/agent/transpiler/vars.go @@ -97,7 +97,7 @@ func (v *Vars) Lookup(name string) (interface{}, bool) { func nodeToValue(node Node) Node { switch n := node.(type) { case *Key: - return n.value.(Node) + return n.value } return node } diff --git a/x-pack/elastic-agent/pkg/artifact/download/composed/downloader_test.go b/x-pack/elastic-agent/pkg/artifact/download/composed/downloader_test.go index 81e9af137dc..faf0f2f26b9 100644 --- a/x-pack/elastic-agent/pkg/artifact/download/composed/downloader_test.go +++ b/x-pack/elastic-agent/pkg/artifact/download/composed/downloader_test.go @@ -38,19 +38,19 @@ func (d *SuccDownloader) Called() bool { return d.called } func TestComposed(t *testing.T) { testCases := []testCase{ - testCase{ + { downloaders: []CheckableDownloader{&FailingDownloader{}, &SuccDownloader{}}, checkFunc: func(d []CheckableDownloader) bool { return d[0].Called() && d[1].Called() }, expectedResult: true, - }, testCase{ + }, { downloaders: []CheckableDownloader{&SuccDownloader{}, &SuccDownloader{}}, checkFunc: func(d []CheckableDownloader) bool { return d[0].Called() && !d[1].Called() }, expectedResult: true, - }, testCase{ + }, { downloaders: []CheckableDownloader{&SuccDownloader{}, &FailingDownloader{}}, checkFunc: func(d []CheckableDownloader) bool { return d[0].Called() && !d[1].Called() }, expectedResult: true, - }, testCase{ + }, { downloaders: []CheckableDownloader{&FailingDownloader{}, &FailingDownloader{}}, checkFunc: func(d []CheckableDownloader) bool { return d[0].Called() && d[1].Called() }, expectedResult: false, @@ -59,7 +59,7 @@ func TestComposed(t *testing.T) { for _, tc := range testCases { d := NewDownloader(tc.downloaders[0], tc.downloaders[1]) - r, _ := d.Download(nil, program.Spec{Name: "a", Cmd: "a", Artifact: "a/a"}, "b") + r, _ := d.Download(context.TODO(), program.Spec{Name: "a", Cmd: "a", Artifact: "a/a"}, "b") assert.Equal(t, tc.expectedResult, r == "succ") diff --git a/x-pack/elastic-agent/pkg/artifact/download/fs/verifier_test.go b/x-pack/elastic-agent/pkg/artifact/download/fs/verifier_test.go index 38d17dadf4c..8abea0e59f0 100644 --- a/x-pack/elastic-agent/pkg/artifact/download/fs/verifier_test.go +++ b/x-pack/elastic-agent/pkg/artifact/download/fs/verifier_test.go @@ -28,11 +28,6 @@ var ( beatSpec = program.Spec{Name: "Filebeat", Cmd: "filebeat", Artifact: "beat/filebeat"} ) -type testCase struct { - system string - arch string -} - func TestFetchVerify(t *testing.T) { timeout := 15 * time.Second dropPath := filepath.Join("testdata", "drop") diff --git a/x-pack/elastic-agent/pkg/artifact/download/http/downloader_test.go b/x-pack/elastic-agent/pkg/artifact/download/http/downloader_test.go index 4c6c79997cb..1db7f9e40cc 100644 --- a/x-pack/elastic-agent/pkg/artifact/download/http/downloader_test.go +++ b/x-pack/elastic-agent/pkg/artifact/download/http/downloader_test.go @@ -21,8 +21,7 @@ func TestDownloadBodyError(t *testing.T) { // part way through the download, while copying the response body. type connKey struct{} - var srv *httptest.Server - srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) w.(http.Flusher).Flush() conn := r.Context().Value(connKey{}).(net.Conn) diff --git a/x-pack/elastic-agent/pkg/artifact/install/zip/zip_installer.go b/x-pack/elastic-agent/pkg/artifact/install/zip/zip_installer.go index eba432feefb..625d90b2b20 100644 --- a/x-pack/elastic-agent/pkg/artifact/install/zip/zip_installer.go +++ b/x-pack/elastic-agent/pkg/artifact/install/zip/zip_installer.go @@ -18,11 +18,6 @@ import ( "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/artifact" ) -const ( - // powershellCmdTemplate uses elevated execution policy to avoid failure in case script execution is disabled on the system - powershellCmdTemplate = `set-executionpolicy unrestricted; cd %s; .\install-service-%s.ps1` -) - // Installer or zip packages type Installer struct { config *artifact.Config diff --git a/x-pack/elastic-agent/pkg/capabilities/capabilities_test.go b/x-pack/elastic-agent/pkg/capabilities/capabilities_test.go index 46107463151..5dbd46a4303 100644 --- a/x-pack/elastic-agent/pkg/capabilities/capabilities_test.go +++ b/x-pack/elastic-agent/pkg/capabilities/capabilities_test.go @@ -57,6 +57,8 @@ func TestLoadCapabilities(t *testing.T) { defer resultCloser.Close() expectedMap, err := expectedConfig.ToMapStr() + assert.NoError(t, err) + fixInputsType(expectedMap) fixInputsType(resultConfig) diff --git a/x-pack/elastic-agent/pkg/capabilities/rule_test.go b/x-pack/elastic-agent/pkg/capabilities/rule_test.go index 5f3bab860bf..c6e367fc517 100644 --- a/x-pack/elastic-agent/pkg/capabilities/rule_test.go +++ b/x-pack/elastic-agent/pkg/capabilities/rule_test.go @@ -15,7 +15,7 @@ import ( func TestUnmarshal(t *testing.T) { t.Run("valid json", func(t *testing.T) { - rr := &ruleDefinitions{Capabilities: make([]ruler, 0, 0)} + rr := &ruleDefinitions{Capabilities: make([]ruler, 0)} err := json.Unmarshal(jsonDefinitionValid, &rr) @@ -35,7 +35,7 @@ func TestUnmarshal(t *testing.T) { }) t.Run("valid yaml", func(t *testing.T) { - rr := &ruleDefinitions{Capabilities: make([]ruler, 0, 0)} + rr := &ruleDefinitions{Capabilities: make([]ruler, 0)} err := yaml.Unmarshal(yamlDefinitionValid, &rr) diff --git a/x-pack/elastic-agent/pkg/composable/providers/docker/docker.go b/x-pack/elastic-agent/pkg/composable/providers/docker/docker.go index 902ceb7c832..ad49bac6288 100644 --- a/x-pack/elastic-agent/pkg/composable/providers/docker/docker.go +++ b/x-pack/elastic-agent/pkg/composable/providers/docker/docker.go @@ -91,9 +91,7 @@ func (c *dynamicProvider) Run(comm composable.DynamicProviderComm) error { }) stoppers[data.container.ID] = stopper case data := <-stopTrigger: - if _, ok := stoppers[data.container.ID]; ok { - delete(stoppers, data.container.ID) - } + delete(stoppers, data.container.ID) comm.Remove(data.container.ID) } } diff --git a/x-pack/elastic-agent/pkg/composable/registry.go b/x-pack/elastic-agent/pkg/composable/registry.go index e9c8c0fb037..fa1acf59b4c 100644 --- a/x-pack/elastic-agent/pkg/composable/registry.go +++ b/x-pack/elastic-agent/pkg/composable/registry.go @@ -21,7 +21,7 @@ type providerRegistry struct { // Providers holds all known providers, they must be added to it to enable them for use var Providers = &providerRegistry{ - contextProviders: make(map[string]ContextProviderBuilder, 0), - dynamicProviders: make(map[string]DynamicProviderBuilder, 0), + contextProviders: make(map[string]ContextProviderBuilder), + dynamicProviders: make(map[string]DynamicProviderBuilder), logger: logp.NewLogger("dynamic"), } diff --git a/x-pack/elastic-agent/pkg/core/monitoring/beats/beats_monitor.go b/x-pack/elastic-agent/pkg/core/monitoring/beats/beats_monitor.go index 5944afa4f0c..f2066bf04ec 100644 --- a/x-pack/elastic-agent/pkg/core/monitoring/beats/beats_monitor.go +++ b/x-pack/elastic-agent/pkg/core/monitoring/beats/beats_monitor.go @@ -223,9 +223,7 @@ func monitoringDrop(path string) (drop string) { return "" } - if strings.HasPrefix(path, httpPlusPrefix) { - path = strings.TrimPrefix(path, httpPlusPrefix) - } + path = strings.TrimPrefix(path, httpPlusPrefix) // npipe is virtual without a drop if isNpipe(path) { diff --git a/x-pack/elastic-agent/pkg/core/monitoring/monitor.go b/x-pack/elastic-agent/pkg/core/monitoring/monitor.go index 61ebdf3c771..00c7a50003a 100644 --- a/x-pack/elastic-agent/pkg/core/monitoring/monitor.go +++ b/x-pack/elastic-agent/pkg/core/monitoring/monitor.go @@ -7,10 +7,8 @@ package monitoring import ( "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/agent/configuration" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/agent/program" - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/artifact" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/config" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/monitoring/beats" - monitoringConfig "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/monitoring/config" ) // Monitor is a monitoring interface providing information about the way @@ -30,12 +28,6 @@ type Monitor interface { Close() } -// TODO: changeme -type wrappedConfig struct { - DownloadConfig *artifact.Config `yaml:"agent.download" config:"agent.download"` - MonitoringConfig *monitoringConfig.MonitoringConfig `config:"agent.monitoring" yaml:"agent.monitoring"` -} - // NewMonitor creates a monitor based on a process configuration. func NewMonitor(cfg *configuration.SettingsConfig) (Monitor, error) { return beats.NewMonitor(cfg.DownloadConfig, cfg.MonitoringConfig), nil diff --git a/x-pack/elastic-agent/pkg/core/plugin/process/watch_posix.go b/x-pack/elastic-agent/pkg/core/plugin/process/watch_posix.go index fe20029c94b..8f5f99e4679 100644 --- a/x-pack/elastic-agent/pkg/core/plugin/process/watch_posix.go +++ b/x-pack/elastic-agent/pkg/core/plugin/process/watch_posix.go @@ -21,6 +21,9 @@ func (a *Application) externalProcess(proc *os.Process) { return } + for range time.After(1 * time.Second) { + + } for { select { case <-time.After(1 * time.Second): diff --git a/x-pack/elastic-agent/pkg/core/plugin/service/app.go b/x-pack/elastic-agent/pkg/core/plugin/service/app.go index 97196e0307f..b33561f305f 100644 --- a/x-pack/elastic-agent/pkg/core/plugin/service/app.go +++ b/x-pack/elastic-agent/pkg/core/plugin/service/app.go @@ -38,19 +38,17 @@ var ( // Application encapsulates an application that is ran as a service by the system service manager. type Application struct { - bgContext context.Context - id string - name string - pipelineID string - logLevel string - desc *app.Descriptor - srv *server.Server - srvState *server.ApplicationState - limiter *tokenbucket.Bucket - startContext context.Context - tag app.Taggable - state state.State - reporter state.Reporter + bgContext context.Context + id string + name string + pipelineID string + logLevel string + desc *app.Descriptor + srv *server.Server + srvState *server.ApplicationState + limiter *tokenbucket.Bucket + state state.State + reporter state.Reporter uid int gid int diff --git a/x-pack/elastic-agent/pkg/core/server/server_test.go b/x-pack/elastic-agent/pkg/core/server/server_test.go index 4b4703f27fe..f55b4293b60 100644 --- a/x-pack/elastic-agent/pkg/core/server/server_test.go +++ b/x-pack/elastic-agent/pkg/core/server/server_test.go @@ -785,7 +785,7 @@ func waitFor(check func() error) error { if err == nil { return nil } - if time.Now().Sub(started) >= 5*time.Second { + if time.Since(started) >= 5*time.Second { return fmt.Errorf("check timed out after 5 second: %s", err) } time.Sleep(10 * time.Millisecond) diff --git a/x-pack/elastic-agent/pkg/crypto/io.go b/x-pack/elastic-agent/pkg/crypto/io.go index fca7cb6b188..be3751c5be7 100644 --- a/x-pack/elastic-agent/pkg/crypto/io.go +++ b/x-pack/elastic-agent/pkg/crypto/io.go @@ -217,7 +217,6 @@ type Reader struct { err error readHeader bool gcm cipher.AEAD - iv []byte buf []byte eof bool } diff --git a/x-pack/elastic-agent/pkg/crypto/io_test.go b/x-pack/elastic-agent/pkg/crypto/io_test.go index 46847643010..1e3bd24685f 100644 --- a/x-pack/elastic-agent/pkg/crypto/io_test.go +++ b/x-pack/elastic-agent/pkg/crypto/io_test.go @@ -29,7 +29,7 @@ func TestIO(t *testing.T) { require.Equal(t, len(msg), n) // Guard to make sure we have not the same bytes. - require.True(t, bytes.Index(dest.Bytes(), msg) == -1) + require.False(t, bytes.Contains(dest.Bytes(), msg)) r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) @@ -56,7 +56,7 @@ func TestIO(t *testing.T) { require.Equal(t, int64(len(msg)), n) // Guard to make sure we have not the same bytes. - require.True(t, bytes.Index(dest.Bytes(), msg) == -1) + require.False(t, bytes.Contains(dest.Bytes(), msg)) r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) @@ -81,7 +81,7 @@ func TestIO(t *testing.T) { require.Equal(t, len(msg), n) // Guard to make sure we have not the same bytes. - require.True(t, bytes.Index(dest.Bytes(), msg) == -1) + require.False(t, bytes.Contains(dest.Bytes(), msg)) r, err := NewReaderWithDefaults(dest, []byte("bad password")) require.NoError(t, err) @@ -110,7 +110,7 @@ func TestIO(t *testing.T) { require.True(t, len(dest.Bytes()) > 0) // Guard to make sure we have not the same bytes. - require.True(t, bytes.Index(dest.Bytes(), msg) == -1) + require.False(t, bytes.Contains(dest.Bytes(), msg)) r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) @@ -136,7 +136,7 @@ func TestIO(t *testing.T) { require.True(t, n == 2048) // Guard to make sure we have not the same bytes. - require.True(t, bytes.Index(dest.Bytes(), msg) == -1) + require.False(t, bytes.Contains(dest.Bytes(), msg)) r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) @@ -151,6 +151,7 @@ func TestIO(t *testing.T) { t.Run("Missing explicit version", func(t *testing.T) { raw, err := randomBytes(2048) + require.NoError(t, err) c := bytes.NewBuffer(raw) r, err := NewReaderWithDefaults(c, []byte("bad password")) @@ -182,7 +183,7 @@ func TestIO(t *testing.T) { require.Equal(t, 19, n) // Guard to make sure we have not the same bytes. - require.True(t, bytes.Index(dest.Bytes(), expected) == -1) + require.False(t, bytes.Contains(dest.Bytes(), expected)) r, err := NewReaderWithDefaults(dest, passwd) require.NoError(t, err) diff --git a/x-pack/elastic-agent/pkg/eql/compare.go b/x-pack/elastic-agent/pkg/eql/compare.go index 9381f254fde..3c7c082f0c1 100644 --- a/x-pack/elastic-agent/pkg/eql/compare.go +++ b/x-pack/elastic-agent/pkg/eql/compare.go @@ -11,8 +11,6 @@ import ( type operand interface{} -type compare func(left, right operand) (bool, error) - func compareEQ(left, right operand) (bool, error) { switch v := left.(type) { case *null: @@ -367,8 +365,6 @@ func compareGTE(left, right operand) (bool, error) { } } -type logical func(left, right operand) (bool, error) - func logicalAND(left, right operand) (bool, error) { switch l := left.(type) { case bool: diff --git a/x-pack/elastic-agent/pkg/eql/expression.go b/x-pack/elastic-agent/pkg/eql/expression.go index eb0d5b08b4b..951074d3142 100644 --- a/x-pack/elastic-agent/pkg/eql/expression.go +++ b/x-pack/elastic-agent/pkg/eql/expression.go @@ -33,7 +33,6 @@ var ( type Expression struct { expression string tree antlr.ParseTree - vars VarStore } // Eval evaluates the expression using a visitor and the provided methods registry, will return true diff --git a/x-pack/elastic-agent/pkg/eql/methods_str.go b/x-pack/elastic-agent/pkg/eql/methods_str.go index b7c49a61036..f32011a9431 100644 --- a/x-pack/elastic-agent/pkg/eql/methods_str.go +++ b/x-pack/elastic-agent/pkg/eql/methods_str.go @@ -84,9 +84,8 @@ func number(args []interface{}) (interface{}, error) { return nil, fmt.Errorf("number: argument 1 must be an integer; recieved %T", args[1]) } } - if strings.HasPrefix(input, "0x") { - input = input[2:] - } + input = strings.TrimPrefix(input, "0x") + n, err := strconv.ParseInt(input, base, 64) if err != nil { return nil, fmt.Errorf("number: failed to convert '%s' to integer", input) diff --git a/x-pack/elastic-agent/pkg/eql/visitor.go b/x-pack/elastic-agent/pkg/eql/visitor.go index f7d6ddffa79..3e7f633daf5 100644 --- a/x-pack/elastic-agent/pkg/eql/visitor.go +++ b/x-pack/elastic-agent/pkg/eql/visitor.go @@ -218,10 +218,7 @@ func (v *expVisitor) VisitExpArithmeticLT(ctx *parser.ExpArithmeticLTContext) in } func (v *expVisitor) VisitBoolean(ctx *parser.BooleanContext) interface{} { - if ctx.TRUE() != nil { - return true - } - return false + return ctx.TRUE() != nil } func (v *expVisitor) VisitArguments(ctx *parser.ArgumentsContext) interface{} { diff --git a/x-pack/elastic-agent/pkg/fleetapi/ack_cmd_test.go b/x-pack/elastic-agent/pkg/fleetapi/ack_cmd_test.go index e11d0b2958d..e384ced92a1 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/ack_cmd_test.go +++ b/x-pack/elastic-agent/pkg/fleetapi/ack_cmd_test.go @@ -43,7 +43,7 @@ func TestAck(t *testing.T) { id := responses.Events[0].ActionID require.Equal(t, "my-id", id) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, diff --git a/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker.go b/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker.go index 6acdda0d31c..cebf49b027f 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker.go +++ b/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker.go @@ -13,9 +13,7 @@ import ( "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/agent/errors" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/logger" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/fleetapi" - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/fleetapi/acker" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/fleetapi/client" - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/scheduler" ) const fleetTimeFormat = "2006-01-02T15:04:05.99999-07:00" @@ -24,23 +22,11 @@ type agentInfo interface { AgentID() string } -type fleetReporter interface { - Events() ([]fleetapi.SerializableEvent, func()) -} - -type dispatcher interface { - Dispatch(acker acker.Acker, actions ...fleetapi.Action) error -} - // Acker is acker capable of acking action in fleet. type Acker struct { - log *logger.Logger - dispatcher dispatcher - client client.Sender - scheduler scheduler.Scheduler - agentInfo agentInfo - reporter fleetReporter - done chan struct{} + log *logger.Logger + client client.Sender + agentInfo agentInfo } // NewAcker creates a new fleet acker. diff --git a/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker_test.go b/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker_test.go index 51c7fabbae3..91533ff1ec8 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker_test.go +++ b/x-pack/elastic-agent/pkg/fleetapi/acker/fleet/fleet_acker_test.go @@ -15,13 +15,11 @@ import ( "net/url" "sync" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/logger" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/fleetapi" - repo "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/reporter" ) func TestAcker(t *testing.T) { @@ -112,14 +110,6 @@ type testAgentInfo struct{} func (testAgentInfo) AgentID() string { return "agent-secret" } -type testStateEvent struct{} - -func (testStateEvent) Type() string { return repo.EventTypeState } -func (testStateEvent) SubType() string { return repo.EventSubTypeInProgress } -func (testStateEvent) Time() time.Time { return time.Unix(0, 1) } -func (testStateEvent) Message() string { return "hello" } -func (testStateEvent) Payload() map[string]interface{} { return map[string]interface{}{"key": 1} } - func wrapStrToResp(code int, body string) *http.Response { return &http.Response{ Status: fmt.Sprintf("%d %s", code, http.StatusText(code)), @@ -129,6 +119,6 @@ func wrapStrToResp(code int, body string) *http.Response { ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(body)), ContentLength: int64(len(body)), - Header: make(http.Header, 0), + Header: make(http.Header), } } diff --git a/x-pack/elastic-agent/pkg/fleetapi/acker/lazy/lazy_acker_test.go b/x-pack/elastic-agent/pkg/fleetapi/acker/lazy/lazy_acker_test.go index f7357468e8d..fb24d291207 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/acker/lazy/lazy_acker_test.go +++ b/x-pack/elastic-agent/pkg/fleetapi/acker/lazy/lazy_acker_test.go @@ -16,14 +16,12 @@ import ( "strings" "sync" "testing" - "time" "github.com/stretchr/testify/assert" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/logger" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/fleetapi" "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/fleetapi/acker/fleet" - repo "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/reporter" ) func TestLazyAcker(t *testing.T) { @@ -171,14 +169,6 @@ type testAgentInfo struct{} func (testAgentInfo) AgentID() string { return "agent-secret" } -type testStateEvent struct{} - -func (testStateEvent) Type() string { return repo.EventTypeState } -func (testStateEvent) SubType() string { return repo.EventSubTypeInProgress } -func (testStateEvent) Time() time.Time { return time.Unix(0, 1) } -func (testStateEvent) Message() string { return "hello" } -func (testStateEvent) Payload() map[string]interface{} { return map[string]interface{}{"key": 1} } - func wrapStrToResp(code int, body string) *http.Response { return &http.Response{ Status: fmt.Sprintf("%d %s", code, http.StatusText(code)), @@ -188,6 +178,6 @@ func wrapStrToResp(code int, body string) *http.Response { ProtoMinor: 1, Body: ioutil.NopCloser(bytes.NewBufferString(body)), ContentLength: int64(len(body)), - Header: make(http.Header, 0), + Header: make(http.Header), } } diff --git a/x-pack/elastic-agent/pkg/fleetapi/checkin_cmd_test.go b/x-pack/elastic-agent/pkg/fleetapi/checkin_cmd_test.go index 470cd6d444b..86cc814e882 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/checkin_cmd_test.go +++ b/x-pack/elastic-agent/pkg/fleetapi/checkin_cmd_test.go @@ -38,7 +38,7 @@ func TestCheckin(t *testing.T) { path := fmt.Sprintf("/api/fleet/agents/%s/checkin", agentInfo.AgentID()) mux.HandleFunc(path, authHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, @@ -87,7 +87,7 @@ func TestCheckin(t *testing.T) { path := fmt.Sprintf("/api/fleet/agents/%s/checkin", agentInfo.AgentID()) mux.HandleFunc(path, authHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, @@ -148,7 +148,7 @@ func TestCheckin(t *testing.T) { path := fmt.Sprintf("/api/fleet/agents/%s/checkin", agentInfo.AgentID()) mux.HandleFunc(path, authHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, @@ -180,7 +180,7 @@ func TestCheckin(t *testing.T) { path := fmt.Sprintf("/api/fleet/agents/%s/checkin", agentInfo.AgentID()) mux.HandleFunc(path, authHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, @@ -214,7 +214,7 @@ func TestCheckin(t *testing.T) { assert.Equal(t, "linux", req.Metadata.OS.Name) w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, @@ -248,7 +248,7 @@ func TestCheckin(t *testing.T) { assert.Nil(t, req.Metadata) w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, raw) + fmt.Fprint(w, raw) }, withAPIKey)) return mux }, withAPIKey, diff --git a/x-pack/elastic-agent/pkg/fleetapi/client/client.go b/x-pack/elastic-agent/pkg/fleetapi/client/client.go index 5930798a1c5..6fe59c14429 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/client/client.go +++ b/x-pack/elastic-agent/pkg/fleetapi/client/client.go @@ -110,10 +110,10 @@ func ExtractError(resp io.Reader) error { // System errors doesn't return a message, fleet code can return a Message key which has more // information. if len(e.Message) == 0 { - return fmt.Errorf("Status code: %d, Kibana returned an error: %s", e.StatusCode, e.Error) + return fmt.Errorf("status code: %d, Kibana returned an error: %s", e.StatusCode, e.Error) } return fmt.Errorf( - "Status code: %d, Kibana returned an error: %s, message: %s", + "status code: %d, Kibana returned an error: %s, message: %s", e.StatusCode, e.Error, e.Message, diff --git a/x-pack/elastic-agent/pkg/fleetapi/client/client_test.go b/x-pack/elastic-agent/pkg/fleetapi/client/client_test.go index ca603fbaf3e..098a314af2a 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/client/client_test.go +++ b/x-pack/elastic-agent/pkg/fleetapi/client/client_test.go @@ -29,7 +29,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", authHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }, "abc123")) return mux }, func(t *testing.T, host string) { @@ -58,7 +58,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", authHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }, "secret")) return mux }, func(t *testing.T, host string) { @@ -82,7 +82,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) require.Equal(t, r.Header.Get("User-Agent"), "Elastic Agent v8.0.0") }) return mux @@ -116,6 +116,7 @@ func TestHTTPClient(t *testing.T) { client, err := kibana.NewWithRawConfig(nil, cfg, func(wrapped http.RoundTripper) (http.RoundTripper, error) { return NewFleetAuthRoundTripper(wrapped, "abc123") }) + require.NoError(t, err) _, err = client.Send(timeoutCtx, "GET", "/echo-hello", nil, nil, nil) require.Error(t, err) diff --git a/x-pack/elastic-agent/pkg/fleetapi/client/helper_test.go b/x-pack/elastic-agent/pkg/fleetapi/client/helper_test.go index 49d237e44a8..fce400ef067 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/client/helper_test.go +++ b/x-pack/elastic-agent/pkg/fleetapi/client/helper_test.go @@ -9,11 +9,6 @@ import ( "net/http/httptest" "strings" "testing" - - "github.com/stretchr/testify/require" - - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/core/logger" - "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/kibana" ) func authHandler(handler http.HandlerFunc, apiKey string) http.HandlerFunc { @@ -37,21 +32,3 @@ func withServer(m func(t *testing.T) *http.ServeMux, test func(t *testing.T, hos test(t, s.Listener.Addr().String()) } } - -func withServerWithAuthClient( - m func(t *testing.T) *http.ServeMux, - apiKey string, - test func(t *testing.T, client Sender), -) func(t *testing.T) { - - return withServer(m, func(t *testing.T, host string) { - log, _ := logger.New("") - cfg := &kibana.Config{ - Host: host, - } - - client, err := NewAuthWithConfig(log, apiKey, cfg) - require.NoError(t, err) - test(t, client) - }) -} diff --git a/x-pack/elastic-agent/pkg/fleetapi/client/round_trippers.go b/x-pack/elastic-agent/pkg/fleetapi/client/round_trippers.go index c2a0f0cb84c..a0c4c04e068 100644 --- a/x-pack/elastic-agent/pkg/fleetapi/client/round_trippers.go +++ b/x-pack/elastic-agent/pkg/fleetapi/client/round_trippers.go @@ -16,8 +16,7 @@ var ErrInvalidAPIKey = errors.New("invalid api key to authenticate with fleet") // FleetUserAgentRoundTripper adds the Fleet user agent. type FleetUserAgentRoundTripper struct { - rt http.RoundTripper - version string + rt http.RoundTripper } // RoundTrip adds the Fleet user agent string to every request. diff --git a/x-pack/elastic-agent/pkg/kibana/client_test.go b/x-pack/elastic-agent/pkg/kibana/client_test.go index 36d24b88a00..7fa0aea16e0 100644 --- a/x-pack/elastic-agent/pkg/kibana/client_test.go +++ b/x-pack/elastic-agent/pkg/kibana/client_test.go @@ -79,7 +79,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/nested/echo-hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }) return addCatchAll(mux, t) }, func(t *testing.T, host string) { @@ -88,9 +88,11 @@ func TestHTTPClient(t *testing.T) { url := "http://" + host + "/" c, err := NewConfigFromURL(url) - client, err := NewWithConfig(l, c, noopWrapper) + require.NoError(t, err) + client, err := NewWithConfig(l, c, noopWrapper) require.NoError(t, err) + resp, err := client.Send(ctx, "GET", "/nested/echo-hello", nil, nil, nil) require.NoError(t, err) @@ -107,7 +109,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }) return mux }, func(t *testing.T, host string) { @@ -133,7 +135,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/mycustompath/echo-hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }) return mux }, func(t *testing.T, host string) { @@ -160,7 +162,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", basicAuthHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }, "hello", "world", "testing")) return mux }, func(t *testing.T, host string) { @@ -188,7 +190,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", basicAuthHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }, "hello", "world", "testing")) return mux }, func(t *testing.T, host string) { @@ -212,7 +214,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) require.Equal(t, r.Header.Get("User-Agent"), "custom-agent") }) return mux @@ -242,7 +244,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", enforceKibanaHandler(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }, "8.0.0")) return mux }, func(t *testing.T, host string) { @@ -271,7 +273,7 @@ func TestHTTPClient(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/echo-hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) - fmt.Fprintf(w, msg) + fmt.Fprint(w, msg) }) return mux }, func(t *testing.T, host string) { diff --git a/x-pack/elastic-agent/pkg/reporter/fleet/reporter.go b/x-pack/elastic-agent/pkg/reporter/fleet/reporter.go index b4bd233d205..779108c8a7b 100644 --- a/x-pack/elastic-agent/pkg/reporter/fleet/reporter.go +++ b/x-pack/elastic-agent/pkg/reporter/fleet/reporter.go @@ -15,13 +15,6 @@ import ( "github.com/elastic/beats/v7/x-pack/elastic-agent/pkg/reporter/fleet/config" ) -const ( - defaultThreshold = 1000 - agentIDKey = "elastic.agent.id" -) - -type ackFn func() - type event struct { AgentID string `json:"agent_id"` EventType string `json:"type"` diff --git a/x-pack/elastic-agent/pkg/reporter/log/reporter.go b/x-pack/elastic-agent/pkg/reporter/log/reporter.go index e21864679e4..8651d7b800b 100644 --- a/x-pack/elastic-agent/pkg/reporter/log/reporter.go +++ b/x-pack/elastic-agent/pkg/reporter/log/reporter.go @@ -53,23 +53,5 @@ func defaultFormatFunc(e reporter.Event) string { ) } -type reportableEvent struct { - Type string - SubType string - Time string - Message string - Payload map[string]interface{} `json:"payload,omitempty"` -} - -func makeEventReportable(event reporter.Event) reportableEvent { - return reportableEvent{ - Type: event.Type(), - SubType: event.SubType(), - Time: event.Time().Format(timeFormat), - Message: event.Message(), - Payload: event.Payload(), - } -} - // Check it is reporter.Backend var _ reporter.Backend = &Reporter{} diff --git a/x-pack/elastic-agent/pkg/tokenbucket/token_bucket.go b/x-pack/elastic-agent/pkg/tokenbucket/token_bucket.go index 45f3452c0d6..f5d7d2d26e2 100644 --- a/x-pack/elastic-agent/pkg/tokenbucket/token_bucket.go +++ b/x-pack/elastic-agent/pkg/tokenbucket/token_bucket.go @@ -14,7 +14,6 @@ import ( // Bucket is a Token Bucket for rate limiting type Bucket struct { - size int dropAmount int rateChan chan struct{} closeChan chan struct{}