diff --git a/devenv/docker/blocks/alert_webhook_listener/main.go b/devenv/docker/blocks/alert_webhook_listener/main.go index 8eac84b0faa..4cf9e83a585 100644 --- a/devenv/docker/blocks/alert_webhook_listener/main.go +++ b/devenv/docker/blocks/alert_webhook_listener/main.go @@ -3,14 +3,13 @@ package main import ( "fmt" "io" - "io/ioutil" "log" "net/http" "strings" ) func hello(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { return } diff --git a/pkg/api/avatar/avatar.go b/pkg/api/avatar/avatar.go index 4ff143a67c7..6ba3e485c88 100644 --- a/pkg/api/avatar/avatar.go +++ b/pkg/api/avatar/avatar.go @@ -11,9 +11,9 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "net/http" "net/url" + "os" "path/filepath" "regexp" "strconv" @@ -188,7 +188,7 @@ func newNotFound(cfg *setting.Cfg) *Avatar { // It's safe to ignore gosec warning G304 since the variable part of the file path comes from a configuration // variable. // nolint:gosec - if data, err := ioutil.ReadFile(path); err != nil { + if data, err := os.ReadFile(path); err != nil { alog.Error("Failed to read user_profile.png", "path", path) } else { avatar.data = bytes.NewBuffer(data) diff --git a/pkg/api/dashboard_test.go b/pkg/api/dashboard_test.go index b945132816c..5ce637ba1c8 100644 --- a/pkg/api/dashboard_test.go +++ b/pkg/api/dashboard_test.go @@ -5,8 +5,8 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net/http" + "os" "testing" "github.com/stretchr/testify/assert" @@ -77,7 +77,7 @@ func TestGetHomeDashboard(t *testing.T) { dash.Meta.IsHome = true dash.Meta.FolderTitle = "General" - homeDashJSON, err := ioutil.ReadFile(tc.expectedDashboardPath) + homeDashJSON, err := os.ReadFile(tc.expectedDashboardPath) require.NoError(t, err, "must be able to read expected dashboard file") hs.Cfg.DefaultHomeDashboardPath = tc.defaultSetting bytes, err := simplejson.NewJson(homeDashJSON) diff --git a/pkg/api/frontend_logging_test.go b/pkg/api/frontend_logging_test.go index 3fcb64dce46..9dfb161a11a 100644 --- a/pkg/api/frontend_logging_test.go +++ b/pkg/api/frontend_logging_test.go @@ -2,7 +2,6 @@ package api import ( "errors" - "io/ioutil" "net/url" "os" "strings" @@ -68,7 +67,7 @@ func logSentryEventScenario(t *testing.T, desc string, event frontendlogging.Fro return nil, errors.New("epic hard drive failure") } if strings.HasSuffix(path, "foo.js.map") { - f, err := ioutil.ReadFile("./frontendlogging/test-data/foo.js.map") + f, err := os.ReadFile("./frontendlogging/test-data/foo.js.map") require.NoError(t, err) return f, nil } @@ -140,7 +139,7 @@ func logGrafanaJavascriptAgentEventScenario(t *testing.T, desc string, event fro return nil, errors.New("epic hard drive failure") } if strings.HasSuffix(path, "foo.js.map") { - f, err := ioutil.ReadFile("./frontendlogging/test-data/foo.js.map") + f, err := os.ReadFile("./frontendlogging/test-data/foo.js.map") require.NoError(t, err) return f, nil } diff --git a/pkg/api/frontendlogging/source_maps.go b/pkg/api/frontendlogging/source_maps.go index 9391ff0fab7..09536c24e5b 100644 --- a/pkg/api/frontendlogging/source_maps.go +++ b/pkg/api/frontendlogging/source_maps.go @@ -1,7 +1,7 @@ package frontendlogging import ( - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -39,7 +39,7 @@ func ReadSourceMapFromFS(dir string, path string) ([]byte, error) { logger.Error("Failed to close source map file", "err", err) } }() - return ioutil.ReadAll(file) + return io.ReadAll(file) } type SourceMapStore struct { diff --git a/pkg/api/login_test.go b/pkg/api/login_test.go index 678a25fcbcd..de7c4915a8a 100644 --- a/pkg/api/login_test.go +++ b/pkg/api/login_test.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "strings" @@ -61,7 +60,7 @@ func fakeViewIndex(t *testing.T) { } func getBody(resp *httptest.ResponseRecorder) (string, error) { - responseData, err := ioutil.ReadAll(resp.Body) + responseData, err := io.ReadAll(resp.Body) if err != nil { return "", err } diff --git a/pkg/api/plugin_dashboards_test.go b/pkg/api/plugin_dashboards_test.go index ae375adc17e..1c5b7c0db1f 100644 --- a/pkg/api/plugin_dashboards_test.go +++ b/pkg/api/plugin_dashboards_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -89,7 +89,7 @@ func TestGetPluginDashboards(t *testing.T) { resp, err := sendGetPluginDashboardsRequestForSignedInUser(t, s, existingPluginID, user) require.NoError(t, err) require.Equal(t, http.StatusOK, resp.StatusCode) - bytes, err := ioutil.ReadAll(resp.Body) + bytes, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) var listResp []*plugindashboards.PluginDashboard diff --git a/pkg/api/plugin_metrics_test.go b/pkg/api/plugin_metrics_test.go index 935434b00ad..03acced669c 100644 --- a/pkg/api/plugin_metrics_test.go +++ b/pkg/api/plugin_metrics_test.go @@ -2,7 +2,7 @@ package api import ( "context" - "io/ioutil" + "io" "net/http" "testing" @@ -39,7 +39,7 @@ func TestPluginMetricsEndpoint(t *testing.T) { require.NoError(t, err) require.NotNil(t, resp) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "http_errors=2", string(body)) require.NoError(t, resp.Body.Close()) @@ -53,7 +53,7 @@ func TestPluginMetricsEndpoint(t *testing.T) { require.NoError(t, err) require.NotNil(t, resp) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Empty(t, string(body)) require.NoError(t, resp.Body.Close()) @@ -106,7 +106,7 @@ func TestPluginMetricsEndpoint(t *testing.T) { require.NoError(t, err) require.NotNil(t, resp) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "http_errors=2", string(body)) require.NoError(t, resp.Body.Close()) diff --git a/pkg/api/plugin_resource.go b/pkg/api/plugin_resource.go index 29505cffa9c..6dfaf912ab4 100644 --- a/pkg/api/plugin_resource.go +++ b/pkg/api/plugin_resource.go @@ -6,7 +6,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "sync" @@ -121,7 +120,7 @@ func (hs *HTTPServer) makePluginResourceRequest(w http.ResponseWriter, req *http proxyutil.ClearCookieHeader(req, keepCookieModel.KeepCookies) proxyutil.PrepareProxyRequest(req) - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) if err != nil { return fmt.Errorf("failed to read request body: %w", err) } diff --git a/pkg/api/pluginproxy/ds_proxy.go b/pkg/api/pluginproxy/ds_proxy.go index 368bb858f06..49dcd8d0daf 100644 --- a/pkg/api/pluginproxy/ds_proxy.go +++ b/pkg/api/pluginproxy/ds_proxy.go @@ -4,7 +4,7 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strconv" @@ -106,7 +106,7 @@ func (proxy *DataSourceProxy) HandleRequest() { modifyResponse := func(resp *http.Response) error { if resp.StatusCode == 401 { // The data source rejected the request as unauthorized, convert to 400 (bad request) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("failed to read data source response body: %w", err) } @@ -118,7 +118,7 @@ func (proxy *DataSourceProxy) HandleRequest() { *resp = http.Response{ StatusCode: 400, Status: "Bad Request", - Body: ioutil.NopCloser(strings.NewReader(msg)), + Body: io.NopCloser(strings.NewReader(msg)), ContentLength: int64(len(msg)), Header: http.Header{}, } @@ -324,9 +324,9 @@ func (proxy *DataSourceProxy) logRequest() { var body string if proxy.ctx.Req.Body != nil { - buffer, err := ioutil.ReadAll(proxy.ctx.Req.Body) + buffer, err := io.ReadAll(proxy.ctx.Req.Body) if err == nil { - proxy.ctx.Req.Body = ioutil.NopCloser(bytes.NewBuffer(buffer)) + proxy.ctx.Req.Body = io.NopCloser(bytes.NewBuffer(buffer)) body = string(buffer) } } diff --git a/pkg/api/pluginproxy/ds_proxy_test.go b/pkg/api/pluginproxy/ds_proxy_test.go index ee7d1ac2181..b1684d3bc5a 100644 --- a/pkg/api/pluginproxy/ds_proxy_test.go +++ b/pkg/api/pluginproxy/ds_proxy_test.go @@ -5,10 +5,11 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "net/url" + "os" "strings" "testing" "time" @@ -176,7 +177,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) { proxy.matchedRoute = routes[5] ApplyRoute(proxy.ctx.Req.Context(), req, proxy.proxyPath, proxy.matchedRoute, dsInfo, cfg) - content, err := ioutil.ReadAll(req.Body) + content, err := io.ReadAll(req.Body) require.NoError(t, err) require.Equal(t, `{ "url": "https://dynamic.grafana.com", "secret": "123" }`, string(content)) }) @@ -275,7 +276,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) { var authorizationHeaderCall2 string t.Run("first call should add authorization header with access token", func(t *testing.T) { - json, err := ioutil.ReadFile("./test-data/access-token-1.json") + json, err := os.ReadFile("./test-data/access-token-1.json") require.NoError(t, err) originalClient := client @@ -303,7 +304,7 @@ func TestDataSourceProxy_routeRule(t *testing.T) { assert.True(t, strings.HasPrefix(authorizationHeaderCall1, "Bearer eyJ0e")) t.Run("second call to another route should add a different access token", func(t *testing.T) { - json2, err := ioutil.ReadFile("./test-data/access-token-2.json") + json2, err := os.ReadFile("./test-data/access-token-2.json") require.NoError(t, err) req, err := http.NewRequest("GET", "http://localhost/asd", nil) @@ -887,7 +888,7 @@ func (c *httpClientStub) Do(req *http.Request) (*http.Response, error) { body, err := bodyJSON.MarshalJSON() require.NoError(c.t, err) resp := &http.Response{ - Body: ioutil.NopCloser(bytes.NewReader(body)), + Body: io.NopCloser(bytes.NewReader(body)), } return resp, nil diff --git a/pkg/api/pluginproxy/pluginproxy.go b/pkg/api/pluginproxy/pluginproxy.go index 3735a34aa1a..694a56bd1a0 100644 --- a/pkg/api/pluginproxy/pluginproxy.go +++ b/pkg/api/pluginproxy/pluginproxy.go @@ -3,7 +3,7 @@ package pluginproxy import ( "bytes" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httputil" "net/url" @@ -107,9 +107,9 @@ func logAppPluginProxyRequest(appID string, cfg *setting.Cfg, c *models.ReqConte var body string if c.Req.Body != nil { - buffer, err := ioutil.ReadAll(c.Req.Body) + buffer, err := io.ReadAll(c.Req.Body) if err == nil { - c.Req.Body = ioutil.NopCloser(bytes.NewBuffer(buffer)) + c.Req.Body = io.NopCloser(bytes.NewBuffer(buffer)) body = string(buffer) } } diff --git a/pkg/api/pluginproxy/pluginproxy_test.go b/pkg/api/pluginproxy/pluginproxy_test.go index 71bf9fe92db..afdae53cc1d 100644 --- a/pkg/api/pluginproxy/pluginproxy_test.go +++ b/pkg/api/pluginproxy/pluginproxy_test.go @@ -2,7 +2,7 @@ package pluginproxy import ( "context" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -241,7 +241,7 @@ func TestPluginProxy(t *testing.T) { route, store, ) - content, err := ioutil.ReadAll(req.Body) + content, err := io.ReadAll(req.Body) require.NoError(t, err) require.Equal(t, `{ "url": "https://dynamic.grafana.com", "secret": "123" }`, string(content)) }) diff --git a/pkg/api/pluginproxy/utils.go b/pkg/api/pluginproxy/utils.go index 27f237a5ca4..05e9c5a33c8 100644 --- a/pkg/api/pluginproxy/utils.go +++ b/pkg/api/pluginproxy/utils.go @@ -3,7 +3,7 @@ package pluginproxy import ( "bytes" "fmt" - "io/ioutil" + "io" "net/http" "strings" "text/template" @@ -78,7 +78,7 @@ func setBodyContent(req *http.Request, route *plugins.Route, data templateData) return err } - req.Body = ioutil.NopCloser(strings.NewReader(interpolatedBody)) + req.Body = io.NopCloser(strings.NewReader(interpolatedBody)) req.ContentLength = int64(len(interpolatedBody)) } diff --git a/pkg/api/plugins.go b/pkg/api/plugins.go index 0f669caa3cc..38278b4cbdb 100644 --- a/pkg/api/plugins.go +++ b/pkg/api/plugins.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "net/http" "os" "path" @@ -466,7 +465,7 @@ func (hs *HTTPServer) pluginMarkdown(ctx context.Context, pluginId string, name // nolint:gosec // We can ignore the gosec G304 warning since we have cleaned the requested file path and subsequently // use this with a prefix of the plugin's directory, which is set during plugin loading - data, err := ioutil.ReadFile(path) + data, err := os.ReadFile(path) if err != nil { return nil, err } diff --git a/pkg/api/plugins_test.go b/pkg/api/plugins_test.go index d36261b7edd..bda3ae0c920 100644 --- a/pkg/api/plugins_test.go +++ b/pkg/api/plugins_test.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -101,9 +100,9 @@ func Test_PluginsInstallAndUninstall(t *testing.T) { func Test_GetPluginAssets(t *testing.T) { pluginID := "test-plugin" pluginDir := "." - tmpFile, err := ioutil.TempFile(pluginDir, "") + tmpFile, err := os.CreateTemp(pluginDir, "") require.NoError(t, err) - tmpFileInParentDir, err := ioutil.TempFile("..", "") + tmpFileInParentDir, err := os.CreateTemp("..", "") require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll(tmpFile.Name()) diff --git a/pkg/api/preferences_test.go b/pkg/api/preferences_test.go index 5796ad1e867..160e36713b8 100644 --- a/pkg/api/preferences_test.go +++ b/pkg/api/preferences_test.go @@ -2,7 +2,7 @@ package api import ( "encoding/json" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -60,7 +60,7 @@ func TestAPIEndpoint_GetCurrentOrgPreferences_LegacyAccessControl(t *testing.T) response := callAPI(sc.server, http.MethodGet, getOrgPreferencesURL, nil, t) assert.Equal(t, http.StatusOK, response.Code) var resp map[string]interface{} - b, err := ioutil.ReadAll(response.Body) + b, err := io.ReadAll(response.Body) assert.NoError(t, err) assert.NoError(t, json.Unmarshal(b, &resp)) assert.Equal(t, "home", resp["homeDashboardUID"]) diff --git a/pkg/build/config/version.go b/pkg/build/config/version.go index 04854ca018d..b13a7da7d95 100644 --- a/pkg/build/config/version.go +++ b/pkg/build/config/version.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "log" "os" "path/filepath" @@ -103,7 +102,7 @@ func shortenBuildID(buildID string) string { func GetGrafanaVersion(buildID, grafanaDir string) (string, error) { pkgJSONPath := filepath.Join(grafanaDir, "package.json") //nolint:gosec - pkgJSONB, err := ioutil.ReadFile(pkgJSONPath) + pkgJSONB, err := os.ReadFile(pkgJSONPath) if err != nil { return "", fmt.Errorf("failed to read %q: %w", pkgJSONPath, err) } diff --git a/pkg/build/cryptoutil/md5.go b/pkg/build/cryptoutil/md5.go index 68dba9233b0..fa4b4fcc5ec 100644 --- a/pkg/build/cryptoutil/md5.go +++ b/pkg/build/cryptoutil/md5.go @@ -4,7 +4,6 @@ import ( "crypto/md5" "fmt" "io" - "io/ioutil" "log" "os" ) @@ -28,7 +27,7 @@ func MD5File(fpath string) error { } // nolint:gosec - if err := ioutil.WriteFile(fpath+".md5", []byte(fmt.Sprintf("%x\n", h.Sum(nil))), 0664); err != nil { + if err := os.WriteFile(fpath+".md5", []byte(fmt.Sprintf("%x\n", h.Sum(nil))), 0664); err != nil { return err } diff --git a/pkg/build/docker/build.go b/pkg/build/docker/build.go index 5a95ec11463..f77d54cd43e 100644 --- a/pkg/build/docker/build.go +++ b/pkg/build/docker/build.go @@ -5,7 +5,6 @@ import ( "encoding/hex" "fmt" "io" - "io/ioutil" "log" "os" "os/exec" @@ -20,7 +19,7 @@ func verifyArchive(archive string) error { log.Printf("Verifying checksum of %q", archive) //nolint:gosec - shaB, err := ioutil.ReadFile(archive + ".sha256") + shaB, err := os.ReadFile(archive + ".sha256") if err != nil { return err } diff --git a/pkg/build/plugins/download.go b/pkg/build/plugins/download.go index 3c3fc56a6ad..6b8dc56264d 100644 --- a/pkg/build/plugins/download.go +++ b/pkg/build/plugins/download.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -54,7 +53,7 @@ func Download(ctx context.Context, grafanaDir string, p syncutil.WorkerPool) err var m pluginsManifest manifestPath := filepath.Join(grafanaDir, "plugins-bundled", "external.json") //nolint:gosec - manifestB, err := ioutil.ReadFile(manifestPath) + manifestB, err := os.ReadFile(manifestPath) if err != nil { return fmt.Errorf("failed to open plugins manifest %q: %w", manifestPath, err) } diff --git a/pkg/build/plugins/manifest.go b/pkg/build/plugins/manifest.go index 037bb176a2c..61174bec105 100644 --- a/pkg/build/plugins/manifest.go +++ b/pkg/build/plugins/manifest.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "log" "net/http" "os" @@ -105,7 +104,7 @@ func BuildManifest(ctx context.Context, dpath string, signingAdmin bool) error { } }() if resp.StatusCode != 200 { - msg, err := ioutil.ReadAll(resp.Body) + msg, err := io.ReadAll(resp.Body) if err != nil { log.Printf("Failed to read response body: %s", err) msg = []byte("") diff --git a/pkg/cmd/grafana-cli/services/api_client.go b/pkg/cmd/grafana-cli/services/api_client.go index fa793d81eb4..8fa93c24390 100644 --- a/pkg/cmd/grafana-cli/services/api_client.go +++ b/pkg/cmd/grafana-cli/services/api_client.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -142,7 +141,7 @@ func sendRequestGetBytes(client http.Client, repoUrl string, subPaths ...string) logger.Warn("Failed to close stream", "err", err) } }() - return ioutil.ReadAll(bodyReader) + return io.ReadAll(bodyReader) } func sendRequest(client http.Client, repoUrl string, subPaths ...string) (io.ReadCloser, error) { @@ -191,7 +190,7 @@ func handleResponse(res *http.Response) (io.ReadCloser, error) { } if res.StatusCode/100 == 4 { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) defer func() { if err := res.Body.Close(); err != nil { logger.Warn("Failed to close response body", "err", err) diff --git a/pkg/cmd/grafana-cli/services/api_client_test.go b/pkg/cmd/grafana-cli/services/api_client_test.go index 5825e670799..2c3cbe83808 100644 --- a/pkg/cmd/grafana-cli/services/api_client_test.go +++ b/pkg/cmd/grafana-cli/services/api_client_test.go @@ -4,7 +4,6 @@ import ( "bytes" "errors" "io" - "io/ioutil" "net/http" "testing" @@ -19,7 +18,7 @@ func TestHandleResponse(t *testing.T) { resp := makeResponse(t, 200, "test") bodyReader, err := handleResponse(resp) require.NoError(t, err) - body, err := ioutil.ReadAll(bodyReader) + body, err := io.ReadAll(bodyReader) require.NoError(t, err) assert.Equal(t, "test", string(body)) }) @@ -81,7 +80,7 @@ func makeResponse(t *testing.T, status int, body string) *http.Response { func makeBody(t *testing.T, body string) io.ReadCloser { t.Helper() - reader := ioutil.NopCloser(bytes.NewReader([]byte(body))) + reader := io.NopCloser(bytes.NewReader([]byte(body))) t.Cleanup(func() { err := reader.Close() assert.NoError(t, err) diff --git a/pkg/cmd/grafana-cli/services/io_util.go b/pkg/cmd/grafana-cli/services/io_util.go index 38aa81d94f7..ce0c240f7dd 100644 --- a/pkg/cmd/grafana-cli/services/io_util.go +++ b/pkg/cmd/grafana-cli/services/io_util.go @@ -25,5 +25,5 @@ func (i IoUtilImp) ReadFile(filename string) ([]byte, error) { // from command line flag "pluginsDir". If the user shouldn't be reading from this directory, they shouldn't have // the permission in the file system. // nolint:gosec - return ioutil.ReadFile(filename) + return os.ReadFile(filename) } diff --git a/pkg/codegen/coremodel.go b/pkg/codegen/coremodel.go index 0c6e6c7b32a..214310e3dde 100644 --- a/pkg/codegen/coremodel.go +++ b/pkg/codegen/coremodel.go @@ -8,7 +8,7 @@ import ( "go/format" "go/parser" "go/token" - "io/ioutil" + "io" "os" "path/filepath" "regexp" @@ -79,7 +79,7 @@ func ExtractLineage(path string, lib thema.Library) (*ExtractedLineage, error) { return nil, fmt.Errorf("could not open lineage file at %s: %w", path, err) } - byt, err := ioutil.ReadAll(f) + byt, err := io.ReadAll(f) if err != nil { return nil, err } diff --git a/pkg/components/imguploader/azureblobuploader.go b/pkg/components/imguploader/azureblobuploader.go index 736de276bfa..8598665df21 100644 --- a/pkg/components/imguploader/azureblobuploader.go +++ b/pkg/components/imguploader/azureblobuploader.go @@ -9,7 +9,6 @@ import ( "encoding/xml" "fmt" "io" - "io/ioutil" "mime" "net/http" "net/url" @@ -77,7 +76,7 @@ func (az *AzureBlobUploader) Upload(ctx context.Context, imageDiskPath string) ( }() if resp.StatusCode > 400 && resp.StatusCode < 600 { - body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20)) + body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return "", err } @@ -256,14 +255,15 @@ func tryget(headers map[string][]string, key string) string { /* Based on Azure docs: - Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element - 1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. - 2) Convert each HTTP header name to lowercase. - 3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string. - 4) Unfold the string by replacing any breaking white space with a single space. - 5) Trim any white space around the colon in the header. - 6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. + Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element + + 1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header. + 2) Convert each HTTP header name to lowercase. + 3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string. + 4) Unfold the string by replacing any breaking white space with a single space. + 5) Trim any white space around the colon in the header. + 6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string. */ func (a *Auth) canonicalizedHeaders(req *http.Request) string { var buffer bytes.Buffer @@ -288,25 +288,26 @@ func (a *Auth) canonicalizedHeaders(req *http.Request) string { /* Based on Azure docs - Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element -1) Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed. -2) Append the resource's encoded URI path, without any query parameters. -3) Retrieve all query parameters on the resource URI, including the comp parameter if it exists. -4) Convert all parameter names to lowercase. -5) Sort the query parameters lexicographically by parameter name, in ascending order. -6) URL-decode each query parameter name and value. -7) Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value: - parameter-name:parameter-value + Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element -8) If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list: - parameter-name:parameter-value-1,parameter-value-2,parameter-value-n + 1. Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed. + 2. Append the resource's encoded URI path, without any query parameters. + 3. Retrieve all query parameters on the resource URI, including the comp parameter if it exists. + 4. Convert all parameter names to lowercase. + 5. Sort the query parameters lexicographically by parameter name, in ascending order. + 6. URL-decode each query parameter name and value. + 7. Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value: + parameter-name:parameter-value + + 8. If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list: + parameter-name:parameter-value-1,parameter-value-2,parameter-value-n 9) Append a new line character (\n) after each name-value pair. Rules: - 1) Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string. - 2) Avoid using commas in query parameter values. + 1. Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string. + 2. Avoid using commas in query parameter values. */ func (a *Auth) canonicalizedResource(req *http.Request) string { var buffer bytes.Buffer diff --git a/pkg/components/imguploader/gcs/gcsuploader.go b/pkg/components/imguploader/gcs/gcsuploader.go index 391e5b78ece..005e473d896 100644 --- a/pkg/components/imguploader/gcs/gcsuploader.go +++ b/pkg/components/imguploader/gcs/gcsuploader.go @@ -5,7 +5,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "os" "path" "path/filepath" @@ -75,7 +74,7 @@ func (u *Uploader) Upload(ctx context.Context, imageDiskPath string) (string, er var keyData []byte if u.KeyFile != "" { u.log.Debug("Opening key file ", u.KeyFile) - keyData, err = ioutil.ReadFile(u.KeyFile) + keyData, err = os.ReadFile(u.KeyFile) if err != nil { return "", err } diff --git a/pkg/components/imguploader/gcs/gcsuploader_test.go b/pkg/components/imguploader/gcs/gcsuploader_test.go index 10a2079f2dc..77f0790e033 100644 --- a/pkg/components/imguploader/gcs/gcsuploader_test.go +++ b/pkg/components/imguploader/gcs/gcsuploader_test.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -115,7 +115,7 @@ func TestUploadToGCS_DefaultCredentials(t *testing.T) { content := []byte("test\n") tmpDir := t.TempDir() fpath := filepath.Join(tmpDir, "test.png") - err := ioutil.WriteFile(fpath, content, 0600) + err := os.WriteFile(fpath, content, 0600) require.NoError(t, err) t.Run("Without signed URL", func(t *testing.T) { diff --git a/pkg/components/imguploader/webdavuploader.go b/pkg/components/imguploader/webdavuploader.go index 7e6207f95d1..5099164516f 100644 --- a/pkg/components/imguploader/webdavuploader.go +++ b/pkg/components/imguploader/webdavuploader.go @@ -4,10 +4,11 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/url" + "os" "path" "strings" "time" @@ -58,7 +59,7 @@ func (u *WebdavUploader) Upload(ctx context.Context, imgToUpload string) (string // We can ignore the gosec G304 warning on this one because `imgToUpload` comes // from alert notifiers and is only used to upload images generated by alerting. // nolint:gosec - imgData, err := ioutil.ReadFile(imgToUpload) + imgData, err := os.ReadFile(imgToUpload) if err != nil { return "", err } @@ -85,7 +86,7 @@ func (u *WebdavUploader) Upload(ctx context.Context, imgToUpload string) (string }() if res.StatusCode != http.StatusCreated { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return "", fmt.Errorf("failed to read response body: %w", err) } diff --git a/pkg/infra/filestorage/fs_integration_test.go b/pkg/infra/filestorage/fs_integration_test.go index 89a152a962a..39719d1aba7 100644 --- a/pkg/infra/filestorage/fs_integration_test.go +++ b/pkg/infra/filestorage/fs_integration_test.go @@ -4,7 +4,6 @@ import ( "context" "encoding/base64" "fmt" - "io/ioutil" "os" "path" "testing" @@ -87,7 +86,7 @@ func runTests(createCases func() []fsTestCase, t *testing.T) { setupLocalFs := func() { commonSetup() - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") tempDir = tmpDir if err != nil { t.Fatal(err) @@ -102,7 +101,7 @@ func runTests(createCases func() []fsTestCase, t *testing.T) { setupLocalFsNestedPath := func() { commonSetup() - tmpDir, err := ioutil.TempDir("", "") + tmpDir, err := os.MkdirTemp("", "") if err != nil { t.Fatal(err) } diff --git a/pkg/infra/fs/copy_test.go b/pkg/infra/fs/copy_test.go index f77dbc5a0b3..e3304ff0d9d 100644 --- a/pkg/infra/fs/copy_test.go +++ b/pkg/infra/fs/copy_test.go @@ -1,7 +1,6 @@ package fs import ( - "io/ioutil" "os" "path/filepath" "strings" @@ -12,16 +11,16 @@ import ( ) func TestCopyFile(t *testing.T) { - src, err := ioutil.TempFile("", "") + src, err := os.CreateTemp("", "") require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll(src.Name()) assert.NoError(t, err) }) - err = ioutil.WriteFile(src.Name(), []byte("Contents"), 0600) + err = os.WriteFile(src.Name(), []byte("Contents"), 0600) require.NoError(t, err) - dst, err := ioutil.TempFile("", "") + dst, err := os.CreateTemp("", "") require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll(dst.Name()) @@ -35,18 +34,18 @@ func TestCopyFile(t *testing.T) { func TestCopyFile_Permissions(t *testing.T) { const perms = os.FileMode(0700) - src, err := ioutil.TempFile("", "") + src, err := os.CreateTemp("", "") require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll(src.Name()) assert.NoError(t, err) }) - err = ioutil.WriteFile(src.Name(), []byte("Contents"), 0600) + err = os.WriteFile(src.Name(), []byte("Contents"), 0600) require.NoError(t, err) err = os.Chmod(src.Name(), perms) require.NoError(t, err) - dst, err := ioutil.TempFile("", "") + dst, err := os.CreateTemp("", "") require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll(dst.Name()) @@ -65,7 +64,7 @@ func TestCopyFile_Permissions(t *testing.T) { // Test case where destination directory doesn't exist. func TestCopyFile_NonExistentDestDir(t *testing.T) { // nolint:gosec - src, err := ioutil.TempFile("", "") + src, err := os.CreateTemp("", "") require.NoError(t, err) t.Cleanup(func() { err := os.RemoveAll(src.Name()) @@ -82,7 +81,7 @@ func TestCopyRecursive_NonExistentDest(t *testing.T) { err := os.MkdirAll(filepath.Join(src, "data"), 0750) require.NoError(t, err) // nolint:gosec - err = ioutil.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644) + err = os.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644) require.NoError(t, err) dstParent := t.TempDir() @@ -101,7 +100,7 @@ func TestCopyRecursive_ExistentDest(t *testing.T) { err := os.MkdirAll(filepath.Join(src, "data"), 0750) require.NoError(t, err) // nolint:gosec - err = ioutil.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644) + err = os.WriteFile(filepath.Join(src, "data", "file.txt"), []byte("Test"), 0644) require.NoError(t, err) dst := t.TempDir() @@ -139,10 +138,10 @@ func compareDirs(t *testing.T, src, dst string) { } // nolint:gosec - srcData, err := ioutil.ReadFile(srcPath) + srcData, err := os.ReadFile(srcPath) require.NoError(t, err) // nolint:gosec - dstData, err := ioutil.ReadFile(dstPath) + dstData, err := os.ReadFile(dstPath) require.NoError(t, err) require.Equal(t, srcData, dstData) diff --git a/pkg/infra/fs/exists_test.go b/pkg/infra/fs/exists_test.go index 3b6dbec3442..e04591969ef 100644 --- a/pkg/infra/fs/exists_test.go +++ b/pkg/infra/fs/exists_test.go @@ -1,7 +1,6 @@ package fs import ( - "io/ioutil" "os" "testing" @@ -17,7 +16,7 @@ func TestExists_NonExistent(t *testing.T) { } func TestExists_Existent(t *testing.T) { - f, err := ioutil.TempFile("", "") + f, err := os.CreateTemp("", "") require.NoError(t, err) t.Cleanup(func() { err := os.Remove(f.Name()) diff --git a/pkg/infra/httpclient/count_bytes_reader_test.go b/pkg/infra/httpclient/count_bytes_reader_test.go index d8cb077328d..96e94cf551f 100644 --- a/pkg/infra/httpclient/count_bytes_reader_test.go +++ b/pkg/infra/httpclient/count_bytes_reader_test.go @@ -2,7 +2,7 @@ package httpclient import ( "fmt" - "io/ioutil" + "io" "strings" "testing" @@ -20,14 +20,14 @@ func TestCountBytesReader(t *testing.T) { for index, tc := range tcs { t.Run(fmt.Sprintf("Test CountBytesReader %d", index), func(t *testing.T) { - body := ioutil.NopCloser(strings.NewReader(tc.body)) + body := io.NopCloser(strings.NewReader(tc.body)) var actualBytesRead int64 readCloser := CountBytesReader(body, func(bytesRead int64) { actualBytesRead = bytesRead }) - bodyBytes, err := ioutil.ReadAll(readCloser) + bodyBytes, err := io.ReadAll(readCloser) require.NoError(t, err) err = readCloser.Close() require.NoError(t, err) diff --git a/pkg/infra/httpclient/httpclientprovider/response_limit_middleware_test.go b/pkg/infra/httpclient/httpclientprovider/response_limit_middleware_test.go index 4a4064a8f44..88a0d572b86 100644 --- a/pkg/infra/httpclient/httpclientprovider/response_limit_middleware_test.go +++ b/pkg/infra/httpclient/httpclientprovider/response_limit_middleware_test.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -27,7 +27,7 @@ func TestResponseLimitMiddleware(t *testing.T) { for _, tc := range tcs { t.Run(fmt.Sprintf("Test ResponseLimitMiddleware with limit: %d", tc.limit), func(t *testing.T) { finalRoundTripper := httpclient.RoundTripperFunc(func(req *http.Request) (*http.Response, error) { - return &http.Response{StatusCode: http.StatusOK, Request: req, Body: ioutil.NopCloser(strings.NewReader("dummy"))}, nil + return &http.Response{StatusCode: http.StatusOK, Request: req, Body: io.NopCloser(strings.NewReader("dummy"))}, nil }) mw := ResponseLimitMiddleware(tc.limit) @@ -46,7 +46,7 @@ func TestResponseLimitMiddleware(t *testing.T) { require.NotNil(t, res.Body) require.NoError(t, res.Body.Close()) - bodyBytes, err := ioutil.ReadAll(res.Body) + bodyBytes, err := io.ReadAll(res.Body) if err != nil { require.EqualError(t, tc.err, err.Error()) } else { diff --git a/pkg/infra/httpclient/httpclientprovider/testing.go b/pkg/infra/httpclient/httpclientprovider/testing.go index f14f882105f..e85d30640e2 100644 --- a/pkg/infra/httpclient/httpclientprovider/testing.go +++ b/pkg/infra/httpclient/httpclientprovider/testing.go @@ -2,7 +2,7 @@ package httpclientprovider import ( "bytes" - "io/ioutil" + "io" "net/http" "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient" @@ -18,7 +18,7 @@ func (c *testContext) createRoundTripper(name string) http.RoundTripper { return &http.Response{ StatusCode: http.StatusOK, Request: req, - Body: ioutil.NopCloser(bytes.NewBufferString("")), + Body: io.NopCloser(bytes.NewBufferString("")), }, nil }) } diff --git a/pkg/infra/httpclient/max_bytes_reader_test.go b/pkg/infra/httpclient/max_bytes_reader_test.go index 13742107550..1f48be0bbc5 100644 --- a/pkg/infra/httpclient/max_bytes_reader_test.go +++ b/pkg/infra/httpclient/max_bytes_reader_test.go @@ -3,7 +3,7 @@ package httpclient import ( "errors" "fmt" - "io/ioutil" + "io" "strings" "testing" @@ -23,10 +23,10 @@ func TestMaxBytesReader(t *testing.T) { } for _, tc := range tcs { t.Run(fmt.Sprintf("Test MaxBytesReader with limit: %d", tc.limit), func(t *testing.T) { - body := ioutil.NopCloser(strings.NewReader("dummy")) + body := io.NopCloser(strings.NewReader("dummy")) readCloser := MaxBytesReader(body, tc.limit) - bodyBytes, err := ioutil.ReadAll(readCloser) + bodyBytes, err := io.ReadAll(readCloser) if err != nil { require.EqualError(t, tc.err, err.Error()) } else { diff --git a/pkg/infra/log/log.go b/pkg/infra/log/log.go index fc469f3716e..b74e9b91c5c 100644 --- a/pkg/infra/log/log.go +++ b/pkg/infra/log/log.go @@ -7,7 +7,6 @@ package log import ( "fmt" "io" - "io/ioutil" "os" "path/filepath" "sort" @@ -46,7 +45,7 @@ func init() { // Use discard by default format := func(w io.Writer) gokitlog.Logger { - return gokitlog.NewLogfmtLogger(gokitlog.NewSyncWriter(ioutil.Discard)) + return gokitlog.NewLogfmtLogger(gokitlog.NewSyncWriter(io.Discard)) } logger := level.NewFilter(format(os.Stderr), level.AllowInfo()) root = newManager(logger) @@ -205,9 +204,12 @@ func (cl *ConcreteLogger) New(ctx ...interface{}) *ConcreteLogger { // name plus additional contextual information, you must use the // Logger interface New method for it to work as expected. // Example creating a shared logger: -// requestLogger := log.New("request-logger") +// +// requestLogger := log.New("request-logger") +// // Example creating a contextual logger: -// contextualLogger := requestLogger.New("username", "user123") +// +// contextualLogger := requestLogger.New("username", "user123") func New(ctx ...interface{}) *ConcreteLogger { if len(ctx) == 0 { return root.New() diff --git a/pkg/infra/usagestats/service/usage_stats_test.go b/pkg/infra/usagestats/service/usage_stats_test.go index f68cd2c8c22..d394f7b1af2 100644 --- a/pkg/infra/usagestats/service/usage_stats_test.go +++ b/pkg/infra/usagestats/service/usage_stats_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "net/http/httptest" "runtime" @@ -84,7 +84,7 @@ func TestMetrics(t *testing.T) { ch := make(chan httpResp) ticker := time.NewTicker(2 * time.Second) ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - buf, err := ioutil.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) if err != nil { t.Logf("Fake HTTP handler received an error: %s", err.Error()) ch <- httpResp{ diff --git a/pkg/infra/usagestats/statscollector/prometheus_flavor.go b/pkg/infra/usagestats/statscollector/prometheus_flavor.go index 5539d66af74..4bb88ae6959 100644 --- a/pkg/infra/usagestats/statscollector/prometheus_flavor.go +++ b/pkg/infra/usagestats/statscollector/prometheus_flavor.go @@ -3,7 +3,7 @@ package statscollector import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "time" @@ -107,7 +107,7 @@ func (s *Service) detectPrometheusVariant(ctx context.Context, ds *datasources.D return "unknown", nil } - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { s.log.Error("Failed to read Prometheus build info", "error", err) return "", err diff --git a/pkg/login/social/common.go b/pkg/login/social/common.go index f94aa3e0663..309ede7cd0e 100644 --- a/pkg/login/social/common.go +++ b/pkg/login/social/common.go @@ -4,7 +4,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "strings" @@ -54,7 +54,7 @@ func (s *SocialBase) httpGet(client *http.Client, url string) (response httpGetR } }() - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { return } diff --git a/pkg/login/social/generic_oauth.go b/pkg/login/social/generic_oauth.go index 8fa7ab43d40..cb682fcc0e8 100644 --- a/pkg/login/social/generic_oauth.go +++ b/pkg/login/social/generic_oauth.go @@ -7,7 +7,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/mail" "regexp" @@ -259,7 +259,7 @@ func (s *SocialGenericOAuth) extractFromToken(token *oauth2.Token) *UserInfoJson s.log.Warn("Failed closing zlib reader", "error", err) } }() - rawJSON, err = ioutil.ReadAll(fr) + rawJSON, err = io.ReadAll(fr) if err != nil { s.log.Error("Error decompressing payload", "error", err) return nil diff --git a/pkg/login/social/social.go b/pkg/login/social/social.go index 9c1f6396425..fb28128b665 100644 --- a/pkg/login/social/social.go +++ b/pkg/login/social/social.go @@ -5,8 +5,8 @@ import ( "crypto/x509" "encoding/json" "fmt" - "io/ioutil" "net/http" + "os" "strings" "context" @@ -388,7 +388,7 @@ func (ss *SocialService) GetOAuthHttpClient(name string) (*http.Client, error) { } if info.TlsClientCa != "" { - caCert, err := ioutil.ReadFile(info.TlsClientCa) + caCert, err := os.ReadFile(info.TlsClientCa) if err != nil { logger.Error("Failed to setup TlsClientCa", "oauth", name, "error", err) return nil, fmt.Errorf("failed to setup TlsClientCa: %w", err) diff --git a/pkg/middleware/recovery.go b/pkg/middleware/recovery.go index 20b317b4e9d..ccb0c2b1efd 100644 --- a/pkg/middleware/recovery.go +++ b/pkg/middleware/recovery.go @@ -19,8 +19,8 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" "net/http" + "os" "runtime" "github.com/grafana/grafana/pkg/infra/log" @@ -54,7 +54,7 @@ func stack(skip int) []byte { // We can ignore the gosec G304 warning on this one because `file` // comes from the runtime.Caller() function. // nolint:gosec - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) if err != nil { continue } diff --git a/pkg/plugins/backendplugin/grpcplugin/log_wrapper.go b/pkg/plugins/backendplugin/grpcplugin/log_wrapper.go index 65c1948b0d4..92ce80e93c1 100644 --- a/pkg/plugins/backendplugin/grpcplugin/log_wrapper.go +++ b/pkg/plugins/backendplugin/grpcplugin/log_wrapper.go @@ -3,7 +3,6 @@ package grpcplugin import ( "fmt" "io" - "io/ioutil" "log" glog "github.com/grafana/grafana/pkg/infra/log" @@ -159,5 +158,5 @@ func (lw logWrapper) StandardLogger(ops *hclog.StandardLoggerOptions) *log.Logge // Return a value that conforms to io.Writer, which can be passed into log.SetOutput() func (lw logWrapper) StandardWriter(opts *hclog.StandardLoggerOptions) io.Writer { - return ioutil.Discard + return io.Discard } diff --git a/pkg/plugins/manager/installer/installer.go b/pkg/plugins/manager/installer/installer.go index 5f6ccf87c19..56064105720 100644 --- a/pkg/plugins/manager/installer/installer.go +++ b/pkg/plugins/manager/installer/installer.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "net/url" @@ -125,7 +124,7 @@ func (i *Installer) Install(ctx context.Context, pluginID, version, pluginsDir, i.log.Debugf("Installing plugin\nfrom: %s\ninto: %s", pluginZipURL, pluginsDir) // Create temp file for downloading zip file - tmpFile, err := ioutil.TempFile("", "*.zip") + tmpFile, err := os.CreateTemp("", "*.zip") if err != nil { return fmt.Errorf("%v: %w", "failed to create temporary file", err) } @@ -288,7 +287,7 @@ func (i *Installer) sendRequestGetBytes(URL string, subPaths ...string) ([]byte, i.log.Warn("Failed to close stream", "err", err) } }() - return ioutil.ReadAll(bodyReader) + return io.ReadAll(bodyReader) } func (i *Installer) sendRequest(URL string, subPaths ...string) (io.ReadCloser, error) { @@ -342,7 +341,7 @@ func (i *Installer) createRequest(URL string, subPaths ...string) (*http.Request func (i *Installer) handleResponse(res *http.Response) (io.ReadCloser, error) { if res.StatusCode/100 == 4 { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) defer func() { if err := res.Body.Close(); err != nil { i.log.Warn("Failed to close response body", "err", err) @@ -676,12 +675,12 @@ func toPluginDTO(pluginDir, pluginID string) (InstalledPlugin, error) { // It's safe to ignore gosec warning G304 since the file path suffix is hardcoded // nolint:gosec - data, err := ioutil.ReadFile(distPluginDataPath) + data, err := os.ReadFile(distPluginDataPath) if err != nil { pluginDataPath := filepath.Join(pluginDir, pluginID, "plugin.json") // It's safe to ignore gosec warning G304 since the file path suffix is hardcoded // nolint:gosec - data, err = ioutil.ReadFile(pluginDataPath) + data, err = os.ReadFile(pluginDataPath) if err != nil { return InstalledPlugin{}, errors.New("Could not find dist/plugin.json or plugin.json on " + pluginID + " in " + pluginDir) } diff --git a/pkg/plugins/manager/signature/manifest.go b/pkg/plugins/manager/signature/manifest.go index 49b126390b3..a1086daeddc 100644 --- a/pkg/plugins/manager/signature/manifest.go +++ b/pkg/plugins/manager/signature/manifest.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/url" "os" "path" @@ -29,7 +28,8 @@ import ( ) // Soon we can fetch keys from: -// https://grafana.com/api/plugins/ci/keys +// +// https://grafana.com/api/plugins/ci/keys const publicKeyText = `-----BEGIN PGP PUBLIC KEY BLOCK----- Version: OpenPGP.js v4.10.1 Comment: https://openpgpjs.org @@ -116,7 +116,7 @@ func Calculate(mlog log.Logger, plugin *plugins.Plugin) (plugins.Signature, erro // nolint:gosec // We can ignore the gosec G304 warning on this one because `manifestPath` is based // on plugin the folder structure on disk and not user input. - byteValue, err := ioutil.ReadFile(manifestPath) + byteValue, err := os.ReadFile(manifestPath) if err != nil || len(byteValue) < 10 { mlog.Debug("Plugin is unsigned", "id", plugin.ID) return plugins.Signature{ diff --git a/pkg/server/server.go b/pkg/server/server.go index 420c5e60e70..46d73989df0 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "net" "os" "path/filepath" @@ -233,7 +232,7 @@ func (s *Server) writePIDFile() { // Retrieve the PID and write it to file. pid := strconv.Itoa(os.Getpid()) - if err := ioutil.WriteFile(s.pidFile, []byte(pid), 0644); err != nil { + if err := os.WriteFile(s.pidFile, []byte(pid), 0644); err != nil { s.log.Error("Failed to write pidfile", "error", err) os.Exit(1) } diff --git a/pkg/services/alerting/alerting_usage_test.go b/pkg/services/alerting/alerting_usage_test.go index 1392742541e..a2e9f48563e 100644 --- a/pkg/services/alerting/alerting_usage_test.go +++ b/pkg/services/alerting/alerting_usage_test.go @@ -3,7 +3,7 @@ package alerting import ( "context" "encoding/json" - "io/ioutil" + "os" "testing" "github.com/google/go-cmp/cmp" @@ -34,7 +34,7 @@ func TestAlertingUsageStats(t *testing.T) { var createFake = func(file string) *simplejson.Json { // Ignore gosec warning G304 since it's a test // nolint:gosec - content, err := ioutil.ReadFile(file) + content, err := os.ReadFile(file) require.NoError(t, err, "expected to be able to read file") j, err := simplejson.NewJson(content) @@ -104,7 +104,7 @@ func TestParsingAlertRuleSettings(t *testing.T) { t.Run(tc.name, func(t *testing.T) { var settings json.Marshaler if tc.file != "" { - content, err := ioutil.ReadFile(tc.file) + content, err := os.ReadFile(tc.file) require.NoError(t, err, "expected to be able to read file") settings, err = simplejson.NewJson(content) diff --git a/pkg/services/alerting/extractor_test.go b/pkg/services/alerting/extractor_test.go index fd178802e38..f39bbd883b5 100644 --- a/pkg/services/alerting/extractor_test.go +++ b/pkg/services/alerting/extractor_test.go @@ -3,7 +3,7 @@ package alerting import ( "context" "errors" - "io/ioutil" + "os" "testing" "time" @@ -27,7 +27,7 @@ func TestAlertRuleExtraction(t *testing.T) { defaultDs := &datasources.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true, Uid: "def-uid"} graphite2Ds := &datasources.DataSource{Id: 15, OrgId: 1, Name: "graphite2", Uid: "graphite2-uid"} - json, err := ioutil.ReadFile("./testdata/graphite-alert.json") + json, err := os.ReadFile("./testdata/graphite-alert.json") require.Nil(t, err) dsPermissions := permissions.NewMockDatasourcePermissionService() @@ -117,7 +117,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Panels missing id should return error", func(t *testing.T) { - panelWithoutID, err := ioutil.ReadFile("./testdata/panels-missing-id.json") + panelWithoutID, err := os.ReadFile("./testdata/panels-missing-id.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(panelWithoutID) @@ -133,7 +133,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Panels missing id should return error", func(t *testing.T) { - panelWithIDZero, err := ioutil.ReadFile("./testdata/panel-with-id-0.json") + panelWithIDZero, err := os.ReadFile("./testdata/panel-with-id-0.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(panelWithIDZero) @@ -149,7 +149,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Cannot save panel with query that is referenced by legacy alerting", func(t *testing.T) { - panelWithQuery, err := ioutil.ReadFile("./testdata/panel-with-bad-query-id.json") + panelWithQuery, err := os.ReadFile("./testdata/panel-with-bad-query-id.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(panelWithQuery) require.Nil(t, err) @@ -163,7 +163,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Panel does not have datasource configured, use the default datasource", func(t *testing.T) { - panelWithoutSpecifiedDatasource, err := ioutil.ReadFile("./testdata/panel-without-specified-datasource.json") + panelWithoutSpecifiedDatasource, err := os.ReadFile("./testdata/panel-without-specified-datasource.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(panelWithoutSpecifiedDatasource) @@ -183,7 +183,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Parse alerts from dashboard without rows", func(t *testing.T) { - json, err := ioutil.ReadFile("./testdata/v5-dashboard.json") + json, err := os.ReadFile("./testdata/v5-dashboard.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(json) @@ -210,7 +210,7 @@ func TestAlertRuleExtraction(t *testing.T) { err = sqlStore.CreateAlertNotificationCommand(context.Background(), &secondNotification) require.Nil(t, err) - json, err := ioutil.ReadFile("./testdata/influxdb-alert.json") + json, err := os.ReadFile("./testdata/influxdb-alert.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(json) @@ -236,7 +236,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Should be able to extract collapsed panels", func(t *testing.T) { - json, err := ioutil.ReadFile("./testdata/collapsed-panels.json") + json, err := os.ReadFile("./testdata/collapsed-panels.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(json) @@ -255,7 +255,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Parse and validate dashboard without id and containing an alert", func(t *testing.T) { - json, err := ioutil.ReadFile("./testdata/dash-without-id.json") + json, err := os.ReadFile("./testdata/dash-without-id.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(json) @@ -275,7 +275,7 @@ func TestAlertRuleExtraction(t *testing.T) { }) t.Run("Extract data source given new DataSourceRef object model", func(t *testing.T) { - json, err := ioutil.ReadFile("./testdata/panel-with-datasource-ref.json") + json, err := os.ReadFile("./testdata/panel-with-datasource-ref.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(json) @@ -308,7 +308,7 @@ func TestFilterPermissionsErrors(t *testing.T) { // mock data defaultDs := &datasources.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true, Uid: "def-uid"} - json, err := ioutil.ReadFile("./testdata/graphite-alert.json") + json, err := os.ReadFile("./testdata/graphite-alert.json") require.Nil(t, err) dashJSON, err := simplejson.NewJson(json) require.Nil(t, err) diff --git a/pkg/services/auth/jwt/auth_test.go b/pkg/services/auth/jwt/auth_test.go index de6e5351341..18351482df4 100644 --- a/pkg/services/auth/jwt/auth_test.go +++ b/pkg/services/auth/jwt/auth_test.go @@ -6,7 +6,6 @@ import ( "encoding/base64" "encoding/json" "encoding/pem" - "io/ioutil" "net/http" "net/http/httptest" "os" @@ -66,7 +65,7 @@ func TestVerifyUsingJWKSetFile(t *testing.T) { configure := func(t *testing.T, cfg *setting.Cfg) { t.Helper() - file, err := ioutil.TempFile(os.TempDir(), "jwk-*.json") + file, err := os.CreateTemp(os.TempDir(), "jwk-*.json") require.NoError(t, err) t.Cleanup(func() { if err := os.Remove(file.Name()); err != nil { @@ -402,7 +401,7 @@ func scenarioRunner(fn scenarioFunc, cbs ...configureFunc) func(t *testing.T) { func configurePKIXPublicKeyFile(t *testing.T, cfg *setting.Cfg) { t.Helper() - file, err := ioutil.TempFile(os.TempDir(), "public-key-*.pem") + file, err := os.CreateTemp(os.TempDir(), "public-key-*.pem") require.NoError(t, err) t.Cleanup(func() { if err := os.Remove(file.Name()); err != nil { diff --git a/pkg/services/auth/jwt/key_sets.go b/pkg/services/auth/jwt/key_sets.go index 04ddba6b69c..63d4c940e73 100644 --- a/pkg/services/auth/jwt/key_sets.go +++ b/pkg/services/auth/jwt/key_sets.go @@ -9,7 +9,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -83,7 +82,7 @@ func (s *AuthService) initKeySet() error { } }() - data, err := ioutil.ReadAll(file) + data, err := io.ReadAll(file) if err != nil { return err } diff --git a/pkg/services/dashboardimport/service/service_test.go b/pkg/services/dashboardimport/service/service_test.go index 39f15f329a0..8fe87b7416f 100644 --- a/pkg/services/dashboardimport/service/service_test.go +++ b/pkg/services/dashboardimport/service/service_test.go @@ -2,7 +2,7 @@ package service import ( "context" - "io/ioutil" + "os" "path/filepath" "testing" @@ -144,7 +144,7 @@ func TestImportDashboardService(t *testing.T) { func loadTestDashboard(ctx context.Context, req *plugindashboards.LoadPluginDashboardRequest) (*plugindashboards.LoadPluginDashboardResponse, error) { // It's safe to ignore gosec warning G304 since this is a test and arguments comes from test configuration. // nolint:gosec - bytes, err := ioutil.ReadFile(filepath.Join("testdata", req.Reference)) + bytes, err := os.ReadFile(filepath.Join("testdata", req.Reference)) if err != nil { return nil, err } diff --git a/pkg/services/datasources/service/datasource_service_test.go b/pkg/services/datasources/service/datasource_service_test.go index 7685e5df0f2..b29974fc695 100644 --- a/pkg/services/datasources/service/datasource_service_test.go +++ b/pkg/services/datasources/service/datasource_service_test.go @@ -3,7 +3,7 @@ package service import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -449,7 +449,7 @@ func TestService_GetHttpTransport(t *testing.T) { err := res.Body.Close() require.NoError(t, err) }) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) bodyStr := string(body) require.Equal(t, "Ok", bodyStr) diff --git a/pkg/services/export/commit_helper.go b/pkg/services/export/commit_helper.go index a244cc47ae7..c86a0e93055 100644 --- a/pkg/services/export/commit_helper.go +++ b/pkg/services/export/commit_helper.go @@ -3,7 +3,6 @@ package export import ( "context" "fmt" - "io/ioutil" "os" "path" "strings" @@ -108,7 +107,7 @@ func (ch *commitHelper) add(opts commitOptions) error { } } - err = ioutil.WriteFile(b.fpath, body, 0644) + err = os.WriteFile(b.fpath, body, 0644) if err != nil { return err } diff --git a/pkg/services/export/export_dash_thumbs.go b/pkg/services/export/export_dash_thumbs.go index fe3143cb01b..d794723a11b 100644 --- a/pkg/services/export/export_dash_thumbs.go +++ b/pkg/services/export/export_dash_thumbs.go @@ -3,7 +3,7 @@ package export import ( "encoding/json" "fmt" - "io/ioutil" + "os" "path/filepath" "strings" "time" @@ -13,7 +13,7 @@ import ( func exportDashboardThumbnails(helper *commitHelper, job *gitExportJob) error { alias := make(map[string]string, 100) - aliasLookup, err := ioutil.ReadFile(filepath.Join(helper.orgDir, "root-alias.json")) + aliasLookup, err := os.ReadFile(filepath.Join(helper.orgDir, "root-alias.json")) if err != nil { return fmt.Errorf("missing dashboard alias files (must export dashboards first)") } diff --git a/pkg/services/featuremgmt/settings.go b/pkg/services/featuremgmt/settings.go index dc2137bf567..3ff22a61cad 100644 --- a/pkg/services/featuremgmt/settings.go +++ b/pkg/services/featuremgmt/settings.go @@ -1,7 +1,7 @@ package featuremgmt import ( - "io/ioutil" + "os" "gopkg.in/yaml.v2" ) @@ -23,7 +23,7 @@ func readConfigFile(filename string) (*configBody, error) { // Can ignore gosec G304 because the file path is forced within config subfolder //nolint:gosec - yamlFile, err := ioutil.ReadFile(filename) + yamlFile, err := os.ReadFile(filename) if err != nil { return cfg, err } diff --git a/pkg/services/featuremgmt/toggles_gen_test.go b/pkg/services/featuremgmt/toggles_gen_test.go index dc72fa4aaaa..4abde90385d 100644 --- a/pkg/services/featuremgmt/toggles_gen_test.go +++ b/pkg/services/featuremgmt/toggles_gen_test.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "html/template" - "io/ioutil" "os" "path/filepath" "strings" @@ -61,7 +60,7 @@ func TestFeatureToggleFiles(t *testing.T) { func verifyAndGenerateFile(t *testing.T, fpath string, gen string) { // nolint:gosec // We can ignore the gosec G304 warning since this is a test and the function is only called explicitly above - body, err := ioutil.ReadFile(fpath) + body, err := os.ReadFile(fpath) if err == nil { if diff := cmp.Diff(gen, string(body)); diff != "" { str := fmt.Sprintf("body mismatch (-want +got):\n%s\n", diff) diff --git a/pkg/services/ldap/ldap.go b/pkg/services/ldap/ldap.go index 03cfa9b09d1..4120d89a5fd 100644 --- a/pkg/services/ldap/ldap.go +++ b/pkg/services/ldap/ldap.go @@ -5,9 +5,9 @@ import ( "crypto/x509" "errors" "fmt" - "io/ioutil" "math" "net" + "os" "strconv" "strings" "time" @@ -101,7 +101,7 @@ func (server *Server) Dial() error { for _, caCertFile := range strings.Split(server.Config.RootCACert, " ") { // nolint:gosec // We can ignore the gosec G304 warning on this one because `caCertFile` comes from ldap config. - pem, err := ioutil.ReadFile(caCertFile) + pem, err := os.ReadFile(caCertFile) if err != nil { return err } diff --git a/pkg/services/ldap/settings.go b/pkg/services/ldap/settings.go index 5449dd892f1..dbada844bec 100644 --- a/pkg/services/ldap/settings.go +++ b/pkg/services/ldap/settings.go @@ -2,7 +2,7 @@ package ldap import ( "fmt" - "io/ioutil" + "os" "sync" "github.com/BurntSushi/toml" @@ -123,7 +123,7 @@ func readConfig(configFile string) (*Config, error) { // nolint:gosec // We can ignore the gosec G304 warning on this one because `filename` comes from grafana configuration file - fileBytes, err := ioutil.ReadFile(configFile) + fileBytes, err := os.ReadFile(configFile) if err != nil { return nil, fmt.Errorf("%v: %w", "Failed to load LDAP config file", err) } diff --git a/pkg/services/live/live.go b/pkg/services/live/live.go index bfa42b421b1..1a403d80824 100644 --- a/pkg/services/live/live.go +++ b/pkg/services/live/live.go @@ -5,7 +5,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -1124,7 +1124,7 @@ func (s *DryRunRuleStorage) ListChannelRules(_ context.Context, _ int64) ([]pipe // HandlePipelineConvertTestHTTP ... func (g *GrafanaLive) HandlePipelineConvertTestHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } @@ -1169,7 +1169,7 @@ func (g *GrafanaLive) HandlePipelineConvertTestHTTP(c *models.ReqContext) respon // HandleChannelRulesPostHTTP ... func (g *GrafanaLive) HandleChannelRulesPostHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } @@ -1189,7 +1189,7 @@ func (g *GrafanaLive) HandleChannelRulesPostHTTP(c *models.ReqContext) response. // HandleChannelRulesPutHTTP ... func (g *GrafanaLive) HandleChannelRulesPutHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } @@ -1212,7 +1212,7 @@ func (g *GrafanaLive) HandleChannelRulesPutHTTP(c *models.ReqContext) response.R // HandleChannelRulesDeleteHTTP ... func (g *GrafanaLive) HandleChannelRulesDeleteHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } @@ -1259,7 +1259,7 @@ func (g *GrafanaLive) HandleWriteConfigsListHTTP(c *models.ReqContext) response. // HandleWriteConfigsPostHTTP ... func (g *GrafanaLive) HandleWriteConfigsPostHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } @@ -1279,7 +1279,7 @@ func (g *GrafanaLive) HandleWriteConfigsPostHTTP(c *models.ReqContext) response. // HandleWriteConfigsPutHTTP ... func (g *GrafanaLive) HandleWriteConfigsPutHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } @@ -1323,7 +1323,7 @@ func (g *GrafanaLive) HandleWriteConfigsPutHTTP(c *models.ReqContext) response.R // HandleWriteConfigsDeleteHTTP ... func (g *GrafanaLive) HandleWriteConfigsDeleteHTTP(c *models.ReqContext) response.Response { - body, err := ioutil.ReadAll(c.Req.Body) + body, err := io.ReadAll(c.Req.Body) if err != nil { return response.Error(http.StatusInternalServerError, "Error reading body", err) } diff --git a/pkg/services/live/pipeline/converter_json_auto_test.go b/pkg/services/live/pipeline/converter_json_auto_test.go index 045a4b53a7f..1b0759595a9 100644 --- a/pkg/services/live/pipeline/converter_json_auto_test.go +++ b/pkg/services/live/pipeline/converter_json_auto_test.go @@ -3,7 +3,7 @@ package pipeline import ( "context" "flag" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -19,7 +19,7 @@ func loadTestJson(t testing.TB, file string) []byte { t.Helper() // Safe to disable, this is a test. // nolint:gosec - content, err := ioutil.ReadFile(filepath.Join("testdata", file+".json")) + content, err := os.ReadFile(filepath.Join("testdata", file+".json")) require.NoError(t, err, "expected to be able to read file") require.True(t, len(content) > 0) return content diff --git a/pkg/services/live/pipeline/storage_file.go b/pkg/services/live/pipeline/storage_file.go index db135edffad..c2e850b7794 100644 --- a/pkg/services/live/pipeline/storage_file.go +++ b/pkg/services/live/pipeline/storage_file.go @@ -5,7 +5,6 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" "os" "path/filepath" @@ -240,7 +239,7 @@ func (f *FileStorage) readRules() (ChannelRules, error) { ruleFile := f.ruleFilePath() // Safe to ignore gosec warning G304. // nolint:gosec - ruleBytes, err := ioutil.ReadFile(ruleFile) + ruleBytes, err := os.ReadFile(ruleFile) if err != nil { return ChannelRules{}, fmt.Errorf("can't read pipeline rules: %s: %w", f.ruleFilePath(), err) } @@ -309,7 +308,7 @@ func (f *FileStorage) readWriteConfigs() (WriteConfigs, error) { filePath := f.writeConfigsFilePath() // Safe to ignore gosec warning G304. // nolint:gosec - bytes, err := ioutil.ReadFile(filePath) + bytes, err := os.ReadFile(filePath) if err != nil { return WriteConfigs{}, fmt.Errorf("can't read %s file: %w", filePath, err) } diff --git a/pkg/services/live/telemetry/telegraf/convert_test.go b/pkg/services/live/telemetry/telegraf/convert_test.go index 691474e4c09..3a51f4cc16b 100644 --- a/pkg/services/live/telemetry/telegraf/convert_test.go +++ b/pkg/services/live/telemetry/telegraf/convert_test.go @@ -4,7 +4,7 @@ import ( "encoding/json" "flag" "fmt" - "io/ioutil" + "os" "path/filepath" "testing" @@ -18,7 +18,7 @@ func loadTestData(tb testing.TB, file string) []byte { tb.Helper() // Safe to disable, this is a test. // nolint:gosec - content, err := ioutil.ReadFile(filepath.Join("testdata", file+".txt")) + content, err := os.ReadFile(filepath.Join("testdata", file+".txt")) require.NoError(tb, err, "expected to be able to read file") require.True(tb, len(content) > 0) return content @@ -28,7 +28,7 @@ func checkTestData(t *testing.T, file string) *backend.DataResponse { t.Helper() // Safe to disable, this is a test. // nolint:gosec - content, err := ioutil.ReadFile(filepath.Join("testdata", file+".txt")) + content, err := os.ReadFile(filepath.Join("testdata", file+".txt")) require.NoError(t, err, "expected to be able to read file") require.True(t, len(content) > 0) @@ -143,13 +143,13 @@ func TestConverter_Convert_NumFrameFields(t *testing.T) { frameJSON, err := json.MarshalIndent(frame, "", " ") require.NoError(t, err) if *update { - if err := ioutil.WriteFile(goldenFile, frameJSON, 0600); err != nil { + if err := os.WriteFile(goldenFile, frameJSON, 0600); err != nil { t.Fatal(err) } } // Safe to disable, this is a test. // nolint:gosec - want, err := ioutil.ReadFile(goldenFile) + want, err := os.ReadFile(goldenFile) if err != nil { t.Fatal(err) } @@ -223,13 +223,13 @@ func TestConverter_Convert_NumFrameFields_LabelsColumn(t *testing.T) { frameJSON, err := json.MarshalIndent(frame, "", " ") require.NoError(t, err) if *update { - if err := ioutil.WriteFile(goldenFile, frameJSON, 0600); err != nil { + if err := os.WriteFile(goldenFile, frameJSON, 0600); err != nil { t.Fatal(err) } } // Safe to disable, this is a test. // nolint:gosec - want, err := ioutil.ReadFile(goldenFile) + want, err := os.ReadFile(goldenFile) if err != nil { t.Fatal(err) } diff --git a/pkg/services/ngalert/api/tooling/cmd/clean-swagger/main.go b/pkg/services/ngalert/api/tooling/cmd/clean-swagger/main.go index 8c4a11269c9..c92b82232e4 100644 --- a/pkg/services/ngalert/api/tooling/cmd/clean-swagger/main.go +++ b/pkg/services/ngalert/api/tooling/cmd/clean-swagger/main.go @@ -3,8 +3,8 @@ package main import ( "encoding/json" "flag" - "io/ioutil" "log" + "os" "strings" ) @@ -22,7 +22,7 @@ func main() { } //nolint - b, err := ioutil.ReadFile(input) + b, err := os.ReadFile(input) if err != nil { log.Fatal(err) } @@ -101,7 +101,7 @@ func main() { log.Fatal(err) } - err = ioutil.WriteFile(output, out, 0644) + err = os.WriteFile(output, out, 0644) if err != nil { log.Fatal(err) } diff --git a/pkg/services/ngalert/api/tooling/definitions/alertmanager_test.go b/pkg/services/ngalert/api/tooling/definitions/alertmanager_test.go index 5b94268dcf4..03c8a1ca627 100644 --- a/pkg/services/ngalert/api/tooling/definitions/alertmanager_test.go +++ b/pkg/services/ngalert/api/tooling/definitions/alertmanager_test.go @@ -3,7 +3,7 @@ package definitions import ( "encoding/json" "errors" - "io/ioutil" + "os" "strings" "testing" @@ -808,10 +808,10 @@ alertmanager_config: | func Test_GettableUserConfigRoundtrip(t *testing.T) { // raw contains secret fields. We'll unmarshal, re-marshal, and ensure // the fields are not redacted. - yamlEncoded, err := ioutil.ReadFile("alertmanager_test_artifact.yaml") + yamlEncoded, err := os.ReadFile("alertmanager_test_artifact.yaml") require.Nil(t, err) - jsonEncoded, err := ioutil.ReadFile("alertmanager_test_artifact.json") + jsonEncoded, err := os.ReadFile("alertmanager_test_artifact.json") require.Nil(t, err) // test GettableUserConfig (yamlDecode -> jsonEncode) @@ -1031,7 +1031,7 @@ routes: } func Test_Marshaling_Validation(t *testing.T) { - jsonEncoded, err := ioutil.ReadFile("alertmanager_test_artifact.json") + jsonEncoded, err := os.ReadFile("alertmanager_test_artifact.json") require.Nil(t, err) var tmp GettableUserConfig diff --git a/pkg/services/ngalert/notifier/channels/default_template.go b/pkg/services/ngalert/notifier/channels/default_template.go index 7798b2fd31c..1ff8ab5792b 100644 --- a/pkg/services/ngalert/notifier/channels/default_template.go +++ b/pkg/services/ngalert/notifier/channels/default_template.go @@ -1,7 +1,6 @@ package channels import ( - "io/ioutil" "os" "testing" @@ -92,7 +91,7 @@ Labels: ` func templateForTests(t *testing.T) *template.Template { - f, err := ioutil.TempFile("/tmp", "template") + f, err := os.CreateTemp("/tmp", "template") require.NoError(t, err) defer func(f *os.File) { _ = f.Close() diff --git a/pkg/services/ngalert/notifier/channels/default_template_test.go b/pkg/services/ngalert/notifier/channels/default_template_test.go index 2647a1876be..534eaa38648 100644 --- a/pkg/services/ngalert/notifier/channels/default_template_test.go +++ b/pkg/services/ngalert/notifier/channels/default_template_test.go @@ -2,7 +2,6 @@ package channels import ( "context" - "io/ioutil" "net/url" "os" "testing" @@ -56,7 +55,7 @@ func TestDefaultTemplateString(t *testing.T) { }, } - f, err := ioutil.TempFile("/tmp", "template") + f, err := os.CreateTemp("/tmp", "template") require.NoError(t, err) defer func(f *os.File) { _ = f.Close() diff --git a/pkg/services/ngalert/notifier/channels/teams_test.go b/pkg/services/ngalert/notifier/channels/teams_test.go index c52f805dc93..b7c8004c654 100644 --- a/pkg/services/ngalert/notifier/channels/teams_test.go +++ b/pkg/services/ngalert/notifier/channels/teams_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -268,7 +268,7 @@ func TestTeamsNotifier(t *testing.T) { expBody, err := json.Marshal(c.expMsg) require.NoError(t, err) - body, err := ioutil.ReadAll(clientStub.lastRequest.Body) + body, err := io.ReadAll(clientStub.lastRequest.Body) require.NoError(t, err) require.JSONEq(t, string(expBody), string(body)) }) @@ -311,6 +311,6 @@ func newMockClient(resp *mockResponse) *mockClient { func makeResponse(status int, body string) *http.Response { return &http.Response{ StatusCode: status, - Body: ioutil.NopCloser(strings.NewReader(body)), + Body: io.NopCloser(strings.NewReader(body)), } } diff --git a/pkg/services/ngalert/notifier/config.go b/pkg/services/ngalert/notifier/config.go index 1879773bd38..343b0b1c853 100644 --- a/pkg/services/ngalert/notifier/config.go +++ b/pkg/services/ngalert/notifier/config.go @@ -36,7 +36,7 @@ func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool, // Check if the template file already exists and if it has changed // We can safely ignore gosec here as we've previously checked the filename is clean // nolint:gosec - if tmpl, err := ioutil.ReadFile(file); err == nil && string(tmpl) == content { + if tmpl, err := os.ReadFile(file); err == nil && string(tmpl) == content { // Templates file is the same we have, no-op and continue. continue } else if err != nil && !os.IsNotExist(err) { @@ -45,7 +45,7 @@ func PersistTemplates(cfg *api.PostableUserConfig, path string) ([]string, bool, // We can safely ignore gosec here as we've previously checked the filename is clean // nolint:gosec - if err := ioutil.WriteFile(file, []byte(content), 0644); err != nil { + if err := os.WriteFile(file, []byte(content), 0644); err != nil { return nil, false, fmt.Errorf("unable to create Alertmanager template file %q: %s", file, err) } diff --git a/pkg/services/ngalert/notifier/config_test.go b/pkg/services/ngalert/notifier/config_test.go index a987dfc86ad..4568eaed635 100644 --- a/pkg/services/ngalert/notifier/config_test.go +++ b/pkg/services/ngalert/notifier/config_test.go @@ -3,6 +3,7 @@ package notifier import ( "errors" "io/ioutil" + "os" "path/filepath" "testing" @@ -71,7 +72,7 @@ func TestPersistTemplates(t *testing.T) { dir := t.TempDir() // Write "existing files" for name, content := range tt.existingTemplates { - err := ioutil.WriteFile(filepath.Join(dir, name), []byte(content), 0644) + err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0644) require.NoError(t, err) } c := &api.PostableUserConfig{TemplateFiles: tt.templates} @@ -87,7 +88,7 @@ func TestPersistTemplates(t *testing.T) { } // Safe to disable, this is a test. // nolint:gosec - content, err := ioutil.ReadFile(filepath.Join(dir, f.Name())) + content, err := os.ReadFile(filepath.Join(dir, f.Name())) // nolint:gosec require.NoError(t, err) files[f.Name()] = string(content) diff --git a/pkg/services/ngalert/notifier/file_store_test.go b/pkg/services/ngalert/notifier/file_store_test.go index b6268a6d649..255a7e65716 100644 --- a/pkg/services/ngalert/notifier/file_store_test.go +++ b/pkg/services/ngalert/notifier/file_store_test.go @@ -2,7 +2,6 @@ package notifier import ( "context" - "io/ioutil" "os" "path/filepath" "testing" @@ -24,7 +23,7 @@ func TestFileStore_FilepathFor_DirectoryNotExist(t *testing.T) { r, err := fs.FilepathFor(context.Background(), filekey) require.NoError(t, err) require.Equal(t, filePath, r) - f, err := ioutil.ReadFile(filepath.Clean(filePath)) + f, err := os.ReadFile(filepath.Clean(filePath)) require.NoError(t, err) require.Equal(t, "silence1,silence3", string(f)) require.NoError(t, os.Remove(filePath)) @@ -44,7 +43,7 @@ func TestFileStore_FilepathFor(t *testing.T) { r, err := fs.FilepathFor(context.Background(), filekey) require.NoError(t, err) require.Equal(t, filePath, r) - f, err := ioutil.ReadFile(filepath.Clean(filePath)) + f, err := os.ReadFile(filepath.Clean(filePath)) require.NoError(t, err) require.Equal(t, "silence1,silence2", string(f)) require.NoError(t, os.Remove(filePath)) @@ -56,7 +55,7 @@ func TestFileStore_FilepathFor(t *testing.T) { r, err := fs.FilepathFor(context.Background(), filekey) require.NoError(t, err) require.Equal(t, filePath, r) - f, err := ioutil.ReadFile(filepath.Clean(filePath)) + f, err := os.ReadFile(filepath.Clean(filePath)) require.NoError(t, err) require.Equal(t, "silence1,silence3", string(f)) require.NoError(t, os.Remove(filePath)) @@ -68,7 +67,7 @@ func TestFileStore_FilepathFor(t *testing.T) { r, err := fs.FilepathFor(context.Background(), filekey) require.NoError(t, err) require.Equal(t, filePath, r) - _, err = ioutil.ReadFile(filepath.Clean(filePath)) + _, err = os.ReadFile(filepath.Clean(filePath)) require.Error(t, err) } } diff --git a/pkg/services/ngalert/sender/testing.go b/pkg/services/ngalert/sender/testing.go index ffec49634bc..2f6d06a2aa2 100644 --- a/pkg/services/ngalert/sender/testing.go +++ b/pkg/services/ngalert/sender/testing.go @@ -2,7 +2,7 @@ package sender import ( "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" "sync" @@ -71,7 +71,7 @@ func (am *FakeExternalAlertmanager) Alerts() amv2.PostableAlerts { func (am *FakeExternalAlertmanager) Handler() func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { - b, err := ioutil.ReadAll(r.Body) + b, err := io.ReadAll(r.Body) require.NoError(am.t, err) a := amv2.PostableAlerts{} diff --git a/pkg/services/notifications/send_email_integration_test.go b/pkg/services/notifications/send_email_integration_test.go index 456e4011a59..a33d2781fa4 100644 --- a/pkg/services/notifications/send_email_integration_test.go +++ b/pkg/services/notifications/send_email_integration_test.go @@ -2,7 +2,7 @@ package notifications import ( "context" - "io/ioutil" + "os" "testing" "github.com/grafana/grafana/pkg/models" @@ -62,9 +62,9 @@ func TestEmailIntegrationTest(t *testing.T) { sentMsg := <-ns.mailQueue require.Equal(t, sentMsg.From, "Grafana Admin ") require.Equal(t, sentMsg.To[0], "asdf@asdf.com") - err = ioutil.WriteFile("../../../tmp/test_email.html", []byte(sentMsg.Body["text/html"]), 0777) + err = os.WriteFile("../../../tmp/test_email.html", []byte(sentMsg.Body["text/html"]), 0777) require.NoError(t, err) - err = ioutil.WriteFile("../../../tmp/test_email.txt", []byte(sentMsg.Body["text/plain"]), 0777) + err = os.WriteFile("../../../tmp/test_email.txt", []byte(sentMsg.Body["text/plain"]), 0777) require.NoError(t, err) }) }) diff --git a/pkg/services/notifications/webhook.go b/pkg/services/notifications/webhook.go index 15acd8ea2fd..6ff7df5efe8 100644 --- a/pkg/services/notifications/webhook.go +++ b/pkg/services/notifications/webhook.go @@ -5,7 +5,7 @@ import ( "context" "crypto/tls" "fmt" - "io/ioutil" + "io" "net" "net/http" "time" @@ -88,7 +88,7 @@ func (ns *NotificationService) sendWebRequestSync(ctx context.Context, webhook * } }() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return err } diff --git a/pkg/services/provisioning/alerting/config_reader.go b/pkg/services/provisioning/alerting/config_reader.go index 9eaccff3c63..281b3ca31b8 100644 --- a/pkg/services/provisioning/alerting/config_reader.go +++ b/pkg/services/provisioning/alerting/config_reader.go @@ -5,6 +5,7 @@ import ( "fmt" "io/fs" "io/ioutil" + "os" "path/filepath" "strings" @@ -65,7 +66,7 @@ func (cr *rulesConfigReader) parseConfig(path string, file fs.FileInfo) (*Alerti filename, _ := filepath.Abs(filepath.Join(path, file.Name())) // nolint:gosec // We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath - yamlFile, err := ioutil.ReadFile(filename) + yamlFile, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/pkg/services/provisioning/dashboards/config_reader.go b/pkg/services/provisioning/dashboards/config_reader.go index ab65d1f8539..ee28778c2a4 100644 --- a/pkg/services/provisioning/dashboards/config_reader.go +++ b/pkg/services/provisioning/dashboards/config_reader.go @@ -24,7 +24,7 @@ func (cr *configReader) parseConfigs(file os.FileInfo) ([]*config, error) { // nolint:gosec // We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath - yamlFile, err := ioutil.ReadFile(filename) + yamlFile, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/pkg/services/provisioning/dashboards/file_reader.go b/pkg/services/provisioning/dashboards/file_reader.go index 35e16e870ea..bf074d96b4e 100644 --- a/pkg/services/provisioning/dashboards/file_reader.go +++ b/pkg/services/provisioning/dashboards/file_reader.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "os" "path/filepath" "strings" @@ -397,7 +397,7 @@ func (fr *FileReader) readDashboardFromFile(path string, lastModified time.Time, } }() - all, err := ioutil.ReadAll(reader) + all, err := io.ReadAll(reader) if err != nil { return nil, err } diff --git a/pkg/services/provisioning/datasources/config_reader.go b/pkg/services/provisioning/datasources/config_reader.go index c50191dc4b8..e0c12f8dd63 100644 --- a/pkg/services/provisioning/datasources/config_reader.go +++ b/pkg/services/provisioning/datasources/config_reader.go @@ -55,7 +55,7 @@ func (cr *configReader) parseDatasourceConfig(path string, file os.FileInfo) (*c // nolint:gosec // We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath - yamlFile, err := ioutil.ReadFile(filename) + yamlFile, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/pkg/services/provisioning/notifiers/config_reader.go b/pkg/services/provisioning/notifiers/config_reader.go index b502c3872e7..f76aefdb49a 100644 --- a/pkg/services/provisioning/notifiers/config_reader.go +++ b/pkg/services/provisioning/notifiers/config_reader.go @@ -70,7 +70,7 @@ func (cr *configReader) parseNotificationConfig(path string, file os.FileInfo) ( // nolint:gosec // We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath - yamlFile, err := ioutil.ReadFile(filename) + yamlFile, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/pkg/services/provisioning/plugins/config_reader.go b/pkg/services/provisioning/plugins/config_reader.go index 78aa3936ae2..56243e827d0 100644 --- a/pkg/services/provisioning/plugins/config_reader.go +++ b/pkg/services/provisioning/plugins/config_reader.go @@ -73,7 +73,7 @@ func (cr *configReaderImpl) parsePluginConfig(path string, file os.FileInfo) (*p // nolint:gosec // We can ignore the gosec G304 warning on this one because `filename` comes from ps.Cfg.ProvisioningPath - yamlFile, err := ioutil.ReadFile(filename) + yamlFile, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/pkg/services/provisioning/values/values_test.go b/pkg/services/provisioning/values/values_test.go index 8f5209fb1dc..8a3615f21c6 100644 --- a/pkg/services/provisioning/values/values_test.go +++ b/pkg/services/provisioning/values/values_test.go @@ -3,7 +3,6 @@ package values import ( "errors" "fmt" - "io/ioutil" "os" "testing" @@ -311,7 +310,7 @@ func TestValues_readFile(t *testing.T) { Val StringValue `yaml:"val"` } - f, err := ioutil.TempFile(os.TempDir(), "file expansion *") + f, err := os.CreateTemp(os.TempDir(), "file expansion *") require.NoError(t, err) file := f.Name() diff --git a/pkg/services/searchV2/index.go b/pkg/services/searchV2/index.go index 8560aa54df1..4c0626340c7 100644 --- a/pkg/services/searchV2/index.go +++ b/pkg/services/searchV2/index.go @@ -5,7 +5,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "os/exec" "runtime" @@ -356,7 +355,7 @@ func (i *searchIndex) reportSizeOfIndexDiskBackup(orgID int64) { defer cancel() // create a temp directory to store the index - tmpDir, err := ioutil.TempDir("", "grafana.dashboard_index") + tmpDir, err := os.MkdirTemp("", "grafana.dashboard_index") if err != nil { i.logger.Error("can't create temp dir", "error", err) return diff --git a/pkg/services/sqlstore/tls_mysql.go b/pkg/services/sqlstore/tls_mysql.go index 10ac56004a7..bb7baf2f4e6 100644 --- a/pkg/services/sqlstore/tls_mysql.go +++ b/pkg/services/sqlstore/tls_mysql.go @@ -4,7 +4,7 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" + "os" "github.com/grafana/grafana/pkg/infra/log" ) @@ -13,7 +13,7 @@ var tlslog = log.New("tls_mysql") func makeCert(config DatabaseConfig) (*tls.Config, error) { rootCertPool := x509.NewCertPool() - pem, err := ioutil.ReadFile(config.CaCertPath) + pem, err := os.ReadFile(config.CaCertPath) if err != nil { return nil, fmt.Errorf("could not read DB CA Cert path %q: %w", config.CaCertPath, err) } diff --git a/pkg/services/store/config.go b/pkg/services/store/config.go index acbd2a492ce..9b9efca498b 100644 --- a/pkg/services/store/config.go +++ b/pkg/services/store/config.go @@ -3,7 +3,6 @@ package store import ( "encoding/json" "fmt" - "io/ioutil" "os" "path/filepath" @@ -32,7 +31,7 @@ func LoadStorageConfig(cfg *setting.Cfg, features featuremgmt.FeatureToggles) (* if _, err := os.Stat(fpath); err == nil { // nolint:gosec // We can ignore the gosec G304 warning since the path is hardcoded above - body, err := ioutil.ReadFile(fpath) + body, err := os.ReadFile(fpath) if err != nil { return g, err } @@ -96,7 +95,7 @@ func (c *GlobalStorageConfig) save() error { if err != nil { return err } - return ioutil.WriteFile(c.filepath, out, 0600) + return os.WriteFile(c.filepath, out, 0600) } type RootStorageConfig struct { diff --git a/pkg/services/store/http.go b/pkg/services/store/http.go index b68df21b368..6d6edd9c52b 100644 --- a/pkg/services/store/http.go +++ b/pkg/services/store/http.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "strings" @@ -114,7 +113,7 @@ func (s *standardStorageService) doUpload(c *models.ReqContext) response.Respons if err != nil { return response.Error(500, "Internal Server Error", err) } - data, err := ioutil.ReadAll(file) + data, err := io.ReadAll(file) if err != nil { return response.Error(500, "Internal Server Error", err) } diff --git a/pkg/services/store/service_test.go b/pkg/services/store/service_test.go index 3e443d442cd..1f08ff5ee48 100644 --- a/pkg/services/store/service_test.go +++ b/pkg/services/store/service_test.go @@ -3,7 +3,7 @@ package store import ( "bytes" "context" - "io/ioutil" + "os" "path/filepath" "testing" @@ -24,9 +24,9 @@ var ( AllowUnsanitizedSvgUpload: true, }, } - htmlBytes, _ = ioutil.ReadFile("testdata/page.html") - jpgBytes, _ = ioutil.ReadFile("testdata/image.jpg") - svgBytes, _ = ioutil.ReadFile("testdata/image.svg") + htmlBytes, _ = os.ReadFile("testdata/page.html") + jpgBytes, _ = os.ReadFile("testdata/image.jpg") + svgBytes, _ = os.ReadFile("testdata/image.svg") dummyUser = &user.SignedInUser{OrgId: 1} allowAllAuthService = newStaticStorageAuthService(func(ctx context.Context, user *user.SignedInUser, storageName string) map[string]filestorage.PathFilter { return map[string]filestorage.PathFilter{ diff --git a/pkg/services/thumbs/service.go b/pkg/services/thumbs/service.go index 78f24a01263..d208743dc1b 100644 --- a/pkg/services/thumbs/service.go +++ b/pkg/services/thumbs/service.go @@ -5,7 +5,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "time" @@ -388,7 +387,7 @@ func (hs *thumbService) SetImage(c *models.ReqContext) { hs.log.Info("File Size: %+v\n", handler.Size) hs.log.Info("MIME Header: %+v\n", handler.Header) - fileBytes, err := ioutil.ReadAll(file) + fileBytes, err := io.ReadAll(file) if err != nil { fmt.Println(err) c.JSON(400, map[string]string{"error": "error reading file"}) diff --git a/pkg/services/updatechecker/grafana.go b/pkg/services/updatechecker/grafana.go index f66fb76e9d6..bfe8dbe5a7d 100644 --- a/pkg/services/updatechecker/grafana.go +++ b/pkg/services/updatechecker/grafana.go @@ -3,7 +3,7 @@ package updatechecker import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "strings" "sync" @@ -68,7 +68,7 @@ func (s *GrafanaService) checkForUpdates() { s.log.Warn("Failed to close response body", "err", err) } }() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { s.log.Debug("Update check failed, reading response from github.com", "error", err) return diff --git a/pkg/services/updatechecker/plugins.go b/pkg/services/updatechecker/plugins.go index 967fdb9fdcb..8ba7c27348d 100644 --- a/pkg/services/updatechecker/plugins.go +++ b/pkg/services/updatechecker/plugins.go @@ -3,7 +3,7 @@ package updatechecker import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "strings" "sync" @@ -99,7 +99,7 @@ func (s *PluginsService) checkForUpdates(ctx context.Context) { } }() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { s.log.Debug("Update check failed, reading response from grafana.com", "error", err.Error()) return diff --git a/pkg/services/updatechecker/plugins_test.go b/pkg/services/updatechecker/plugins_test.go index 29cb69e268b..44994f92882 100644 --- a/pkg/services/updatechecker/plugins_test.go +++ b/pkg/services/updatechecker/plugins_test.go @@ -2,7 +2,7 @@ package updatechecker import ( "context" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -190,7 +190,7 @@ func (c *fakeHTTPClient) Get(url string) (*http.Response, error) { c.requestURL = url resp := &http.Response{ - Body: ioutil.NopCloser(strings.NewReader(c.fakeResp)), + Body: io.NopCloser(strings.NewReader(c.fakeResp)), } return resp, nil diff --git a/pkg/setting/expanders.go b/pkg/setting/expanders.go index 4ec438d8c7a..76736de054f 100644 --- a/pkg/setting/expanders.go +++ b/pkg/setting/expanders.go @@ -2,7 +2,6 @@ package setting import ( "fmt" - "io/ioutil" "os" "regexp" "sort" @@ -145,7 +144,7 @@ func (e fileExpander) Expand(s string) (string, error) { // nolint:gosec // We can ignore the gosec G304 warning on this one because `s` comes from configuration section keys - f, err := ioutil.ReadFile(s) + f, err := os.ReadFile(s) if err != nil { return "", err } diff --git a/pkg/setting/expanders_test.go b/pkg/setting/expanders_test.go index 061e9a7e950..a4687157ddd 100644 --- a/pkg/setting/expanders_test.go +++ b/pkg/setting/expanders_test.go @@ -3,7 +3,6 @@ package setting import ( "errors" "fmt" - "io/ioutil" "math/rand" "os" "testing" @@ -35,7 +34,7 @@ func TestExpandVar_EnvSuccessful(t *testing.T) { } func TestExpandVar_FileSuccessful(t *testing.T) { - f, err := ioutil.TempFile(os.TempDir(), "file expansion *") + f, err := os.CreateTemp(os.TempDir(), "file expansion *") require.NoError(t, err) file := f.Name() diff --git a/pkg/tests/api/alerting/api_admin_configuration_test.go b/pkg/tests/api/alerting/api_admin_configuration_test.go index 01fcf12114f..ece71e7c75a 100644 --- a/pkg/tests/api/alerting/api_admin_configuration_test.go +++ b/pkg/tests/api/alerting/api_admin_configuration_test.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" "time" @@ -62,7 +62,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { { alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := getRequest(t, alertsURL, http.StatusNotFound) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} err = json.Unmarshal(b, &res) @@ -82,7 +82,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := postRequest(t, alertsURL, buf.String(), http.StatusBadRequest) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} err = json.Unmarshal(b, &res) @@ -103,7 +103,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := postRequest(t, alertsURL, buf.String(), http.StatusBadRequest) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} err = json.Unmarshal(b, &res) @@ -125,7 +125,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := postRequest(t, alertsURL, buf.String(), http.StatusCreated) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} err = json.Unmarshal(b, &res) @@ -137,7 +137,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { { alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := getRequest(t, alertsURL, http.StatusOK) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.JSONEq(t, fmt.Sprintf("{\"alertmanagers\":[\"%s\",\"%s\"], \"alertmanagersChoice\": %q}\n", fakeAM1.URL(), fakeAM2.URL(), ngmodels.ExternalAlertmanagers), string(b)) } @@ -147,7 +147,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { alertsURL := fmt.Sprintf("http://grafana:password@%s/api/v1/ngalert/alertmanagers", grafanaListedAddr) require.Eventually(t, func() bool { resp := getRequest(t, alertsURL, http.StatusOK) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var alertmanagers apimodels.GettableAlertmanagers @@ -227,7 +227,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { alertsURL := fmt.Sprintf("http://admin-42:admin-42@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := postRequest(t, alertsURL, buf.String(), http.StatusCreated) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} err = json.Unmarshal(b, &res) @@ -239,7 +239,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { { alertsURL := fmt.Sprintf("http://admin-42:admin-42@%s/api/v1/ngalert/admin_config", grafanaListedAddr) resp := getRequest(t, alertsURL, http.StatusOK) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.JSONEq(t, fmt.Sprintf("{\"alertmanagers\":[\"%s\"], \"alertmanagersChoice\": %q}\n", fakeAM3.URL(), ngmodels.AllAlertmanagers), string(b)) } @@ -249,7 +249,7 @@ func TestAdminConfiguration_SendingToExternalAlertmanagers(t *testing.T) { alertsURL := fmt.Sprintf("http://admin-42:admin-42@%s/api/v1/ngalert/alertmanagers", grafanaListedAddr) require.Eventually(t, func() bool { resp := getRequest(t, alertsURL, http.StatusOK) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var alertmanagers apimodels.GettableAlertmanagers diff --git a/pkg/tests/api/alerting/api_alertmanager_configuration_test.go b/pkg/tests/api/alerting/api_alertmanager_configuration_test.go index 4da868528df..8abf9294559 100644 --- a/pkg/tests/api/alerting/api_alertmanager_configuration_test.go +++ b/pkg/tests/api/alerting/api_alertmanager_configuration_test.go @@ -3,7 +3,7 @@ package alerting import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "regexp" "testing" @@ -87,7 +87,7 @@ func TestAlertmanagerConfigurationIsTransactional(t *testing.T) { } ` resp := postRequest(t, alertConfigURL, payload, http.StatusBadRequest) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} require.NoError(t, json.Unmarshal(b, &res)) diff --git a/pkg/tests/api/alerting/api_alertmanager_test.go b/pkg/tests/api/alerting/api_alertmanager_test.go index 07793a5e0eb..1fbc16b9e01 100644 --- a/pkg/tests/api/alerting/api_alertmanager_test.go +++ b/pkg/tests/api/alerting/api_alertmanager_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "regexp" "strings" @@ -127,7 +127,7 @@ func TestAMConfigAccess(t *testing.T) { }) require.NoError(t, err) require.Equal(t, tc.expStatus, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Contains(t, string(b), tc.expBody) }) @@ -194,7 +194,7 @@ func TestAMConfigAccess(t *testing.T) { }) require.NoError(t, err) require.Equal(t, tc.expStatus, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if tc.expStatus == http.StatusOK { re := regexp.MustCompile(`"uid":"([\w|-]+)"`) b = re.ReplaceAll(b, []byte(`"uid":""`)) @@ -260,7 +260,7 @@ func TestAMConfigAccess(t *testing.T) { }) require.NoError(t, err) require.Equal(t, tc.expStatus, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) if tc.expStatus == http.StatusAccepted { re := regexp.MustCompile(`"id":"([\w|-]+)"`) @@ -309,7 +309,7 @@ func TestAMConfigAccess(t *testing.T) { require.Equal(t, tc.expStatus, resp.StatusCode) require.NoError(t, err) if tc.expStatus == http.StatusOK { - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) blob = b } @@ -379,7 +379,7 @@ func TestAMConfigAccess(t *testing.T) { }) require.NoError(t, err) require.Equal(t, tc.expStatus, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) if tc.expStatus == http.StatusOK { unconsumedSilenceIdx++ @@ -410,7 +410,7 @@ func TestAlertAndGroupsQuery(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusUnauthorized, resp.StatusCode) require.JSONEq(t, `{"message": "Unauthorized"}`, string(b)) @@ -435,7 +435,7 @@ func TestAlertAndGroupsQuery(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusUnauthorized, resp.StatusCode) @@ -454,7 +454,7 @@ func TestAlertAndGroupsQuery(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.JSONEq(t, "[]", string(b)) @@ -470,7 +470,7 @@ func TestAlertAndGroupsQuery(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -529,7 +529,7 @@ func TestAlertAndGroupsQuery(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -704,7 +704,7 @@ func TestDeleteFolderWithRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, 200, resp.StatusCode) @@ -781,7 +781,7 @@ func TestDeleteFolderWithRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusBadRequest, resp.StatusCode) require.JSONEq(t, `{"message":"folder cannot be deleted: folder contains alert rules"}`, string(b)) @@ -799,7 +799,7 @@ func TestDeleteFolderWithRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.JSONEq(t, `{"id":1,"message":"Folder default deleted","title":"default"}`, string(b)) @@ -815,7 +815,7 @@ func TestDeleteFolderWithRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, 200, resp.StatusCode) @@ -1155,7 +1155,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -1322,7 +1322,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -1428,7 +1428,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -1500,7 +1500,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -1617,7 +1617,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -1702,7 +1702,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -1774,7 +1774,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusAccepted, resp.StatusCode) @@ -1793,7 +1793,7 @@ func TestAlertRuleCRUD(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusAccepted, resp.StatusCode) @@ -1822,7 +1822,7 @@ func TestAlertmanagerStatus(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.JSONEq(t, ` @@ -1904,7 +1904,7 @@ func TestQuota(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -2022,7 +2022,7 @@ func TestQuota(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -2318,7 +2318,7 @@ func TestEval(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) res := Response{} err = json.Unmarshal(b, &res) @@ -2501,7 +2501,7 @@ func TestEval(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) res := Response{} err = json.Unmarshal(b, &res) diff --git a/pkg/tests/api/alerting/api_available_channel_test.go b/pkg/tests/api/alerting/api_available_channel_test.go index 9e6417d95a8..bbf605de55c 100644 --- a/pkg/tests/api/alerting/api_available_channel_test.go +++ b/pkg/tests/api/alerting/api_available_channel_test.go @@ -3,7 +3,7 @@ package alerting import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -40,7 +40,7 @@ func TestAvailableChannels(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) diff --git a/pkg/tests/api/alerting/api_notification_channel_test.go b/pkg/tests/api/alerting/api_notification_channel_test.go index 8808e6ce06f..be91682a440 100644 --- a/pkg/tests/api/alerting/api_notification_channel_test.go +++ b/pkg/tests/api/alerting/api_notification_channel_test.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "mime/multipart" "net" "net/http" @@ -59,7 +58,7 @@ func TestTestReceivers(t *testing.T) { require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) res := Response{} err = json.Unmarshal(b, &res) @@ -110,7 +109,7 @@ func TestTestReceivers(t *testing.T) { require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -189,7 +188,7 @@ func TestTestReceivers(t *testing.T) { require.NoError(t, resp.Body.Close()) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -276,7 +275,7 @@ func TestTestReceivers(t *testing.T) { }) require.Equal(t, http.StatusRequestTimeout, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -375,7 +374,7 @@ func TestTestReceivers(t *testing.T) { }) require.Equal(t, http.StatusMultiStatus, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -478,7 +477,7 @@ func TestTestReceiversAlertCustomization(t *testing.T) { require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -568,7 +567,7 @@ func TestTestReceiversAlertCustomization(t *testing.T) { require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -655,7 +654,7 @@ func TestTestReceiversAlertCustomization(t *testing.T) { require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var result apimodels.TestReceiversResult @@ -752,7 +751,7 @@ func TestNotificationChannels(t *testing.T) { // There are no notification channel config initially - so it returns the default configuration. alertsURL := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr) resp := getRequest(t, alertsURL, http.StatusOK) // nolint - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.JSONEq(t, defaultAlertmanagerConfigJSON, string(b)) } @@ -812,14 +811,14 @@ func TestNotificationChannels(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 202, resp.StatusCode) require.JSONEq(t, `{"message":"configuration deleted; the default is applied"}`, string(b)) alertsURL := fmt.Sprintf("http://grafana:password@%s/api/alertmanager/grafana/config/api/v1/alerts", grafanaListedAddr) resp = getRequest(t, alertsURL, http.StatusOK) // nolint - b, err = ioutil.ReadAll(resp.Body) + b, err = io.ReadAll(resp.Body) require.NoError(t, err) require.JSONEq(t, defaultAlertmanagerConfigJSON, string(b)) } diff --git a/pkg/tests/api/alerting/api_prometheus_test.go b/pkg/tests/api/alerting/api_prometheus_test.go index a88c86b9943..3a8f32cc331 100644 --- a/pkg/tests/api/alerting/api_prometheus_test.go +++ b/pkg/tests/api/alerting/api_prometheus_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "sort" "testing" @@ -74,7 +74,7 @@ func TestPrometheusRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, 200, resp.StatusCode) require.JSONEq(t, `{"status": "success", "data": {"groups": []}}`, string(b)) @@ -149,7 +149,7 @@ func TestPrometheusRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -203,7 +203,7 @@ func TestPrometheusRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, 400, resp.StatusCode) @@ -222,7 +222,7 @@ func TestPrometheusRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -275,7 +275,7 @@ func TestPrometheusRules(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.JSONEq(t, ` @@ -414,7 +414,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 202) @@ -501,7 +501,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -518,7 +518,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -535,7 +535,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -552,7 +552,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -569,7 +569,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -587,7 +587,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { require.NoError(t, err) }) require.Equal(t, http.StatusBadRequest, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} require.NoError(t, json.Unmarshal(b, &res)) @@ -605,7 +605,7 @@ func TestPrometheusRulesFilterByDashboard(t *testing.T) { require.NoError(t, err) }) require.Equal(t, http.StatusBadRequest, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} require.NoError(t, json.Unmarshal(b, &res)) @@ -657,7 +657,7 @@ func TestPrometheusRulesPermissions(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -687,7 +687,7 @@ func TestPrometheusRulesPermissions(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -712,7 +712,7 @@ func TestPrometheusRulesPermissions(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) diff --git a/pkg/tests/api/alerting/api_ruler_test.go b/pkg/tests/api/alerting/api_ruler_test.go index 96a755135ac..95b4b9c0c40 100644 --- a/pkg/tests/api/alerting/api_ruler_test.go +++ b/pkg/tests/api/alerting/api_ruler_test.go @@ -3,7 +3,7 @@ package alerting import ( "encoding/json" "fmt" - "io/ioutil" + "io" "math/rand" "net/http" "testing" @@ -64,7 +64,7 @@ func TestAlertRulePermissions(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) @@ -187,7 +187,7 @@ func TestAlertRulePermissions(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err = ioutil.ReadAll(resp.Body) + b, err = io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) @@ -261,7 +261,7 @@ func TestAlertRulePermissions(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, resp.StatusCode, 200) @@ -604,7 +604,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -622,7 +622,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -640,7 +640,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -657,7 +657,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -675,7 +675,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -693,7 +693,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { require.NoError(t, err) }) require.Equal(t, http.StatusBadRequest, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} require.NoError(t, json.Unmarshal(b, &res)) @@ -711,7 +711,7 @@ func TestRulerRulesFilterByDashboard(t *testing.T) { require.NoError(t, err) }) require.Equal(t, http.StatusBadRequest, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var res map[string]interface{} require.NoError(t, json.Unmarshal(b, &res)) diff --git a/pkg/tests/api/alerting/testing.go b/pkg/tests/api/alerting/testing.go index 3fc58e6b854..0b2540a7628 100644 --- a/pkg/tests/api/alerting/testing.go +++ b/pkg/tests/api/alerting/testing.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "strings" "testing" @@ -55,7 +54,7 @@ func getRequest(t *testing.T, url string, expStatusCode int) *http.Response { require.NoError(t, resp.Body.Close()) }) if expStatusCode != resp.StatusCode { - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) t.Fatal(string(b)) } @@ -72,7 +71,7 @@ func postRequest(t *testing.T, url string, body string, expStatusCode int) *http require.NoError(t, resp.Body.Close()) }) if expStatusCode != resp.StatusCode { - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) t.Fatal(string(b)) } @@ -81,7 +80,7 @@ func postRequest(t *testing.T, url string, body string, expStatusCode int) *http func getBody(t *testing.T, body io.ReadCloser) string { t.Helper() - b, err := ioutil.ReadAll(body) + b, err := io.ReadAll(body) require.NoError(t, err) return string(b) } @@ -217,7 +216,7 @@ func (a apiClient) PostRulesGroup(t *testing.T, folder string, group *apimodels. defer func() { _ = resp.Body.Close() }() - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) return resp.StatusCode, string(b) } @@ -231,7 +230,7 @@ func (a apiClient) GetRulesGroup(t *testing.T, folder string, group string) apim defer func() { _ = resp.Body.Close() }() - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, http.StatusAccepted, resp.StatusCode) @@ -249,7 +248,7 @@ func (a apiClient) GetAllRulesGroupInFolder(t *testing.T, folder string) apimode defer func() { _ = resp.Body.Close() }() - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, http.StatusAccepted, resp.StatusCode) diff --git a/pkg/tests/api/correlations/correlations_create_test.go b/pkg/tests/api/correlations/correlations_create_test.go index aa3fcee75b2..ba34820567f 100644 --- a/pkg/tests/api/correlations/correlations_create_test.go +++ b/pkg/tests/api/correlations/correlations_create_test.go @@ -3,7 +3,7 @@ package correlations import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -64,7 +64,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusUnauthorized, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -84,7 +84,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusForbidden, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -104,7 +104,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusBadRequest, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -126,7 +126,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusNotFound, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -149,7 +149,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusNotFound, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -172,7 +172,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusForbidden, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -195,7 +195,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response correlations.CreateCorrelationResponseBody @@ -225,7 +225,7 @@ func TestIntegrationCreateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response correlations.CreateCorrelationResponseBody diff --git a/pkg/tests/api/correlations/correlations_delete_test.go b/pkg/tests/api/correlations/correlations_delete_test.go index a09d330b64e..d92d5623427 100644 --- a/pkg/tests/api/correlations/correlations_delete_test.go +++ b/pkg/tests/api/correlations/correlations_delete_test.go @@ -3,7 +3,7 @@ package correlations import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -64,7 +64,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { }) require.Equal(t, http.StatusUnauthorized, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -83,7 +83,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { }) require.Equal(t, http.StatusForbidden, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -103,7 +103,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { require.Equal(t, http.StatusNotFound, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -123,7 +123,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { }) require.Equal(t, http.StatusNotFound, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -143,7 +143,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { }) require.Equal(t, http.StatusForbidden, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -169,7 +169,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response correlations.CreateCorrelationResponseBody @@ -201,7 +201,7 @@ func TestIntegrationDeleteCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response correlations.CreateCorrelationResponseBody diff --git a/pkg/tests/api/correlations/correlations_update_test.go b/pkg/tests/api/correlations/correlations_update_test.go index d6165f82b31..0e54593adfe 100644 --- a/pkg/tests/api/correlations/correlations_update_test.go +++ b/pkg/tests/api/correlations/correlations_update_test.go @@ -3,7 +3,7 @@ package correlations import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "testing" @@ -65,7 +65,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusUnauthorized, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -85,7 +85,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusForbidden, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -105,7 +105,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusNotFound, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -128,7 +128,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusNotFound, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -149,7 +149,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusForbidden, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -177,7 +177,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusBadRequest, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response errorResponseBody @@ -196,7 +196,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusBadRequest, res.StatusCode) - responseBody, err = ioutil.ReadAll(res.Body) + responseBody, err = io.ReadAll(res.Body) require.NoError(t, err) err = json.Unmarshal(responseBody, &response) @@ -217,7 +217,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusBadRequest, res.StatusCode) - responseBody, err = ioutil.ReadAll(res.Body) + responseBody, err = io.ReadAll(res.Body) require.NoError(t, err) err = json.Unmarshal(responseBody, &response) @@ -245,7 +245,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response correlations.UpdateCorrelationResponseBody @@ -277,7 +277,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err := ioutil.ReadAll(res.Body) + responseBody, err := io.ReadAll(res.Body) require.NoError(t, err) var response correlations.UpdateCorrelationResponseBody @@ -299,7 +299,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err = ioutil.ReadAll(res.Body) + responseBody, err = io.ReadAll(res.Body) require.NoError(t, err) err = json.Unmarshal(responseBody, &response) @@ -320,7 +320,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err = ioutil.ReadAll(res.Body) + responseBody, err = io.ReadAll(res.Body) require.NoError(t, err) err = json.Unmarshal(responseBody, &response) @@ -342,7 +342,7 @@ func TestIntegrationUpdateCorrelation(t *testing.T) { }) require.Equal(t, http.StatusOK, res.StatusCode) - responseBody, err = ioutil.ReadAll(res.Body) + responseBody, err = io.ReadAll(res.Body) require.NoError(t, err) err = json.Unmarshal(responseBody, &response) diff --git a/pkg/tests/api/dashboards/api_dashboards_test.go b/pkg/tests/api/dashboards/api_dashboards_test.go index c3f1ea2d230..7e8841dedb0 100644 --- a/pkg/tests/api/dashboards/api_dashboards_test.go +++ b/pkg/tests/api/dashboards/api_dashboards_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -62,7 +62,7 @@ func TestDashboardQuota(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) dashboardDTO := &plugindashboards.PluginDashboard{} err = json.Unmarshal(b, dashboardDTO) @@ -87,7 +87,7 @@ func TestDashboardQuota(t *testing.T) { err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.Equal(t, http.StatusForbidden, resp.StatusCode) require.JSONEq(t, `{"message":"Quota reached"}`, string(b)) @@ -124,10 +124,10 @@ providers: path: %s`, provDashboardsDir)) err := os.WriteFile(provDashboardsCfg, blob, 0644) require.NoError(t, err) - input, err := ioutil.ReadFile(filepath.Join("./home.json")) + input, err := os.ReadFile(filepath.Join("./home.json")) require.NoError(t, err) provDashboardFile := filepath.Join(provDashboardsDir, "home.json") - err = ioutil.WriteFile(provDashboardFile, input, 0644) + err = os.WriteFile(provDashboardFile, input, 0644) require.NoError(t, err) grafanaListedAddr, store := testinfra.StartGrafana(t, dir, path) // Create user @@ -152,7 +152,7 @@ providers: err := resp.Body.Close() require.NoError(t, err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) dashboardList := &models.HitList{} err = json.Unmarshal(b, dashboardList) @@ -219,7 +219,7 @@ providers: if tc.expErrReason == "" { return } - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) dashboardErr := &errorResponseBody{} err = json.Unmarshal(b, dashboardErr) @@ -245,7 +245,7 @@ providers: }) assert.Equal(t, http.StatusBadRequest, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) dashboardErr := &errorResponseBody{} err = json.Unmarshal(b, dashboardErr) diff --git a/pkg/tests/api/plugins/api_plugins_test.go b/pkg/tests/api/plugins/api_plugins_test.go index db58b42b5e5..91ba72c5794 100644 --- a/pkg/tests/api/plugins/api_plugins_test.go +++ b/pkg/tests/api/plugins/api_plugins_test.go @@ -5,8 +5,9 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" + "os" "path/filepath" "testing" @@ -86,7 +87,7 @@ func TestPlugins(t *testing.T) { }) require.NoError(t, err) require.Equal(t, tc.expStatus, resp.StatusCode) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) expResp := expectedResp(t, tc.expRespPath) @@ -128,7 +129,7 @@ func makePostRequest(t *testing.T, URL string) (int, map[string]interface{}) { _ = resp.Body.Close() fmt.Printf("Failed to close response body err: %s", err) }) - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) require.NoError(t, err) var body = make(map[string]interface{}) @@ -144,7 +145,7 @@ func grafanaAPIURL(username string, grafanaListedAddr string, path string) strin func expectedResp(t *testing.T, filename string) string { //nolint:GOSEC - contents, err := ioutil.ReadFile(filepath.Join("data", filename)) + contents, err := os.ReadFile(filepath.Join("data", filename)) if err != nil { t.Errorf("failed to load %s: %v", filename, err) } @@ -153,7 +154,7 @@ func expectedResp(t *testing.T, filename string) string { } func updateRespSnapshot(t *testing.T, filename string, body string) { - err := ioutil.WriteFile(filepath.Join("data", filename), []byte(body), 0600) + err := os.WriteFile(filepath.Join("data", filename), []byte(body), 0600) if err != nil { t.Errorf("error writing snapshot %s: %v", filename, err) } diff --git a/pkg/tsdb/azuremonitor/azuremonitor-resource-handler.go b/pkg/tsdb/azuremonitor/azuremonitor-resource-handler.go index 82e148c5984..264891e935c 100644 --- a/pkg/tsdb/azuremonitor/azuremonitor-resource-handler.go +++ b/pkg/tsdb/azuremonitor/azuremonitor-resource-handler.go @@ -2,7 +2,7 @@ package azuremonitor import ( "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" @@ -40,7 +40,7 @@ func (s *httpServiceProxy) Do(rw http.ResponseWriter, req *http.Request, cli *ht } }() - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { rw.WriteHeader(http.StatusInternalServerError) _, err = rw.Write([]byte(fmt.Sprintf("unexpected error %v", err))) diff --git a/pkg/tsdb/azuremonitor/azuremonitor-resource-handler_test.go b/pkg/tsdb/azuremonitor/azuremonitor-resource-handler_test.go index 61b71e480de..6c7457ef064 100644 --- a/pkg/tsdb/azuremonitor/azuremonitor-resource-handler_test.go +++ b/pkg/tsdb/azuremonitor/azuremonitor-resource-handler_test.go @@ -1,7 +1,7 @@ package azuremonitor import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -71,7 +71,7 @@ func Test_proxyRequest(t *testing.T) { t.Errorf("Unexpected headers: %v", res.Header()) } result := rw.Result() - body, err := ioutil.ReadAll(result.Body) + body, err := io.ReadAll(result.Body) if err != nil { t.Error(err) } diff --git a/pkg/tsdb/azuremonitor/azuremonitor_test.go b/pkg/tsdb/azuremonitor/azuremonitor_test.go index d4555dfa706..98621dfb0f0 100644 --- a/pkg/tsdb/azuremonitor/azuremonitor_test.go +++ b/pkg/tsdb/azuremonitor/azuremonitor_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "errors" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -205,7 +205,7 @@ func TestCheckHealth(t *testing.T) { } return &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewBuffer(bodyMarshal)), + Body: io.NopCloser(bytes.NewBuffer(bodyMarshal)), Header: make(http.Header), }, nil } else { @@ -218,7 +218,7 @@ func TestCheckHealth(t *testing.T) { } return &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewBuffer(bodyMarshal)), + Body: io.NopCloser(bytes.NewBuffer(bodyMarshal)), Header: make(http.Header), }, nil } @@ -231,13 +231,13 @@ func TestCheckHealth(t *testing.T) { if !fail { return &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewBufferString("OK")), + Body: io.NopCloser(bytes.NewBufferString("OK")), Header: make(http.Header), }, nil } else { return &http.Response{ StatusCode: 404, - Body: ioutil.NopCloser(bytes.NewBufferString("not found")), + Body: io.NopCloser(bytes.NewBufferString("not found")), Header: make(http.Header), }, nil } @@ -247,7 +247,7 @@ func TestCheckHealth(t *testing.T) { okClient := NewTestClient(func(req *http.Request) (*http.Response, error) { return &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewBufferString("OK")), + Body: io.NopCloser(bytes.NewBufferString("OK")), Header: make(http.Header), }, nil }) @@ -258,7 +258,7 @@ func TestCheckHealth(t *testing.T) { } return &http.Response{ StatusCode: 404, - Body: ioutil.NopCloser(bytes.NewBufferString("not found")), + Body: io.NopCloser(bytes.NewBufferString("not found")), Header: make(http.Header), }, nil }) diff --git a/pkg/tsdb/azuremonitor/loganalytics/azure-log-analytics-datasource.go b/pkg/tsdb/azuremonitor/loganalytics/azure-log-analytics-datasource.go index 7e18db1f721..1e75ea5dca5 100644 --- a/pkg/tsdb/azuremonitor/loganalytics/azure-log-analytics-datasource.go +++ b/pkg/tsdb/azuremonitor/loganalytics/azure-log-analytics-datasource.go @@ -6,7 +6,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -273,7 +273,7 @@ func (ar *AzureLogAnalyticsResponse) GetPrimaryResultTable() (*types.AzureRespon } func (e *AzureLogAnalyticsDatasource) unmarshalResponse(res *http.Response) (AzureLogAnalyticsResponse, error) { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return AzureLogAnalyticsResponse{}, err } diff --git a/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go b/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go index c3cb16f8eac..36d71776960 100644 --- a/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go +++ b/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -234,7 +234,7 @@ func (e *AzureMonitorDatasource) createRequest(ctx context.Context, dsInfo types } func (e *AzureMonitorDatasource) unmarshalResponse(res *http.Response) (types.AzureMonitorResponse, error) { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return types.AzureMonitorResponse{}, err } @@ -445,9 +445,12 @@ func formatAzureMonitorLegendKey(alias string, resourceName string, metricName s } // Map values from: -// https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit +// +// https://docs.microsoft.com/en-us/rest/api/monitor/metrics/list#unit +// // to -// https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24 +// +// https://github.com/grafana/grafana/blob/main/packages/grafana-data/src/valueFormats/categories.ts#L24 func toGrafanaUnit(unit string) string { switch unit { case "BitsPerSecond": diff --git a/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource_test.go b/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource_test.go index 27ba75c83ee..11f76834bd6 100644 --- a/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource_test.go +++ b/pkg/tsdb/azuremonitor/metrics/azuremonitor-datasource_test.go @@ -4,9 +4,9 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" "net/http" "net/url" + "os" "path/filepath" "testing" "time" @@ -651,7 +651,7 @@ func loadTestFile(t *testing.T, name string) types.AzureMonitorResponse { path := filepath.Join("../testdata", name) // Ignore gosec warning G304 since it's a test // nolint:gosec - jsonBody, err := ioutil.ReadFile(path) + jsonBody, err := os.ReadFile(path) require.NoError(t, err) var azData types.AzureMonitorResponse diff --git a/pkg/tsdb/azuremonitor/resourcegraph/azure-resource-graph-datasource.go b/pkg/tsdb/azuremonitor/resourcegraph/azure-resource-graph-datasource.go index 08d36c785df..f2de8407575 100644 --- a/pkg/tsdb/azuremonitor/resourcegraph/azure-resource-graph-datasource.go +++ b/pkg/tsdb/azuremonitor/resourcegraph/azure-resource-graph-datasource.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -238,7 +238,7 @@ func (e *AzureResourceGraphDatasource) createRequest(ctx context.Context, dsInfo } func (e *AzureResourceGraphDatasource) unmarshalResponse(res *http.Response) (AzureResourceGraphResponse, error) { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return AzureResourceGraphResponse{}, err } diff --git a/pkg/tsdb/cloudmonitoring/cloudmonitoring.go b/pkg/tsdb/cloudmonitoring/cloudmonitoring.go index df8679d1dfe..d65c1abdcbf 100644 --- a/pkg/tsdb/cloudmonitoring/cloudmonitoring.go +++ b/pkg/tsdb/cloudmonitoring/cloudmonitoring.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "math" "net/http" "net/url" @@ -627,7 +626,7 @@ func (s *Service) getDefaultProject(ctx context.Context, dsInfo datasourceInfo) } func unmarshalResponse(res *http.Response) (cloudMonitoringResponse, error) { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return cloudMonitoringResponse{}, err } diff --git a/pkg/tsdb/cloudmonitoring/resource_handler.go b/pkg/tsdb/cloudmonitoring/resource_handler.go index 3c94b219766..bbc582868a4 100644 --- a/pkg/tsdb/cloudmonitoring/resource_handler.go +++ b/pkg/tsdb/cloudmonitoring/resource_handler.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" "regexp" @@ -216,7 +215,7 @@ func decode(encoding string, original io.ReadCloser) ([]byte, error) { return nil, fmt.Errorf("unexpected encoding type %v", err) } - body, err := ioutil.ReadAll(reader) + body, err := io.ReadAll(reader) if err != nil { return nil, err } diff --git a/pkg/tsdb/cloudmonitoring/resource_handler_test.go b/pkg/tsdb/cloudmonitoring/resource_handler_test.go index 74fba70ee0e..05453795997 100644 --- a/pkg/tsdb/cloudmonitoring/resource_handler_test.go +++ b/pkg/tsdb/cloudmonitoring/resource_handler_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -78,7 +78,7 @@ func Test_doRequest(t *testing.T) { t.Errorf("Unexpected headers: %v", res.Header()) } result := rw.Result() - body, err := ioutil.ReadAll(result.Body) + body, err := io.ReadAll(result.Body) if err != nil { t.Error(err) } diff --git a/pkg/tsdb/cloudmonitoring/time_series_filter_test.go b/pkg/tsdb/cloudmonitoring/time_series_filter_test.go index 9981b38ed12..4fe5fda29ad 100644 --- a/pkg/tsdb/cloudmonitoring/time_series_filter_test.go +++ b/pkg/tsdb/cloudmonitoring/time_series_filter_test.go @@ -3,9 +3,9 @@ package cloudmonitoring import ( "encoding/json" "fmt" - "io/ioutil" "math" "net/url" + "os" "strconv" "testing" "time" @@ -479,7 +479,7 @@ func loadTestFile(path string) (cloudMonitoringResponse, error) { // Can ignore gosec warning G304 here since it's a test path // nolint:gosec - jsonBody, err := ioutil.ReadFile(path) + jsonBody, err := os.ReadFile(path) if err != nil { return data, err } diff --git a/pkg/tsdb/cloudwatch/response_parser_test.go b/pkg/tsdb/cloudwatch/response_parser_test.go index 0eb9b126caa..823901932a7 100644 --- a/pkg/tsdb/cloudwatch/response_parser_test.go +++ b/pkg/tsdb/cloudwatch/response_parser_test.go @@ -2,7 +2,7 @@ package cloudwatch import ( "encoding/json" - "io/ioutil" + "os" "path/filepath" "strings" "testing" @@ -17,7 +17,7 @@ import ( func loadGetMetricDataOutputsFromFile(filePath string) ([]*cloudwatch.GetMetricDataOutput, error) { var getMetricDataOutputs []*cloudwatch.GetMetricDataOutput cleanFilePath := filepath.Clean(filePath) - jsonBody, err := ioutil.ReadFile(cleanFilePath) + jsonBody, err := os.ReadFile(cleanFilePath) if err != nil { return getMetricDataOutputs, err } diff --git a/pkg/tsdb/elasticsearch/client/client.go b/pkg/tsdb/elasticsearch/client/client.go index 3118693b2b7..cbd018af976 100644 --- a/pkg/tsdb/elasticsearch/client/client.go +++ b/pkg/tsdb/elasticsearch/client/client.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -224,13 +224,13 @@ func (c *baseClientImpl) ExecuteMultisearch(r *MultiSearchRequest) (*MultiSearch var bodyBytes []byte if c.debugEnabled { - tmpBytes, err := ioutil.ReadAll(res.Body) + tmpBytes, err := io.ReadAll(res.Body) if err != nil { clientLog.Error("failed to read http response bytes", "error", err) } else { bodyBytes = make([]byte, len(tmpBytes)) copy(bodyBytes, tmpBytes) - res.Body = ioutil.NopCloser(bytes.NewBuffer(tmpBytes)) + res.Body = io.NopCloser(bytes.NewBuffer(tmpBytes)) } } diff --git a/pkg/tsdb/elasticsearch/client/client_test.go b/pkg/tsdb/elasticsearch/client/client_test.go index f9f460a5295..102cde6043e 100644 --- a/pkg/tsdb/elasticsearch/client/client_test.go +++ b/pkg/tsdb/elasticsearch/client/client_test.go @@ -3,7 +3,7 @@ package es import ( "bytes" "context" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -350,7 +350,7 @@ func httpClientScenario(t *testing.T, desc string, ds *DatasourceInfo, fn scenar } ts := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { sc.request = r - buf, err := ioutil.ReadAll(r.Body) + buf, err := io.ReadAll(r.Body) require.NoError(t, err) sc.requestBody = bytes.NewBuffer(buf) diff --git a/pkg/tsdb/graphite/graphite.go b/pkg/tsdb/graphite/graphite.go index 2844ac5ad70..37c1f53b7f7 100644 --- a/pkg/tsdb/graphite/graphite.go +++ b/pkg/tsdb/graphite/graphite.go @@ -5,7 +5,7 @@ import ( "encoding/json" "errors" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -184,7 +184,7 @@ func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) } func (s *Service) parseResponse(res *http.Response) ([]TargetResponseDTO, error) { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, err } diff --git a/pkg/tsdb/graphite/graphite_test.go b/pkg/tsdb/graphite/graphite_test.go index 3b58e3c2822..291bd3b7f9e 100644 --- a/pkg/tsdb/graphite/graphite_test.go +++ b/pkg/tsdb/graphite/graphite_test.go @@ -2,7 +2,7 @@ package graphite import ( "encoding/json" - "io/ioutil" + "io" "net/http" "reflect" "strings" @@ -68,7 +68,7 @@ func TestFixIntervalFormat(t *testing.T) { ) expectedFrames := data.Frames{expectedFrame} - httpResponse := &http.Response{StatusCode: 200, Body: ioutil.NopCloser(strings.NewReader(body))} + httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))} dataFrames, err := service.toDataFrames(httpResponse) require.NoError(t, err) @@ -101,7 +101,7 @@ func TestFixIntervalFormat(t *testing.T) { ) expectedFrames := data.Frames{expectedFrame} - httpResponse := &http.Response{StatusCode: 200, Body: ioutil.NopCloser(strings.NewReader(body))} + httpResponse := &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body))} dataFrames, err := service.toDataFrames(httpResponse) require.NoError(t, err) diff --git a/pkg/tsdb/influxdb/flux/executor_test.go b/pkg/tsdb/influxdb/flux/executor_test.go index 49da2154394..e7a8085c6fa 100644 --- a/pkg/tsdb/influxdb/flux/executor_test.go +++ b/pkg/tsdb/influxdb/flux/executor_test.go @@ -3,9 +3,9 @@ package flux import ( "context" "fmt" - "io/ioutil" "net/http" "net/http/httptest" + "os" "path/filepath" "testing" "time" @@ -34,7 +34,7 @@ type MockRunner struct { } func (r *MockRunner) runQuery(ctx context.Context, q string) (*api.QueryTableResult, error) { - bytes, err := ioutil.ReadFile(filepath.Join("testdata", r.testDataPath)) + bytes, err := os.ReadFile(filepath.Join("testdata", r.testDataPath)) if err != nil { return nil, err } diff --git a/pkg/tsdb/influxdb/influxdb_test.go b/pkg/tsdb/influxdb/influxdb_test.go index f3c7d76f085..4d58cd2e5fa 100644 --- a/pkg/tsdb/influxdb/influxdb_test.go +++ b/pkg/tsdb/influxdb/influxdb_test.go @@ -2,7 +2,7 @@ package influxdb import ( "context" - "io/ioutil" + "io" "net/url" "testing" @@ -48,7 +48,7 @@ func TestExecutor_createRequest(t *testing.T) { q := req.URL.Query().Get("q") assert.Empty(t, q) - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) require.NoError(t, err) testBodyValues := url.Values{} diff --git a/pkg/tsdb/influxdb/mocks_test.go b/pkg/tsdb/influxdb/mocks_test.go index a030cee03f6..42e0e0618a9 100644 --- a/pkg/tsdb/influxdb/mocks_test.go +++ b/pkg/tsdb/influxdb/mocks_test.go @@ -4,8 +4,9 @@ import ( "bytes" "errors" "fmt" - "io/ioutil" + "io" "net/http" + "os" "github.com/grafana/grafana-plugin-sdk-go/backend" sdkhttpclient "github.com/grafana/grafana-plugin-sdk-go/backend/httpclient" @@ -53,7 +54,7 @@ func (f *fakeInstance) Get(pluginContext backend.PluginContext) (instancemgmt.In }, res: &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{}`))), + Body: io.NopCloser(bytes.NewReader([]byte(`{}`))), }, rt: f.fakeRoundTripper, } @@ -90,17 +91,17 @@ func (rt *RoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { res := &http.Response{ StatusCode: http.StatusOK, Status: "200 OK", - Body: ioutil.NopCloser(bytes.NewBufferString("{}")), + Body: io.NopCloser(bytes.NewBufferString("{}")), } if rt.Body != "" { - res.Body = ioutil.NopCloser(bytes.NewBufferString(rt.Body)) + res.Body = io.NopCloser(bytes.NewBufferString(rt.Body)) } if rt.FileName != "" { - b, err := ioutil.ReadFile(rt.FileName) + b, err := os.ReadFile(rt.FileName) if err != nil { return res, fmt.Errorf("error reading testdata file %s", rt.FileName) } - reader := ioutil.NopCloser(bytes.NewReader(b)) + reader := io.NopCloser(bytes.NewReader(b)) res.Body = reader } if res.Body != nil { diff --git a/pkg/tsdb/influxdb/response_parser_test.go b/pkg/tsdb/influxdb/response_parser_test.go index 430f1bde2c3..cc43c83f518 100644 --- a/pkg/tsdb/influxdb/response_parser_test.go +++ b/pkg/tsdb/influxdb/response_parser_test.go @@ -3,7 +3,6 @@ package influxdb import ( "encoding/json" "io" - "io/ioutil" "strings" "testing" "time" @@ -17,7 +16,7 @@ import ( ) func prepare(text string) io.ReadCloser { - return ioutil.NopCloser(strings.NewReader(text)) + return io.NopCloser(strings.NewReader(text)) } func addQueryToQueries(query Query) []Query { diff --git a/pkg/tsdb/opentsdb/opentsdb.go b/pkg/tsdb/opentsdb/opentsdb.go index a6dbad80cc3..954e5c08319 100644 --- a/pkg/tsdb/opentsdb/opentsdb.go +++ b/pkg/tsdb/opentsdb/opentsdb.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/url" "path" @@ -130,7 +130,7 @@ func (s *Service) createRequest(ctx context.Context, dsInfo *datasourceInfo, dat func (s *Service) parseResponse(res *http.Response) (*backend.QueryDataResponse, error) { resp := backend.NewQueryDataResponse() - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return nil, err } diff --git a/pkg/tsdb/opentsdb/opentsdb_test.go b/pkg/tsdb/opentsdb/opentsdb_test.go index e7f10821086..42c7eacfa89 100644 --- a/pkg/tsdb/opentsdb/opentsdb_test.go +++ b/pkg/tsdb/opentsdb/opentsdb_test.go @@ -2,7 +2,7 @@ package opentsdb import ( "context" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -27,7 +27,7 @@ func TestOpenTsdbExecutor(t *testing.T) { require.NoError(t, err) assert.Equal(t, "POST", req.Method) - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) require.NoError(t, err) testBody := "{\"start\":0,\"end\":0,\"queries\":null}" @@ -37,7 +37,7 @@ func TestOpenTsdbExecutor(t *testing.T) { t.Run("Parse response should handle invalid JSON", func(t *testing.T) { response := `{ invalid }` - result, err := service.parseResponse(&http.Response{Body: ioutil.NopCloser(strings.NewReader(response))}) + result, err := service.parseResponse(&http.Response{Body: io.NopCloser(strings.NewReader(response))}) require.Nil(t, result) require.Error(t, err) }) @@ -65,7 +65,7 @@ func TestOpenTsdbExecutor(t *testing.T) { 50}), ) - resp := http.Response{Body: ioutil.NopCloser(strings.NewReader(response))} + resp := http.Response{Body: io.NopCloser(strings.NewReader(response))} resp.StatusCode = 200 result, err := service.parseResponse(&resp) require.NoError(t, err) diff --git a/pkg/tsdb/postgres/tlsmanager.go b/pkg/tsdb/postgres/tlsmanager.go index 08e79a8b155..5011beb9cfa 100644 --- a/pkg/tsdb/postgres/tlsmanager.go +++ b/pkg/tsdb/postgres/tlsmanager.go @@ -2,7 +2,6 @@ package postgres import ( "fmt" - "io/ioutil" "os" "path/filepath" "strconv" @@ -122,7 +121,7 @@ func writeCertFile(logger log.Logger, fileContent string, generatedFilePath stri fileContent = strings.TrimSpace(fileContent) if fileContent != "" { logger.Debug("Writing cert file", "path", generatedFilePath) - if err := ioutil.WriteFile(generatedFilePath, []byte(fileContent), 0600); err != nil { + if err := os.WriteFile(generatedFilePath, []byte(fileContent), 0600); err != nil { return err } // Make sure the file has the permissions expected by the Postgresql driver, otherwise it will bail diff --git a/pkg/tsdb/prometheus/client/client_test.go b/pkg/tsdb/prometheus/client/client_test.go index cb2b2bd8e33..17b287aff4d 100644 --- a/pkg/tsdb/prometheus/client/client_test.go +++ b/pkg/tsdb/prometheus/client/client_test.go @@ -2,7 +2,7 @@ package client import ( "context" - "io/ioutil" + "io" "net/http" "testing" @@ -49,7 +49,7 @@ func TestClient(t *testing.T) { require.NoError(t, err) require.NotNil(t, doer.Req) require.Equal(t, http.MethodPost, doer.Req.Method) - body, err := ioutil.ReadAll(doer.Req.Body) + body, err := io.ReadAll(doer.Req.Body) require.NoError(t, err) require.Equal(t, []byte("match%5B%5D: ALERTS\nstart: 1655271408\nend: 1655293008"), body) require.Equal(t, "http://localhost:9090/api/v1/series", doer.Req.URL.String()) @@ -74,7 +74,7 @@ func TestClient(t *testing.T) { require.NoError(t, err) require.NotNil(t, doer.Req) require.Equal(t, http.MethodGet, doer.Req.Method) - body, err := ioutil.ReadAll(doer.Req.Body) + body, err := io.ReadAll(doer.Req.Body) require.NoError(t, err) require.Equal(t, []byte{}, body) require.Equal(t, "http://localhost:9090/api/v1/series?match%5B%5D=ALERTS&start=1655272558&end=1655294158", doer.Req.URL.String()) diff --git a/pkg/tsdb/prometheus/querydata/framing_test.go b/pkg/tsdb/prometheus/querydata/framing_test.go index a551c1f2080..3514dde3986 100644 --- a/pkg/tsdb/prometheus/querydata/framing_test.go +++ b/pkg/tsdb/prometheus/querydata/framing_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -124,7 +124,7 @@ func runQuery(response []byte, q *backend.QueryDataRequest, wide bool) (*backend } res := &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(response)), + Body: io.NopCloser(bytes.NewReader(response)), } tCtx.httpProvider.setResponse(res) return tCtx.queryData.Execute(context.Background(), q) diff --git a/pkg/tsdb/prometheus/querydata/prometeus_bench_test.go b/pkg/tsdb/prometheus/querydata/prometeus_bench_test.go index 564d4ea6308..9ffe2e44b56 100644 --- a/pkg/tsdb/prometheus/querydata/prometeus_bench_test.go +++ b/pkg/tsdb/prometheus/querydata/prometeus_bench_test.go @@ -5,7 +5,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "math/rand" "net/http" "strings" @@ -29,7 +29,7 @@ func BenchmarkJson(b *testing.B) { for n := 0; n < b.N; n++ { res := http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(body)), + Body: io.NopCloser(bytes.NewReader(body)), } tCtx.httpProvider.setResponse(&res) _, err := tCtx.queryData.Execute(context.Background(), q) diff --git a/pkg/tsdb/prometheus/querydata/request_test.go b/pkg/tsdb/prometheus/querydata/request_test.go index 1092fc8e2e8..75d4ed3ef0e 100644 --- a/pkg/tsdb/prometheus/querydata/request_test.go +++ b/pkg/tsdb/prometheus/querydata/request_test.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "encoding/json" - "io/ioutil" + "io" "math" "net/http" "testing" @@ -388,7 +388,7 @@ func toAPIResponse(d interface{}) (*http.Response, error) { return &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader(raw)), + Body: io.NopCloser(bytes.NewReader(raw)), }, nil } @@ -405,7 +405,7 @@ func setup(wideFrames bool) (*testContext, error) { }, res: &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(bytes.NewReader([]byte(`{}`))), + Body: io.NopCloser(bytes.NewReader([]byte(`{}`))), }, } settings := backend.DataSourceInstanceSettings{ diff --git a/pkg/tsdb/tempo/tempo.go b/pkg/tsdb/tempo/tempo.go index 866f68276e4..6dee8319a97 100644 --- a/pkg/tsdb/tempo/tempo.go +++ b/pkg/tsdb/tempo/tempo.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "github.com/grafana/grafana-plugin-sdk-go/backend" @@ -89,7 +89,7 @@ func (s *Service) QueryData(ctx context.Context, req *backend.QueryDataRequest) } }() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return &backend.QueryDataResponse{}, err } diff --git a/pkg/tsdb/tempo/trace_transform_test.go b/pkg/tsdb/tempo/trace_transform_test.go index 84d212fd9da..ae153162a39 100644 --- a/pkg/tsdb/tempo/trace_transform_test.go +++ b/pkg/tsdb/tempo/trace_transform_test.go @@ -2,7 +2,7 @@ package tempo import ( "encoding/json" - "io/ioutil" + "os" "testing" "github.com/grafana/grafana-plugin-sdk-go/data" @@ -17,7 +17,7 @@ func TestTraceToFrame(t *testing.T) { // https://github.com/grafana/tempo/tree/master/pkg/tempopb to create the protobuf structs from something like // json. At the moment just saving some real tempo proto response into file and loading was the easiest and // as my patience was diminished trying to figure this out, I say it's good enough. - proto, err := ioutil.ReadFile("testData/tempo_proto_response") + proto, err := os.ReadFile("testData/tempo_proto_response") require.NoError(t, err) otTrace, err := otlp.NewProtobufTracesUnmarshaler().UnmarshalTraces(proto) diff --git a/pkg/tsdb/testdatasource/resource_handler.go b/pkg/tsdb/testdatasource/resource_handler.go index 8b64a2cfeb8..06615f22919 100644 --- a/pkg/tsdb/testdatasource/resource_handler.go +++ b/pkg/tsdb/testdatasource/resource_handler.go @@ -4,7 +4,6 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "sort" "strconv" @@ -118,7 +117,7 @@ func createJSONHandler(logger log.Logger) http.Handler { logger.Warn("Failed to close response body", "err", err) } }() - b, err := ioutil.ReadAll(req.Body) + b, err := io.ReadAll(req.Body) if err != nil { logger.Error("Failed to read request body to bytes", "error", err) } else { diff --git a/pkg/web/webtest/webtest_test.go b/pkg/web/webtest/webtest_test.go index e5aea951888..7cc9f3090ce 100644 --- a/pkg/web/webtest/webtest_test.go +++ b/pkg/web/webtest/webtest_test.go @@ -2,7 +2,7 @@ package webtest import ( "encoding/json" - "io/ioutil" + "io" "net/http" "strings" "testing" @@ -61,7 +61,7 @@ func verifyRequest(t *testing.T, s *Server, req *http.Request, expectedBody stri } else { require.Equal(t, http.MethodPost, req.Method) require.NotNil(t, req.Body) - bytes, err := ioutil.ReadAll(req.Body) + bytes, err := io.ReadAll(req.Body) require.NoError(t, err) require.Equal(t, expectedBody, string(bytes)) } @@ -96,7 +96,7 @@ func TestServerClient(t *testing.T) { require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, http.StatusOK, resp.StatusCode) - bytes, err := ioutil.ReadAll(resp.Body) + bytes, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) @@ -118,7 +118,7 @@ func TestServerClient(t *testing.T) { require.NoError(t, err) require.NotNil(t, resp) require.Equal(t, http.StatusOK, resp.StatusCode) - bytes, err := ioutil.ReadAll(resp.Body) + bytes, err := io.ReadAll(resp.Body) require.NoError(t, err) require.NoError(t, resp.Body.Close()) diff --git a/scripts/build/release_publisher/externalrelease.go b/scripts/build/release_publisher/externalrelease.go index dedee4b68b1..31c2daf15ca 100644 --- a/scripts/build/release_publisher/externalrelease.go +++ b/scripts/build/release_publisher/externalrelease.go @@ -2,7 +2,7 @@ package main import ( "fmt" - "io/ioutil" + "io" "net/http" "strings" "time" @@ -62,7 +62,7 @@ func (getHTTPContents) getContents(url string) (string, error) { } defer response.Body.Close() - all, err := ioutil.ReadAll(response.Body) + all, err := io.ReadAll(response.Body) if err != nil { return "", err } diff --git a/scripts/build/release_publisher/publisher.go b/scripts/build/release_publisher/publisher.go index 0c422799327..409cea2b36f 100644 --- a/scripts/build/release_publisher/publisher.go +++ b/scripts/build/release_publisher/publisher.go @@ -4,7 +4,7 @@ import ( "bytes" "encoding/json" "fmt" - "io/ioutil" + "io" "log" "net/http" "strings" @@ -276,7 +276,7 @@ func (p *publisher) postRequest(url string, obj interface{}, desc string) error if res.Body != nil { defer res.Body.Close() - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return err } diff --git a/scripts/openapi3/openapi3conv.go b/scripts/openapi3/openapi3conv.go index 3ae88dc92b6..d3ad1e3d2aa 100644 --- a/scripts/openapi3/openapi3conv.go +++ b/scripts/openapi3/openapi3conv.go @@ -3,11 +3,11 @@ package main import ( "encoding/json" "fmt" + "os" + "github.com/getkin/kin-openapi/openapi2" "github.com/getkin/kin-openapi/openapi2conv" "github.com/getkin/kin-openapi/openapi3" - "io/ioutil" - "os" ) // main This simple script will take the swagger v2 spec generated by grafana and convert them into openapi 3 @@ -30,7 +30,7 @@ func main() { } fmt.Printf("Reading swagger 2 file %s\n", inFile) - byt, err := ioutil.ReadFile(inFile) + byt, err := os.ReadFile(inFile) if err != nil { panic(err) } @@ -54,7 +54,7 @@ func main() { panic(err) } - if err = ioutil.WriteFile(outFile, j3, 0644); err != nil { + if err = os.WriteFile(outFile, j3, 0644); err != nil { panic(err) } fmt.Printf("OpenAPI specs generated in file %s\n", outFile)