From ccbcaed945c0165dd13f802d9ba7ef5478ea92c3 Mon Sep 17 00:00:00 2001 From: blue-troy <12729455+blue-troy@users.noreply.github.com> Date: Wed, 20 Dec 2023 14:24:42 +0800 Subject: [PATCH] refactor: replace depricated io/ioutil package io/ioutil package is deprecated Signed-off-by: blue-troy <12729455+blue-troy@users.noreply.github.com> --- dev-tools/cmd/asset/asset.go | 8 ++--- dev-tools/cmd/license/license_generate.go | 9 +++-- dev-tools/cmd/module_fields/module_fields.go | 3 +- .../module_include_list.go | 3 +- dev-tools/cmd/update_go/update_go_version.go | 7 ++-- dev-tools/mage/check.go | 3 +- dev-tools/mage/common.go | 11 +++---- dev-tools/mage/config.go | 11 +++---- dev-tools/mage/copy.go | 13 ++++++-- dev-tools/mage/gotest.go | 5 ++- dev-tools/mage/integtest_docker.go | 5 ++- dev-tools/mage/kubernetes/kind.go | 10 +++--- dev-tools/mage/kubernetes/kuberemote.go | 4 +-- dev-tools/mage/kubernetes/kubernetes.go | 5 ++- dev-tools/mage/modules.go | 7 ++-- dev-tools/mage/pkgspecs.go | 4 +-- dev-tools/mage/pkgtypes.go | 7 ++-- dev-tools/mage/settings.go | 7 ++-- dev-tools/packaging/package_test.go | 5 ++- filebeat/fileset/fileset.go | 5 ++- filebeat/fileset/modules.go | 5 ++- filebeat/generator/fields/fields.go | 6 ++-- filebeat/generator/generator.go | 5 ++- filebeat/input/file/glob_test.go | 3 +- .../input/file/identifier_inode_deviceid.go | 5 ++- filebeat/input/filestream/filestream_test.go | 3 +- .../filestream/fswatch_test_non_windows.go | 3 +- .../filestream/identifier_inode_deviceid.go | 5 ++- filebeat/input/filestream/identifier_test.go | 5 ++- .../filestream/identifier_test_non_windows.go | 5 ++- filebeat/input/filestream/prospector_test.go | 3 +- filebeat/input/log/input_test.go | 5 ++- filebeat/registrar/migrate.go | 5 ++- filebeat/registrar/migrate_bench_test.go | 7 ++-- filebeat/scripts/tester/main.go | 5 ++- heartbeat/hbtest/hbtestutil.go | 3 +- heartbeat/monitors/active/http/check_test.go | 4 +-- .../monitors/active/http/checkjson_test.go | 6 ++-- heartbeat/monitors/active/http/http_test.go | 3 +- .../monitors/active/http/respbody_test.go | 6 ++-- heartbeat/monitors/active/http/task.go | 4 +-- heartbeat/watcher/watcher.go | 4 +-- libbeat/api/npipe/listener_windows_test.go | 4 +-- libbeat/api/server_windows_test.go | 4 +-- libbeat/asset/registry.go | 4 +-- libbeat/cfgfile/glob_manager_test.go | 11 +++---- libbeat/cfgfile/glob_watcher_test.go | 9 +++-- libbeat/cfgfile/reload_test.go | 5 ++- libbeat/cmd/instance/beat_test.go | 5 ++- libbeat/cmd/keystore.go | 4 +-- libbeat/common/file/file_other_test.go | 7 ++-- libbeat/common/file/file_windows_test.go | 5 ++- libbeat/common/flowhash/communityid_test.go | 3 +- libbeat/dashboards/export.go | 7 ++-- libbeat/dashboards/importer.go | 5 ++- libbeat/dashboards/kibana_loader.go | 8 ++--- libbeat/esleg/eslegclient/bulkapi.go | 3 +- .../connection_integration_test.go | 4 +-- .../fields/module_fields_collector.go | 3 +- libbeat/kibana/index_pattern_generator.go | 3 +- .../kibana/index_pattern_generator_test.go | 11 +++---- libbeat/licenser/elastic_fetcher_test.go | 3 +- .../elasticsearch/client_integration_test.go | 4 +-- .../add_cloud_metadata/http_fetcher.go | 4 +-- libbeat/processors/dissect/dissect_test.go | 3 +- .../publisher/pipeline/stress/stress_test.go | 3 +- .../publisher/queue/diskqueue/acks_test.go | 3 +- .../publisher/queue/diskqueue/queue_test.go | 5 ++- libbeat/publisher/queue/diskqueue/segments.go | 13 ++++++-- libbeat/reader/debug/debug_test.go | 9 +++-- libbeat/reader/multiline/multiline_test.go | 4 +-- libbeat/reader/parser/parser_test.go | 3 +- libbeat/reader/readfile/bench_test.go | 3 +- libbeat/reader/readfile/encode_test.go | 4 +-- .../reader/readfile/encoding/utf16_test.go | 4 +-- libbeat/reader/readfile/line_test.go | 11 +++---- libbeat/scripts/cmd/global_fields/main.go | 3 +- .../statestore/backend/memlog/diskstore.go | 3 +- .../statestore/backend/memlog/memlog_test.go | 9 +++-- .../internal/storecompliance/util.go | 3 +- libbeat/template/load.go | 3 +- libbeat/template/load_integration_test.go | 6 ++-- libbeat/tests/docker/docker.go | 3 +- libbeat/tests/integration/framework.go | 3 +- libbeat/tests/integration/http_test.go | 6 ++-- .../appender/kubernetes/token/token.go | 4 +-- .../appender/kubernetes/token/token_test.go | 3 +- metricbeat/helper/http.go | 6 ++-- metricbeat/helper/http_test.go | 8 ++--- metricbeat/helper/http_windows_test.go | 6 ++-- metricbeat/helper/server/http/http.go | 4 +-- metricbeat/helper/server/http/http_test.go | 4 +-- metricbeat/mb/lightmodules.go | 3 +- metricbeat/mb/testing/data_generator.go | 3 +- metricbeat/mb/testing/lightmodules_test.go | 5 ++- metricbeat/mb/testing/testdata.go | 12 +++---- metricbeat/module/beat/state/data_test.go | 12 +++---- metricbeat/module/beat/stats/data_test.go | 4 +-- .../ceph/cluster_disk/cluster_disk_test.go | 4 +-- .../cluster_health/cluster_health_test.go | 4 +-- .../cluster_status/cluster_status_test.go | 4 +-- .../mgr_cluster_health_test.go | 8 ++--- .../monitor_health/monitor_health_test.go | 4 +-- metricbeat/module/ceph/osd_df/osd_df_test.go | 4 +-- .../module/ceph/osd_tree/osd_tree_test.go | 4 +-- .../module/ceph/pool_disk/pool_disk_test.go | 4 +-- .../module/couchbase/bucket/bucket_test.go | 4 +-- .../module/elasticsearch/ccr/ccr_test.go | 4 +-- .../module/elasticsearch/ccr/data_test.go | 6 ++-- .../elasticsearch/cluster_stats/data_test.go | 12 +++---- .../elasticsearch_integration_test.go | 33 ++++++++++--------- .../module/elasticsearch/enrich/data_test.go | 8 ++--- .../module/elasticsearch/index/data_test.go | 14 ++++---- .../elasticsearch/index_recovery/data_test.go | 6 ++-- .../elasticsearch/index_summary/data_test.go | 8 ++--- .../ingest_pipeline/data_test.go | 6 ++-- .../module/elasticsearch/ml_job/data_test.go | 6 ++-- .../module/elasticsearch/node/data_test.go | 4 +-- .../module/elasticsearch/node/node_test.go | 4 +-- .../elasticsearch/pending_tasks/data_test.go | 16 ++++----- .../module/elasticsearch/shard/data_test.go | 6 ++-- metricbeat/module/elasticsearch/testing.go | 10 +++--- .../module/envoyproxy/server/server_test.go | 8 ++--- metricbeat/module/etcd/leader/leader.go | 4 +-- metricbeat/module/etcd/leader/leader_test.go | 6 ++-- metricbeat/module/etcd/self/self_test.go | 6 ++-- metricbeat/module/etcd/store/store_test.go | 6 ++-- metricbeat/module/haproxy/haproxy.go | 3 +- metricbeat/module/http/json/json.go | 4 +-- metricbeat/module/jolokia/jmx/data_test.go | 14 ++++---- metricbeat/module/kibana/stats/data_test.go | 4 +-- .../kibana/stats/stats_integration_test.go | 4 +-- metricbeat/module/kibana/status/data_test.go | 4 +-- .../kubernetes/container/container_test.go | 4 +-- .../module/kubernetes/node/node_test.go | 4 +-- metricbeat/module/kubernetes/pod/pod_test.go | 4 +-- .../module/kubernetes/system/system_test.go | 4 +-- .../module/kubernetes/volume/volume_test.go | 4 +-- metricbeat/module/linux/rapl/rapl.go | 5 ++- metricbeat/module/linux/util.go | 4 +-- .../logstash/logstash_integration_test.go | 4 +-- metricbeat/module/logstash/node/data_test.go | 4 +-- .../module/logstash/node_stats/data_test.go | 8 ++--- .../module/mongodb/collstats/data_test.go | 4 +-- .../module/nats/connection/connection_test.go | 6 ++-- .../nats/connections/connections_test.go | 6 ++-- metricbeat/module/nats/route/route_test.go | 6 ++-- metricbeat/module/nats/routes/routes_test.go | 6 ++-- metricbeat/module/nats/stats/stats_test.go | 6 ++-- .../nats/subscriptions/subscriptions_test.go | 6 ++-- metricbeat/module/rabbitmq/mtest/server.go | 6 ++-- metricbeat/module/system/entropy/entropy.go | 4 +-- .../module/system/hostnamechange_test.go | 4 +-- .../system/process_summary/process_summary.go | 4 +-- .../module/system/raid/blockinfo/getdev.go | 3 +- .../module/system/raid/blockinfo/parser.go | 14 ++++---- .../module/traefik/health/health_test.go | 4 +-- metricbeat/module/uwsgi/status/status.go | 3 +- .../module/uwsgi/status/status_linux_test.go | 3 +- metricbeat/module/uwsgi/status/status_test.go | 4 +-- metricbeat/module/zookeeper/zookeeper.go | 3 +- metricbeat/scripts/mage/docs_collector.go | 9 +++-- packetbeat/procs/procs_linux_test.go | 5 ++- packetbeat/protos/thrift/thrift_idl_test.go | 3 +- winlogbeat/checkpoint/checkpoint.go | 3 +- winlogbeat/checkpoint/checkpoint_test.go | 7 ++-- winlogbeat/scripts/mage/docs.go | 3 +- .../module/system/login/login_test.go | 5 ++- x-pack/auditbeat/tracing/cpu.go | 4 +-- x-pack/auditbeat/tracing/events_test.go | 7 ++-- x-pack/dockerlogbeat/magefile.go | 5 ++- x-pack/dockerlogbeat/pipelinemock/reader.go | 3 +- x-pack/dockerlogbeat/pipereader/reader.go | 3 +- .../awscloudwatch/input_integration_test.go | 3 +- .../input/awss3/input_benchmark_test.go | 3 +- .../input/awss3/input_integration_test.go | 5 ++- .../filebeat/input/awss3/s3_objects_test.go | 7 ++-- .../filebeat/input/gcppubsub/pubsub_test.go | 4 +-- .../input/netflow/decoder/config/config.go | 3 +- .../input/netflow/decoder/v9/session_test.go | 8 ++--- x-pack/filebeat/input/netflow/definitions.go | 4 +-- x-pack/filebeat/input/netflow/fields_gen.go | 3 +- x-pack/filebeat/input/netflow/netflow_test.go | 11 +++---- x-pack/filebeat/input/o365audit/listblobs.go | 4 +-- .../input/o365audit/listblobs_test.go | 6 ++-- .../functionbeat/manager/aws/cli_manager.go | 3 +- .../manager/core/bundle/bundle.go | 3 +- .../manager/core/bundle/bundle_test.go | 10 +++--- .../monitors/browser/source/project.go | 7 ++-- .../libbeat/common/cloudfoundry/main_test.go | 3 +- .../persistentcache/persistentcache_test.go | 3 +- x-pack/libbeat/persistentcache/store_test.go | 3 +- .../awsfargate/task_stats/task_stats.go | 10 +++--- .../task_stats/task_stats_integration_test.go | 6 ++-- .../module/gcp/carbon/carbon_test.go | 4 +-- .../module/stan/channels/channels_test.go | 6 ++-- .../module/stan/stats/stats_test.go | 6 ++-- .../stan/subscriptions/subscriptions_test.go | 6 ++-- .../metricbeat/module/syncgateway/testing.go | 4 +-- x-pack/winlogbeat/module/testing.go | 5 ++- 200 files changed, 514 insertions(+), 592 deletions(-) diff --git a/dev-tools/cmd/asset/asset.go b/dev-tools/cmd/asset/asset.go index e33f1b82aa7..97b9714c370 100644 --- a/dev-tools/cmd/asset/asset.go +++ b/dev-tools/cmd/asset/asset.go @@ -24,7 +24,7 @@ import ( "bufio" "flag" "fmt" - "io/ioutil" + "io" "os" "github.com/elastic/beats/v7/libbeat/asset" @@ -67,7 +67,7 @@ func main() { beatName = args[1] r := bufio.NewReader(os.Stdin) - data, err = ioutil.ReadAll(r) + data, err = io.ReadAll(r) if err != nil { fmt.Fprintf(os.Stderr, "Error while reading from stdin: %v\n", err) os.Exit(1) @@ -75,7 +75,7 @@ func main() { } else { file = input beatName = args[0] - data, err = ioutil.ReadFile(input) + data, err = os.ReadFile(input) if err != nil { fmt.Fprintf(os.Stderr, "Invalid file path: %s\n", input) os.Exit(1) @@ -99,6 +99,6 @@ func main() { if output == "-" { os.Stdout.Write(bs) } else { - ioutil.WriteFile(output, bs, 0640) + os.WriteFile(output, bs, 0640) } } diff --git a/dev-tools/cmd/license/license_generate.go b/dev-tools/cmd/license/license_generate.go index ec52e0fbe06..3c89957390f 100644 --- a/dev-tools/cmd/license/license_generate.go +++ b/dev-tools/cmd/license/license_generate.go @@ -21,7 +21,6 @@ import ( "bytes" "flag" "go/format" - "io/ioutil" "os" "text/template" ) @@ -65,19 +64,19 @@ func init() { func main() { Headers := make(map[string]string) - content, err := ioutil.ReadFile("APACHE-LICENSE-2.0-header.txt") + content, err := os.ReadFile("APACHE-LICENSE-2.0-header.txt") if err != nil { panic("could not read ASL2 license.") } Headers["ASL2"] = string(content) - content, err = ioutil.ReadFile("ELASTIC-LICENSE-header.txt") + content, err = os.ReadFile("ELASTIC-LICENSE-header.txt") if err != nil { panic("could not read Elastic license.") } Headers["Elastic"] = string(content) - content, err = ioutil.ReadFile("ELASTIC-LICENSE-2.0-header.txt") + content, err = os.ReadFile("ELASTIC-LICENSE-2.0-header.txt") if err != nil { panic("could not read Elastic License 2.0 license.") } @@ -97,6 +96,6 @@ func main() { if output == "-" { os.Stdout.Write(bs) } else { - ioutil.WriteFile(output, bs, 0640) + os.WriteFile(output, bs, 0640) } } diff --git a/dev-tools/cmd/module_fields/module_fields.go b/dev-tools/cmd/module_fields/module_fields.go index 203cc298028..36c11278edc 100644 --- a/dev-tools/cmd/module_fields/module_fields.go +++ b/dev-tools/cmd/module_fields/module_fields.go @@ -20,7 +20,6 @@ package main import ( "flag" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -104,7 +103,7 @@ func main() { log.Fatalf("Error creating golang file from template: %v", err) } - err = ioutil.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644) + err = os.WriteFile(filepath.Join(dir, module, "fields.go"), bs, 0644) if err != nil { log.Fatalf("Error writing fields.go: %v", err) } diff --git a/dev-tools/cmd/module_include_list/module_include_list.go b/dev-tools/cmd/module_include_list/module_include_list.go index f3b6c79ad2b..2cba6968ade 100644 --- a/dev-tools/cmd/module_include_list/module_include_list.go +++ b/dev-tools/cmd/module_include_list/module_include_list.go @@ -22,7 +22,6 @@ import ( "bytes" "flag" "fmt" - "io/ioutil" "log" "os" "path/filepath" @@ -155,7 +154,7 @@ func main() { } // Write the output file. - if err = ioutil.WriteFile(outFile, buf.Bytes(), 0644); err != nil { + if err = os.WriteFile(outFile, buf.Bytes(), 0644); err != nil { log.Fatalf("Failed writing output file: %v", err) } } diff --git a/dev-tools/cmd/update_go/update_go_version.go b/dev-tools/cmd/update_go/update_go_version.go index f589abc756d..3a599961a8a 100644 --- a/dev-tools/cmd/update_go/update_go_version.go +++ b/dev-tools/cmd/update_go/update_go_version.go @@ -20,7 +20,6 @@ package main import ( "flag" "fmt" - "io/ioutil" "os" "strings" ) @@ -52,7 +51,7 @@ func main() { } func getGoVersion() string { - version, err := ioutil.ReadFile(".go-version") + version, err := os.ReadFile(".go-version") checkErr(err) return strings.TrimRight(string(version), "\r\n") } @@ -66,10 +65,10 @@ func checkErr(err error) { func updateGoVersion(oldVersion, newVersion string) { for _, file := range files { fmt.Printf("Updating Go version from %s to %s in %s\n", oldVersion, newVersion, file) - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) checkErr(err) updatedContent := strings.ReplaceAll(string(content), oldVersion, newVersion) - err = ioutil.WriteFile(file, []byte(updatedContent), 0644) + err = os.WriteFile(file, []byte(updatedContent), 0644) checkErr(err) } } diff --git a/dev-tools/mage/check.go b/dev-tools/mage/check.go index a9547634eb5..c677bdfe129 100644 --- a/dev-tools/mage/check.go +++ b/dev-tools/mage/check.go @@ -22,7 +22,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "log" "os" "os/exec" @@ -229,7 +228,7 @@ func CheckDashboardsFormat() error { hasErrors := false for _, file := range dashboardFiles { - d, err := ioutil.ReadFile(file) + d, err := os.ReadFile(file) if err != nil { return fmt.Errorf("failed to read dashboard file %s: %w", file, err) } diff --git a/dev-tools/mage/common.go b/dev-tools/mage/common.go index 1c1ca25d95b..d0c5b31712a 100644 --- a/dev-tools/mage/common.go +++ b/dev-tools/mage/common.go @@ -32,7 +32,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -125,7 +124,7 @@ func joinMaps(args ...map[string]interface{}) map[string]interface{} { } func expandFile(src, dst string, args ...map[string]interface{}) error { - tmplData, err := ioutil.ReadFile(src) + tmplData, err := os.ReadFile(src) if err != nil { return fmt.Errorf("failed reading from template %v: %w", src, err) } @@ -140,7 +139,7 @@ func expandFile(src, dst string, args ...map[string]interface{}) error { return err } - if err = ioutil.WriteFile(createDir(dst), []byte(output), 0644); err != nil { + if err = os.WriteFile(createDir(dst), []byte(output), 0644); err != nil { return fmt.Errorf("failed to write rendered template: %w", err) } @@ -262,13 +261,13 @@ func FindReplace(file string, re *regexp.Regexp, repl string) error { return err } - contents, err := ioutil.ReadFile(file) + contents, err := os.ReadFile(file) if err != nil { return err } out := re.ReplaceAllString(string(contents), repl) - return ioutil.WriteFile(file, []byte(out), info.Mode().Perm()) + return os.WriteFile(file, []byte(out), info.Mode().Perm()) } // MustFindReplace invokes FindReplace and panics if an error occurs. @@ -773,7 +772,7 @@ func CreateSHA512File(file string) error { computedHash := hex.EncodeToString(sum.Sum(nil)) out := fmt.Sprintf("%v %v", computedHash, filepath.Base(file)) - return ioutil.WriteFile(file+".sha512", []byte(out), 0644) + return os.WriteFile(file+".sha512", []byte(out), 0644) } // Mage executes mage targets in the specified directory. diff --git a/dev-tools/mage/config.go b/dev-tools/mage/config.go index 822e7f0f163..bd32e9bdcd2 100644 --- a/dev-tools/mage/config.go +++ b/dev-tools/mage/config.go @@ -21,7 +21,6 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -196,7 +195,7 @@ func makeConfigTemplate(destination string, mode os.FileMode, confParams ConfigF } } - data, err := ioutil.ReadFile(confFile.Template) + data, err := os.ReadFile(confFile.Template) if err != nil { return fmt.Errorf("failed to read config template %q: %w", confFile.Template, err) } @@ -265,7 +264,7 @@ type moduleFieldsYmlData []struct { } func readModuleFieldsYml(path string) (title string, useShort bool, err error) { - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return "", false, err } @@ -302,7 +301,7 @@ func moduleDashes(name string) string { func GenerateModuleReferenceConfig(out string, moduleDirs ...string) error { var moduleConfigs []moduleConfigTemplateData for _, dir := range moduleDirs { - modules, err := ioutil.ReadDir(dir) + modules, err := os.ReadDir(dir) if err != nil { return err } @@ -327,7 +326,7 @@ func GenerateModuleReferenceConfig(out string, moduleDirs ...string) error { var data []byte for _, f := range files { - data, err = ioutil.ReadFile(f) + data, err = os.ReadFile(f) if err != nil { if os.IsNotExist(err) { continue @@ -365,5 +364,5 @@ func GenerateModuleReferenceConfig(out string, moduleDirs ...string) error { "Modules": moduleConfigs, }) - return ioutil.WriteFile(createDir(out), []byte(config), 0644) + return os.WriteFile(createDir(out), []byte(config), 0644) } diff --git a/dev-tools/mage/copy.go b/dev-tools/mage/copy.go index fc9aa854823..d772749717c 100644 --- a/dev-tools/mage/copy.go +++ b/dev-tools/mage/copy.go @@ -20,7 +20,7 @@ package mage import ( "fmt" "io" - "io/ioutil" + "io/fs" "os" "path/filepath" "regexp" @@ -144,11 +144,18 @@ func (t *CopyTask) dirCopy(src, dest string, info os.FileInfo) error { return fmt.Errorf("failed creating dirs: %w", err) } - contents, err := ioutil.ReadDir(src) + contentEntries, err := os.ReadDir(src) if err != nil { return fmt.Errorf("failed to read dir %v: %w", src, err) } - + contents := make([]fs.FileInfo, 0, len(contentEntries)) + for _, entry := range contentEntries { + content, err := entry.Info() + if err != nil { + return fmt.Errorf("failed to stat %v: %w", entry.Name(), err) + } + contents = append(contents, content) + } for _, info := range contents { srcFile := filepath.Join(src, info.Name()) destFile := filepath.Join(dest, info.Name()) diff --git a/dev-tools/mage/gotest.go b/dev-tools/mage/gotest.go index 5065882fdb8..6ece742cd20 100644 --- a/dev-tools/mage/gotest.go +++ b/dev-tools/mage/gotest.go @@ -22,7 +22,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "os" "os/exec" @@ -169,7 +168,7 @@ func DefaultTestBinaryArgs() TestBinaryArgs { // Use MODULE=module to run only tests for `module`. func GoTestIntegrationForModule(ctx context.Context) error { module := EnvOr("MODULE", "") - modulesFileInfo, err := ioutil.ReadDir("./module") + modulesFileInfo, err := os.ReadDir("./module") if err != nil { return err } @@ -356,7 +355,7 @@ func makeCommand(ctx context.Context, env map[string]string, cmd string, args .. for k, v := range env { c.Env = append(c.Env, k+"="+v) } - c.Stdout = ioutil.Discard + c.Stdout = io.Discard if mg.Verbose() { c.Stdout = os.Stdout } diff --git a/dev-tools/mage/integtest_docker.go b/dev-tools/mage/integtest_docker.go index 8c5fb6d3603..27b7ee91b4b 100644 --- a/dev-tools/mage/integtest_docker.go +++ b/dev-tools/mage/integtest_docker.go @@ -22,7 +22,6 @@ import ( "fmt" "go/build" "io" - "io/ioutil" "os" "path" "path/filepath" @@ -356,7 +355,7 @@ func StartIntegTestContainers() error { func StopIntegTestContainers() error { // Docker-compose rm is noisy. So only pass through stderr when in verbose. - out := ioutil.Discard + out := io.Discard if mg.Verbose() { out = os.Stderr } @@ -368,7 +367,7 @@ func StopIntegTestContainers() error { _, err = sh.Exec( composeEnv, - ioutil.Discard, + io.Discard, out, "docker-compose", "-p", DockerComposeProjectName(), diff --git a/dev-tools/mage/kubernetes/kind.go b/dev-tools/mage/kubernetes/kind.go index 133f305fedd..a282946ed9c 100644 --- a/dev-tools/mage/kubernetes/kind.go +++ b/dev-tools/mage/kubernetes/kind.go @@ -19,7 +19,7 @@ package kubernetes import ( "fmt" - "io/ioutil" + "io" "os" "os/exec" "path/filepath" @@ -66,8 +66,8 @@ func (m *KindIntegrationTestStep) Setup(env map[string]string) error { } clusterName := kubernetesClusterName() - stdOut := ioutil.Discard - stdErr := ioutil.Discard + stdOut := io.Discard + stdErr := io.Discard if mg.Verbose() { stdOut = os.Stdout stdErr = os.Stderr @@ -116,8 +116,8 @@ func (m *KindIntegrationTestStep) Setup(env map[string]string) error { // Teardown destroys the kubernetes cluster. func (m *KindIntegrationTestStep) Teardown(env map[string]string) error { - stdOut := ioutil.Discard - stdErr := ioutil.Discard + stdOut := io.Discard + stdErr := io.Discard if mg.Verbose() { stdOut = os.Stdout stdErr = os.Stderr diff --git a/dev-tools/mage/kubernetes/kuberemote.go b/dev-tools/mage/kubernetes/kuberemote.go index 8e9d9897d44..66d1b7bae8d 100644 --- a/dev-tools/mage/kubernetes/kuberemote.go +++ b/dev-tools/mage/kubernetes/kuberemote.go @@ -27,10 +27,10 @@ import ( "encoding/pem" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" + "os" "os/exec" "strings" "time" @@ -622,7 +622,7 @@ func podDone(event watch.Event) (bool, error) { func createTempFile(content []byte) (string, error) { randBytes := make([]byte, 16) rand.Read(randBytes) - tmpfile, err := ioutil.TempFile("", hex.EncodeToString(randBytes)) + tmpfile, err := os.CreateTemp("", hex.EncodeToString(randBytes)) if err != nil { return "", err } diff --git a/dev-tools/mage/kubernetes/kubernetes.go b/dev-tools/mage/kubernetes/kubernetes.go index e93632d7b65..20772c2863d 100644 --- a/dev-tools/mage/kubernetes/kubernetes.go +++ b/dev-tools/mage/kubernetes/kubernetes.go @@ -20,7 +20,6 @@ package kubernetes import ( "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -69,8 +68,8 @@ func (d *KubernetesIntegrationTester) StepRequirements() mage.IntegrationTestSte // Test performs the tests with kubernetes. func (d *KubernetesIntegrationTester) Test(dir string, mageTarget string, env map[string]string) error { - stdOut := ioutil.Discard - stdErr := ioutil.Discard + stdOut := io.Discard + stdErr := io.Discard if mg.Verbose() { stdOut = os.Stdout stdErr = os.Stderr diff --git a/dev-tools/mage/modules.go b/dev-tools/mage/modules.go index 14b7f7ab118..6c2558a8760 100644 --- a/dev-tools/mage/modules.go +++ b/dev-tools/mage/modules.go @@ -19,7 +19,6 @@ package mage import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -54,7 +53,7 @@ func GenerateDirModulesD() error { } moduleName := parts[1] - config, err := ioutil.ReadFile(f) + config, err := os.ReadFile(f) if err != nil { return err } @@ -68,7 +67,7 @@ func GenerateDirModulesD() error { } target := filepath.Join("modules.d", moduleName+".yml.disabled") - err = ioutil.WriteFile(createDir(target), []byte(data), 0644) + err = os.WriteFile(createDir(target), []byte(data), 0644) if err != nil { return err } @@ -128,7 +127,7 @@ func loadModulesD() (modules map[string][]moduleDefinition, err error) { } modules = make(map[string][]moduleDefinition, len(files)) for _, file := range files { - contents, err := ioutil.ReadFile(file) + contents, err := os.ReadFile(file) if err != nil { return nil, fmt.Errorf("reading %s: %w", file, err) } diff --git a/dev-tools/mage/pkgspecs.go b/dev-tools/mage/pkgspecs.go index 9d0a6b339b4..e37955aff5c 100644 --- a/dev-tools/mage/pkgspecs.go +++ b/dev-tools/mage/pkgspecs.go @@ -20,8 +20,8 @@ package mage import ( "bytes" "fmt" - "io/ioutil" "log" + "os" "path/filepath" "gopkg.in/yaml.v2" @@ -89,7 +89,7 @@ func LoadNamedSpec(name string, files ...string) error { func LoadSpecs(files ...string) (map[string][]OSPackageArgs, error) { var data [][]byte for _, file := range files { - d, err := ioutil.ReadFile(file) + d, err := os.ReadFile(file) if err != nil { return nil, fmt.Errorf("failed to read from spec file: %w", err) } diff --git a/dev-tools/mage/pkgtypes.go b/dev-tools/mage/pkgtypes.go index 249612f8feb..40db480522c 100644 --- a/dev-tools/mage/pkgtypes.go +++ b/dev-tools/mage/pkgtypes.go @@ -24,7 +24,6 @@ import ( "compress/gzip" "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -425,7 +424,7 @@ func (s PackageSpec) Evaluate(args ...map[string]interface{}) PackageSpec { } f.Source = filepath.Join(s.packageDir, filepath.Base(f.Target)) - if err = ioutil.WriteFile(CreateDir(f.Source), []byte(content), 0644); err != nil { + if err = os.WriteFile(CreateDir(f.Source), []byte(content), 0644); err != nil { panic(fmt.Errorf("failed to write file containing content for target=%v: %w", target, err)) } case f.Template != "": @@ -568,7 +567,7 @@ func PackageZip(spec PackageSpec) error { spec.OutputFile = Zip.AddFileExtension(spec.OutputFile) // Write the zip file. - if err := ioutil.WriteFile(CreateDir(spec.OutputFile), buf.Bytes(), 0644); err != nil { + if err := os.WriteFile(CreateDir(spec.OutputFile), buf.Bytes(), 0644); err != nil { return fmt.Errorf("failed to write zip file: %w", err) } @@ -631,7 +630,7 @@ func PackageTarGz(spec PackageSpec) error { continue } - tmpdir, err := ioutil.TempDir("", "TmpSymlinkDropPath") + tmpdir, err := os.MkdirTemp("", "TmpSymlinkDropPath") if err != nil { return err } diff --git a/dev-tools/mage/settings.go b/dev-tools/mage/settings.go index 46ccf691502..9a7230279bc 100644 --- a/dev-tools/mage/settings.go +++ b/dev-tools/mage/settings.go @@ -21,7 +21,6 @@ import ( "errors" "fmt" "go/build" - "io/ioutil" "log" "os" "path/filepath" @@ -491,7 +490,7 @@ func (s *BuildVariableSources) GetBeatVersion() (string, error) { return "", err } - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return "", fmt.Errorf("failed to read beat version file=%v: %w", file, err) } @@ -509,7 +508,7 @@ func (s *BuildVariableSources) GetGoVersion() (string, error) { return "", err } - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return "", fmt.Errorf("failed to read go version file=%v: %w", file, err) } @@ -527,7 +526,7 @@ func (s *BuildVariableSources) GetDocBranch() (string, error) { return "", err } - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { return "", fmt.Errorf("failed to read doc branch file=%v: %w", file, err) } diff --git a/dev-tools/packaging/package_test.go b/dev-tools/packaging/package_test.go index 363e6d904d4..fdf8e3a7edb 100644 --- a/dev-tools/packaging/package_test.go +++ b/dev-tools/packaging/package_test.go @@ -30,7 +30,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "path/filepath" "regexp" @@ -805,7 +804,7 @@ type dockerManifest struct { } func readDockerManifest(r io.Reader) (*dockerManifest, error) { - data, err := ioutil.ReadAll(r) + data, err := io.ReadAll(r) if err != nil { return nil, err } @@ -833,7 +832,7 @@ type dockerInfo struct { } func readDockerInfo(r io.Reader) (*dockerInfo, error) { - data, err := ioutil.ReadAll(r) + data, err := io.ReadAll(r) if err != nil { return nil, err } diff --git a/filebeat/fileset/fileset.go b/filebeat/fileset/fileset.go index 7fc91135dcc..9781c3692aa 100644 --- a/filebeat/fileset/fileset.go +++ b/filebeat/fileset/fileset.go @@ -24,7 +24,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -348,7 +347,7 @@ func (fs *Fileset) getInputConfig() (*conf.C, error) { if err != nil { return nil, fmt.Errorf("Error expanding vars on the input path: %w", err) } - contents, err := ioutil.ReadFile(filepath.Join(fs.modulePath, fs.name, path)) + contents, err := os.ReadFile(filepath.Join(fs.modulePath, fs.name, path)) if err != nil { return nil, fmt.Errorf("Error reading input file %s: %w", path, err) } @@ -434,7 +433,7 @@ func (fs *Fileset) GetPipelines(esVersion version.V) (pipelines []pipeline, err return nil, fmt.Errorf("Error expanding vars on the ingest pipeline path: %w", err) } - strContents, err := ioutil.ReadFile(filepath.Join(fs.modulePath, fs.name, path)) + strContents, err := os.ReadFile(filepath.Join(fs.modulePath, fs.name, path)) if err != nil { return nil, fmt.Errorf("Error reading pipeline file %s: %w", path, err) } diff --git a/filebeat/fileset/modules.go b/filebeat/fileset/modules.go index b1482033c91..08d8aff6c37 100644 --- a/filebeat/fileset/modules.go +++ b/filebeat/fileset/modules.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -249,7 +248,7 @@ func mcfgFromConfig(cfg *conf.C) (*ModuleConfig, error) { func getCurrentModuleName(modulePath, module string) (string, bool) { moduleConfigPath := filepath.Join(modulePath, module, "module.yml") - d, err := ioutil.ReadFile(moduleConfigPath) + d, err := os.ReadFile(moduleConfigPath) if err != nil { return module, false } @@ -267,7 +266,7 @@ func getCurrentModuleName(modulePath, module string) (string, bool) { func getModuleFilesets(modulePath, module string) ([]string, error) { module, _ = getCurrentModuleName(modulePath, module) - fileInfos, err := ioutil.ReadDir(filepath.Join(modulePath, module)) + fileInfos, err := os.ReadDir(filepath.Join(modulePath, module)) if err != nil { return []string{}, err } diff --git a/filebeat/generator/fields/fields.go b/filebeat/generator/fields/fields.go index 4727990b233..8683f78df32 100644 --- a/filebeat/generator/fields/fields.go +++ b/filebeat/generator/fields/fields.go @@ -20,7 +20,7 @@ package fields import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "reflect" "regexp" @@ -100,7 +100,7 @@ func Generate(beatsPath, module, fileset string, noDoc bool) error { func readPipeline(filesetPath string) (*pipeline, error) { pipelinePath := filepath.Join(filesetPath, "ingest/pipeline.json") - r, err := ioutil.ReadFile(pipelinePath) + r, err := os.ReadFile(pipelinePath) if err != nil { return nil, err } @@ -116,7 +116,7 @@ func readPipeline(filesetPath string) (*pipeline, error) { func writeFieldsYml(filesetPath string, fieldsBytes []byte) error { output := filepath.Join(filesetPath, "_meta/fields.yml") - return ioutil.WriteFile(output, fieldsBytes, 0o644) + return os.WriteFile(output, fieldsBytes, 0o644) } func newFieldYml(name, typeName string, noDoc bool) *fieldYml { diff --git a/filebeat/generator/generator.go b/filebeat/generator/generator.go index b490864e61b..a8cc280b2e4 100644 --- a/filebeat/generator/generator.go +++ b/filebeat/generator/generator.go @@ -20,7 +20,6 @@ package generator import ( "bytes" "fmt" - "io/ioutil" "os" "path" ) @@ -83,7 +82,7 @@ func copyTemplate(template, dest string, replace map[string]string) error { return err } - err = ioutil.WriteFile(dest, c, 0o644) + err = os.WriteFile(dest, c, 0o644) if err != nil { return fmt.Errorf("cannot copy template: %v", err) } @@ -92,7 +91,7 @@ func copyTemplate(template, dest string, replace map[string]string) error { } func readTemplate(template string, replace map[string]string) ([]byte, error) { - c, err := ioutil.ReadFile(template) + c, err := os.ReadFile(template) if err != nil { return []byte{}, fmt.Errorf("cannot read template: %v", err) } diff --git a/filebeat/input/file/glob_test.go b/filebeat/input/file/glob_test.go index b923f4e5114..2e6f9298dc7 100644 --- a/filebeat/input/file/glob_test.go +++ b/filebeat/input/file/glob_test.go @@ -18,7 +18,6 @@ package file import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -30,7 +29,7 @@ type globTest struct { } func TestGlob(t *testing.T) { - root, err := ioutil.TempDir("", "testglob") + root, err := os.MkdirTemp("", "testglob") if err != nil { t.Fatal(err) } diff --git a/filebeat/input/file/identifier_inode_deviceid.go b/filebeat/input/file/identifier_inode_deviceid.go index 169970c7d36..dd8082f2f06 100644 --- a/filebeat/input/file/identifier_inode_deviceid.go +++ b/filebeat/input/file/identifier_inode_deviceid.go @@ -21,7 +21,6 @@ package file import ( "fmt" - "io/ioutil" "os" "path/filepath" "time" @@ -52,7 +51,7 @@ func newINodeMarkerIdentifier(cfg *conf.C) (StateIdentifier, error) { if err != nil { return nil, fmt.Errorf("error while opening marker file at %s: %v", config.MarkerPath, err) } - markerContent, err := ioutil.ReadFile(config.MarkerPath) + markerContent, err := os.ReadFile(config.MarkerPath) if err != nil { return nil, fmt.Errorf("error while reading marker file at %s: %v", config.MarkerPath, err) } @@ -79,7 +78,7 @@ func (i *inodeMarkerIdentifier) markerContents() string { return "" } if i.markerFileLastModifitaion.Before(fi.ModTime()) { - contents, err := ioutil.ReadFile(i.markerPath) + contents, err := os.ReadFile(i.markerPath) if err != nil { i.log.Errorf("Error while reading contents of marker file: %v", err) return "" diff --git a/filebeat/input/filestream/filestream_test.go b/filebeat/input/filestream/filestream_test.go index 635f711c395..6d5ff4b8282 100644 --- a/filebeat/input/filestream/filestream_test.go +++ b/filebeat/input/filestream/filestream_test.go @@ -20,7 +20,6 @@ package filestream import ( "context" "io" - "io/ioutil" "os" "testing" "time" @@ -110,7 +109,7 @@ func TestLogFileTruncated(t *testing.T) { } func createTestLogFile() *os.File { - f, err := ioutil.TempFile("", "filestream_reader_test") + f, err := os.CreateTemp("", "filestream_reader_test") if err != nil { panic(err) } diff --git a/filebeat/input/filestream/fswatch_test_non_windows.go b/filebeat/input/filestream/fswatch_test_non_windows.go index 9b329a1254c..b56d8f25c3e 100644 --- a/filebeat/input/filestream/fswatch_test_non_windows.go +++ b/filebeat/input/filestream/fswatch_test_non_windows.go @@ -22,7 +22,6 @@ package filestream import ( "context" "errors" - "io/ioutil" "os" "path/filepath" "strconv" @@ -37,7 +36,7 @@ import ( ) func TestFileScannerSymlinks(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "fswatch_test_file_scanner") + tmpDir, err := os.MkdirTemp("", "fswatch_test_file_scanner") if err != nil { t.Fatalf("cannot create temporary test dir: %v", err) } diff --git a/filebeat/input/filestream/identifier_inode_deviceid.go b/filebeat/input/filestream/identifier_inode_deviceid.go index 05a768d2bab..5b203a03fc8 100644 --- a/filebeat/input/filestream/identifier_inode_deviceid.go +++ b/filebeat/input/filestream/identifier_inode_deviceid.go @@ -21,7 +21,6 @@ package filestream import ( "fmt" - "io/ioutil" "os" "path/filepath" "time" @@ -53,7 +52,7 @@ func newINodeMarkerIdentifier(cfg *conf.C) (fileIdentifier, error) { if err != nil { return nil, fmt.Errorf("error while opening marker file at %s: %w", config.MarkerPath, err) } - markerContent, err := ioutil.ReadFile(config.MarkerPath) + markerContent, err := os.ReadFile(config.MarkerPath) if err != nil { return nil, fmt.Errorf("error while reading marker file at %s: %w", config.MarkerPath, err) } @@ -80,7 +79,7 @@ func (i *inodeMarkerIdentifier) markerContents() string { return "" } if i.markerFileLastModifitaion.Before(fi.ModTime()) { - contents, err := ioutil.ReadFile(i.markerPath) + contents, err := os.ReadFile(i.markerPath) if err != nil { i.log.Errorf("Error while reading contents of marker file: %v", err) return "" diff --git a/filebeat/input/filestream/identifier_test.go b/filebeat/input/filestream/identifier_test.go index 1fcd4d73efa..2ffb23827cf 100644 --- a/filebeat/input/filestream/identifier_test.go +++ b/filebeat/input/filestream/identifier_test.go @@ -18,7 +18,6 @@ package filestream import ( - "io/ioutil" "os" "testing" @@ -40,7 +39,7 @@ func TestFileIdentifier(t *testing.T) { require.NoError(t, err) assert.Equal(t, DefaultIdentifierName, identifier.Name()) - tmpFile, err := ioutil.TempFile("", "test_file_identifier_native") + tmpFile, err := os.CreateTemp("", "test_file_identifier_native") if err != nil { t.Fatalf("cannot create temporary file for test: %v", err) } @@ -64,7 +63,7 @@ func TestFileIdentifier(t *testing.T) { require.NoError(t, err) assert.Equal(t, DefaultIdentifierName, identifier.Name()) - tmpFile, err := ioutil.TempFile("", "test_file_identifier_native") + tmpFile, err := os.CreateTemp("", "test_file_identifier_native") if err != nil { t.Fatalf("cannot create temporary file for test: %v", err) } diff --git a/filebeat/input/filestream/identifier_test_non_windows.go b/filebeat/input/filestream/identifier_test_non_windows.go index 3f42ce79cef..7e49a5d3747 100644 --- a/filebeat/input/filestream/identifier_test_non_windows.go +++ b/filebeat/input/filestream/identifier_test_non_windows.go @@ -20,7 +20,6 @@ package filestream import ( - "io/ioutil" "os" "testing" @@ -34,7 +33,7 @@ import ( func TestFileIdentifierInodeMarker(t *testing.T) { t.Run("inode_marker file identifier", func(t *testing.T) { const markerContents = "unique_marker" - markerFile, err := ioutil.TempFile("", "test_file_identifier_inode_marker_identifier") + markerFile, err := os.CreateTemp("", "test_file_identifier_inode_marker_identifier") if err != nil { t.Fatalf("cannot create marker file for test: %v", err) } @@ -61,7 +60,7 @@ func TestFileIdentifierInodeMarker(t *testing.T) { require.NoError(t, err) assert.Equal(t, inodeMarkerName, identifier.Name()) - tmpFile, err := ioutil.TempFile("", "test_file_identifier_inode_marker") + tmpFile, err := os.CreateTemp("", "test_file_identifier_inode_marker") if err != nil { t.Fatalf("cannot create temporary file for test: %v", err) } diff --git a/filebeat/input/filestream/prospector_test.go b/filebeat/input/filestream/prospector_test.go index 552b4218c78..f437c39d939 100644 --- a/filebeat/input/filestream/prospector_test.go +++ b/filebeat/input/filestream/prospector_test.go @@ -22,7 +22,6 @@ import ( "context" "fmt" "io/fs" - "io/ioutil" "os" "sync" "testing" @@ -97,7 +96,7 @@ func TestProspector_InitCleanIfRemoved(t *testing.T) { } func TestProspector_InitUpdateIdentifiers(t *testing.T) { - f, err := ioutil.TempFile("", "existing_file") + f, err := os.CreateTemp("", "existing_file") if err != nil { t.Fatalf("cannot create temp file") } diff --git a/filebeat/input/log/input_test.go b/filebeat/input/log/input_test.go index 659013f3266..8c4623790b6 100644 --- a/filebeat/input/log/input_test.go +++ b/filebeat/input/log/input_test.go @@ -20,7 +20,6 @@ package log import ( - "io/ioutil" "os" "path" "sync" @@ -134,13 +133,13 @@ func testInputLifecycle(t *testing.T, context input.Context, closer func(input.C defer goroutines.Check(t) // Prepare a log file - tmpdir, err := ioutil.TempDir(os.TempDir(), "input-test") + tmpdir, err := os.MkdirTemp(os.TempDir(), "input-test") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpdir) logs := []byte("some log line\nother log line\n") - err = ioutil.WriteFile(path.Join(tmpdir, "some.log"), logs, 0o644) + err = os.WriteFile(path.Join(tmpdir, "some.log"), logs, 0o644) assert.NoError(t, err) // Setup the input diff --git a/filebeat/registrar/migrate.go b/filebeat/registrar/migrate.go index 845adba4393..5c4baaed41d 100644 --- a/filebeat/registrar/migrate.go +++ b/filebeat/registrar/migrate.go @@ -20,7 +20,6 @@ package registrar import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" @@ -240,7 +239,7 @@ func (m *Migrator) updateToVersion1(regHome string) error { return fmt.Errorf("migration complete but failed to remove original data file: %v: %w", origDataFile, err) } - if err := ioutil.WriteFile(filepath.Join(regHome, "meta.json"), []byte(`{"version": "1"}`), m.permissions); err != nil { + if err := os.WriteFile(filepath.Join(regHome, "meta.json"), []byte(`{"version": "1"}`), m.permissions); err != nil { return fmt.Errorf("failed to update the meta.json file: %w", err) } @@ -261,7 +260,7 @@ func readVersion(regHome, migrateFile string) (registryVersion, error) { return noRegistry, nil } - tmp, err := ioutil.ReadFile(metaFile) + tmp, err := os.ReadFile(metaFile) if err != nil { return noRegistry, fmt.Errorf("failed to open meta file: %w", err) } diff --git a/filebeat/registrar/migrate_bench_test.go b/filebeat/registrar/migrate_bench_test.go index 756057d72d5..abe41caafed 100644 --- a/filebeat/registrar/migrate_bench_test.go +++ b/filebeat/registrar/migrate_bench_test.go @@ -23,7 +23,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -101,7 +100,7 @@ func tempDir(t testing.TB) string { t.Fatal(err) } - path, err := ioutil.TempDir(cwd, "") + path, err := os.MkdirTemp(cwd, "") if err != nil { t.Fatal(err) } @@ -121,7 +120,7 @@ func mkDir(t testing.TB, path string) { } func clearDir(t testing.TB, path string) { - old, err := ioutil.ReadDir(path) + old, err := os.ReadDir(path) if err != nil { t.Fatal(err) } @@ -134,7 +133,7 @@ func clearDir(t testing.TB, path string) { func writeFile(t testing.TB, path string, contents []byte) { t.Helper() - err := ioutil.WriteFile(path, contents, 0o600) + err := os.WriteFile(path, contents, 0o600) if err != nil { t.Fatal(err) } diff --git a/filebeat/scripts/tester/main.go b/filebeat/scripts/tester/main.go index 79fee6ad541..8f505e6f038 100644 --- a/filebeat/scripts/tester/main.go +++ b/filebeat/scripts/tester/main.go @@ -22,7 +22,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -207,7 +206,7 @@ func getPipelinePath(path, modulesPath string) ([]string, error) { } if stat.IsDir() { - files, err := ioutil.ReadDir(path) + files, err := os.ReadDir(path) if err != nil { return nil, err } @@ -258,7 +257,7 @@ func testPipeline(esURL, path string, logs []string, verbose, simulateVerbose bo } func readPipeline(path string) (map[string]interface{}, error) { - d, err := ioutil.ReadFile(path) + d, err := os.ReadFile(path) if err != nil { return nil, err } diff --git a/heartbeat/hbtest/hbtestutil.go b/heartbeat/hbtest/hbtestutil.go index e73e1efe78f..e3cb21a31b8 100644 --- a/heartbeat/hbtest/hbtestutil.go +++ b/heartbeat/hbtest/hbtestutil.go @@ -22,7 +22,6 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" "math/bits" "net" "net/http" @@ -277,7 +276,7 @@ func RespondingTCPChecks() validator.Validator { func CertToTempFile(t *testing.T, cert *x509.Certificate) *os.File { // Write the certificate to a tempFile. Heartbeat would normally read certs from // disk, not memory, so this little bit of extra work is worthwhile - certFile, err := ioutil.TempFile("", "sslcert") + certFile, err := os.CreateTemp("", "sslcert") require.NoError(t, err) _, _ = certFile.WriteString(x509util.CertToPEMString(cert)) return certFile diff --git a/heartbeat/monitors/active/http/check_test.go b/heartbeat/monitors/active/http/check_test.go index abd9e9252a3..40551842ed7 100644 --- a/heartbeat/monitors/active/http/check_test.go +++ b/heartbeat/monitors/active/http/check_test.go @@ -19,7 +19,7 @@ package http import ( "fmt" - "io/ioutil" + "io" "log" "net/http" "net/http/httptest" @@ -180,7 +180,7 @@ func TestCheckBody(t *testing.T) { for _, n := range test.negative { negativePatterns = append(negativePatterns, match.MustCompile(n)) } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) check := checkBody(positivePatterns, negativePatterns)(res, string(body)) diff --git a/heartbeat/monitors/active/http/checkjson_test.go b/heartbeat/monitors/active/http/checkjson_test.go index 9a197b427e6..54fc4056948 100644 --- a/heartbeat/monitors/active/http/checkjson_test.go +++ b/heartbeat/monitors/active/http/checkjson_test.go @@ -19,7 +19,7 @@ package http import ( "fmt" - "io/ioutil" + "io" "log" "net/http" "net/http/httptest" @@ -122,7 +122,7 @@ func TestCheckJsonExpression(t *testing.T) { ) require.NoError(t, err) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) checkRes := checker(res, string(body)) @@ -218,7 +218,7 @@ func TestCheckJsonCondition(t *testing.T) { checker, err := checkJson([]*jsonResponseCheck{{Description: test.condDesc, Condition: test.condConf}}) require.NoError(t, err) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) checkRes := checker(res, string(body)) diff --git a/heartbeat/monitors/active/http/http_test.go b/heartbeat/monitors/active/http/http_test.go index 20575210ac9..a93840d7cfc 100644 --- a/heartbeat/monitors/active/http/http_test.go +++ b/heartbeat/monitors/active/http/http_test.go @@ -24,7 +24,6 @@ import ( "crypto/x509" "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -579,7 +578,7 @@ func TestHTTPSx509Auth(t *testing.T) { certReader, err := file.ReadOpen(clientCertPath) require.NoError(t, err) - clientCertBytes, err := ioutil.ReadAll(certReader) + clientCertBytes, err := io.ReadAll(certReader) require.NoError(t, err) clientCerts := x509.NewCertPool() diff --git a/heartbeat/monitors/active/http/respbody_test.go b/heartbeat/monitors/active/http/respbody_test.go index cd27e762110..0c798e63074 100644 --- a/heartbeat/monitors/active/http/respbody_test.go +++ b/heartbeat/monitors/active/http/respbody_test.go @@ -21,7 +21,7 @@ import ( "crypto/sha256" "encoding/hex" "fmt" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -233,7 +233,7 @@ func Test_readPrefixAndHash(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - rc := ioutil.NopCloser(strings.NewReader(tt.body)) + rc := io.NopCloser(strings.NewReader(tt.body)) gotRespSize, gotPrefix, gotHashStr, err := readPrefixAndHash(rc, tt.len) if tt.err { @@ -256,5 +256,5 @@ func Test_readPrefixAndHash(t *testing.T) { } func simpleHTTPResponse() *http.Response { - return &http.Response{Body: ioutil.NopCloser(strings.NewReader("hello"))} + return &http.Response{Body: io.NopCloser(strings.NewReader("hello"))} } diff --git a/heartbeat/monitors/active/http/task.go b/heartbeat/monitors/active/http/task.go index 538f5f69615..46c99c55f55 100644 --- a/heartbeat/monitors/active/http/task.go +++ b/heartbeat/monitors/active/http/task.go @@ -23,7 +23,7 @@ import ( "crypto/x509" "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/url" @@ -311,7 +311,7 @@ func execPing( func attachRequestBody(ctx *context.Context, req *http.Request, body []byte) *http.Request { req = req.WithContext(*ctx) if len(body) > 0 { - req.Body = ioutil.NopCloser(bytes.NewBuffer(body)) + req.Body = io.NopCloser(bytes.NewBuffer(body)) req.ContentLength = int64(len(body)) } diff --git a/heartbeat/watcher/watcher.go b/heartbeat/watcher/watcher.go index 0f639665a40..38e1f74ea12 100644 --- a/heartbeat/watcher/watcher.go +++ b/heartbeat/watcher/watcher.go @@ -19,7 +19,7 @@ package watcher import ( "hash/fnv" - "io/ioutil" + "io" "os" "time" @@ -99,7 +99,7 @@ func (w *fileChangeTester) check() ([]byte, bool) { } } - content, err := ioutil.ReadAll(f) + content, err := io.ReadAll(f) if err != nil { logp.Info("Reading file '%v' failed with: %v", w.path, err) return nil, false diff --git a/libbeat/api/npipe/listener_windows_test.go b/libbeat/api/npipe/listener_windows_test.go index b97982ffadc..54fd194dd28 100644 --- a/libbeat/api/npipe/listener_windows_test.go +++ b/libbeat/api/npipe/listener_windows_test.go @@ -21,7 +21,7 @@ package npipe import ( "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -52,7 +52,7 @@ func TestHTTPOverNamedPipe(t *testing.T) { r, err := c.Get("http://npipe/echo-hello") require.NoError(t, err) - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) defer r.Body.Close() assert.Equal(t, "ehlo!", string(body)) diff --git a/libbeat/api/server_windows_test.go b/libbeat/api/server_windows_test.go index b4008017655..541928e2ebe 100644 --- a/libbeat/api/server_windows_test.go +++ b/libbeat/api/server_windows_test.go @@ -20,7 +20,7 @@ package api import ( - "io/ioutil" + "io" "net/http" "testing" @@ -56,7 +56,7 @@ func TestNamedPipe(t *testing.T) { require.NoError(t, err) defer r.Body.Close() - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) require.NoError(t, err) assert.Equal(t, "ehlo!", string(body)) diff --git a/libbeat/asset/registry.go b/libbeat/asset/registry.go index 99fc1a7dba0..a8b818ceea6 100644 --- a/libbeat/asset/registry.go +++ b/libbeat/asset/registry.go @@ -21,7 +21,7 @@ import ( "bytes" "compress/zlib" "encoding/base64" - "io/ioutil" + "io" "sort" ) @@ -119,5 +119,5 @@ func DecodeData(data string) ([]byte, error) { } defer r.Close() - return ioutil.ReadAll(r) + return io.ReadAll(r) } diff --git a/libbeat/cfgfile/glob_manager_test.go b/libbeat/cfgfile/glob_manager_test.go index 808f1bc3394..092b27c9a1a 100644 --- a/libbeat/cfgfile/glob_manager_test.go +++ b/libbeat/cfgfile/glob_manager_test.go @@ -18,7 +18,6 @@ package cfgfile import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -35,7 +34,7 @@ func TestGlobManagerInit(t *testing.T) { func TestGlobManager(t *testing.T) { // Create random temp directory - dir, err := ioutil.TempDir("", "glob_manager") + dir, err := os.MkdirTemp("", "glob_manager") defer os.RemoveAll(dir) if err != nil { t.Fatal(err) @@ -43,13 +42,13 @@ func TestGlobManager(t *testing.T) { // Prepare scenario: content := []byte("test\n") - err = ioutil.WriteFile(dir+"/config1.yml", content, 0644) + err = os.WriteFile(dir+"/config1.yml", content, 0644) assert.NoError(t, err) - err = ioutil.WriteFile(dir+"/config2.yml", content, 0644) + err = os.WriteFile(dir+"/config2.yml", content, 0644) assert.NoError(t, err) - err = ioutil.WriteFile(dir+"/config2-alt.yml.disabled", content, 0644) + err = os.WriteFile(dir+"/config2-alt.yml.disabled", content, 0644) assert.NoError(t, err) - err = ioutil.WriteFile(dir+"/config3.yml.disabled", content, 0644) + err = os.WriteFile(dir+"/config3.yml.disabled", content, 0644) assert.NoError(t, err) // Init Glob Manager diff --git a/libbeat/cfgfile/glob_watcher_test.go b/libbeat/cfgfile/glob_watcher_test.go index 99c9a79b82f..b2e91faeab1 100644 --- a/libbeat/cfgfile/glob_watcher_test.go +++ b/libbeat/cfgfile/glob_watcher_test.go @@ -18,7 +18,6 @@ package cfgfile import ( - "io/ioutil" "math/rand" "os" "strconv" @@ -31,7 +30,7 @@ import ( func TestGlobWatcher(t *testing.T) { // Create random temp directory id := strconv.Itoa(rand.New(rand.NewSource(int64(time.Now().Nanosecond()))).Int()) - dir, err := ioutil.TempDir("", id) + dir, err := os.MkdirTemp("", id) defer os.RemoveAll(dir) assert.NoError(t, err) glob := dir + "/*.yml" @@ -39,9 +38,9 @@ func TestGlobWatcher(t *testing.T) { gcd := NewGlobWatcher(glob) content := []byte("test\n") - err = ioutil.WriteFile(dir+"/config1.yml", content, 0644) + err = os.WriteFile(dir+"/config1.yml", content, 0644) assert.NoError(t, err) - err = ioutil.WriteFile(dir+"/config2.yml", content, 0644) + err = os.WriteFile(dir+"/config2.yml", content, 0644) assert.NoError(t, err) // Make sure not inside compensation time @@ -57,7 +56,7 @@ func TestGlobWatcher(t *testing.T) { assert.NoError(t, err) assert.False(t, changed) - err = ioutil.WriteFile(dir+"/config3.yml", content, 0644) + err = os.WriteFile(dir+"/config3.yml", content, 0644) assert.NoError(t, err) files, changed, err = gcd.Scan() diff --git a/libbeat/cfgfile/reload_test.go b/libbeat/cfgfile/reload_test.go index f28fbd7033a..fd2c964ae9d 100644 --- a/libbeat/cfgfile/reload_test.go +++ b/libbeat/cfgfile/reload_test.go @@ -21,7 +21,6 @@ package cfgfile import ( "fmt" - "io/ioutil" "os" "testing" "time" @@ -34,7 +33,7 @@ import ( func TestReloader(t *testing.T) { // Create random temp directory - dir, err := ioutil.TempDir("", "libbeat-reloader") + dir, err := os.MkdirTemp("", "libbeat-reloader") defer os.RemoveAll(dir) if err != nil { t.Fatal(err) @@ -74,7 +73,7 @@ func TestReloader(t *testing.T) { // Write a file to the reloader path to trigger a real reload content := []byte("test\n") - err = ioutil.WriteFile(dir+"/config1.yml", content, 0644) + err = os.WriteFile(dir+"/config1.yml", content, 0644) assert.NoError(t, err) // Wait for the number of scans to increase at least twice. This is somewhat diff --git a/libbeat/cmd/instance/beat_test.go b/libbeat/cmd/instance/beat_test.go index 52e55941225..17060b8e491 100644 --- a/libbeat/cmd/instance/beat_test.go +++ b/libbeat/cmd/instance/beat_test.go @@ -20,7 +20,6 @@ package instance import ( - "io/ioutil" "os" "testing" @@ -124,7 +123,7 @@ func TestEmptyMetaJson(t *testing.T) { } // prepare empty meta file - metaFile, err := ioutil.TempFile("../test", "meta.json") + metaFile, err := os.CreateTemp("../test", "meta.json") assert.Equal(t, nil, err, "Unable to create temporary meta file") metaPath := metaFile.Name() @@ -145,7 +144,7 @@ func TestMetaJsonWithTimestamp(t *testing.T) { } firstStart := firstBeat.Info.FirstStart - metaFile, err := ioutil.TempFile("../test", "meta.json") + metaFile, err := os.CreateTemp("../test", "meta.json") assert.Equal(t, nil, err, "Unable to create temporary meta file") metaPath := metaFile.Name() diff --git a/libbeat/cmd/keystore.go b/libbeat/cmd/keystore.go index 7f5ecd78c41..608bdebe912 100644 --- a/libbeat/cmd/keystore.go +++ b/libbeat/cmd/keystore.go @@ -21,7 +21,7 @@ import ( "bufio" "errors" "fmt" - "io/ioutil" + "io" "os" "strings" "syscall" @@ -200,7 +200,7 @@ func addKey(store keystore.Keystore, keys []string, force, stdin bool) error { var keyValue []byte if stdin { reader := bufio.NewReader(os.Stdin) - keyValue, err = ioutil.ReadAll(reader) + keyValue, err = io.ReadAll(reader) if err != nil { return fmt.Errorf("could not read input from stdin") } diff --git a/libbeat/common/file/file_other_test.go b/libbeat/common/file/file_other_test.go index 014f761520b..0678283f139 100644 --- a/libbeat/common/file/file_other_test.go +++ b/libbeat/common/file/file_other_test.go @@ -20,7 +20,6 @@ package file import ( - "io/ioutil" "math" "os" "runtime" @@ -30,7 +29,7 @@ import ( ) func TestGetOSFileState(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") assert.NoError(t, err) fileinfo, err := file.Stat() @@ -49,7 +48,7 @@ func TestGetOSFileState(t *testing.T) { } func TestGetOSFileStateStat(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") assert.NoError(t, err) fileinfo, err := os.Stat(file.Name()) @@ -68,7 +67,7 @@ func TestGetOSFileStateStat(t *testing.T) { } func TestRemoved(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") assert.NoError(t, err) assert.NoError(t, os.Remove(file.Name())) diff --git a/libbeat/common/file/file_windows_test.go b/libbeat/common/file/file_windows_test.go index ec5d8f7b4af..a00e2205436 100644 --- a/libbeat/common/file/file_windows_test.go +++ b/libbeat/common/file/file_windows_test.go @@ -20,7 +20,6 @@ package file import ( - "io/ioutil" "os" "testing" @@ -28,7 +27,7 @@ import ( ) func TestGetOSState(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") assert.NoError(t, err) fileinfo, err := file.Stat() @@ -42,7 +41,7 @@ func TestGetOSState(t *testing.T) { } func TestGetOSStateStat(t *testing.T) { - file, err := ioutil.TempFile("", "") + file, err := os.CreateTemp("", "") assert.NoError(t, err) fileinfo, err := os.Stat(file.Name()) diff --git a/libbeat/common/flowhash/communityid_test.go b/libbeat/common/flowhash/communityid_test.go index 4398d60d946..9426011afe7 100644 --- a/libbeat/common/flowhash/communityid_test.go +++ b/libbeat/common/flowhash/communityid_test.go @@ -23,7 +23,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -60,7 +59,7 @@ func TestPCAPFiles(t *testing.T) { if *update { data := strings.Join(result, "") - err = ioutil.WriteFile(goldenName, []byte(data), 0644) + err = os.WriteFile(goldenName, []byte(data), 0644) if err != nil { t.Fatal(err) } diff --git a/libbeat/dashboards/export.go b/libbeat/dashboards/export.go index 54aace94aaa..22eee2db6b1 100644 --- a/libbeat/dashboards/export.go +++ b/libbeat/dashboards/export.go @@ -23,7 +23,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "path" "path/filepath" @@ -61,7 +60,7 @@ func Export(client *kibana.Client, id string) ([]byte, error) { // ExportAllFromYml exports all dashboards found in the YML file func ExportAllFromYml(client *kibana.Client, ymlPath string) ([][]byte, ListYML, error) { - b, err := ioutil.ReadFile(ymlPath) + b, err := os.ReadFile(ymlPath) if err != nil { return nil, ListYML{}, fmt.Errorf("error opening the list of dashboards: %w", err) } @@ -102,7 +101,7 @@ func SaveToFile(dashboard []byte, filename, root string, version version.V) erro out := filepath.Join(root, dashboardsPath, filename) - return ioutil.WriteFile(out, dashboard, OutputPermission) + return os.WriteFile(out, dashboard, OutputPermission) } // SaveToFile creates the required directories if needed and saves dashboard. @@ -163,6 +162,6 @@ func saveAsset(line []byte, assetRoot string) error { if err != nil { return fmt.Errorf("failed to get indented bytes: %+v", err) } - return ioutil.WriteFile(out, assetIndented, OutputPermission) + return os.WriteFile(out, assetIndented, OutputPermission) } diff --git a/libbeat/dashboards/importer.go b/libbeat/dashboards/importer.go index 3d3658d7c83..257a967b48c 100644 --- a/libbeat/dashboards/importer.go +++ b/libbeat/dashboards/importer.go @@ -22,7 +22,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "os" "path" @@ -197,7 +196,7 @@ func (imp Importer) unzip(archive, target string) error { func (imp Importer) ImportArchive() error { var archive string - target, err := ioutil.TempDir("", "tmp") + target, err := os.MkdirTemp("", "tmp") if err != nil { return fmt.Errorf("Failed to generate a temporary directory name: %v", err) } @@ -252,7 +251,7 @@ func (imp Importer) ImportArchive() error { } func getDirectories(target string) ([]string, error) { - files, err := ioutil.ReadDir(target) + files, err := os.ReadDir(target) if err != nil { return nil, err } diff --git a/libbeat/dashboards/kibana_loader.go b/libbeat/dashboards/kibana_loader.go index 55d195c4f8e..56c412eb4b0 100644 --- a/libbeat/dashboards/kibana_loader.go +++ b/libbeat/dashboards/kibana_loader.go @@ -21,8 +21,8 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "net/url" + "os" "path/filepath" "time" @@ -110,7 +110,7 @@ func (loader KibanaLoader) ImportIndexFile(file string) error { loader.statusMsg("Importing index file from %s", file) // read json file - reader, err := ioutil.ReadFile(file) + reader, err := os.ReadFile(file) if err != nil { return fmt.Errorf("fail to read index-pattern from file %s: %w", file, err) } @@ -158,7 +158,7 @@ func (loader KibanaLoader) ImportDashboard(file string) error { params.Set("overwrite", "true") // read json file - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) if err != nil { return fmt.Errorf("fail to read dashboard from file %s: %w", file, err) } @@ -203,7 +203,7 @@ func (loader KibanaLoader) addReferences(path string, dashboard []byte) (string, if _, ok := loader.loadedAssets[referencePath]; ok { continue } - refContents, err := ioutil.ReadFile(referencePath) + refContents, err := os.ReadFile(referencePath) if err != nil { return "", fmt.Errorf("fail to read referenced asset from file %s: %w", referencePath, err) } diff --git a/libbeat/esleg/eslegclient/bulkapi.go b/libbeat/esleg/eslegclient/bulkapi.go index 56a36ccf145..1db777c2838 100644 --- a/libbeat/esleg/eslegclient/bulkapi.go +++ b/libbeat/esleg/eslegclient/bulkapi.go @@ -23,7 +23,6 @@ import ( "encoding/json" "errors" "io" - "io/ioutil" "net/http" "strings" @@ -142,7 +141,7 @@ func (r *bulkRequest) reset(body BodyEncoder) { rc, ok := bdy.(io.ReadCloser) if !ok && body != nil { - rc = ioutil.NopCloser(bdy) + rc = io.NopCloser(bdy) } switch v := bdy.(type) { diff --git a/libbeat/esleg/eslegclient/connection_integration_test.go b/libbeat/esleg/eslegclient/connection_integration_test.go index b4e277ed1a6..7df991d5cb1 100644 --- a/libbeat/esleg/eslegclient/connection_integration_test.go +++ b/libbeat/esleg/eslegclient/connection_integration_test.go @@ -21,7 +21,7 @@ package eslegclient import ( "context" - "io/ioutil" + "io" "math/rand" "net" "net/http" @@ -166,7 +166,7 @@ func startTestProxy(t *testing.T, redirectURL string) *httptest.Server { require.NoError(t, err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) for _, header := range []string{"Content-Encoding", "Content-Type"} { diff --git a/libbeat/generator/fields/module_fields_collector.go b/libbeat/generator/fields/module_fields_collector.go index 85f917cacf6..c9fe790519c 100644 --- a/libbeat/generator/fields/module_fields_collector.go +++ b/libbeat/generator/fields/module_fields_collector.go @@ -18,7 +18,6 @@ package fields import ( - "io/ioutil" "os" "path/filepath" ) @@ -80,7 +79,7 @@ func CollectFiles(module string, modulesPath string) ([]*YmlFile, error) { files = append(files, ymls...) modulesRoot := filepath.Base(modulesPath) - sets, err := ioutil.ReadDir(filepath.Join(modulesPath, module)) + sets, err := os.ReadDir(filepath.Join(modulesPath, module)) if err != nil { return nil, err } diff --git a/libbeat/kibana/index_pattern_generator.go b/libbeat/kibana/index_pattern_generator.go index 98e5e3bb8db..72f7611bef6 100644 --- a/libbeat/kibana/index_pattern_generator.go +++ b/libbeat/kibana/index_pattern_generator.go @@ -19,7 +19,6 @@ package kibana import ( "encoding/json" - "io/ioutil" "os" "path/filepath" "regexp" @@ -144,7 +143,7 @@ func dumpToFile(f string, pattern mapstr.M) error { if err != nil { return err } - err = ioutil.WriteFile(f, patternIndent, 0644) + err = os.WriteFile(f, patternIndent, 0644) if err != nil { return err } diff --git a/libbeat/kibana/index_pattern_generator_test.go b/libbeat/kibana/index_pattern_generator_test.go index aa6d4a929fa..0711fc34029 100644 --- a/libbeat/kibana/index_pattern_generator_test.go +++ b/libbeat/kibana/index_pattern_generator_test.go @@ -21,7 +21,6 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" "os" "strings" "testing" @@ -40,7 +39,7 @@ func TestNewGenerator(t *testing.T) { tmpDir := tmpPath(t) defer os.RemoveAll(tmpDir) - data, err := ioutil.ReadFile("./testdata/fields.yml") + data, err := os.ReadFile("./testdata/fields.yml") if err != nil { t.Fatal(err) } @@ -80,7 +79,7 @@ func TestGenerate(t *testing.T) { versions := []*version.V{v7} var d mapstr.M for _, version := range versions { - data, err := ioutil.ReadFile("./testdata/fields.yml") + data, err := os.ReadFile("./testdata/fields.yml") if err != nil { t.Fatal(err) } @@ -119,7 +118,7 @@ func TestGenerateExtensive(t *testing.T) { var d mapstr.M for _, version := range versions { - data, err := ioutil.ReadFile("testdata/extensive/fields.yml") + data, err := os.ReadFile("testdata/extensive/fields.yml") if err != nil { t.Fatal(err) } @@ -227,7 +226,7 @@ func find(a []map[string]interface{}, key, val string) int { } func readNDJSON(path string) ([]map[string]interface{}, error) { - f, err := ioutil.ReadFile(path) + f, err := os.ReadFile(path) if err != nil { return nil, err } @@ -246,7 +245,7 @@ func readNDJSON(path string) ([]map[string]interface{}, error) { } func tmpPath(t testing.TB) string { - tmpDir, err := ioutil.TempDir("", "kibana-tests") + tmpDir, err := os.MkdirTemp("", "kibana-tests") if err != nil { t.Fatal(err) } diff --git a/libbeat/licenser/elastic_fetcher_test.go b/libbeat/licenser/elastic_fetcher_test.go index 731bf5c0618..505e9868d5a 100644 --- a/libbeat/licenser/elastic_fetcher_test.go +++ b/libbeat/licenser/elastic_fetcher_test.go @@ -18,7 +18,6 @@ package licenser import ( - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -120,7 +119,7 @@ func TestParseJSON(t *testing.T) { t.Run(path, func(t *testing.T) { h := func(w http.ResponseWriter, r *http.Request) { - json, err := ioutil.ReadFile(path) + json, err := os.ReadFile(path) if err != nil { t.Fatal("could not read JSON") } diff --git a/libbeat/outputs/elasticsearch/client_integration_test.go b/libbeat/outputs/elasticsearch/client_integration_test.go index 7a8a06becca..7d470a021ca 100644 --- a/libbeat/outputs/elasticsearch/client_integration_test.go +++ b/libbeat/outputs/elasticsearch/client_integration_test.go @@ -22,7 +22,7 @@ package elasticsearch import ( "context" "fmt" - "io/ioutil" + "io" "math/rand" "net/http" "net/http/httptest" @@ -493,7 +493,7 @@ func startTestProxy(t *testing.T, redirectURL string) *httptest.Server { require.NoError(t, err) defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) for _, header := range []string{"Content-Encoding", "Content-Type"} { diff --git a/libbeat/processors/add_cloud_metadata/http_fetcher.go b/libbeat/processors/add_cloud_metadata/http_fetcher.go index 4ca27f53d4a..03d5e8d78f8 100644 --- a/libbeat/processors/add_cloud_metadata/http_fetcher.go +++ b/libbeat/processors/add_cloud_metadata/http_fetcher.go @@ -22,7 +22,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" cfg "github.com/elastic/elastic-agent-libs/config" @@ -110,7 +110,7 @@ func (f *httpMetadataFetcher) fetchRaw( return } - all, err := ioutil.ReadAll(rsp.Body) + all, err := io.ReadAll(rsp.Body) if err != nil { result.err = fmt.Errorf("failed requesting %v metadata: %w", f.provider, err) return diff --git a/libbeat/processors/dissect/dissect_test.go b/libbeat/processors/dissect/dissect_test.go index 3543d8c3821..9f95912ec0a 100644 --- a/libbeat/processors/dissect/dissect_test.go +++ b/libbeat/processors/dissect/dissect_test.go @@ -20,7 +20,6 @@ package dissect import ( "encoding/json" "fmt" - "io/ioutil" "os" "regexp" "testing" @@ -132,7 +131,7 @@ type dissectTest struct { var tests []dissectTest func init() { - content, err := ioutil.ReadFile("testdata/dissect_tests.json") + content, err := os.ReadFile("testdata/dissect_tests.json") if err != nil { fmt.Printf("could not read the content of 'dissect_tests', error: %s", err) os.Exit(1) diff --git a/libbeat/publisher/pipeline/stress/stress_test.go b/libbeat/publisher/pipeline/stress/stress_test.go index 9b918b25003..1922a020e51 100644 --- a/libbeat/publisher/pipeline/stress/stress_test.go +++ b/libbeat/publisher/pipeline/stress/stress_test.go @@ -22,7 +22,6 @@ package stress_test import ( "flag" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -82,7 +81,7 @@ func TestPipeline(t *testing.T) { name = strings.Replace(name, "/", "-", -1) name = strings.Replace(name, "\\", "-", -1) - dir, err := ioutil.TempDir("", "") + dir, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } diff --git a/libbeat/publisher/queue/diskqueue/acks_test.go b/libbeat/publisher/queue/diskqueue/acks_test.go index bacdf6689d5..00c2e11f426 100644 --- a/libbeat/publisher/queue/diskqueue/acks_test.go +++ b/libbeat/publisher/queue/diskqueue/acks_test.go @@ -19,7 +19,6 @@ package diskqueue import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -238,7 +237,7 @@ func TestAddFrames(t *testing.T) { } func runAddFramesTest(t *testing.T, name string, test addFramesTest) { - dir, err := ioutil.TempDir("", "diskqueue_acks_test") + dir, err := os.MkdirTemp("", "diskqueue_acks_test") if err != nil { t.Fatal(err) } diff --git a/libbeat/publisher/queue/diskqueue/queue_test.go b/libbeat/publisher/queue/diskqueue/queue_test.go index c0b780ffb38..014737b2ea8 100644 --- a/libbeat/publisher/queue/diskqueue/queue_test.go +++ b/libbeat/publisher/queue/diskqueue/queue_test.go @@ -19,7 +19,6 @@ package diskqueue import ( "flag" - "io/ioutil" "math/rand" "os" "testing" @@ -79,7 +78,7 @@ func TestProduceConsumer(t *testing.T) { } func TestMetrics(t *testing.T) { - dir, err := ioutil.TempDir("", "diskqueue_metrics") + dir, err := os.MkdirTemp("", "diskqueue_metrics") defer func() { _ = os.RemoveAll(dir) }() @@ -118,7 +117,7 @@ func sendEventsToQueue(count int, prod queue.Producer) { func makeTestQueue() queuetest.QueueFactory { return func(t *testing.T) queue.Queue { - dir, err := ioutil.TempDir("", "diskqueue_test") + dir, err := os.MkdirTemp("", "diskqueue_test") if err != nil { t.Fatal(err) } diff --git a/libbeat/publisher/queue/diskqueue/segments.go b/libbeat/publisher/queue/diskqueue/segments.go index cc73ec17d8e..91413550d93 100644 --- a/libbeat/publisher/queue/diskqueue/segments.go +++ b/libbeat/publisher/queue/diskqueue/segments.go @@ -22,7 +22,7 @@ import ( "errors" "fmt" "io" - "io/ioutil" + "io/fs" "os" "path" "sort" @@ -170,11 +170,18 @@ func (s bySegmentID) Less(i, j int) bool { return s[i].id < s[j].id } // Scan the given path for segment files, and return them in a list // ordered by segment id. func scanExistingSegments(logger *logp.Logger, pathStr string) ([]*queueSegment, error) { - files, err := ioutil.ReadDir(pathStr) + fileEntries, err := os.ReadDir(pathStr) if err != nil { return nil, fmt.Errorf("couldn't read queue directory '%s': %w", pathStr, err) } - + files := make([]fs.FileInfo, 0, len(fileEntries)) + for _, entry := range fileEntries { + info, err := entry.Info() + if err != nil { + return nil, fmt.Errorf("couldn't get file info '%s': %w", entry.Name(), err) + } + files = append(files, info) + } segments := []*queueSegment{} for _, file := range files { components := strings.Split(file.Name(), ".") diff --git a/libbeat/reader/debug/debug_test.go b/libbeat/reader/debug/debug_test.go index 1ae268cce83..c283c642e2b 100644 --- a/libbeat/reader/debug/debug_test.go +++ b/libbeat/reader/debug/debug_test.go @@ -20,7 +20,6 @@ package debug import ( "bytes" "io" - "io/ioutil" "testing" "github.com/stretchr/testify/assert" @@ -79,7 +78,7 @@ func testCheckContent(t *testing.T) { s.WriteString("hello world") s.WriteByte(0x00) s.WriteString("hello world") - r := ioutil.NopCloser(&s) + r := io.NopCloser(&s) reader, _ := NewReader(logp.L(), r, 5, 3, check) @@ -93,7 +92,7 @@ func testCheckContent(t *testing.T) { func testConsumeAll(t *testing.T) { c, _ := common.RandomBytes(2000) - reader := ioutil.NopCloser(bytes.NewReader(c)) + reader := io.NopCloser(bytes.NewReader(c)) var buf bytes.Buffer consumed := 0 debug, _ := NewReader(logp.L(), reader, 8, 20, makeNullCheck(logp.L(), 1)) @@ -108,7 +107,7 @@ func testConsumeAll(t *testing.T) { } func testEmptyBuffer(t *testing.T) { - buf := ioutil.NopCloser(&bytes.Buffer{}) + buf := io.NopCloser(&bytes.Buffer{}) debug, _ := NewReader(logp.L(), buf, 8, 20, makeNullCheck(logp.L(), 1)) data := make([]byte, 33) n, err := debug.Read(data) @@ -136,7 +135,7 @@ func testSilent(t *testing.T) { b.Write([]byte{'a', 'b', 'c', 'd', 0x00, 'e'}) b.Write([]byte{'a', 'b', 'c', 'd', 0x00, 'e'}) b.Write([]byte{'a', 'b', 'c', 'd', 0x00, 'e'}) - r := ioutil.NopCloser(&b) + r := io.NopCloser(&b) debug, _ := NewReader(logp.L(), r, 3, 2, check) consumed := 0 diff --git a/libbeat/reader/multiline/multiline_test.go b/libbeat/reader/multiline/multiline_test.go index cd05fa13c46..25d4db13983 100644 --- a/libbeat/reader/multiline/multiline_test.go +++ b/libbeat/reader/multiline/multiline_test.go @@ -22,7 +22,7 @@ package multiline import ( "bytes" "errors" - "io/ioutil" + "io" "os" "strings" "testing" @@ -376,7 +376,7 @@ func createMultilineTestReader(t *testing.T, in *bytes.Buffer, cfg Config) reade } var r reader.Reader - r, err = readfile.NewEncodeReader(ioutil.NopCloser(in), readfile.Config{ + r, err = readfile.NewEncodeReader(io.NopCloser(in), readfile.Config{ Codec: enc, BufferSize: 4096, Terminator: readfile.LineFeed, diff --git a/libbeat/reader/parser/parser_test.go b/libbeat/reader/parser/parser_test.go index d49cf3f2fe0..691a7ab6522 100644 --- a/libbeat/reader/parser/parser_test.go +++ b/libbeat/reader/parser/parser_test.go @@ -19,7 +19,6 @@ package parser import ( "io" - "io/ioutil" "strings" "testing" @@ -779,7 +778,7 @@ func testReader(lines string) reader.Reader { if err != nil { panic(err) } - r, err := readfile.NewEncodeReader(ioutil.NopCloser(reader), readfile.Config{ + r, err := readfile.NewEncodeReader(io.NopCloser(reader), readfile.Config{ Codec: enc, BufferSize: 1024, Terminator: readfile.AutoLineTerminator, diff --git a/libbeat/reader/readfile/bench_test.go b/libbeat/reader/readfile/bench_test.go index e1d61248848..954b9bab84d 100644 --- a/libbeat/reader/readfile/bench_test.go +++ b/libbeat/reader/readfile/bench_test.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math/rand" "testing" @@ -40,7 +39,7 @@ func BenchmarkEncoderReader(b *testing.B) { b.Run(name, func(b *testing.B) { b.ReportAllocs() for bN := 0; bN < b.N; bN++ { - reader, err := NewEncodeReader(ioutil.NopCloser(bytes.NewReader(lines)), Config{encoding.Nop, bufferSize, LineFeed, lineMaxLimit, false}) + reader, err := NewEncodeReader(io.NopCloser(bytes.NewReader(lines)), Config{encoding.Nop, bufferSize, LineFeed, lineMaxLimit, false}) if err != nil { b.Fatal("failed to initialize reader:", err) } diff --git a/libbeat/reader/readfile/encode_test.go b/libbeat/reader/readfile/encode_test.go index 6c65c48846e..0529744c0c2 100644 --- a/libbeat/reader/readfile/encode_test.go +++ b/libbeat/reader/readfile/encode_test.go @@ -19,7 +19,7 @@ package readfile import ( "bytes" - "io/ioutil" + "io" "testing" "github.com/stretchr/testify/assert" @@ -47,7 +47,7 @@ func TestEncodeLines(t *testing.T) { for name, testCase := range testCases { t.Run(name, func(t *testing.T) { - r := ioutil.NopCloser(bytes.NewReader(testCase.Input)) + r := io.NopCloser(bytes.NewReader(testCase.Input)) codec, err := encFactory(r) assert.Nil(t, err, "failed to initialize encoding: %v", err) diff --git a/libbeat/reader/readfile/encoding/utf16_test.go b/libbeat/reader/readfile/encoding/utf16_test.go index ce14657fa7f..7c0b734b4f8 100644 --- a/libbeat/reader/readfile/encoding/utf16_test.go +++ b/libbeat/reader/readfile/encoding/utf16_test.go @@ -21,7 +21,7 @@ package encoding import ( "bytes" - "io/ioutil" + "io" "testing" "github.com/stretchr/testify/assert" @@ -95,7 +95,7 @@ func TestUtf16BOMEncodings(t *testing.T) { assert.Equal(t, test.expectedOffset, contentOffset) if err == nil { reader := transform.NewReader(rawReader, encoding.NewDecoder()) - content, _ := ioutil.ReadAll(reader) + content, _ := io.ReadAll(reader) assert.Equal(t, text, content) } } diff --git a/libbeat/reader/readfile/line_test.go b/libbeat/reader/readfile/line_test.go index 5bc064785f1..166b0d4d97f 100644 --- a/libbeat/reader/readfile/line_test.go +++ b/libbeat/reader/readfile/line_test.go @@ -25,7 +25,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "math/rand" "strings" "testing" @@ -106,7 +105,7 @@ func TestReaderEncodings(t *testing.T) { } // create line reader - reader, err := NewLineReader(ioutil.NopCloser(buffer), Config{codec, 1024, test.lineTerminator, unlimited, test.collectOnEOF}) + reader, err := NewLineReader(io.NopCloser(buffer), Config{codec, 1024, test.lineTerminator, unlimited, test.collectOnEOF}) if err != nil { t.Fatal("failed to initialize reader:", err) } @@ -225,7 +224,7 @@ func TestLineTerminators(t *testing.T) { buffer.Write([]byte("this is my second line")) buffer.Write(nl) - reader, err := NewLineReader(ioutil.NopCloser(buffer), Config{codec, 1024, terminator, unlimited, false}) + reader, err := NewLineReader(io.NopCloser(buffer), Config{codec, 1024, terminator, unlimited, false}) if err != nil { t.Errorf("failed to initialize reader: %v", err) continue @@ -303,7 +302,7 @@ func testReadLines(t *testing.T, inputLines [][]byte, eofOnLastRead bool) { } codec, _ := encoding.Plain(r) - reader, err := NewLineReader(ioutil.NopCloser(r), Config{codec, buffer.Len(), LineFeed, unlimited, false}) + reader, err := NewLineReader(io.NopCloser(r), Config{codec, buffer.Len(), LineFeed, unlimited, false}) if err != nil { t.Fatalf("Error initializing reader: %v", err) } @@ -419,7 +418,7 @@ func TestMaxBytesLimit(t *testing.T) { } // Create line reader - reader, err := NewLineReader(ioutil.NopCloser(strings.NewReader(input)), Config{codec, bufferSize, LineFeed, lineMaxLimit, false}) + reader, err := NewLineReader(io.NopCloser(strings.NewReader(input)), Config{codec, bufferSize, LineFeed, lineMaxLimit, false}) if err != nil { t.Fatal("failed to initialize reader:", err) } @@ -478,7 +477,7 @@ func TestBufferSize(t *testing.T) { codec, _ := codecFactory(bytes.NewBuffer(nil)) bufferSize := 10 - in := ioutil.NopCloser(strings.NewReader(strings.Join(lines, ""))) + in := io.NopCloser(strings.NewReader(strings.Join(lines, ""))) reader, err := NewLineReader(in, Config{codec, bufferSize, AutoLineTerminator, 1024, false}) if err != nil { t.Fatal("failed to initialize reader:", err) diff --git a/libbeat/scripts/cmd/global_fields/main.go b/libbeat/scripts/cmd/global_fields/main.go index 914556e350a..f4055981a69 100644 --- a/libbeat/scripts/cmd/global_fields/main.go +++ b/libbeat/scripts/cmd/global_fields/main.go @@ -21,7 +21,6 @@ import ( "bytes" "flag" "fmt" - "io/ioutil" "os" "path/filepath" @@ -110,7 +109,7 @@ func main() { return } - err = ioutil.WriteFile(output, buffer.Bytes(), 0644) + err = os.WriteFile(output, buffer.Bytes(), 0644) if err != nil { fmt.Fprintf(os.Stderr, "Cannot write global fields.yml file for %s: %v", name, err) } diff --git a/libbeat/statestore/backend/memlog/diskstore.go b/libbeat/statestore/backend/memlog/diskstore.go index bc44263206d..9a771c9829e 100644 --- a/libbeat/statestore/backend/memlog/diskstore.go +++ b/libbeat/statestore/backend/memlog/diskstore.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -438,7 +437,7 @@ func updateActiveMarker(log *logp.Logger, homePath, checkpointFilePath string) e log.Errorf("Failed to remove old temporary active.dat.tmp file: %v", err) return err } - if err := ioutil.WriteFile(tmpLink, []byte(checkpointFilePath), 0600); err != nil { + if err := os.WriteFile(tmpLink, []byte(checkpointFilePath), 0600); err != nil { log.Errorf("Failed to write temporary pointer file: %v", err) return err } diff --git a/libbeat/statestore/backend/memlog/memlog_test.go b/libbeat/statestore/backend/memlog/memlog_test.go index c2f1a283c1d..cfec1381430 100644 --- a/libbeat/statestore/backend/memlog/memlog_test.go +++ b/libbeat/statestore/backend/memlog/memlog_test.go @@ -20,7 +20,6 @@ package memlog import ( "encoding/json" "io" - "io/ioutil" "math" "os" "path/filepath" @@ -59,7 +58,7 @@ func TestCompliance_AlwaysCheckpoint(t *testing.T) { func TestLoadVersion1(t *testing.T) { dataHome := "testdata/1" - list, err := ioutil.ReadDir(dataHome) + list, err := os.ReadDir(dataHome) if err != nil { t.Fatal(err) } @@ -80,7 +79,7 @@ func TestLoadVersion1(t *testing.T) { } func testLoadVersion1Case(t *testing.T, dataPath string) { - path, err := ioutil.TempDir("", "") + path, err := os.MkdirTemp("", "") if err != nil { t.Fatalf("Failed to create temporary test directory: %v", err) } @@ -93,7 +92,7 @@ func testLoadVersion1Case(t *testing.T, dataPath string) { } // load expected test results - raw, err := ioutil.ReadFile(filepath.Join(path, "expected.json")) + raw, err := os.ReadFile(filepath.Join(path, "expected.json")) if err != nil { t.Fatalf("Failed to load expected.json: %v", err) } @@ -210,7 +209,7 @@ func copyDir(to, from string) error { } } - list, err := ioutil.ReadDir(from) + list, err := os.ReadDir(from) if err != nil { return err } diff --git a/libbeat/statestore/internal/storecompliance/util.go b/libbeat/statestore/internal/storecompliance/util.go index 68ddf20182d..881bef8f898 100644 --- a/libbeat/statestore/internal/storecompliance/util.go +++ b/libbeat/statestore/internal/storecompliance/util.go @@ -19,7 +19,6 @@ package storecompliance import ( "fmt" - "io/ioutil" "os" "testing" @@ -58,7 +57,7 @@ func WithPath(factory BackendFactory, fn func(*testing.T, *Registry)) func(t *te // defer cleanup() // ... func SetupRegistry(t testing.TB, factory BackendFactory) (*Registry, func()) { - path, err := ioutil.TempDir(defaultTempDir, "") + path, err := os.MkdirTemp(defaultTempDir, "") if err != nil { t.Fatalf("Failed to create temporary test directory: %v", err) } diff --git a/libbeat/template/load.go b/libbeat/template/load.go index c2c1375664d..26fd8dcc40b 100644 --- a/libbeat/template/load.go +++ b/libbeat/template/load.go @@ -21,7 +21,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net/http" "os" @@ -282,7 +281,7 @@ func (b *templateBuilder) buildBodyFromJSON(config TemplateConfig) (mapstr.M, er return nil, fmt.Errorf("error checking json file %s for template: %w", jsonPath, err) } b.log.Debugf("Loading json template from file %s", jsonPath) - content, err := ioutil.ReadFile(jsonPath) + content, err := os.ReadFile(jsonPath) if err != nil { return nil, fmt.Errorf("error reading file %s for template: %w", jsonPath, err) diff --git a/libbeat/template/load_integration_test.go b/libbeat/template/load_integration_test.go index b3aafad5d69..bc2cb1938f4 100644 --- a/libbeat/template/load_integration_test.go +++ b/libbeat/template/load_integration_test.go @@ -22,10 +22,10 @@ package template import ( "encoding/json" "fmt" - "io/ioutil" "math/rand" "net/http" "net/http/httptest" + "os" "path/filepath" "strconv" "strings" @@ -270,7 +270,7 @@ func TestESLoader_Load(t *testing.T) { }) t.Run("preserve existing data stream even if overwriting templates is allowed", func(t *testing.T) { - fields, err := ioutil.ReadFile(path(t, []string{"testdata", "default_fields.yml"})) + fields, err := os.ReadFile(path(t, []string{"testdata", "default_fields.yml"})) require.NoError(t, err) setup := newTestSetup(t, TemplateConfig{Enabled: true, Overwrite: true}) setup.mustLoad(fields) @@ -310,7 +310,7 @@ func TestESLoader_Load(t *testing.T) { }) t.Run("load template successful", func(t *testing.T) { - fields, err := ioutil.ReadFile(path(t, []string{"testdata", "default_fields.yml"})) + fields, err := os.ReadFile(path(t, []string{"testdata", "default_fields.yml"})) require.NoError(t, err) for run, data := range map[string]struct { cfg TemplateConfig diff --git a/libbeat/tests/docker/docker.go b/libbeat/tests/docker/docker.go index 0c3c8878c9d..a14d6150565 100644 --- a/libbeat/tests/docker/docker.go +++ b/libbeat/tests/docker/docker.go @@ -21,7 +21,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "github.com/elastic/elastic-agent-autodiscover/docker" @@ -82,7 +81,7 @@ func (c Client) imagePull(image string) (err error) { defer respBody.Close() // Read all the response, to be sure that the pull has finished before returning. - _, err = io.Copy(ioutil.Discard, respBody) + _, err = io.Copy(io.Discard, respBody) if err != nil { return fmt.Errorf("reading response for image %s: %w", image, err) } diff --git a/libbeat/tests/integration/framework.go b/libbeat/tests/integration/framework.go index 046c578d7cd..c90068b9409 100644 --- a/libbeat/tests/integration/framework.go +++ b/libbeat/tests/integration/framework.go @@ -26,7 +26,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -508,7 +507,7 @@ func (b *BeatProc) LoadMeta() (Meta, error) { } defer metaFile.Close() - metaBytes, err := ioutil.ReadAll(metaFile) + metaBytes, err := io.ReadAll(metaFile) require.NoError(b.t, err, "error reading meta file") err = json.Unmarshal(metaBytes, &m) require.NoError(b.t, err, "error unmarshalling meta data") diff --git a/libbeat/tests/integration/http_test.go b/libbeat/tests/integration/http_test.go index bb2f7bde924..ca58b27014a 100644 --- a/libbeat/tests/integration/http_test.go +++ b/libbeat/tests/integration/http_test.go @@ -21,7 +21,7 @@ package integration import ( "encoding/json" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -62,7 +62,7 @@ output.console: require.NoError(t, err) require.Equal(t, http.StatusOK, r.StatusCode, "incorrect status code") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) require.NoError(t, err) var m map[string]interface{} err = json.Unmarshal(body, &m) @@ -93,7 +93,7 @@ output.console: require.NoError(t, err) require.Equal(t, http.StatusOK, r.StatusCode, "incorrect status code") - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) require.NoError(t, err) var m Stats diff --git a/metricbeat/autodiscover/appender/kubernetes/token/token.go b/metricbeat/autodiscover/appender/kubernetes/token/token.go index 4c474d36b16..3f18a9521ac 100644 --- a/metricbeat/autodiscover/appender/kubernetes/token/token.go +++ b/metricbeat/autodiscover/appender/kubernetes/token/token.go @@ -19,7 +19,7 @@ package token import ( "fmt" - "io/ioutil" + "os" "github.com/elastic/beats/v7/libbeat/autodiscover" "github.com/elastic/beats/v7/libbeat/common/cfgwarn" @@ -127,7 +127,7 @@ func (t *tokenAppender) getAuthHeaderFromToken() string { var token string if t.TokenPath != "" { - b, err := ioutil.ReadFile(t.TokenPath) + b, err := os.ReadFile(t.TokenPath) if err != nil { logp.Err("Reading token file failed with err: %v", err) } diff --git a/metricbeat/autodiscover/appender/kubernetes/token/token_test.go b/metricbeat/autodiscover/appender/kubernetes/token/token_test.go index 62243867958..cc65b6e8fab 100644 --- a/metricbeat/autodiscover/appender/kubernetes/token/token_test.go +++ b/metricbeat/autodiscover/appender/kubernetes/token/token_test.go @@ -18,7 +18,6 @@ package token import ( - "io/ioutil" "os" "testing" @@ -101,7 +100,7 @@ token_path: "test" } func writeFile(name, message string) { - ioutil.WriteFile(name, []byte(message), os.ModePerm) + os.WriteFile(name, []byte(message), os.ModePerm) } func deleteFile(name string) { diff --git a/metricbeat/helper/http.go b/metricbeat/helper/http.go index 9b8cf792879..91ede88ec14 100644 --- a/metricbeat/helper/http.go +++ b/metricbeat/helper/http.go @@ -23,8 +23,8 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" + "os" "github.com/elastic/beats/v7/libbeat/version" "github.com/elastic/beats/v7/metricbeat/helper/dialer" @@ -179,7 +179,7 @@ func (h *HTTP) FetchContent() ([]byte, error) { return nil, fmt.Errorf("HTTP error %d in %s: %s", resp.StatusCode, h.name, resp.Status) } - return ioutil.ReadAll(resp.Body) + return io.ReadAll(resp.Body) } // FetchScanner returns a Scanner for the content. @@ -214,7 +214,7 @@ func (h *HTTP) FetchJSON() (map[string]interface{}, error) { func getAuthHeaderFromToken(path string) (string, error) { var token string - b, err := ioutil.ReadFile(path) + b, err := os.ReadFile(path) if err != nil { return "", fmt.Errorf("reading bearer token file: %w", err) } diff --git a/metricbeat/helper/http_test.go b/metricbeat/helper/http_test.go index 2fbfea0d1ad..64e3e4ad3c2 100644 --- a/metricbeat/helper/http_test.go +++ b/metricbeat/helper/http_test.go @@ -19,7 +19,7 @@ package helper import ( "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -55,7 +55,7 @@ func TestGetAuthHeaderFromToken(t *testing.T) { for _, test := range tests { t.Run(test.Name, func(t *testing.T) { content := []byte(test.Content) - tmpfile, err := ioutil.TempFile("", "token") + tmpfile, err := os.CreateTemp("", "token") if err != nil { t.Fatal(err) } @@ -243,7 +243,7 @@ func TestOverUnixSocket(t *testing.T) { for title, c := range cases { t.Run(title, func(t *testing.T) { - tmpDir, err := ioutil.TempDir("", "testsocket") + tmpDir, err := os.MkdirTemp("", "testsocket") require.NoError(t, err) defer os.RemoveAll(tmpDir) @@ -262,7 +262,7 @@ func TestOverUnixSocket(t *testing.T) { r, err := h.FetchResponse() require.NoError(t, err) defer r.Body.Close() - content, err := ioutil.ReadAll(r.Body) + content, err := io.ReadAll(r.Body) require.NoError(t, err) assert.Equal(t, []byte("ehlo!"), content) }) diff --git a/metricbeat/helper/http_windows_test.go b/metricbeat/helper/http_windows_test.go index 021659c5ba3..75300c5db8f 100644 --- a/metricbeat/helper/http_windows_test.go +++ b/metricbeat/helper/http_windows_test.go @@ -21,7 +21,7 @@ package helper import ( "fmt" - "io/ioutil" + "io" "net/http" "runtime" "testing" @@ -68,7 +68,7 @@ func TestOverNamedpipe(t *testing.T) { r, err := h.FetchResponse() require.NoError(t, err) defer r.Body.Close() - content, err := ioutil.ReadAll(r.Body) + content, err := io.ReadAll(r.Body) require.NoError(t, err) assert.Equal(t, []byte("ehlo!"), content) }) @@ -101,7 +101,7 @@ func TestOverNamedpipe(t *testing.T) { r, err := h.FetchResponse() require.NoError(t, err) defer r.Body.Close() - content, err := ioutil.ReadAll(r.Body) + content, err := io.ReadAll(r.Body) require.NoError(t, err) assert.Equal(t, []byte("ehlo!"), content) }) diff --git a/metricbeat/helper/server/http/http.go b/metricbeat/helper/server/http/http.go index 782b0938471..e8af09156b8 100644 --- a/metricbeat/helper/server/http/http.go +++ b/metricbeat/helper/server/http/http.go @@ -19,7 +19,7 @@ package http import ( "context" - "io/ioutil" + "io" "net" "net/http" "strconv" @@ -147,7 +147,7 @@ func (h *HttpServer) handleFunc(writer http.ResponseWriter, req *http.Request) { meta["Content-Type"] = contentType } - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) if err != nil { logp.Err("Error reading body: %v", err) http.Error(writer, "Unexpected error reading request payload", http.StatusBadRequest) diff --git a/metricbeat/helper/server/http/http_test.go b/metricbeat/helper/server/http/http_test.go index 7decdd821be..729ca58dd7f 100644 --- a/metricbeat/helper/server/http/http_test.go +++ b/metricbeat/helper/server/http/http_test.go @@ -24,7 +24,7 @@ import ( "context" "crypto/tls" "fmt" - "io/ioutil" + "io" "net" "net/http" "strconv" @@ -230,7 +230,7 @@ func writeToServer(t *testing.T, message, host string, port int, connectionMetho if connectionMethod == "GET" { if resp.StatusCode == http.StatusOK { - bodyBytes, err2 := ioutil.ReadAll(resp.Body) + bodyBytes, err2 := io.ReadAll(resp.Body) if err2 != nil { t.Error(err) t.FailNow() diff --git a/metricbeat/mb/lightmodules.go b/metricbeat/mb/lightmodules.go index 50293d7f60b..c0c7b6aeccf 100644 --- a/metricbeat/mb/lightmodules.go +++ b/metricbeat/mb/lightmodules.go @@ -19,7 +19,6 @@ package mb import ( "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -260,7 +259,7 @@ func (s *LightModulesSource) moduleNames() ([]string, error) { s.log.Debugf("Light modules directory '%d' doesn't exist", dir) continue } - files, err := ioutil.ReadDir(dir) + files, err := os.ReadDir(dir) if err != nil { return nil, fmt.Errorf("listing modules on path '%s': %w", dir, err) } diff --git a/metricbeat/mb/testing/data_generator.go b/metricbeat/mb/testing/data_generator.go index 00dce1ea7f0..7e97ee762a4 100644 --- a/metricbeat/mb/testing/data_generator.go +++ b/metricbeat/mb/testing/data_generator.go @@ -20,7 +20,6 @@ package testing import ( "encoding/json" "fmt" - "io/ioutil" "os" "path" "testing" @@ -184,7 +183,7 @@ func WriteEventToDataJSON(t testing.TB, fullEvent beat.Event, postfixPath string t.Fatal(err) } - if err = ioutil.WriteFile(p, output, 0644); err != nil { + if err = os.WriteFile(p, output, 0644); err != nil { t.Fatal(err) } } diff --git a/metricbeat/mb/testing/lightmodules_test.go b/metricbeat/mb/testing/lightmodules_test.go index 04211144c62..c3b5ae04306 100644 --- a/metricbeat/mb/testing/lightmodules_test.go +++ b/metricbeat/mb/testing/lightmodules_test.go @@ -22,7 +22,6 @@ package testing import ( "encoding/json" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -103,7 +102,7 @@ func TestDataLightModuleWithProcessors(t *testing.T) { assert.Empty(t, errs) assert.NotEmpty(t, events) - dir, err := ioutil.TempDir("", "_meta-*") + dir, err := os.MkdirTemp("", "_meta-*") require.NoError(t, err) defer os.RemoveAll(dir) @@ -127,7 +126,7 @@ func TestDataLightModuleWithProcessors(t *testing.T) { } } - d, err := ioutil.ReadFile(dataPath) + d, err := os.ReadFile(dataPath) require.NoError(t, err) err = json.Unmarshal(d, &event) diff --git a/metricbeat/mb/testing/testdata.go b/metricbeat/mb/testing/testdata.go index 60455c1d635..57cc9c023c4 100644 --- a/metricbeat/mb/testing/testdata.go +++ b/metricbeat/mb/testing/testdata.go @@ -20,9 +20,9 @@ package testing import ( "encoding/json" "fmt" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "sort" "strings" @@ -131,7 +131,7 @@ func ReadDataConfig(t *testing.T, f string) DataConfig { t.Helper() config := defaultDataConfig() - configFile, err := ioutil.ReadFile(f) + configFile, err := os.ReadFile(f) if err != nil { t.Fatalf("failed to read '%s': %v", f, err) } @@ -294,13 +294,13 @@ func runTest(t *testing.T, file string, module, metricSetName string, config Dat if err != nil { t.Fatal(err) } - if err = ioutil.WriteFile(expectedFile, outputIndented, 0644); err != nil { + if err = os.WriteFile(expectedFile, outputIndented, 0644); err != nil { t.Fatal(err) } } // Read expected file - expected, err := ioutil.ReadFile(expectedFile) + expected, err := os.ReadFile(expectedFile) if err != nil { t.Fatalf("could not read file: %s", err) } @@ -362,7 +362,7 @@ func writeDataJSON(t *testing.T, data mapstr.M, path string) { // Add hardcoded timestamp data.Put("@timestamp", "2019-03-01T08:05:34.853Z") output, err := json.MarshalIndent(&data, "", " ") - if err = ioutil.WriteFile(path, output, 0644); err != nil { + if err = os.WriteFile(path, output, 0644); err != nil { t.Fatal(err) } } @@ -494,7 +494,7 @@ func getConfig(module, metricSet, url string, config DataConfig) map[string]inte // server starts a server with a mock output func server(t *testing.T, path string, url string, contentType string) *httptest.Server { - body, err := ioutil.ReadFile(path) + body, err := os.ReadFile(path) if err != nil { t.Fatalf("could not read file: %s", err) } diff --git a/metricbeat/module/beat/state/data_test.go b/metricbeat/module/beat/state/data_test.go index 4d94a3f24da..e3c3e0a0c78 100644 --- a/metricbeat/module/beat/state/data_test.go +++ b/metricbeat/module/beat/state/data_test.go @@ -20,7 +20,7 @@ package state import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -42,7 +42,7 @@ func TestEventMapping(t *testing.T) { } for _, f := range files { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -62,7 +62,7 @@ func TestUuidFromEsOutput(t *testing.T) { Beat: "testbeat", } - input, err := ioutil.ReadFile("./_meta/test/uuid_es_output.json") + input, err := os.ReadFile("./_meta/test/uuid_es_output.json") require.NoError(t, err) err = eventMapping(reporter, info, input, true) @@ -86,7 +86,7 @@ func TestNoEventIfEsOutputButNoUuidYet(t *testing.T) { Beat: "testbeat", } - input, err := ioutil.ReadFile("./_meta/test/uuid_es_output_pre_connect.json") + input, err := os.ReadFile("./_meta/test/uuid_es_output_pre_connect.json") require.NoError(t, err) err = eventMapping(reporter, info, input, true) @@ -103,7 +103,7 @@ func TestUuidFromMonitoringConfig(t *testing.T) { Beat: "testbeat", } - input, err := ioutil.ReadFile("./_meta/test/uuid_monitoring_config.json") + input, err := os.ReadFile("./_meta/test/uuid_monitoring_config.json") require.NoError(t, err) err = eventMapping(reporter, info, input, true) @@ -127,7 +127,7 @@ func TestNoUuidInMonitoringConfig(t *testing.T) { Beat: "testbeat", } - input, err := ioutil.ReadFile("./_meta/test/uuid_no_monitoring_config.json") + input, err := os.ReadFile("./_meta/test/uuid_no_monitoring_config.json") require.NoError(t, err) err = eventMapping(reporter, info, input, true) diff --git a/metricbeat/module/beat/stats/data_test.go b/metricbeat/module/beat/stats/data_test.go index 5e8c2c51b3c..b5ce00f8289 100644 --- a/metricbeat/module/beat/stats/data_test.go +++ b/metricbeat/module/beat/stats/data_test.go @@ -20,7 +20,7 @@ package stats import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -44,7 +44,7 @@ func TestEventMapping(t *testing.T) { clusterUUID := "foo" for _, f := range files { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/ceph/cluster_disk/cluster_disk_test.go b/metricbeat/module/ceph/cluster_disk/cluster_disk_test.go index 3848c2b7024..4d1456af41f 100644 --- a/metricbeat/module/ceph/cluster_disk/cluster_disk_test.go +++ b/metricbeat/module/ceph/cluster_disk/cluster_disk_test.go @@ -18,9 +18,9 @@ package cluster_disk import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/df_sample_response.json") + response, err := os.ReadFile(absPath + "/df_sample_response.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/ceph/cluster_health/cluster_health_test.go b/metricbeat/module/ceph/cluster_health/cluster_health_test.go index 73f0dadc727..90214b55d6b 100644 --- a/metricbeat/module/ceph/cluster_health/cluster_health_test.go +++ b/metricbeat/module/ceph/cluster_health/cluster_health_test.go @@ -18,9 +18,9 @@ package cluster_health import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/sample_response.json") + response, err := os.ReadFile(absPath + "/sample_response.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/ceph/cluster_status/cluster_status_test.go b/metricbeat/module/ceph/cluster_status/cluster_status_test.go index 38b4968c498..c66e01fdc23 100644 --- a/metricbeat/module/ceph/cluster_status/cluster_status_test.go +++ b/metricbeat/module/ceph/cluster_status/cluster_status_test.go @@ -18,9 +18,9 @@ package cluster_status import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/status_sample_response.json") + response, err := os.ReadFile(absPath + "/status_sample_response.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/ceph/mgr_cluster_health/mgr_cluster_health_test.go b/metricbeat/module/ceph/mgr_cluster_health/mgr_cluster_health_test.go index 9da0c6f276d..f57be73bca9 100644 --- a/metricbeat/module/ceph/mgr_cluster_health/mgr_cluster_health_test.go +++ b/metricbeat/module/ceph/mgr_cluster_health/mgr_cluster_health_test.go @@ -19,9 +19,9 @@ package mgr_cluster_health import ( "encoding/json" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -41,9 +41,9 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("./_meta/testdata/") assert.NoError(t, err) - statusResponse, err := ioutil.ReadFile(absPath + "/status.json") + statusResponse, err := os.ReadFile(absPath + "/status.json") assert.NoError(t, err) - timeSyncStatusResponse, err := ioutil.ReadFile(absPath + "/time_sync_status.json") + timeSyncStatusResponse, err := os.ReadFile(absPath + "/time_sync_status.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -93,7 +93,7 @@ func TestFetchEventContents_Failed(t *testing.T) { absPath, err := filepath.Abs("./_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/failed.json") + response, err := os.ReadFile(absPath + "/failed.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/ceph/monitor_health/monitor_health_test.go b/metricbeat/module/ceph/monitor_health/monitor_health_test.go index b58ad8389a0..89002f98240 100644 --- a/metricbeat/module/ceph/monitor_health/monitor_health_test.go +++ b/metricbeat/module/ceph/monitor_health/monitor_health_test.go @@ -18,9 +18,9 @@ package monitor_health import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -36,7 +36,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/sample_response.json") + response, err := os.ReadFile(absPath + "/sample_response.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/ceph/osd_df/osd_df_test.go b/metricbeat/module/ceph/osd_df/osd_df_test.go index bef039597dd..df6b1716430 100644 --- a/metricbeat/module/ceph/osd_df/osd_df_test.go +++ b/metricbeat/module/ceph/osd_df/osd_df_test.go @@ -18,9 +18,9 @@ package osd_df import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -33,7 +33,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/osd_df_sample_response.json") + response, err := os.ReadFile(absPath + "/osd_df_sample_response.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/ceph/osd_tree/osd_tree_test.go b/metricbeat/module/ceph/osd_tree/osd_tree_test.go index 872da2d32c9..4e88e67fbd5 100644 --- a/metricbeat/module/ceph/osd_tree/osd_tree_test.go +++ b/metricbeat/module/ceph/osd_tree/osd_tree_test.go @@ -18,9 +18,9 @@ package osd_tree import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -33,7 +33,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/osd_tree_sample_response.json") + response, err := os.ReadFile(absPath + "/osd_tree_sample_response.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/ceph/pool_disk/pool_disk_test.go b/metricbeat/module/ceph/pool_disk/pool_disk_test.go index d28aadd54c3..06dc3f029ff 100644 --- a/metricbeat/module/ceph/pool_disk/pool_disk_test.go +++ b/metricbeat/module/ceph/pool_disk/pool_disk_test.go @@ -18,9 +18,9 @@ package pool_disk import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -34,7 +34,7 @@ func TestFetchEventContents(t *testing.T) { absPath, err := filepath.Abs("../_meta/testdata/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/df_sample_response.json") + response, err := os.ReadFile(absPath + "/df_sample_response.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/couchbase/bucket/bucket_test.go b/metricbeat/module/couchbase/bucket/bucket_test.go index 44bde0ca928..9712b18eaec 100644 --- a/metricbeat/module/couchbase/bucket/bucket_test.go +++ b/metricbeat/module/couchbase/bucket/bucket_test.go @@ -20,9 +20,9 @@ package bucket import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -37,7 +37,7 @@ func TestFetchEventContents(t *testing.T) { assert.NoError(t, err) // response is a raw response from a couchbase - response, err := ioutil.ReadFile(absPath + "/sample_response.json") + response, err := os.ReadFile(absPath + "/sample_response.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/elasticsearch/ccr/ccr_test.go b/metricbeat/module/elasticsearch/ccr/ccr_test.go index 4890637de1b..14333534995 100644 --- a/metricbeat/module/elasticsearch/ccr/ccr_test.go +++ b/metricbeat/module/elasticsearch/ccr/ccr_test.go @@ -18,9 +18,9 @@ package ccr import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "strconv" "strings" "testing" @@ -44,7 +44,7 @@ func createEsMuxer(esVersion, license string, ccrEnabled bool) *http.ServeMux { http.NotFound(w, r) } - input, _ := ioutil.ReadFile("./_meta/test/root.710.json") + input, _ := os.ReadFile("./_meta/test/root.710.json") input = []byte(strings.Replace(string(input), "7.10.0", esVersion, -1)) w.Write(input) } diff --git a/metricbeat/module/elasticsearch/ccr/data_test.go b/metricbeat/module/elasticsearch/ccr/data_test.go index d6181ed24ea..ac94ebc718f 100644 --- a/metricbeat/module/elasticsearch/ccr/data_test.go +++ b/metricbeat/module/elasticsearch/ccr/data_test.go @@ -20,9 +20,9 @@ package ccr import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/require" @@ -41,7 +41,7 @@ func TestMapper(t *testing.T) { } func TestEmpty(t *testing.T) { - input, err := ioutil.ReadFile("./_meta/test/empty.700.json") + input, err := os.ReadFile("./_meta/test/empty.700.json") require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -53,7 +53,7 @@ func TestEmpty(t *testing.T) { func TestData(t *testing.T) { mux := createEsMuxer("7.6.0", "platinum", true) mux.Handle("/_ccr/stats", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/ccr_stats.700.json") + input, _ := os.ReadFile("./_meta/test/ccr_stats.700.json") w.Write(input) })) diff --git a/metricbeat/module/elasticsearch/cluster_stats/data_test.go b/metricbeat/module/elasticsearch/cluster_stats/data_test.go index 1a96664ccff..fec9d67d057 100644 --- a/metricbeat/module/elasticsearch/cluster_stats/data_test.go +++ b/metricbeat/module/elasticsearch/cluster_stats/data_test.go @@ -20,9 +20,9 @@ package cluster_stats import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/require" @@ -45,7 +45,7 @@ func createEsMuxer(license string) *http.ServeMux { http.NotFound(w, r) } - input, _ := ioutil.ReadFile("./_meta/test/root.710.json") + input, _ := os.ReadFile("./_meta/test/root.710.json") w.Write(input) } licenseHandler := func(w http.ResponseWriter, r *http.Request) { @@ -61,25 +61,25 @@ func createEsMuxer(license string) *http.ServeMux { mux.Handle("/_xpack/usage", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/xpack-usage.710.json") + input, _ := os.ReadFile("./_meta/test/xpack-usage.710.json") w.Write(input) })) mux.Handle("/_cluster/settings", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/cluster-settings.710.json") + input, _ := os.ReadFile("./_meta/test/cluster-settings.710.json") w.Write(input) })) mux.Handle("/_cluster/stats", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/cluster_stats.710.json") + input, _ := os.ReadFile("./_meta/test/cluster_stats.710.json") w.Write(input) })) mux.Handle("/_cluster/state/version,master_node,nodes,routing_table", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/cluster_state.710.json") + input, _ := os.ReadFile("./_meta/test/cluster_state.710.json") w.Write(input) })) diff --git a/metricbeat/module/elasticsearch/elasticsearch_integration_test.go b/metricbeat/module/elasticsearch/elasticsearch_integration_test.go index 3d102a2fd62..3478dd768b4 100644 --- a/metricbeat/module/elasticsearch/elasticsearch_integration_test.go +++ b/metricbeat/module/elasticsearch/elasticsearch_integration_test.go @@ -24,9 +24,10 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "math/rand" "net/http" + "os" "strings" "testing" "time" @@ -214,7 +215,7 @@ func createIndex(host string, isHidden bool) (string, error) { return "", fmt.Errorf("could not send create index request: %w", err) } defer resp.Body.Close() - respBody, err := ioutil.ReadAll(resp.Body) + respBody, err := io.ReadAll(resp.Body) if resp.StatusCode != 200 { return "", fmt.Errorf("HTTP error %d: %s, %s", resp.StatusCode, resp.Status, string(respBody)) @@ -254,7 +255,7 @@ func enableTrialLicense(host string, version *version.V) error { defer resp.Body.Close() if resp.StatusCode != 200 { - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return err } @@ -279,7 +280,7 @@ func checkTrialLicenseEnabled(host string, version *version.V) (bool, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } @@ -302,7 +303,7 @@ func checkTrialLicenseEnabled(host string, version *version.V) (bool, error) { func createMLJob(host string, version *version.V) error { - mlJob, err := ioutil.ReadFile("ml_job/_meta/test/test_job.json") + mlJob, err := os.ReadFile("ml_job/_meta/test/test_job.json") if err != nil { return err } @@ -370,7 +371,7 @@ func checkCCRStatsExists(host string) (bool, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return false, err } @@ -389,7 +390,7 @@ func checkCCRStatsExists(host string) (bool, error) { } func setupCCRRemote(host string) error { - remoteSettings, err := ioutil.ReadFile("ccr/_meta/test/test_remote_settings.json") + remoteSettings, err := os.ReadFile("ccr/_meta/test/test_remote_settings.json") if err != nil { return err } @@ -400,7 +401,7 @@ func setupCCRRemote(host string) error { } func createCCRLeaderIndex(host string) error { - leaderIndex, err := ioutil.ReadFile("ccr/_meta/test/test_leader_index.json") + leaderIndex, err := os.ReadFile("ccr/_meta/test/test_leader_index.json") if err != nil { return err } @@ -411,7 +412,7 @@ func createCCRLeaderIndex(host string) error { } func createCCRFollowerIndex(host string) error { - followerIndex, err := ioutil.ReadFile("ccr/_meta/test/test_follower_index.json") + followerIndex, err := os.ReadFile("ccr/_meta/test/test_follower_index.json") if err != nil { return err } @@ -465,7 +466,7 @@ func createEnrichStats(host string) error { } func createEnrichSourceIndex(host string) error { - sourceDoc, err := ioutil.ReadFile("enrich/_meta/test/source_doc.json") + sourceDoc, err := os.ReadFile("enrich/_meta/test/source_doc.json") if err != nil { return err } @@ -476,7 +477,7 @@ func createEnrichSourceIndex(host string) error { } func createEnrichPolicy(host string) error { - policy, err := ioutil.ReadFile("enrich/_meta/test/policy.json") + policy, err := os.ReadFile("enrich/_meta/test/policy.json") if err != nil { return err } @@ -493,7 +494,7 @@ func executeEnrichPolicy(host string) error { } func createEnrichIngestPipeline(host string) error { - pipeline, err := ioutil.ReadFile("enrich/_meta/test/ingest_pipeline.json") + pipeline, err := os.ReadFile("enrich/_meta/test/ingest_pipeline.json") if err != nil { return err } @@ -504,7 +505,7 @@ func createEnrichIngestPipeline(host string) error { } func ingestAndEnrichDoc(host string) error { - targetDoc, err := ioutil.ReadFile("enrich/_meta/test/target_doc.json") + targetDoc, err := os.ReadFile("enrich/_meta/test/target_doc.json") if err != nil { return err } @@ -529,7 +530,7 @@ func countCatItems(elasticsearchHostPort, catObject, extraParams string) (int, e } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return 0, err } @@ -566,7 +567,7 @@ func getElasticsearchVersion(elasticsearchHostPort string) (*version.V, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -607,7 +608,7 @@ func httpSendJSON(host, path, method string, body []byte) ([]byte, *http.Respons } defer resp.Body.Close() - body, err = ioutil.ReadAll(resp.Body) + body, err = io.ReadAll(resp.Body) if err != nil { return nil, nil, err } diff --git a/metricbeat/module/elasticsearch/enrich/data_test.go b/metricbeat/module/elasticsearch/enrich/data_test.go index f2dbaaacc22..2372f1aa747 100644 --- a/metricbeat/module/elasticsearch/enrich/data_test.go +++ b/metricbeat/module/elasticsearch/enrich/data_test.go @@ -20,9 +20,9 @@ package enrich import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/require" @@ -41,7 +41,7 @@ func TestMapper(t *testing.T) { } func TestEmpty(t *testing.T) { - input, err := ioutil.ReadFile("./_meta/test/empty.750.json") + input, err := os.ReadFile("./_meta/test/empty.750.json") require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -76,13 +76,13 @@ func createEsMuxer(esVersion, license string, ccrEnabled bool) *http.ServeMux { mux.Handle("/_xpack/usage", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/xpack-usage.710.json") + input, _ := os.ReadFile("./_meta/test/xpack-usage.710.json") w.Write(input) })) mux.Handle("/_enrich/_stats", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/enrich_stats.750.json") + input, _ := os.ReadFile("./_meta/test/enrich_stats.750.json") w.Write(input) })) diff --git a/metricbeat/module/elasticsearch/index/data_test.go b/metricbeat/module/elasticsearch/index/data_test.go index f755f13f5a4..a57fdeb2b2c 100644 --- a/metricbeat/module/elasticsearch/index/data_test.go +++ b/metricbeat/module/elasticsearch/index/data_test.go @@ -20,9 +20,9 @@ package index import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "strings" "testing" "time" @@ -72,7 +72,7 @@ func TestEmpty(t *testing.T) { t.Fatal(err) } - input, err := ioutil.ReadFile("./_meta/test/empty.512.json") + input, err := os.ReadFile("./_meta/test/empty.512.json") require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -89,16 +89,16 @@ func createEsMuxer(esVersion, license string, ccrEnabled bool) *http.ServeMux { } rootHandler := func(w http.ResponseWriter, r *http.Request) { if strings.Contains(r.URL.Path, "_stats") { - input, _ := ioutil.ReadFile("./_meta/test/stats.800.snapshot.20201118.json") + input, _ := os.ReadFile("./_meta/test/stats.800.snapshot.20201118.json") w.Write(input) return } else if r.URL.Path != "/" { - input, _ := ioutil.ReadFile("./_meta/test/settings.json") + input, _ := os.ReadFile("./_meta/test/settings.json") w.Write(input) return } - input, _ := ioutil.ReadFile("./_meta/test/root.710.json") + input, _ := os.ReadFile("./_meta/test/root.710.json") w.Write(input) } @@ -114,13 +114,13 @@ func createEsMuxer(esVersion, license string, ccrEnabled bool) *http.ServeMux { mux.Handle("/_xpack/usage", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/xpack-usage.710.json") + input, _ := os.ReadFile("./_meta/test/xpack-usage.710.json") w.Write(input) })) mux.Handle("/_cluster/state/metadata,routing_table", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/cluster_state.710.json") + input, _ := os.ReadFile("./_meta/test/cluster_state.710.json") w.Write(input) })) diff --git a/metricbeat/module/elasticsearch/index_recovery/data_test.go b/metricbeat/module/elasticsearch/index_recovery/data_test.go index 5a2f07221ce..142249bd9e5 100644 --- a/metricbeat/module/elasticsearch/index_recovery/data_test.go +++ b/metricbeat/module/elasticsearch/index_recovery/data_test.go @@ -20,9 +20,9 @@ package index_recovery import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" mbtest "github.com/elastic/beats/v7/metricbeat/mb/testing" @@ -46,7 +46,7 @@ func createEsMuxer(license string) *http.ServeMux { http.NotFound(w, r) } - input, _ := ioutil.ReadFile("./_meta/test/root.710.json") + input, _ := os.ReadFile("./_meta/test/root.710.json") w.Write(input) } licenseHandler := func(w http.ResponseWriter, r *http.Request) { @@ -60,7 +60,7 @@ func createEsMuxer(license string) *http.ServeMux { mux.Handle("/_xpack/license", http.HandlerFunc(licenseHandler)) // for before 7.0 mux.Handle("/", http.HandlerFunc(rootHandler)) mux.Handle("/_recovery", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - content, _ := ioutil.ReadFile("./_meta/test/recovery.710.json") + content, _ := os.ReadFile("./_meta/test/recovery.710.json") w.Write(content) })) diff --git a/metricbeat/module/elasticsearch/index_summary/data_test.go b/metricbeat/module/elasticsearch/index_summary/data_test.go index 3df0e61b269..a03b20375b9 100644 --- a/metricbeat/module/elasticsearch/index_summary/data_test.go +++ b/metricbeat/module/elasticsearch/index_summary/data_test.go @@ -20,9 +20,9 @@ package index_summary import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/require" @@ -48,7 +48,7 @@ func createEsMuxer(license string) *http.ServeMux { http.NotFound(w, r) } - input, _ := ioutil.ReadFile("../index/_meta/test/root.710.json") + input, _ := os.ReadFile("../index/_meta/test/root.710.json") w.Write(input) } licenseHandler := func(w http.ResponseWriter, r *http.Request) { @@ -62,7 +62,7 @@ func createEsMuxer(license string) *http.ServeMux { mux.Handle("/_xpack/license", http.HandlerFunc(licenseHandler)) // for before 7.0 mux.Handle("/", http.HandlerFunc(rootHandler)) mux.Handle("/_stats", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - content, _ := ioutil.ReadFile("../index/_meta/test/stats.700-alpha1.json") + content, _ := os.ReadFile("../index/_meta/test/stats.700-alpha1.json") w.Write(content) })) @@ -86,7 +86,7 @@ func TestMapper(t *testing.T) { } func TestEmpty(t *testing.T) { - input, err := ioutil.ReadFile("../index/_meta/test/empty.512.json") + input, err := os.ReadFile("../index/_meta/test/empty.512.json") require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/elasticsearch/ingest_pipeline/data_test.go b/metricbeat/module/elasticsearch/ingest_pipeline/data_test.go index 5ae9ad6def5..1a0426cf208 100644 --- a/metricbeat/module/elasticsearch/ingest_pipeline/data_test.go +++ b/metricbeat/module/elasticsearch/ingest_pipeline/data_test.go @@ -18,7 +18,7 @@ package ingest_pipeline import ( - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/require" @@ -36,7 +36,7 @@ func TestMapper(t *testing.T) { ClusterName: "helloworld", } - ingestData, err := ioutil.ReadFile("./_meta/test/stats.json") + ingestData, err := os.ReadFile("./_meta/test/stats.json") require.NoError(t, err) err = eventsMapping(reporter, info, ingestData, true, true) @@ -92,7 +92,7 @@ func TestSampling(t *testing.T) { ClusterName: "helloworld", } - ingestData, err := ioutil.ReadFile("./_meta/test/stats.json") + ingestData, err := os.ReadFile("./_meta/test/stats.json") require.NoError(t, err) err = eventsMapping(reporter, info, ingestData, true, false) // set sampling to false diff --git a/metricbeat/module/elasticsearch/ml_job/data_test.go b/metricbeat/module/elasticsearch/ml_job/data_test.go index 53f9cd89945..55c6b45c1bb 100644 --- a/metricbeat/module/elasticsearch/ml_job/data_test.go +++ b/metricbeat/module/elasticsearch/ml_job/data_test.go @@ -20,9 +20,9 @@ package ml_job import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "strconv" "strings" "testing" @@ -50,7 +50,7 @@ func TestData(t *testing.T) { http.NotFound(w, r) } - input, _ := ioutil.ReadFile("./_meta/test/root.710.json") + input, _ := os.ReadFile("./_meta/test/root.710.json") input = []byte(strings.Replace(string(input), "7.10.0", "7.10.0", -1)) w.Write(input) } @@ -70,7 +70,7 @@ func TestData(t *testing.T) { mux.Handle("/_xpack", http.HandlerFunc(xpackHandler)) mux.Handle("/_ml/anomaly_detectors/_all/_stats", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/ml.711.json") + input, _ := os.ReadFile("./_meta/test/ml.711.json") w.Write(input) })) diff --git a/metricbeat/module/elasticsearch/node/data_test.go b/metricbeat/module/elasticsearch/node/data_test.go index 46c62f77ffa..33b66f4e281 100644 --- a/metricbeat/module/elasticsearch/node/data_test.go +++ b/metricbeat/module/elasticsearch/node/data_test.go @@ -20,7 +20,7 @@ package node import ( - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/require" @@ -42,7 +42,7 @@ func TestGetMappings(t *testing.T) { func TestInvalid(t *testing.T) { file := "./_meta/test/invalid.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/elasticsearch/node/node_test.go b/metricbeat/module/elasticsearch/node/node_test.go index 32f91bc8c60..8df98cc9c4d 100644 --- a/metricbeat/module/elasticsearch/node/node_test.go +++ b/metricbeat/module/elasticsearch/node/node_test.go @@ -21,9 +21,9 @@ package node import ( "encoding/base64" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -42,7 +42,7 @@ func TestFetch(t *testing.T) { for _, f := range files { t.Run(f, func(t *testing.T) { - response, err := ioutil.ReadFile(f) + response, err := os.ReadFile(f) require.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/elasticsearch/pending_tasks/data_test.go b/metricbeat/module/elasticsearch/pending_tasks/data_test.go index c863800ba8a..a8faf63c849 100644 --- a/metricbeat/module/elasticsearch/pending_tasks/data_test.go +++ b/metricbeat/module/elasticsearch/pending_tasks/data_test.go @@ -20,7 +20,7 @@ package pending_tasks import ( - "io/ioutil" + "os" "reflect" "testing" "time" @@ -42,7 +42,7 @@ var info = elasticsearch.Info{ func TestEmptyQueueShouldGiveNoError(t *testing.T) { file := "./_meta/test/empty.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -52,7 +52,7 @@ func TestEmptyQueueShouldGiveNoError(t *testing.T) { func TestNotEmptyQueueShouldGiveNoError(t *testing.T) { file := "./_meta/test/tasks.622.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -64,7 +64,7 @@ func TestNotEmptyQueueShouldGiveNoError(t *testing.T) { func TestEmptyQueueShouldGiveZeroEvent(t *testing.T) { file := "./_meta/test/empty.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -75,7 +75,7 @@ func TestEmptyQueueShouldGiveZeroEvent(t *testing.T) { func TestNotEmptyQueueShouldGiveSeveralEvents(t *testing.T) { file := "./_meta/test/tasks.622.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -86,7 +86,7 @@ func TestNotEmptyQueueShouldGiveSeveralEvents(t *testing.T) { func TestInvalidJsonForRequiredFieldShouldThrowError(t *testing.T) { file := "./_meta/test/invalid_required_field.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -96,7 +96,7 @@ func TestInvalidJsonForRequiredFieldShouldThrowError(t *testing.T) { func TestInvalidJsonForBadFormatShouldThrowError(t *testing.T) { file := "./_meta/test/invalid_format.json" - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -198,7 +198,7 @@ func TestEventsMappedMatchToContentReceived(t *testing.T) { } for iter, testCase := range testCases { - content, err := ioutil.ReadFile(testCase.given) + content, err := os.ReadFile(testCase.given) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/elasticsearch/shard/data_test.go b/metricbeat/module/elasticsearch/shard/data_test.go index 9abb100484b..5f2e8a237e0 100644 --- a/metricbeat/module/elasticsearch/shard/data_test.go +++ b/metricbeat/module/elasticsearch/shard/data_test.go @@ -18,9 +18,9 @@ package shard import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -36,7 +36,7 @@ func TestStats(t *testing.T) { require.NoError(t, err) for _, f := range files { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -58,7 +58,7 @@ func TestData(t *testing.T) { })) mux.Handle("/_cluster/state/version,nodes,master_node,routing_table", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/routing_table.710.json") + input, _ := os.ReadFile("./_meta/test/routing_table.710.json") w.Write(input) })) diff --git a/metricbeat/module/elasticsearch/testing.go b/metricbeat/module/elasticsearch/testing.go index 63f041c44fd..470ae726a92 100644 --- a/metricbeat/module/elasticsearch/testing.go +++ b/metricbeat/module/elasticsearch/testing.go @@ -20,7 +20,7 @@ package elasticsearch import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -41,7 +41,7 @@ func TestMapper(t *testing.T, glob string, mapper func(mb.ReporterV2, []byte) er for _, f := range files { t.Run(f, func(t *testing.T) { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -67,7 +67,7 @@ func TestMapperWithInfo(t *testing.T, glob string, mapper func(mb.ReporterV2, In for _, f := range files { t.Run(f, func(t *testing.T) { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -93,7 +93,7 @@ func TestMapperWithMetricSetAndInfo(t *testing.T, glob string, ms MetricSetAPI, for _, f := range files { t.Run(f, func(t *testing.T) { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -125,7 +125,7 @@ func TestMapperWithHttpHelper(t *testing.T, glob string, httpClient *helper.HTTP for _, f := range files { t.Run(f, func(t *testing.T) { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/envoyproxy/server/server_test.go b/metricbeat/module/envoyproxy/server/server_test.go index 6db24061360..02affcc37cd 100644 --- a/metricbeat/module/envoyproxy/server/server_test.go +++ b/metricbeat/module/envoyproxy/server/server_test.go @@ -18,9 +18,9 @@ package server import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "strings" "testing" @@ -35,7 +35,7 @@ import ( const testFile = "../_meta/test/serverstats" func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile(testFile) + content, err := os.ReadFile(testFile) assert.NoError(t, err) event, err := eventMapping(content) @@ -119,7 +119,7 @@ func TestFetchEventContent(t *testing.T) { absPath, err := filepath.Abs("../_meta/test/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/serverstats") + response, err := os.ReadFile(absPath + "/serverstats") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -155,7 +155,7 @@ func TestFetchTimeout(t *testing.T) { absPath, err := filepath.Abs("../_meta/test/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/serverstats") + response, err := os.ReadFile(absPath + "/serverstats") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/etcd/leader/leader.go b/metricbeat/module/etcd/leader/leader.go index 4d9238924cf..a4d20799a94 100644 --- a/metricbeat/module/etcd/leader/leader.go +++ b/metricbeat/module/etcd/leader/leader.go @@ -20,7 +20,7 @@ package leader import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "github.com/elastic/elastic-agent-libs/logp" @@ -93,7 +93,7 @@ func (m *MetricSet) Fetch(reporter mb.ReporterV2) error { } defer res.Body.Close() - content, err := ioutil.ReadAll(res.Body) + content, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("error reading body response: %w", err) } diff --git a/metricbeat/module/etcd/leader/leader_test.go b/metricbeat/module/etcd/leader/leader_test.go index 3119b6bb0f0..8099f82972f 100644 --- a/metricbeat/module/etcd/leader/leader_test.go +++ b/metricbeat/module/etcd/leader/leader_test.go @@ -19,9 +19,9 @@ package leader import ( "encoding/json" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "regexp" @@ -33,7 +33,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("../_meta/test/leaderstats.json") + content, err := os.ReadFile("../_meta/test/leaderstats.json") assert.NoError(t, err) var data Leader @@ -109,7 +109,7 @@ func TestFetchEventContent(t *testing.T) { absPath, err := filepath.Abs(mockedFetchLocation + tc.mockedFetchFile) assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath) + response, err := os.ReadFile(absPath) assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/etcd/self/self_test.go b/metricbeat/module/etcd/self/self_test.go index 9d1b8f2d266..5b27a8c1b12 100644 --- a/metricbeat/module/etcd/self/self_test.go +++ b/metricbeat/module/etcd/self/self_test.go @@ -18,9 +18,9 @@ package self import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "github.com/stretchr/testify/assert" @@ -31,7 +31,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("../_meta/test/selfstats.json") + content, err := os.ReadFile("../_meta/test/selfstats.json") assert.NoError(t, err) event := eventMapping(content) @@ -43,7 +43,7 @@ func TestFetchEventContent(t *testing.T) { absPath, err := filepath.Abs("../_meta/test/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/selfstats.json") + response, err := os.ReadFile(absPath + "/selfstats.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/etcd/store/store_test.go b/metricbeat/module/etcd/store/store_test.go index a3a72ec6a13..862cc25c200 100644 --- a/metricbeat/module/etcd/store/store_test.go +++ b/metricbeat/module/etcd/store/store_test.go @@ -18,9 +18,9 @@ package store import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "github.com/stretchr/testify/assert" @@ -32,7 +32,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("../_meta/test/storestats.json") + content, err := os.ReadFile("../_meta/test/storestats.json") assert.NoError(t, err) event := eventMapping(content) @@ -44,7 +44,7 @@ func TestFetchEventContent(t *testing.T) { absPath, err := filepath.Abs("../_meta/test/") assert.NoError(t, err) - response, err := ioutil.ReadFile(absPath + "/storestats.json") + response, err := os.ReadFile(absPath + "/storestats.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/haproxy/haproxy.go b/metricbeat/module/haproxy/haproxy.go index dcc639dcc87..39b187210bf 100644 --- a/metricbeat/module/haproxy/haproxy.go +++ b/metricbeat/module/haproxy/haproxy.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/url" "strings" @@ -260,7 +259,7 @@ func (c *Client) GetInfo() (*Info, error) { return nil, err } - if b, err := ioutil.ReadAll(res); err == nil { + if b, err := io.ReadAll(res); err == nil { resultMap := map[string]interface{}{} diff --git a/metricbeat/module/http/json/json.go b/metricbeat/module/http/json/json.go index e312a950cae..b8930bccbd7 100644 --- a/metricbeat/module/http/json/json.go +++ b/metricbeat/module/http/json/json.go @@ -20,7 +20,7 @@ package json import ( "encoding/json" "fmt" - "io/ioutil" + "io" "github.com/elastic/beats/v7/metricbeat/helper" "github.com/elastic/beats/v7/metricbeat/mb" @@ -128,7 +128,7 @@ func (m *MetricSet) Fetch(reporter mb.ReporterV2) error { } }() - body, err := ioutil.ReadAll(response.Body) + body, err := io.ReadAll(response.Body) if err != nil { return err } diff --git a/metricbeat/module/jolokia/jmx/data_test.go b/metricbeat/module/jolokia/jmx/data_test.go index 8357bb5d455..9affd340169 100644 --- a/metricbeat/module/jolokia/jmx/data_test.go +++ b/metricbeat/module/jolokia/jmx/data_test.go @@ -18,7 +18,7 @@ package jmx import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -33,7 +33,7 @@ func TestEventMapper(t *testing.T) { require.NotNil(t, absPath) require.NoError(t, err) - jolokiaResponse, err := ioutil.ReadFile(absPath + "/jolokia_response.json") + jolokiaResponse, err := os.ReadFile(absPath + "/jolokia_response.json") require.NoError(t, err) @@ -104,7 +104,7 @@ func TestEventGroupingMapper(t *testing.T) { require.NotNil(t, absPath) require.NoError(t, err) - jolokiaResponse, err := ioutil.ReadFile(absPath + "/jolokia_response.json") + jolokiaResponse, err := os.ReadFile(absPath + "/jolokia_response.json") require.NoError(t, err) @@ -181,7 +181,7 @@ func TestEventGroupingMapperGetRequest(t *testing.T) { require.NotNil(t, absPath) require.NoError(t, err) - jolokiaResponse, err := ioutil.ReadFile(absPath + "/jolokia_get_response.json") + jolokiaResponse, err := os.ReadFile(absPath + "/jolokia_get_response.json") require.NoError(t, err) @@ -230,7 +230,7 @@ func TestEventGroupingMapperGetRequestUptime(t *testing.T) { require.NotNil(t, absPath) require.NoError(t, err) - jolokiaResponse, err := ioutil.ReadFile(absPath + "/jolokia_get_response_uptime.json") + jolokiaResponse, err := os.ReadFile(absPath + "/jolokia_get_response_uptime.json") require.NoError(t, err) @@ -264,7 +264,7 @@ func TestEventMapperWithWildcard(t *testing.T) { require.NotNil(t, absPath) require.NoError(t, err) - jolokiaResponse, err := ioutil.ReadFile(absPath + "/jolokia_response_wildcard.json") + jolokiaResponse, err := os.ReadFile(absPath + "/jolokia_response_wildcard.json") require.NoError(t, err) @@ -305,7 +305,7 @@ func TestEventGroupingMapperWithWildcard(t *testing.T) { require.NotNil(t, absPath) require.NoError(t, err) - jolokiaResponse, err := ioutil.ReadFile(absPath + "/jolokia_response_wildcard.json") + jolokiaResponse, err := os.ReadFile(absPath + "/jolokia_response_wildcard.json") require.NoError(t, err) diff --git a/metricbeat/module/kibana/stats/data_test.go b/metricbeat/module/kibana/stats/data_test.go index 7bf59ef0efc..0b4ecab1abb 100644 --- a/metricbeat/module/kibana/stats/data_test.go +++ b/metricbeat/module/kibana/stats/data_test.go @@ -20,7 +20,7 @@ package stats import ( - "io/ioutil" + "os" "path/filepath" "testing" @@ -35,7 +35,7 @@ func TestEventMapping(t *testing.T) { require.NoError(t, err) for _, f := range files { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/kibana/stats/stats_integration_test.go b/metricbeat/module/kibana/stats/stats_integration_test.go index 0e51253b091..734355cc672 100644 --- a/metricbeat/module/kibana/stats/stats_integration_test.go +++ b/metricbeat/module/kibana/stats/stats_integration_test.go @@ -21,7 +21,7 @@ package stats import ( "encoding/json" - "io/ioutil" + "io" "net/http" "testing" @@ -88,7 +88,7 @@ func getKibanaVersion(t *testing.T, kibanaHostPort string) (*version.V, error) { } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/metricbeat/module/kibana/status/data_test.go b/metricbeat/module/kibana/status/data_test.go index 3ec2ceb3bb6..084f52b056e 100644 --- a/metricbeat/module/kibana/status/data_test.go +++ b/metricbeat/module/kibana/status/data_test.go @@ -20,7 +20,7 @@ package status import ( - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/require" @@ -30,7 +30,7 @@ import ( func TestEventMapping(t *testing.T) { f := "./_meta/test/input.json" - content, err := ioutil.ReadFile(f) + content, err := os.ReadFile(f) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} diff --git a/metricbeat/module/kubernetes/container/container_test.go b/metricbeat/module/kubernetes/container/container_test.go index a444e83c6cc..1a3b1a70b7a 100644 --- a/metricbeat/module/kubernetes/container/container_test.go +++ b/metricbeat/module/kubernetes/container/container_test.go @@ -20,7 +20,7 @@ package container import ( - "io/ioutil" + "io" "os" "testing" @@ -70,7 +70,7 @@ func (s *ContainerTestSuite) ReadTestFile(testFile string) []byte { f, err := os.Open(testFile) s.NoError(err, "cannot open test file "+testFile) - body, err := ioutil.ReadAll(f) + body, err := io.ReadAll(f) s.NoError(err, "cannot read test file "+testFile) return body diff --git a/metricbeat/module/kubernetes/node/node_test.go b/metricbeat/module/kubernetes/node/node_test.go index 537d9c67103..66b279d2738 100644 --- a/metricbeat/module/kubernetes/node/node_test.go +++ b/metricbeat/module/kubernetes/node/node_test.go @@ -20,7 +20,7 @@ package node import ( - "io/ioutil" + "io" "os" "testing" @@ -46,7 +46,7 @@ func (s *NodeTestSuite) ReadTestFile(testFile string) []byte { f, err := os.Open(testFile) s.NoError(err, "cannot open test file "+testFile) - body, err := ioutil.ReadAll(f) + body, err := io.ReadAll(f) s.NoError(err, "cannot read test file "+testFile) return body diff --git a/metricbeat/module/kubernetes/pod/pod_test.go b/metricbeat/module/kubernetes/pod/pod_test.go index e4aaca06f2b..81cade5820b 100644 --- a/metricbeat/module/kubernetes/pod/pod_test.go +++ b/metricbeat/module/kubernetes/pod/pod_test.go @@ -20,7 +20,7 @@ package pod import ( - "io/ioutil" + "io" "os" "testing" @@ -77,7 +77,7 @@ func (s *PodTestSuite) ReadTestFile(testFile string) []byte { f, err := os.Open(testFile) s.NoError(err, "cannot open test file "+testFile) - body, err := ioutil.ReadAll(f) + body, err := io.ReadAll(f) s.NoError(err, "cannot read test file "+testFile) return body diff --git a/metricbeat/module/kubernetes/system/system_test.go b/metricbeat/module/kubernetes/system/system_test.go index cdc23220d2b..da36fa6a4a1 100644 --- a/metricbeat/module/kubernetes/system/system_test.go +++ b/metricbeat/module/kubernetes/system/system_test.go @@ -20,7 +20,7 @@ package system import ( - "io/ioutil" + "io" "os" "testing" @@ -38,7 +38,7 @@ func TestEventMapping(t *testing.T) { f, err := os.Open(testFile) assert.NoError(t, err, "cannot open test file "+testFile) - body, err := ioutil.ReadAll(f) + body, err := io.ReadAll(f) assert.NoError(t, err, "cannot read test file "+testFile) events, err := eventMapping(body, logger) diff --git a/metricbeat/module/kubernetes/volume/volume_test.go b/metricbeat/module/kubernetes/volume/volume_test.go index 719cc48b61d..1cc24a2434d 100644 --- a/metricbeat/module/kubernetes/volume/volume_test.go +++ b/metricbeat/module/kubernetes/volume/volume_test.go @@ -20,7 +20,7 @@ package volume import ( - "io/ioutil" + "io" "os" "testing" @@ -38,7 +38,7 @@ func TestEventMapping(t *testing.T) { f, err := os.Open(testFile) assert.NoError(t, err, "cannot open test file "+testFile) - body, err := ioutil.ReadAll(f) + body, err := io.ReadAll(f) assert.NoError(t, err, "cannot read test file "+testFile) events, err := eventMapping(body, logger) diff --git a/metricbeat/module/linux/rapl/rapl.go b/metricbeat/module/linux/rapl/rapl.go index 5dd823efc54..8e10395fbf4 100644 --- a/metricbeat/module/linux/rapl/rapl.go +++ b/metricbeat/module/linux/rapl/rapl.go @@ -22,7 +22,6 @@ package rapl import ( "errors" "fmt" - "io/ioutil" "os" "os/user" "path/filepath" @@ -231,7 +230,7 @@ func topoPkgCPUMap(hostfs resolve.Resolver) (map[int][]int, error) { sysdir := "/sys/devices/system/cpu/" cpuMap := make(map[int][]int) - files, err := ioutil.ReadDir(hostfs.ResolveHostFS(sysdir)) + files, err := os.ReadDir(hostfs.ResolveHostFS(sysdir)) if err != nil { return nil, err } @@ -242,7 +241,7 @@ func topoPkgCPUMap(hostfs resolve.Resolver) (map[int][]int, error) { if file.IsDir() && re.MatchString(file.Name()) { fullPkg := hostfs.ResolveHostFS(filepath.Join(sysdir, file.Name(), "/topology/physical_package_id")) - dat, err := ioutil.ReadFile(fullPkg) + dat, err := os.ReadFile(fullPkg) if err != nil { return nil, fmt.Errorf("error reading file %s: %w", fullPkg, err) } diff --git a/metricbeat/module/linux/util.go b/metricbeat/module/linux/util.go index def4603c816..85244bd138e 100644 --- a/metricbeat/module/linux/util.go +++ b/metricbeat/module/linux/util.go @@ -19,7 +19,7 @@ package linux import ( "fmt" - "io/ioutil" + "os" "strconv" "strings" ) @@ -28,7 +28,7 @@ import ( // /sysfs contains a number of metrics broken out by values in individual files, so this is a useful helper function to have func ReadIntFromFile(path string, base int) (int64, error) { - raw, err := ioutil.ReadFile(path) + raw, err := os.ReadFile(path) if err != nil { return 0, fmt.Errorf("error reading file %s: %w", path, err) } diff --git a/metricbeat/module/logstash/logstash_integration_test.go b/metricbeat/module/logstash/logstash_integration_test.go index 5865867cf1f..21dd8291ec9 100644 --- a/metricbeat/module/logstash/logstash_integration_test.go +++ b/metricbeat/module/logstash/logstash_integration_test.go @@ -21,7 +21,7 @@ package logstash_test import ( "encoding/json" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -105,7 +105,7 @@ func getESClusterUUID(t *testing.T, host string) string { ClusterUUID string `json:"cluster_uuid"` } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) require.NoError(t, err) json.Unmarshal(data, &body) diff --git a/metricbeat/module/logstash/node/data_test.go b/metricbeat/module/logstash/node/data_test.go index 9591137f6f9..b940bca8d4e 100644 --- a/metricbeat/module/logstash/node/data_test.go +++ b/metricbeat/module/logstash/node/data_test.go @@ -21,7 +21,7 @@ package node import ( "encoding/json" - "io/ioutil" + "os" "path/filepath" "testing" @@ -38,7 +38,7 @@ func TestEventMapping(t *testing.T) { require.NoError(t, err) for _, f := range files { - input, err := ioutil.ReadFile(f) + input, err := os.ReadFile(f) require.NoError(t, err) var data map[string]interface{} diff --git a/metricbeat/module/logstash/node_stats/data_test.go b/metricbeat/module/logstash/node_stats/data_test.go index e111d7107a8..9a6576ea6f7 100644 --- a/metricbeat/module/logstash/node_stats/data_test.go +++ b/metricbeat/module/logstash/node_stats/data_test.go @@ -21,9 +21,9 @@ package node_stats import ( "fmt" - "io/ioutil" "net/http" "net/http/httptest" + osutil "os" "testing" "github.com/elastic/beats/v7/metricbeat/module/logstash" @@ -57,7 +57,7 @@ func EventMappingForFiles(t *testing.T, fixtureVersions []string, expectedEvents for _, f := range fixtureVersions { path := fmt.Sprintf("./_meta/test/node_stats.%s.json", f) - input, err := ioutil.ReadFile(path) + input, err := osutil.ReadFile(path) require.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} @@ -75,13 +75,13 @@ func TestData(t *testing.T) { http.NotFound(w, r) } - input, _ := ioutil.ReadFile("./_meta/test/root.710.json") + input, _ := osutil.ReadFile("./_meta/test/root.710.json") w.Write(input) })) mux.Handle("/_node/stats", http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("./_meta/test/node_stats.710.json") + input, _ := osutil.ReadFile("./_meta/test/node_stats.710.json") w.Write(input) })) diff --git a/metricbeat/module/mongodb/collstats/data_test.go b/metricbeat/module/mongodb/collstats/data_test.go index a921d14d727..f10e8aa0a8c 100644 --- a/metricbeat/module/mongodb/collstats/data_test.go +++ b/metricbeat/module/mongodb/collstats/data_test.go @@ -21,7 +21,7 @@ package collstats import ( "encoding/json" - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/assert" @@ -31,7 +31,7 @@ import ( func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/input.json") + content, err := os.ReadFile("./_meta/test/input.json") assert.NoError(t, err) data := mapstr.M{} diff --git a/metricbeat/module/nats/connection/connection_test.go b/metricbeat/module/nats/connection/connection_test.go index d6b95960aef..2413445e36b 100644 --- a/metricbeat/module/nats/connection/connection_test.go +++ b/metricbeat/module/nats/connection/connection_test.go @@ -18,9 +18,9 @@ package connection import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/connectionsmetrics.json") + content, err := os.ReadFile("./_meta/test/connectionsmetrics.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventsMapping(reporter, content) @@ -40,7 +40,7 @@ func TestEventMapping(t *testing.T) { func TestFetchEventContent(t *testing.T) { absPath, _ := filepath.Abs("./_meta/test") - response, _ := ioutil.ReadFile(absPath + "/connectionsmetrics.json") + response, _ := os.ReadFile(absPath + "/connectionsmetrics.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/nats/connections/connections_test.go b/metricbeat/module/nats/connections/connections_test.go index e55bf173071..76d9ce6f553 100644 --- a/metricbeat/module/nats/connections/connections_test.go +++ b/metricbeat/module/nats/connections/connections_test.go @@ -18,9 +18,9 @@ package connections import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/connectionsmetrics.json") + content, err := os.ReadFile("./_meta/test/connectionsmetrics.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventMapping(reporter, content) @@ -43,7 +43,7 @@ func TestEventMapping(t *testing.T) { func TestFetchEventContent(t *testing.T) { absPath, _ := filepath.Abs("./_meta/test") - response, _ := ioutil.ReadFile(absPath + "/connectionsmetrics.json") + response, _ := os.ReadFile(absPath + "/connectionsmetrics.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/nats/route/route_test.go b/metricbeat/module/nats/route/route_test.go index 72f5f2f3794..27dc63c31b9 100644 --- a/metricbeat/module/nats/route/route_test.go +++ b/metricbeat/module/nats/route/route_test.go @@ -18,9 +18,9 @@ package route import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/routesmetrics.json") + content, err := os.ReadFile("./_meta/test/routesmetrics.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventsMapping(reporter, content) @@ -40,7 +40,7 @@ func TestEventMapping(t *testing.T) { func TestFetchEventContent(t *testing.T) { absPath, _ := filepath.Abs("./_meta/test") - response, _ := ioutil.ReadFile(absPath + "/routesmetrics.json") + response, _ := os.ReadFile(absPath + "/routesmetrics.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/nats/routes/routes_test.go b/metricbeat/module/nats/routes/routes_test.go index bf987019885..e3fafca5883 100644 --- a/metricbeat/module/nats/routes/routes_test.go +++ b/metricbeat/module/nats/routes/routes_test.go @@ -18,9 +18,9 @@ package routes import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/routesmetrics.json") + content, err := os.ReadFile("./_meta/test/routesmetrics.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventMapping(reporter, content) @@ -43,7 +43,7 @@ func TestEventMapping(t *testing.T) { func TestFetchEventContent(t *testing.T) { absPath, _ := filepath.Abs("./_meta/test") - response, _ := ioutil.ReadFile(absPath + "/routesmetrics.json") + response, _ := os.ReadFile(absPath + "/routesmetrics.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/nats/stats/stats_test.go b/metricbeat/module/nats/stats/stats_test.go index 922ccaf65f4..27da416074d 100644 --- a/metricbeat/module/nats/stats/stats_test.go +++ b/metricbeat/module/nats/stats/stats_test.go @@ -18,9 +18,9 @@ package stats import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/statsmetrics.json") + content, err := os.ReadFile("./_meta/test/statsmetrics.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventMapping(reporter, content) @@ -43,7 +43,7 @@ func TestEventMapping(t *testing.T) { func TestFetchEventContent(t *testing.T) { absPath, _ := filepath.Abs("./_meta/test/") - response, _ := ioutil.ReadFile(absPath + "/statsmetrics.json") + response, _ := os.ReadFile(absPath + "/statsmetrics.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/nats/subscriptions/subscriptions_test.go b/metricbeat/module/nats/subscriptions/subscriptions_test.go index d0b7e567b4e..312a9f0e32c 100644 --- a/metricbeat/module/nats/subscriptions/subscriptions_test.go +++ b/metricbeat/module/nats/subscriptions/subscriptions_test.go @@ -18,9 +18,9 @@ package subscriptions import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -30,7 +30,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/subscriptionsmetrics.json") + content, err := os.ReadFile("./_meta/test/subscriptionsmetrics.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventMapping(reporter, content) @@ -43,7 +43,7 @@ func TestEventMapping(t *testing.T) { func TestFetchEventContent(t *testing.T) { absPath, _ := filepath.Abs("./_meta/test/") - response, _ := ioutil.ReadFile(absPath + "/subscriptionsmetrics.json") + response, _ := os.ReadFile(absPath + "/subscriptionsmetrics.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/metricbeat/module/rabbitmq/mtest/server.go b/metricbeat/module/rabbitmq/mtest/server.go index 9a5d33ef780..585d16b6dc3 100644 --- a/metricbeat/module/rabbitmq/mtest/server.go +++ b/metricbeat/module/rabbitmq/mtest/server.go @@ -18,9 +18,9 @@ package mtest import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -58,12 +58,12 @@ func Server(t *testing.T, c ServerConfig) *httptest.Server { } for k := range responses { - r, err := ioutil.ReadFile(filepath.Join(absPath, responses[k].file)) + r, err := os.ReadFile(filepath.Join(absPath, responses[k].file)) responses[k].body = r assert.NoError(t, err) } - notFound, err := ioutil.ReadFile(filepath.Join(absPath, "notfound_response.json")) + notFound, err := os.ReadFile(filepath.Join(absPath, "notfound_response.json")) assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/system/entropy/entropy.go b/metricbeat/module/system/entropy/entropy.go index a9ea007af69..851219521c4 100644 --- a/metricbeat/module/system/entropy/entropy.go +++ b/metricbeat/module/system/entropy/entropy.go @@ -21,7 +21,7 @@ package entropy import ( "fmt" - "io/ioutil" + "os" "strconv" "strings" @@ -85,7 +85,7 @@ func (m *MetricSet) Fetch(report mb.ReporterV2) error { func getEntropyData(path string) (int, error) { //This will be a number in the range 0 to 4096. - raw, err := ioutil.ReadFile(path) + raw, err := os.ReadFile(path) if err != nil { return 0, fmt.Errorf("error reading from random: %w", err) } diff --git a/metricbeat/module/system/hostnamechange_test.go b/metricbeat/module/system/hostnamechange_test.go index ecbaa27e767..f3f69698023 100644 --- a/metricbeat/module/system/hostnamechange_test.go +++ b/metricbeat/module/system/hostnamechange_test.go @@ -19,7 +19,7 @@ package system import ( "bytes" - "io/ioutil" + "os" "testing" ) @@ -28,7 +28,7 @@ import ( // is running. func TestHostDashboardHasChangeableHost(t *testing.T) { dashPath := "_meta/kibana/7/dashboard/79ffd6e0-faa0-11e6-947f-177f697178b8-ecs.json" - contents, err := ioutil.ReadFile(dashPath) + contents, err := os.ReadFile(dashPath) if err != nil { t.Fatalf("Error reading file %s: %v", dashPath, err) } diff --git a/metricbeat/module/system/process_summary/process_summary.go b/metricbeat/module/system/process_summary/process_summary.go index c64a0c1d3e1..7f346b10110 100644 --- a/metricbeat/module/system/process_summary/process_summary.go +++ b/metricbeat/module/system/process_summary/process_summary.go @@ -21,7 +21,7 @@ package process_summary import ( "fmt" - "io/ioutil" + "os" "runtime" "strconv" "strings" @@ -107,7 +107,7 @@ func (m *MetricSet) Fetch(r mb.ReporterV2) error { // threadStats returns a map of state counts for running threads on a system func threadStats(sys resolve.Resolver) (mapstr.M, error) { statPath := sys.ResolveHostFS("/proc/stat") - procData, err := ioutil.ReadFile(statPath) + procData, err := os.ReadFile(statPath) if err != nil { return nil, fmt.Errorf("error reading procfs file %s: %w", statPath, err) } diff --git a/metricbeat/module/system/raid/blockinfo/getdev.go b/metricbeat/module/system/raid/blockinfo/getdev.go index 02527c80636..9f4fb4a380b 100644 --- a/metricbeat/module/system/raid/blockinfo/getdev.go +++ b/metricbeat/module/system/raid/blockinfo/getdev.go @@ -19,14 +19,13 @@ package blockinfo import ( "fmt" - "io/ioutil" "os" "path/filepath" ) // ListAll lists all the multi-disk devices in a RAID array func ListAll(path string) ([]MDDevice, error) { - dir, err := ioutil.ReadDir(path) + dir, err := os.ReadDir(path) if err != nil { return nil, fmt.Errorf("could not read directory: %w", err) } diff --git a/metricbeat/module/system/raid/blockinfo/parser.go b/metricbeat/module/system/raid/blockinfo/parser.go index 3763ed28ab6..c167a10dc40 100644 --- a/metricbeat/module/system/raid/blockinfo/parser.go +++ b/metricbeat/module/system/raid/blockinfo/parser.go @@ -19,7 +19,7 @@ package blockinfo import ( "fmt" - "io/ioutil" + "os" "path/filepath" "strconv" "strings" @@ -43,7 +43,7 @@ func isRedundant(raidStr string) bool { func parseIntVal(path string) (int64, error) { var value int64 - raw, err := ioutil.ReadFile(path) + raw, err := os.ReadFile(path) if err != nil { return value, err } @@ -61,7 +61,7 @@ func parseIntVal(path string) (int64, error) { // if there's no sync operation in progress, the file will just have 'none' // in which case, default to to the overall size func getSyncStatus(path string, size int64) (SyncStatus, error) { - raw, err := ioutil.ReadFile(filepath.Join(path, "md", "sync_completed")) + raw, err := os.ReadFile(filepath.Join(path, "md", "sync_completed")) if err != nil { return SyncStatus{}, fmt.Errorf("could not open sync_completed: %w", err) } @@ -102,7 +102,7 @@ func newMD(path string) (MDDevice, error) { dev.Size = size //RAID array state - state, err := ioutil.ReadFile(filepath.Join(path, "md", "array_state")) + state, err := os.ReadFile(filepath.Join(path, "md", "array_state")) if err != nil { return dev, fmt.Errorf("could not open array_state: %w", err) } @@ -115,7 +115,7 @@ func newMD(path string) (MDDevice, error) { } dev.DiskStates = disks - level, err := ioutil.ReadFile(filepath.Join(path, "md", "level")) + level, err := os.ReadFile(filepath.Join(path, "md", "level")) if err != nil { return dev, fmt.Errorf("could not get raid level: %w", err) } @@ -126,7 +126,7 @@ func newMD(path string) (MDDevice, error) { //Get the sync action //Will be idle if nothing is going on - syncAction, err := ioutil.ReadFile(filepath.Join(path, "md", "sync_action")) + syncAction, err := os.ReadFile(filepath.Join(path, "md", "sync_action")) if err != nil { return dev, fmt.Errorf("could not open sync_action: %w", err) } @@ -187,7 +187,7 @@ func getDisks(path string) (DiskStates, error) { } func getDisk(path string) (string, error) { - state, err := ioutil.ReadFile(filepath.Join(path, "state")) + state, err := os.ReadFile(filepath.Join(path, "state")) if err != nil { return "", fmt.Errorf("error getting disk state: %w", err) } diff --git a/metricbeat/module/traefik/health/health_test.go b/metricbeat/module/traefik/health/health_test.go index d6edbd5fe3d..5b2a1c1ec70 100644 --- a/metricbeat/module/traefik/health/health_test.go +++ b/metricbeat/module/traefik/health/health_test.go @@ -21,9 +21,9 @@ package health import ( "fmt" - "io/ioutil" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/assert" @@ -35,7 +35,7 @@ import ( ) func TestFetchEventContents(t *testing.T) { - mockResponse, err := ioutil.ReadFile("./_meta/test/simple.json") + mockResponse, err := os.ReadFile("./_meta/test/simple.json") assert.NoError(t, err) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/metricbeat/module/uwsgi/status/status.go b/metricbeat/module/uwsgi/status/status.go index 8ade1df3a8d..79cf0fad039 100644 --- a/metricbeat/module/uwsgi/status/status.go +++ b/metricbeat/module/uwsgi/status/status.go @@ -21,7 +21,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -89,7 +88,7 @@ func fetchStatData(URL string) ([]byte, error) { return nil, errors.New("unknown scheme") } - data, err := ioutil.ReadAll(reader) + data, err := io.ReadAll(reader) if err != nil { return nil, fmt.Errorf("uwsgi data read failed: %w", err) } diff --git a/metricbeat/module/uwsgi/status/status_linux_test.go b/metricbeat/module/uwsgi/status/status_linux_test.go index bbd84faf85a..1a61c90a676 100644 --- a/metricbeat/module/uwsgi/status/status_linux_test.go +++ b/metricbeat/module/uwsgi/status/status_linux_test.go @@ -18,7 +18,6 @@ package status import ( - "io/ioutil" "net" "os" "sync" @@ -30,7 +29,7 @@ import ( ) func TestFetchDataUnixSock(t *testing.T) { - tmpfile, err := ioutil.TempFile("", "mb_uwsgi_status") + tmpfile, err := os.CreateTemp("", "mb_uwsgi_status") assert.NoError(t, err) fname := tmpfile.Name() os.Remove(fname) diff --git a/metricbeat/module/uwsgi/status/status_test.go b/metricbeat/module/uwsgi/status/status_test.go index f8ab2133e86..e222f340d79 100644 --- a/metricbeat/module/uwsgi/status/status_test.go +++ b/metricbeat/module/uwsgi/status/status_test.go @@ -18,10 +18,10 @@ package status import ( - "io/ioutil" "net" "net/http" "net/http/httptest" + "os" "path/filepath" "sync" "testing" @@ -40,7 +40,7 @@ func testData(t *testing.T) (data []byte) { return } - data, err = ioutil.ReadFile(filepath.Join(absPath, "/data.json")) + data, err = os.ReadFile(filepath.Join(absPath, "/data.json")) if err != nil { t.Fatalf("ReadFile failed: %s", err.Error()) return diff --git a/metricbeat/module/zookeeper/zookeeper.go b/metricbeat/module/zookeeper/zookeeper.go index 3c8c4573177..a869fa0b355 100644 --- a/metricbeat/module/zookeeper/zookeeper.go +++ b/metricbeat/module/zookeeper/zookeeper.go @@ -26,7 +26,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "strings" "time" @@ -55,7 +54,7 @@ func RunCommand(command, address string, timeout time.Duration) (io.Reader, erro return nil, fmt.Errorf("writing command '%s' failed: %w", command, err) } - result, err := ioutil.ReadAll(conn) + result, err := io.ReadAll(conn) if err != nil { return nil, fmt.Errorf("read failed: %w", err) } diff --git a/metricbeat/scripts/mage/docs_collector.go b/metricbeat/scripts/mage/docs_collector.go index 9d270905e6c..ea83300edc1 100644 --- a/metricbeat/scripts/mage/docs_collector.go +++ b/metricbeat/scripts/mage/docs_collector.go @@ -20,7 +20,6 @@ package mage import ( "encoding/json" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -166,7 +165,7 @@ func getDefaultMetricsets() (map[string][]string, error) { // loadModuleFields loads the module-specific fields.yml file func loadModuleFields(file string) (moduleData, error) { - fd, err := ioutil.ReadFile(file) + fd, err := os.ReadFile(file) if err != nil { return moduleData{}, fmt.Errorf("failed to read from spec file: %w", err) } @@ -188,7 +187,7 @@ func loadModuleFields(file string) (moduleData, error) { // getReleaseState gets the release tag in the metricset-level fields.yml, since that's all we need from that file func getReleaseState(metricsetPath string) (string, error) { - raw, err := ioutil.ReadFile(metricsetPath) + raw, err := os.ReadFile(metricsetPath) if err != nil { return "", fmt.Errorf("failed to read from spec file: %w", err) } @@ -233,7 +232,7 @@ func getConfigfile(modulePath string) (string, error) { return "", fmt.Errorf("could not find a config file in %s", modulePath) } - raw, err := ioutil.ReadFile(goodPath) + raw, err := os.ReadFile(goodPath) return string(raw), err } @@ -330,7 +329,7 @@ func gatherData(modules []string) ([]moduleData, error) { } //dump the contents of the module asciidoc - moduleDoc, err := ioutil.ReadFile(filepath.Join(module, "_meta/docs.asciidoc")) + moduleDoc, err := os.ReadFile(filepath.Join(module, "_meta/docs.asciidoc")) if err != nil { return moduleList, err } diff --git a/packetbeat/procs/procs_linux_test.go b/packetbeat/procs/procs_linux_test.go index 3923bc21109..ead75c41a3c 100644 --- a/packetbeat/procs/procs_linux_test.go +++ b/packetbeat/procs/procs_linux_test.go @@ -20,7 +20,6 @@ package procs import ( - "io/ioutil" "os" "path/filepath" "testing" @@ -44,7 +43,7 @@ func TestFindSocketsOfPid(t *testing.T) { } // Create fake proc file system - pathPrefix, err := ioutil.TempDir("", "find-sockets") + pathPrefix, err := os.MkdirTemp("", "find-sockets") if err != nil { t.Error("TempDir failed:", err) return @@ -116,7 +115,7 @@ func createFakeDirectoryStructure(prefix string, files []testProcFile) error { } if !file.isLink { - err = ioutil.WriteFile(filepath.Join(prefix, file.path), + err = os.WriteFile(filepath.Join(prefix, file.path), []byte(file.contents), 0o644) if err != nil { return err diff --git a/packetbeat/protos/thrift/thrift_idl_test.go b/packetbeat/protos/thrift/thrift_idl_test.go index 1dd39a99916..f45d0eca405 100644 --- a/packetbeat/protos/thrift/thrift_idl_test.go +++ b/packetbeat/protos/thrift/thrift_idl_test.go @@ -18,7 +18,6 @@ package thrift import ( - "io/ioutil" "os" "testing" @@ -26,7 +25,7 @@ import ( ) func thriftIdlForTesting(t *testing.T, content string) *thriftIdl { - f, _ := ioutil.TempFile("", "") + f, _ := os.CreateTemp("", "") defer os.Remove(f.Name()) f.WriteString(content) diff --git a/winlogbeat/checkpoint/checkpoint.go b/winlogbeat/checkpoint/checkpoint.go index efaf4ef71a7..e450d1b040a 100644 --- a/winlogbeat/checkpoint/checkpoint.go +++ b/winlogbeat/checkpoint/checkpoint.go @@ -22,7 +22,6 @@ package checkpoint import ( "fmt" - "io/ioutil" "os" "path/filepath" "sort" @@ -267,7 +266,7 @@ func (c *Checkpoint) read() (*PersistedState, error) { c.fileLock.RLock() defer c.fileLock.RUnlock() - contents, err := ioutil.ReadFile(c.file) + contents, err := os.ReadFile(c.file) if err != nil { if os.IsNotExist(err) { err = nil diff --git a/winlogbeat/checkpoint/checkpoint_test.go b/winlogbeat/checkpoint/checkpoint_test.go index 4724d64f921..f29b8e5280f 100644 --- a/winlogbeat/checkpoint/checkpoint_test.go +++ b/winlogbeat/checkpoint/checkpoint_test.go @@ -20,7 +20,6 @@ package checkpoint import ( - "io/ioutil" "os" "path/filepath" "runtime" @@ -58,7 +57,7 @@ func eventually(t *testing.T, predicate func() (bool, error), timeout time.Durat // Test that a write is triggered when the maximum time period since the last // write is reached. func TestWriteTimedFlush(t *testing.T) { - dir, err := ioutil.TempDir("", "wlb-checkpoint-test") + dir, err := os.MkdirTemp("", "wlb-checkpoint-test") if err != nil { t.Fatal(err) } @@ -103,7 +102,7 @@ func TestWriteTimedFlush(t *testing.T) { // Test that createDir creates the directory with 0750 permissions. func TestCreateDir(t *testing.T) { - dir, err := ioutil.TempDir("", "wlb-checkpoint-test") + dir, err := os.MkdirTemp("", "wlb-checkpoint-test") if err != nil { t.Fatal(err) } @@ -142,7 +141,7 @@ func TestCreateDir(t *testing.T) { // Test createDir when the directory already exists to verify that no error is // returned. func TestCreateDirAlreadyExists(t *testing.T) { - dir, err := ioutil.TempDir("", "wlb-checkpoint-test") + dir, err := os.MkdirTemp("", "wlb-checkpoint-test") if err != nil { t.Fatal(err) } diff --git a/winlogbeat/scripts/mage/docs.go b/winlogbeat/scripts/mage/docs.go index 510ae7558ec..ec119d70c8c 100644 --- a/winlogbeat/scripts/mage/docs.go +++ b/winlogbeat/scripts/mage/docs.go @@ -19,7 +19,6 @@ package mage import ( "fmt" - "io/ioutil" "os" "path/filepath" "regexp" @@ -89,5 +88,5 @@ func moduleDocs() error { } fmt.Printf(">> update:moduleDocs: Collecting module documentation for %v.\n", strings.Join(names, ", ")) - return ioutil.WriteFile(mage.OSSBeatDir("docs/modules_list.asciidoc"), []byte(content), 0o644) + return os.WriteFile(mage.OSSBeatDir("docs/modules_list.asciidoc"), []byte(content), 0o644) } diff --git a/x-pack/auditbeat/module/system/login/login_test.go b/x-pack/auditbeat/module/system/login/login_test.go index d929a6f88d4..755c3d2adf0 100644 --- a/x-pack/auditbeat/module/system/login/login_test.go +++ b/x-pack/auditbeat/module/system/login/login_test.go @@ -9,7 +9,6 @@ package login import ( "encoding/binary" "io" - "io/ioutil" "net" "os" "path/filepath" @@ -276,7 +275,7 @@ func getBaseConfig() map[string]interface{} { // setupTestDir creates a temporary directory, copies the test files into it, // and returns the path. func setupTestDir(t *testing.T) string { - tmp, err := ioutil.TempDir("", "auditbeat-login-test-dir") + tmp, err := os.MkdirTemp("", "auditbeat-login-test-dir") if err != nil { t.Fatal("failed to create temp dir") } @@ -287,7 +286,7 @@ func setupTestDir(t *testing.T) string { } func copyDir(t *testing.T, src, dst string) { - files, err := ioutil.ReadDir(src) + files, err := os.ReadDir(src) if err != nil { t.Fatalf("failed to read %v", src) } diff --git a/x-pack/auditbeat/tracing/cpu.go b/x-pack/auditbeat/tracing/cpu.go index e0fd15e09ce..19e0d9993ca 100644 --- a/x-pack/auditbeat/tracing/cpu.go +++ b/x-pack/auditbeat/tracing/cpu.go @@ -9,7 +9,7 @@ package tracing import ( "bytes" "fmt" - "io/ioutil" + "os" "strconv" "strings" ) @@ -72,7 +72,7 @@ func (s CPUSet) AsList() []int { // NewCPUSetFromFile creates a new CPUSet from the contents of a file. func NewCPUSetFromFile(path string) (cpus CPUSet, err error) { - contents, err := ioutil.ReadFile(path) + contents, err := os.ReadFile(path) if err != nil { return cpus, err } diff --git a/x-pack/auditbeat/tracing/events_test.go b/x-pack/auditbeat/tracing/events_test.go index d89f4946ca1..d16a9d58bcb 100644 --- a/x-pack/auditbeat/tracing/events_test.go +++ b/x-pack/auditbeat/tracing/events_test.go @@ -9,7 +9,6 @@ package tracing import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" "strings" @@ -301,7 +300,7 @@ func TestKProbeReal(t *testing.T) { func TestKProbeEventsList(t *testing.T) { // Make dir to monitor. - tmpDir, err := ioutil.TempDir("", "events_test") + tmpDir, err := os.MkdirTemp("", "events_test") if err != nil { t.Fatal(err) } @@ -358,7 +357,7 @@ w:future feature func TestKProbeEventsAddRemoveKProbe(t *testing.T) { // Make dir to monitor. - tmpDir, err := ioutil.TempDir("", "events_test") + tmpDir, err := os.MkdirTemp("", "events_test") if err != nil { t.Fatal(err) } @@ -397,7 +396,7 @@ w:future feature off, err := file.Seek(int64(0), io.SeekStart) assert.NoError(t, err) assert.Equal(t, int64(0), off) - contents, err := ioutil.ReadAll(file) + contents, err := io.ReadAll(file) assert.NoError(t, err) expected := append([]byte(baseContents), []byte( `p:kprobe/myprobe sys_open path=+0(%di):string mode=%si diff --git a/x-pack/dockerlogbeat/magefile.go b/x-pack/dockerlogbeat/magefile.go index 73da67186d7..c813bcaa125 100644 --- a/x-pack/dockerlogbeat/magefile.go +++ b/x-pack/dockerlogbeat/magefile.go @@ -11,7 +11,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path/filepath" "runtime" @@ -93,7 +92,7 @@ func createContainer(ctx context.Context, cli *client.Client, arch string) error } // start to build the root container that'll be used to build the plugin - tmpDir, err := ioutil.TempDir("", "dockerBuildTar") + tmpDir, err := os.MkdirTemp("", "dockerBuildTar") if err != nil { return fmt.Errorf("error locating temp dir: %w", err) } @@ -122,7 +121,7 @@ func createContainer(ctx context.Context, cli *client.Client, arch string) error } defer buildResp.Body.Close() // This blocks until the build operation completes - buildStr, errBufRead := ioutil.ReadAll(buildResp.Body) + buildStr, errBufRead := io.ReadAll(buildResp.Body) if errBufRead != nil { return fmt.Errorf("error reading from docker output: %w", errBufRead) } diff --git a/x-pack/dockerlogbeat/pipelinemock/reader.go b/x-pack/dockerlogbeat/pipelinemock/reader.go index 263e1ff2f78..ff51cc5fbb1 100644 --- a/x-pack/dockerlogbeat/pipelinemock/reader.go +++ b/x-pack/dockerlogbeat/pipelinemock/reader.go @@ -8,7 +8,6 @@ import ( "bytes" "encoding/binary" "io" - "io/ioutil" "testing" "github.com/docker/docker/api/types/plugins/logdriver" @@ -33,7 +32,7 @@ func CreateTestInputFromLine(t *testing.T, line string) io.ReadCloser { writer := new(bytes.Buffer) encodeLog(t, writer, exampleStruct) - return ioutil.NopCloser(writer) + return io.NopCloser(writer) } func encodeLog(t *testing.T, out io.Writer, entry *logdriver.LogEntry) { diff --git a/x-pack/dockerlogbeat/pipereader/reader.go b/x-pack/dockerlogbeat/pipereader/reader.go index 6ca20f301b3..49b8367c888 100644 --- a/x-pack/dockerlogbeat/pipereader/reader.go +++ b/x-pack/dockerlogbeat/pipereader/reader.go @@ -9,7 +9,6 @@ import ( "encoding/binary" "fmt" "io" - "io/ioutil" "syscall" "github.com/containerd/fifo" @@ -61,7 +60,7 @@ func (reader *PipeReader) ReadMessage(log *logdriver.LogEntry) error { } // 2) we have a too-large message. Disregard length bytes - _, err = io.CopyBuffer(ioutil.Discard, io.LimitReader(reader.fifoPipe, int64(lenFrame)), reader.bodyBuf) + _, err = io.CopyBuffer(io.Discard, io.LimitReader(reader.fifoPipe, int64(lenFrame)), reader.bodyBuf) if err != nil { return fmt.Errorf("error emptying buffer: %w", err) } diff --git a/x-pack/filebeat/input/awscloudwatch/input_integration_test.go b/x-pack/filebeat/input/awscloudwatch/input_integration_test.go index f3a45fb5c40..1e94f640891 100644 --- a/x-pack/filebeat/input/awscloudwatch/input_integration_test.go +++ b/x-pack/filebeat/input/awscloudwatch/input_integration_test.go @@ -12,7 +12,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -57,7 +56,7 @@ func getTerraformOutputs(t *testing.T) terraformOutputData { t.Helper() _, filename, _, _ := runtime.Caller(0) - ymlData, err := ioutil.ReadFile(path.Join(path.Dir(filename), terraformOutputYML)) + ymlData, err := os.ReadFile(path.Join(path.Dir(filename), terraformOutputYML)) if os.IsNotExist(err) { t.Skipf("Run 'terraform apply' in %v to setup CloudWatch log groups and log streams for the test.", filepath.Dir(terraformOutputYML)) } diff --git a/x-pack/filebeat/input/awss3/input_benchmark_test.go b/x-pack/filebeat/input/awss3/input_benchmark_test.go index e05e5b461ca..106910956b5 100644 --- a/x-pack/filebeat/input/awss3/input_benchmark_test.go +++ b/x-pack/filebeat/input/awss3/input_benchmark_test.go @@ -8,7 +8,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -132,7 +131,7 @@ type constantS3 struct { var _ s3API = (*constantS3)(nil) func newConstantS3(t testing.TB) *constantS3 { - data, err := ioutil.ReadFile(cloudtrailTestFile) + data, err := os.ReadFile(cloudtrailTestFile) if err != nil { t.Fatal(err) } diff --git a/x-pack/filebeat/input/awss3/input_integration_test.go b/x-pack/filebeat/input/awss3/input_integration_test.go index 62cbc835011..58f03e77687 100644 --- a/x-pack/filebeat/input/awss3/input_integration_test.go +++ b/x-pack/filebeat/input/awss3/input_integration_test.go @@ -12,7 +12,6 @@ import ( "bytes" "context" "fmt" - "io/ioutil" "os" "path" "path/filepath" @@ -64,7 +63,7 @@ func getTerraformOutputs(t *testing.T, isLocalStack bool) terraformOutputData { outputFile = terraformOutputYML } - ymlData, err := ioutil.ReadFile(path.Join(path.Dir(filename), outputFile)) + ymlData, err := os.ReadFile(path.Join(path.Dir(filename), outputFile)) if os.IsNotExist(err) { t.Skipf("Run 'terraform apply' in %v to setup S3 and SQS for the test.", filepath.Dir(outputFile)) } @@ -365,7 +364,7 @@ func uploadS3TestFiles(t *testing.T, region, bucket string, s3Client *s3.Client, _, basefile, _, _ := runtime.Caller(0) basedir := path.Dir(basefile) for _, filename := range filenames { - data, err := ioutil.ReadFile(path.Join(basedir, filename)) + data, err := os.ReadFile(path.Join(basedir, filename)) if err != nil { t.Fatalf("Failed to open file %q, %v", filename, err) } diff --git a/x-pack/filebeat/input/awss3/s3_objects_test.go b/x-pack/filebeat/input/awss3/s3_objects_test.go index 6732c12e057..f8ad084a4d6 100644 --- a/x-pack/filebeat/input/awss3/s3_objects_test.go +++ b/x-pack/filebeat/input/awss3/s3_objects_test.go @@ -8,7 +8,8 @@ import ( "bytes" "context" "errors" - "io/ioutil" + "io" + "os" "path/filepath" "strings" "testing" @@ -27,7 +28,7 @@ import ( ) func newS3Object(t testing.TB, filename, contentType string) (s3EventV2, *s3.GetObjectOutput) { - data, err := ioutil.ReadFile(filename) + data, err := os.ReadFile(filename) if err != nil { t.Fatal(err) } @@ -39,7 +40,7 @@ func newS3GetObjectResponse(filename string, data []byte, contentType string) *s r := bytes.NewReader(data) getObjectOutput := s3.GetObjectOutput{} getObjectOutput.ContentLength = int64(r.Len()) - getObjectOutput.Body = ioutil.NopCloser(r) + getObjectOutput.Body = io.NopCloser(r) if contentType != "" { getObjectOutput.ContentType = &contentType } diff --git a/x-pack/filebeat/input/gcppubsub/pubsub_test.go b/x-pack/filebeat/input/gcppubsub/pubsub_test.go index bceff5dc3c0..7981a3ee772 100644 --- a/x-pack/filebeat/input/gcppubsub/pubsub_test.go +++ b/x-pack/filebeat/input/gcppubsub/pubsub_test.go @@ -7,7 +7,7 @@ package gcppubsub import ( "context" "errors" - "io/ioutil" + "io" "net/http" "os" "strconv" @@ -70,7 +70,7 @@ func testSetup(t *testing.T) (*pubsub.Client, context.CancelFunc) { } defer resp.Body.Close() - _, err = ioutil.ReadAll(resp.Body) + _, err = io.ReadAll(resp.Body) if err != nil { t.Fatal("failed to read response", err) } diff --git a/x-pack/filebeat/input/netflow/decoder/config/config.go b/x-pack/filebeat/input/netflow/decoder/config/config.go index 3f750fd9fef..f0d2862d771 100644 --- a/x-pack/filebeat/input/netflow/decoder/config/config.go +++ b/x-pack/filebeat/input/netflow/decoder/config/config.go @@ -6,7 +6,6 @@ package config import ( "io" - "io/ioutil" "time" "github.com/elastic/beats/v7/x-pack/filebeat/input/netflow/decoder/fields" @@ -24,7 +23,7 @@ type Config struct { var defaultCfg = Config{ protocols: []string{}, - logOutput: ioutil.Discard, + logOutput: io.Discard, expiration: time.Hour, detectReset: true, sharedTemplates: false, diff --git a/x-pack/filebeat/input/netflow/decoder/v9/session_test.go b/x-pack/filebeat/input/netflow/decoder/v9/session_test.go index 80c91845c0a..d6495e7100f 100644 --- a/x-pack/filebeat/input/netflow/decoder/v9/session_test.go +++ b/x-pack/filebeat/input/netflow/decoder/v9/session_test.go @@ -5,7 +5,7 @@ package v9 import ( - "io/ioutil" + "io" "log" "math" "sync" @@ -18,7 +18,7 @@ import ( "github.com/elastic/beats/v7/x-pack/filebeat/input/netflow/decoder/test" ) -var logger = log.New(ioutil.Discard, "", 0) +var logger = log.New(io.Discard, "", 0) func makeSessionKey(t testing.TB, ipPortPair string, domain uint32) SessionKey { return MakeSessionKey(test.MakeAddress(t, ipPortPair), domain, false) @@ -101,7 +101,7 @@ func testTemplate(id uint16) *template.Template { } func TestSessionState(t *testing.T) { - logger := log.New(ioutil.Discard, "", 0) + logger := log.New(io.Discard, "", 0) t.Run("create and get", func(t *testing.T) { s := NewSession(logger) t1 := testTemplate(1) @@ -180,7 +180,7 @@ func TestSessionMap_Cleanup(t *testing.T) { func TestSessionMap_CleanupLoop(t *testing.T) { timeout := time.Millisecond * 100 - sm := NewSessionMap(log.New(ioutil.Discard, "", 0)) + sm := NewSessionMap(log.New(io.Discard, "", 0)) key := makeSessionKey(t, "127.0.0.1:1", 42) s := sm.GetOrCreate(key) diff --git a/x-pack/filebeat/input/netflow/definitions.go b/x-pack/filebeat/input/netflow/definitions.go index 62e6dc3f1b0..a5ed094d8ff 100644 --- a/x-pack/filebeat/input/netflow/definitions.go +++ b/x-pack/filebeat/input/netflow/definitions.go @@ -7,7 +7,7 @@ package netflow import ( "errors" "fmt" - "io/ioutil" + "io" "math" "os" "strconv" @@ -95,7 +95,7 @@ func LoadFieldDefinitionsFromFile(path string) (defs fields.FieldDict, err error return nil, err } defer file.Close() - contents, err := ioutil.ReadAll(file) + contents, err := io.ReadAll(file) if err != nil { return nil, err } diff --git a/x-pack/filebeat/input/netflow/fields_gen.go b/x-pack/filebeat/input/netflow/fields_gen.go index 519e945eba0..9cebc253f0b 100644 --- a/x-pack/filebeat/input/netflow/fields_gen.go +++ b/x-pack/filebeat/input/netflow/fields_gen.go @@ -13,7 +13,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "log" "os" "sort" @@ -119,7 +118,7 @@ func generateFieldsYml(args []string) error { } defer headerHandle.Close() - fileHeader, err := ioutil.ReadAll(headerHandle) + fileHeader, err := io.ReadAll(headerHandle) if err != nil { return fmt.Errorf("failed to read header %s: %v", *header, err) } diff --git a/x-pack/filebeat/input/netflow/netflow_test.go b/x-pack/filebeat/input/netflow/netflow_test.go index b567d67bc43..24ec2f5de19 100644 --- a/x-pack/filebeat/input/netflow/netflow_test.go +++ b/x-pack/filebeat/input/netflow/netflow_test.go @@ -9,7 +9,6 @@ import ( "encoding/binary" "encoding/json" "flag" - "io/ioutil" "net" "os" "path/filepath" @@ -83,7 +82,7 @@ func TestPCAPFiles(t *testing.T) { t.Fatal(err) } - err = ioutil.WriteFile(goldenName, data, 0o644) + err = os.WriteFile(goldenName, data, 0o644) if err != nil { t.Fatal(err) } @@ -115,7 +114,7 @@ func TestDatFiles(t *testing.T) { t.Fatal(err) } - err = ioutil.WriteFile(goldenName, data, 0o644) + err = os.WriteFile(goldenName, data, 0o644) if err != nil { t.Fatal(err) } @@ -141,7 +140,7 @@ func TestDatFiles(t *testing.T) { } func readDatTests(t testing.TB) *DatTests { - data, err := ioutil.ReadFile("testdata/dat_tests.yaml") + data, err := os.ReadFile("testdata/dat_tests.yaml") if err != nil { t.Fatal(err) } @@ -179,7 +178,7 @@ func getFlowsFromDat(t testing.TB, name string, testCase TestCase) TestResult { source := test.MakeAddress(t, datSourceIP+":4444") var events []beat.Event for _, f := range testCase.Files { - dat, err := ioutil.ReadFile(filepath.Join(datDir, f)) + dat, err := os.ReadFile(filepath.Join(datDir, f)) if err != nil { t.Fatal(err) } @@ -268,7 +267,7 @@ func normalize(t testing.TB, result TestResult) TestResult { } func readGoldenFile(t testing.TB, file string) TestResult { - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { t.Fatal(err) } diff --git a/x-pack/filebeat/input/o365audit/listblobs.go b/x-pack/filebeat/input/o365audit/listblobs.go index 58437b9f614..a46c002344a 100644 --- a/x-pack/filebeat/input/o365audit/listblobs.go +++ b/x-pack/filebeat/input/o365audit/listblobs.go @@ -8,7 +8,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "sort" "time" @@ -278,7 +278,7 @@ func readJSONBody(response *http.Response, dest interface{}) error { defer autorest.Respond(response, autorest.ByDiscardingBody(), autorest.ByClosing()) - body, err := ioutil.ReadAll(response.Body) + body, err := io.ReadAll(response.Body) if err != nil { return fmt.Errorf("reading body failed: %w", err) } diff --git a/x-pack/filebeat/input/o365audit/listblobs_test.go b/x-pack/filebeat/input/o365audit/listblobs_test.go index bcc220b43c0..d86a857c179 100644 --- a/x-pack/filebeat/input/o365audit/listblobs_test.go +++ b/x-pack/filebeat/input/o365audit/listblobs_test.go @@ -8,7 +8,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "sort" "strconv" @@ -107,7 +107,7 @@ func (f *fakePoll) deliverResult(t testing.TB, pl poll.Transaction, msg interfac } response := &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(js)), + Body: io.NopCloser(bytes.NewReader(js)), ContentLength: int64(len(js)), } if nextUrl != "" { @@ -163,7 +163,7 @@ func (f *fakePoll) subscriptionError(t testing.TB, lb listBlob) (subscribe, list t.Log(string(js)) resp := &http.Response{ StatusCode: 400, - Body: ioutil.NopCloser(bytes.NewReader(js)), + Body: io.NopCloser(bytes.NewReader(js)), } for _, a := range lb.OnResponse(resp) { if err := a(f); !assert.NoError(t, err) { diff --git a/x-pack/functionbeat/manager/aws/cli_manager.go b/x-pack/functionbeat/manager/aws/cli_manager.go index 0d70235bb36..cade61ee223 100644 --- a/x-pack/functionbeat/manager/aws/cli_manager.go +++ b/x-pack/functionbeat/manager/aws/cli_manager.go @@ -7,7 +7,6 @@ package aws import ( "context" "fmt" - "io/ioutil" "os" "strings" @@ -191,7 +190,7 @@ func (c *CLIManager) Package(outputPattern string) error { } output := strings.ReplaceAll(outputPattern, "{{.Provider}}", "aws") - err = ioutil.WriteFile(output, content, 0644) + err = os.WriteFile(output, content, 0644) if err != nil { return err } diff --git a/x-pack/functionbeat/manager/core/bundle/bundle.go b/x-pack/functionbeat/manager/core/bundle/bundle.go index f034c4400f4..0ec4b5e6ea5 100644 --- a/x-pack/functionbeat/manager/core/bundle/bundle.go +++ b/x-pack/functionbeat/manager/core/bundle/bundle.go @@ -10,7 +10,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "path/filepath" ) @@ -129,7 +128,7 @@ type MemoryFile struct { // Open the reader for the raw byte slice. func (m *MemoryFile) Open() (io.ReadCloser, error) { reader := bytes.NewReader(m.Raw) - return ioutil.NopCloser(reader), nil + return io.NopCloser(reader), nil } // Name returns the path to use in the zip. diff --git a/x-pack/functionbeat/manager/core/bundle/bundle_test.go b/x-pack/functionbeat/manager/core/bundle/bundle_test.go index 89d010522b7..b24ac2ccd59 100644 --- a/x-pack/functionbeat/manager/core/bundle/bundle_test.go +++ b/x-pack/functionbeat/manager/core/bundle/bundle_test.go @@ -7,7 +7,7 @@ package bundle import ( "archive/zip" "bytes" - "io/ioutil" + "io" "os" "testing" @@ -89,7 +89,7 @@ func testArtifact(maxSizeUncompressed, maxSizeCompressed int64) func(t *testing. } defer reader.Close() - raw, err := ioutil.ReadAll(reader) + raw, err := io.ReadAll(reader) if !assert.NoError(t, err) { return } @@ -115,12 +115,12 @@ func TestLocalFile(t *testing.T) { assert.NoError(t, err) }() - content, err := ioutil.ReadAll(reader) + content, err := io.ReadAll(reader) if !assert.NoError(t, err) { return } - raw, _ := ioutil.ReadFile("testdata/lipsum.txt") + raw, _ := os.ReadFile("testdata/lipsum.txt") assert.Equal(t, raw, content) } @@ -141,7 +141,7 @@ func TestMemoryFile(t *testing.T) { assert.NoError(t, err) }() - content, err := ioutil.ReadAll(reader) + content, err := io.ReadAll(reader) if !assert.NoError(t, err) { return } diff --git a/x-pack/heartbeat/monitors/browser/source/project.go b/x-pack/heartbeat/monitors/browser/source/project.go index 7c11de31134..031335950cf 100644 --- a/x-pack/heartbeat/monitors/browser/source/project.go +++ b/x-pack/heartbeat/monitors/browser/source/project.go @@ -11,7 +11,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "os" "os/exec" "path/filepath" @@ -55,7 +54,7 @@ func (p *ProjectSource) Fetch() error { return err } - tf, err := ioutil.TempFile(os.TempDir(), "elastic-synthetics-zip-") + tf, err := os.CreateTemp(os.TempDir(), "elastic-synthetics-zip-") if err != nil { return fmt.Errorf("could not create tmpfile for project monitor source: %w", err) } @@ -67,7 +66,7 @@ func (p *ProjectSource) Fetch() error { return err } - p.TargetDirectory, err = ioutil.TempDir(os.TempDir(), "elastic-synthetics-unzip-") + p.TargetDirectory, err = os.MkdirTemp(os.TempDir(), "elastic-synthetics-unzip-") if err != nil { return fmt.Errorf("could not make temp dir for unzipping project source: %w", err) } @@ -132,7 +131,7 @@ func setupProjectDir(workdir string) error { if err != nil { return err } - err = ioutil.WriteFile(filepath.Join(workdir, "package.json"), pkgJsonContent, defaultMod) + err = os.WriteFile(filepath.Join(workdir, "package.json"), pkgJsonContent, defaultMod) if err != nil { return err } diff --git a/x-pack/libbeat/common/cloudfoundry/main_test.go b/x-pack/libbeat/common/cloudfoundry/main_test.go index 1909adb3f93..2e28c83959f 100644 --- a/x-pack/libbeat/common/cloudfoundry/main_test.go +++ b/x-pack/libbeat/common/cloudfoundry/main_test.go @@ -6,7 +6,6 @@ package cloudfoundry import ( "fmt" - "io/ioutil" "os" "testing" @@ -15,7 +14,7 @@ import ( func TestMain(m *testing.M) { // Override global beats data dir to avoid creating directories in the working copy. - tmpdir, err := ioutil.TempDir("", "beats-data-dir") + tmpdir, err := os.MkdirTemp("", "beats-data-dir") if err != nil { fmt.Printf("Failed to create temporal data directory: %v\n", err) os.Exit(1) diff --git a/x-pack/libbeat/persistentcache/persistentcache_test.go b/x-pack/libbeat/persistentcache/persistentcache_test.go index 416905d2e40..d974bce5e19 100644 --- a/x-pack/libbeat/persistentcache/persistentcache_test.go +++ b/x-pack/libbeat/persistentcache/persistentcache_test.go @@ -6,7 +6,6 @@ package persistentcache import ( "fmt" - "io/ioutil" "math/rand" "os" "path/filepath" @@ -408,7 +407,7 @@ func BenchmarkGet(b *testing.B) { func testOptions(t testing.TB) Options { t.Helper() - tempDir, err := ioutil.TempDir("", "beat-data-dir-") + tempDir, err := os.MkdirTemp("", "beat-data-dir-") require.NoError(t, err) t.Cleanup(func() { os.RemoveAll(tempDir) }) diff --git a/x-pack/libbeat/persistentcache/store_test.go b/x-pack/libbeat/persistentcache/store_test.go index 9ff31d2a179..7aa811c2026 100644 --- a/x-pack/libbeat/persistentcache/store_test.go +++ b/x-pack/libbeat/persistentcache/store_test.go @@ -5,7 +5,6 @@ package persistentcache import ( - "io/ioutil" "os" "testing" @@ -23,7 +22,7 @@ func TestStandaloneStore(t *testing.T) { var key = []byte("somekey") var value = []byte("somevalue") - tempDir, err := ioutil.TempDir("", "beat-data-dir-") + tempDir, err := os.MkdirTemp("", "beat-data-dir-") require.NoError(t, err) t.Cleanup(func() { os.RemoveAll(tempDir) }) diff --git a/x-pack/metricbeat/module/awsfargate/task_stats/task_stats.go b/x-pack/metricbeat/module/awsfargate/task_stats/task_stats.go index 39ed9ba85bb..e37e170188d 100644 --- a/x-pack/metricbeat/module/awsfargate/task_stats/task_stats.go +++ b/x-pack/metricbeat/module/awsfargate/task_stats/task_stats.go @@ -8,7 +8,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "os" "time" @@ -165,9 +165,9 @@ func (m *MetricSet) queryTaskMetadataEndpoints() ([]Stats, error) { } func getTaskStats(taskStatsResp *http.Response) (map[string]types.StatsJSON, error) { - taskStatsBody, err := ioutil.ReadAll(taskStatsResp.Body) + taskStatsBody, err := io.ReadAll(taskStatsResp.Body) if err != nil { - return nil, fmt.Errorf("ioutil.ReadAll failed: %w", err) + return nil, fmt.Errorf("io.ReadAll failed: %w", err) } var taskStatsOutput map[string]types.StatsJSON @@ -179,9 +179,9 @@ func getTaskStats(taskStatsResp *http.Response) (map[string]types.StatsJSON, err } func getTask(taskResp *http.Response) (TaskMetadata, error) { - taskBody, err := ioutil.ReadAll(taskResp.Body) + taskBody, err := io.ReadAll(taskResp.Body) if err != nil { - return TaskMetadata{}, fmt.Errorf("ioutil.ReadAll failed: %w", err) + return TaskMetadata{}, fmt.Errorf("io.ReadAll failed: %w", err) } var taskOutput TaskMetadata diff --git a/x-pack/metricbeat/module/awsfargate/task_stats/task_stats_integration_test.go b/x-pack/metricbeat/module/awsfargate/task_stats/task_stats_integration_test.go index ec5e4ddfab3..112c382c732 100644 --- a/x-pack/metricbeat/module/awsfargate/task_stats/task_stats_integration_test.go +++ b/x-pack/metricbeat/module/awsfargate/task_stats/task_stats_integration_test.go @@ -8,7 +8,7 @@ package task_stats import ( "bytes" - "io/ioutil" + "io" "net/http" "os" "testing" @@ -100,12 +100,12 @@ func TestData(t *testing.T) { // buildResponse is a test helper that loads the content of `filename` and returns // it as the body of a `http.Response`. func buildResponse(filename string) (*http.Response, error) { - fileContent, err := ioutil.ReadFile(filename) + fileContent, err := os.ReadFile(filename) if err != nil { return nil, err } return &http.Response{ - Body: ioutil.NopCloser(bytes.NewReader(fileContent)), + Body: io.NopCloser(bytes.NewReader(fileContent)), }, nil } diff --git a/x-pack/metricbeat/module/gcp/carbon/carbon_test.go b/x-pack/metricbeat/module/gcp/carbon/carbon_test.go index a9b06cdb607..bacab56ff01 100644 --- a/x-pack/metricbeat/module/gcp/carbon/carbon_test.go +++ b/x-pack/metricbeat/module/gcp/carbon/carbon_test.go @@ -6,7 +6,7 @@ package carbon import ( "errors" - "io/ioutil" + "io" "log" "testing" "time" @@ -78,7 +78,7 @@ func TestGetReportMonth(t *testing.T) { } func TestGenerateQuery(t *testing.T) { - log.SetOutput(ioutil.Discard) + log.SetOutput(io.Discard) query := generateQuery("my-table", "jan") diff --git a/x-pack/metricbeat/module/stan/channels/channels_test.go b/x-pack/metricbeat/module/stan/channels/channels_test.go index e78c3907455..1e3775f9960 100644 --- a/x-pack/metricbeat/module/stan/channels/channels_test.go +++ b/x-pack/metricbeat/module/stan/channels/channels_test.go @@ -5,9 +5,9 @@ package channels import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -17,7 +17,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/channels.json") + content, err := os.ReadFile("./_meta/test/channels.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventsMapping(content, reporter) @@ -74,7 +74,7 @@ func TestFetchEventContent(t *testing.T) { func initServer() *httptest.Server { absPath, _ := filepath.Abs("./_meta/test/") - response, _ := ioutil.ReadFile(absPath + "/channels.json") + response, _ := os.ReadFile(absPath + "/channels.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/x-pack/metricbeat/module/stan/stats/stats_test.go b/x-pack/metricbeat/module/stan/stats/stats_test.go index 2e1b19419b9..b8a5e6fd30b 100644 --- a/x-pack/metricbeat/module/stan/stats/stats_test.go +++ b/x-pack/metricbeat/module/stan/stats/stats_test.go @@ -5,9 +5,9 @@ package stats import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -17,7 +17,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/serversz.json") + content, err := os.ReadFile("./_meta/test/serversz.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventMapping(content, reporter) @@ -49,7 +49,7 @@ func TestFetchEventContent(t *testing.T) { func initServer() *httptest.Server { absPath, _ := filepath.Abs("./_meta/test/") - response, _ := ioutil.ReadFile(absPath + "/serversz.json") + response, _ := os.ReadFile(absPath + "/serversz.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/x-pack/metricbeat/module/stan/subscriptions/subscriptions_test.go b/x-pack/metricbeat/module/stan/subscriptions/subscriptions_test.go index c97343ab05a..0a310569e36 100644 --- a/x-pack/metricbeat/module/stan/subscriptions/subscriptions_test.go +++ b/x-pack/metricbeat/module/stan/subscriptions/subscriptions_test.go @@ -5,9 +5,9 @@ package subscriptions import ( - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" @@ -17,7 +17,7 @@ import ( ) func TestEventMapping(t *testing.T) { - content, err := ioutil.ReadFile("./_meta/test/subscriptions.json") + content, err := os.ReadFile("./_meta/test/subscriptions.json") assert.NoError(t, err) reporter := &mbtest.CapturingReporterV2{} err = eventsMapping(content, reporter) @@ -53,7 +53,7 @@ func TestFetchEventContent(t *testing.T) { func initServer() *httptest.Server { absPath, _ := filepath.Abs("./_meta/test/") - response, _ := ioutil.ReadFile(absPath + "/subscriptions.json") + response, _ := os.ReadFile(absPath + "/subscriptions.json") server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) w.Header().Set("Content-Type", "application/json;") diff --git a/x-pack/metricbeat/module/syncgateway/testing.go b/x-pack/metricbeat/module/syncgateway/testing.go index 88c2d309c2a..3b1cd4ece98 100644 --- a/x-pack/metricbeat/module/syncgateway/testing.go +++ b/x-pack/metricbeat/module/syncgateway/testing.go @@ -6,15 +6,15 @@ package syncgateway import ( "fmt" - "io/ioutil" "net/http" + "os" ) func CreateTestMuxer() *http.ServeMux { mux := http.NewServeMux() mux.Handle("/_expvar", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - input, _ := ioutil.ReadFile("../_meta/testdata/expvar.282c.json") + input, _ := os.ReadFile("../_meta/testdata/expvar.282c.json") _, err := w.Write(input) if err != nil { fmt.Println("error writing response on mock server") diff --git a/x-pack/winlogbeat/module/testing.go b/x-pack/winlogbeat/module/testing.go index 3dc628b80a9..303fd244bca 100644 --- a/x-pack/winlogbeat/module/testing.go +++ b/x-pack/winlogbeat/module/testing.go @@ -8,7 +8,6 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" "os" "path/filepath" "reflect" @@ -230,7 +229,7 @@ func writeGolden(t testing.TB, source, dir string, events []mapstr.M) { } outPath := filepath.Join(dir, filepath.Base(source)+".golden.json") - if err := ioutil.WriteFile(outPath, data, 0o644); err != nil { + if err := os.WriteFile(outPath, data, 0o644); err != nil { t.Fatal(err) } } @@ -238,7 +237,7 @@ func writeGolden(t testing.TB, source, dir string, events []mapstr.M) { func readGolden(t testing.TB, source, dir string) []mapstr.M { inPath := filepath.Join(dir, filepath.Base(source)+".golden.json") - data, err := ioutil.ReadFile(inPath) + data, err := os.ReadFile(inPath) if err != nil { t.Fatal(err) }