diff --git a/fs/fs.go b/fs/fs.go index 236ae4ad..e56bc91d 100644 --- a/fs/fs.go +++ b/fs/fs.go @@ -2,14 +2,13 @@ package fs import ( "io" - "io/ioutil" "os" "syscall" ) // Interface is the filesystem interface type. type Interface interface { - ReadDir(string) ([]os.FileInfo, error) + ReadDir(string) ([]os.DirEntry, error) ReadDirNames(string) ([]string, error) ReadDirCount(string) (int, error) ReadFile(string) ([]byte, error) @@ -23,8 +22,8 @@ type realFS struct{} // FS is the way you should access the filesystem. var fs Interface = realFS{} -func (realFS) ReadDir(path string) ([]os.FileInfo, error) { - return ioutil.ReadDir(path) +func (realFS) ReadDir(path string) ([]os.DirEntry, error) { + return os.ReadDir(path) } func (realFS) ReadDirNames(path string) ([]string, error) { @@ -37,7 +36,7 @@ func (realFS) ReadDirNames(path string) ([]string, error) { } func (realFS) ReadFile(path string) ([]byte, error) { - return ioutil.ReadFile(path) + return os.ReadFile(path) } func (realFS) Lstat(path string, stat *syscall.Stat_t) error { @@ -55,7 +54,7 @@ func (realFS) Open(path string) (io.ReadWriteCloser, error) { // trampolines here to allow users to do fs.ReadDir etc // ReadDir see ioutil.ReadDir -func ReadDir(path string) ([]os.FileInfo, error) { +func ReadDir(path string) ([]os.DirEntry, error) { return fs.ReadDir(path) } diff --git a/go.mod b/go.mod index 71308a21..2f5c9d33 100644 --- a/go.mod +++ b/go.mod @@ -1,11 +1,10 @@ module github.com/weaveworks/common -go 1.14 +go 1.21 require ( github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/aws/aws-sdk-go v1.27.0 - github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd // indirect github.com/davecgh/go-spew v1.1.1 github.com/felixge/httpsnoop v1.0.3 github.com/go-kit/log v0.2.1 @@ -14,8 +13,6 @@ require ( github.com/gogo/status v1.0.3 github.com/golang/protobuf v1.5.2 github.com/gorilla/mux v1.7.3 - github.com/mattn/go-colorable v0.0.9 // indirect - github.com/mattn/go-isatty v0.0.4 // indirect github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b github.com/opentracing-contrib/go-grpc v0.0.0-20180928155321-4b5a12d3ff02 github.com/opentracing-contrib/go-stdlib v0.0.0-20190519235532-cf7a6c988dc9 @@ -26,14 +23,42 @@ require ( github.com/prometheus/exporter-toolkit v0.8.2 github.com/sercand/kuberesolver/v4 v4.0.0 github.com/sirupsen/logrus v1.6.0 - github.com/soheilhy/cmux v0.1.5 // indirect + github.com/soheilhy/cmux v0.1.5 github.com/stretchr/testify v1.8.1 github.com/uber/jaeger-client-go v2.28.0+incompatible github.com/uber/jaeger-lib v2.2.0+incompatible github.com/weaveworks/promrus v1.2.0 - go.uber.org/atomic v1.5.1 // indirect golang.org/x/net v0.5.0 golang.org/x/tools v0.3.0 google.golang.org/grpc v1.53.0 gopkg.in/yaml.v2 v2.4.0 ) + +require ( + github.com/beorn7/perks v1.0.1 // indirect + github.com/cespare/xxhash/v2 v2.2.0 // indirect + github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd // indirect + github.com/coreos/go-systemd/v22 v22.4.0 // indirect + github.com/fsnotify/fsnotify v1.5.4 // indirect + github.com/go-logfmt/logfmt v0.5.1 // indirect + github.com/jpillora/backoff v1.0.0 // indirect + github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect + github.com/mattn/go-colorable v0.0.9 // indirect + github.com/mattn/go-isatty v0.0.4 // indirect + github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect + github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f // indirect + github.com/prometheus/client_model v0.3.0 // indirect + github.com/prometheus/common v0.37.0 // indirect + github.com/prometheus/procfs v0.8.0 // indirect + go.uber.org/atomic v1.5.1 // indirect + golang.org/x/crypto v0.0.0-20221012134737-56aed061732a // indirect + golang.org/x/lint v0.0.0-20210508222113-6edffad5e616 // indirect + golang.org/x/oauth2 v0.4.0 // indirect + golang.org/x/sync v0.1.0 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/text v0.6.0 // indirect + google.golang.org/appengine v1.6.7 // indirect + google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect + google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum index 080336b2..6aa60d38 100644 --- a/go.sum +++ b/go.sum @@ -393,7 +393,6 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho= -github.com/alecthomas/units v0.0.0-20211218093645-b94a6e3cc137/go.mod h1:OMCwj8VM1Kc9e19TLln2VL61YJF0x1XFtfdL4JdbSyE= github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= @@ -406,7 +405,6 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/census-instrumentation/opencensus-proto v0.4.1/go.mod h1:4T9NM4+4Vw91VeyqjLS6ao50K5bOcLKN6Q42XnYaRYw= -github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= @@ -636,7 +634,6 @@ github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5Fsn github.com/prometheus/client_golang v1.7.1/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.11.0/go.mod h1:Z6t4BnS23TR94PD6BsDNk8yVqroYurpAkEiz0P2BEV0= github.com/prometheus/client_golang v1.12.1/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrbd179Rt297l4aS6nDY= -github.com/prometheus/client_golang v1.13.0/go.mod h1:vTeo+zgvILHsnnj/39Ou/1fPN5nJFOEMgftOUOmlvYQ= github.com/prometheus/client_golang v1.14.0 h1:nJdhIvne2eSX/XRAFV9PcvFFRbrjbcTUj0VP62TMhnw= github.com/prometheus/client_golang v1.14.0/go.mod h1:8vpkKitgIVNcqrRBWh1C4TIUQgYNtG/XQE4E/Zae36Y= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= @@ -806,7 +803,6 @@ golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96b golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= diff --git a/httpgrpc/server/server.go b/httpgrpc/server/server.go index 25377cc5..3b2d1452 100644 --- a/httpgrpc/server/server.go +++ b/httpgrpc/server/server.go @@ -3,7 +3,7 @@ package server import ( "bytes" "fmt" - "io/ioutil" + "io" "net" "net/http" "net/http/httptest" @@ -102,9 +102,9 @@ func ParseURL(unparsed string) (string, error) { return "", err } parts := strings.SplitN(host, ".", 3) - service, namespace, domain := parts[0], "default", "" + service, _, domain := parts[0], "default", "" if len(parts) > 1 { - namespace = parts[1] + namespace := parts[1] domain = "." + namespace } if len(parts) > 2 { @@ -150,7 +150,7 @@ func NewClient(address string) (*Client, error) { // HTTPRequest wraps an ordinary HTTPRequest with a gRPC one func HTTPRequest(r *http.Request) (*httpgrpc.HTTPRequest, error) { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { return nil, err } @@ -174,7 +174,9 @@ func WriteResponse(w http.ResponseWriter, resp *httpgrpc.HTTPResponse) error { func WriteError(w http.ResponseWriter, err error) { resp, ok := httpgrpc.HTTPResponseFromError(err) if ok { - WriteResponse(w, resp) + if err := WriteResponse(w, resp); err != nil { + logging.Global().Errorf("Failed to write response: %v", err) + } } else { http.Error(w, err.Error(), http.StatusInternalServerError) } diff --git a/httpgrpc/server/server_test.go b/httpgrpc/server/server_test.go index d028d300..7fcf780f 100644 --- a/httpgrpc/server/server_test.go +++ b/httpgrpc/server/server_test.go @@ -9,7 +9,7 @@ import ( "net/http/httptest" "testing" - opentracing "github.com/opentracing/opentracing-go" + "github.com/opentracing/opentracing-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" jaegercfg "github.com/uber/jaeger-client-go/config" @@ -39,7 +39,7 @@ func newTestServer(handler http.Handler) (*testServer, error) { } httpgrpc.RegisterHTTPServer(server.grpcServer, server.Server) - go server.grpcServer.Serve(lis) + go server.grpcServer.Serve(lis) //nolint:errcheck return server, nil } diff --git a/instrument/instrument_test.go b/instrument/instrument_test.go index 77e46256..91934e06 100644 --- a/instrument/instrument_test.go +++ b/instrument/instrument_test.go @@ -3,6 +3,7 @@ package instrument_test import ( "context" "errors" + "github.com/stretchr/testify/require" "testing" "time" @@ -47,10 +48,10 @@ func (c *spyCollector) After(ctx context.Context, method, statusCode string, sta func TestCollectedRequest(t *testing.T) { c := &spyCollector{} fcalled := false - instrument.CollectedRequest(context.Background(), "test", c, nil, func(_ context.Context) error { + require.NoError(t, instrument.CollectedRequest(context.Background(), "test", c, nil, func(_ context.Context) error { fcalled = true return nil - }) + })) assert.True(t, fcalled) assert.True(t, c.before) assert.True(t, c.after) @@ -59,9 +60,9 @@ func TestCollectedRequest(t *testing.T) { func TestCollectedRequest_Error(t *testing.T) { c := &spyCollector{} - instrument.CollectedRequest(context.Background(), "test", c, nil, func(_ context.Context) error { + require.NoError(t, instrument.CollectedRequest(context.Background(), "test", c, nil, func(_ context.Context) error { return errors.New("boom") - }) + })) assert.True(t, c.before) assert.True(t, c.after) assert.Equal(t, "500", c.afterCode) diff --git a/logging/format.go b/logging/format.go index 701b32f5..38f105b7 100644 --- a/logging/format.go +++ b/logging/format.go @@ -15,7 +15,7 @@ type Format struct { // RegisterFlags adds the log format flag to the provided flagset. func (f *Format) RegisterFlags(fs *flag.FlagSet) { - f.Set("logfmt") + f.Set("logfmt") //nolint:errcheck fs.Var(f, "log.format", "Output log messages in the given format. Valid formats: [logfmt, json]") } diff --git a/logging/gokit.go b/logging/gokit.go index e4b6fdc0..94583db4 100644 --- a/logging/gokit.go +++ b/logging/gokit.go @@ -62,31 +62,31 @@ func (s *sprint) String() string { } func (g gokit) Debugf(format string, args ...interface{}) { - level.Debug(g.Logger).Log("msg", &sprintf{format: format, args: args}) + level.Debug(g.Logger).Log("msg", &sprintf{format: format, args: args}) //nolint:errcheck } func (g gokit) Debugln(args ...interface{}) { - level.Debug(g.Logger).Log("msg", &sprint{args: args}) + level.Debug(g.Logger).Log("msg", &sprint{args: args}) //nolint:errcheck } func (g gokit) Infof(format string, args ...interface{}) { - level.Info(g.Logger).Log("msg", &sprintf{format: format, args: args}) + level.Info(g.Logger).Log("msg", &sprintf{format: format, args: args}) //nolint:errcheck } func (g gokit) Infoln(args ...interface{}) { - level.Info(g.Logger).Log("msg", &sprint{args: args}) + level.Info(g.Logger).Log("msg", &sprint{args: args}) //nolint:errcheck } func (g gokit) Warnf(format string, args ...interface{}) { - level.Warn(g.Logger).Log("msg", &sprintf{format: format, args: args}) + level.Warn(g.Logger).Log("msg", &sprintf{format: format, args: args}) //nolint:errcheck } func (g gokit) Warnln(args ...interface{}) { - level.Warn(g.Logger).Log("msg", &sprint{args: args}) + level.Warn(g.Logger).Log("msg", &sprint{args: args}) //nolint:errcheck } func (g gokit) Errorf(format string, args ...interface{}) { - level.Error(g.Logger).Log("msg", &sprintf{format: format, args: args}) + level.Error(g.Logger).Log("msg", &sprintf{format: format, args: args}) //nolint:errcheck } func (g gokit) Errorln(args ...interface{}) { - level.Error(g.Logger).Log("msg", &sprint{args: args}) + level.Error(g.Logger).Log("msg", &sprint{args: args}) //nolint:errcheck } func (g gokit) WithField(key string, value interface{}) Interface { diff --git a/logging/level.go b/logging/level.go index d7b92eaa..fc16e12f 100644 --- a/logging/level.go +++ b/logging/level.go @@ -32,7 +32,7 @@ type Level struct { // RegisterFlags adds the log level flag to the provided flagset. func (l *Level) RegisterFlags(f *flag.FlagSet) { - l.Set("info") + l.Set("info") //nolint:errcheck f.Var(l, "log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error]") } diff --git a/mflag/flag.go b/mflag/flag.go index 22b9111d..bebfd18e 100644 --- a/mflag/flag.go +++ b/mflag/flag.go @@ -230,7 +230,7 @@ func (s *stringValue) Set(val string) error { func (s *stringValue) Get() interface{} { return string(*s) } -func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) } +func (s *stringValue) String() string { return string(*s) } // -- float64 Value type float64Value float64 @@ -1026,7 +1026,9 @@ func (fs *FlagSet) parseOne() (bool, string, error) { return false, "", fs.failf("invalid boolean value %q for -%s: %v", value, name, err) } } else { - fv.Set("true") + if err := fv.Set("true"); err != nil { + return false, "", fs.failf("invalid boolean value for -%s: %v", name, err) + } } } else { // It must have a value, which might be the next argument. @@ -1162,7 +1164,7 @@ func (fs *FlagSet) Parsed() bool { // after all flags are defined and before flags are accessed by the program. func Parse() { // Ignore errors; CommandLine is set for ExitOnError. - CommandLine.Parse(os.Args[1:]) + CommandLine.Parse(os.Args[1:]) //nolint:errcheck } // Parsed returns true if the command-line flags have been parsed. diff --git a/mflag/flag_test.go b/mflag/flag_test.go index 13835554..505dbc60 100644 --- a/mflag/flag_test.go +++ b/mflag/flag_test.go @@ -12,6 +12,8 @@ import ( "strings" "testing" "time" + + "github.com/stretchr/testify/require" ) // ResetForTesting clears all flag state and sets the usage function as directed. @@ -76,14 +78,14 @@ func TestEverything(t *testing.T) { } } // Now set all flags - Set("test_bool", "true") - Set("test_int", "1") - Set("test_int64", "1") - Set("test_uint", "1") - Set("test_uint64", "1") - Set("test_string", "1") - Set("test_float64", "1") - Set("test_duration", "1s") + require.NoError(t, Set("test_bool", "true")) + require.NoError(t, Set("test_int", "1")) + require.NoError(t, Set("test_int64", "1")) + require.NoError(t, Set("test_uint", "1")) + require.NoError(t, Set("test_uint64", "1")) + require.NoError(t, Set("test_string", "1")) + require.NoError(t, Set("test_float64", "1")) + require.NoError(t, Set("testrequire.NoError(_duration", "1s")) desired = "1" Visit(visitor) if len(m) != 8 { @@ -95,9 +97,7 @@ func TestEverything(t *testing.T) { // Now test they're visited in sort order. var flagNames []string Visit(func(f *Flag) { - for _, name := range f.Names { - flagNames = append(flagNames, name) - } + flagNames = append(flagNames, f.Names...) }) if !sort.StringsAreSorted(flagNames) { t.Errorf("flag names not sorted: %v", flagNames) @@ -276,7 +276,7 @@ func testPanic(f *FlagSet, t *testing.T) { args := []string{ "-int", "21", } - f.Parse(args) + require.NoError(t, f.Parse(args)) } func TestParsePanic(t *testing.T) { @@ -368,7 +368,7 @@ func TestSetOutput(t *testing.T) { var buf bytes.Buffer flags.SetOutput(&buf) flags.Init("test", ContinueOnError) - flags.Parse([]string{"-unknown"}) + require.NoError(t, flags.Parse([]string{"-unknown"})) if out := buf.String(); !strings.Contains(out, "-unknown") { t.Logf("expected output mentioning unknown; got %q", out) } @@ -520,7 +520,7 @@ func TestMergeFlags(t *testing.T) { base.String([]string{"f"}, "", "") fs := NewFlagSet("test", ContinueOnError) - Merge(fs, base) + require.NoError(t, Merge(fs, base)) if len(fs.formal) != 1 { t.Fatalf("FlagCount (%d) != number (1) of elements merged", len(fs.formal)) } diff --git a/middleware/grpc_stats_test.go b/middleware/grpc_stats_test.go index f08e2c46..bb6fe573 100644 --- a/middleware/grpc_stats_test.go +++ b/middleware/grpc_stats_test.go @@ -8,16 +8,14 @@ import ( "testing" "time" - "github.com/golang/protobuf/proto" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/testutil" "github.com/stretchr/testify/require" + "github.com/weaveworks/common/middleware/middleware_test" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/health" "google.golang.org/grpc/health/grpc_health_v1" - - "github.com/weaveworks/common/middleware/middleware_test" ) func TestGrpcStats(t *testing.T) { @@ -167,7 +165,7 @@ func TestGrpcStatsStreaming(t *testing.T) { Body: []byte(generateString((ix + 1) * 1024 * 1024)), } - t.Log("Client Sending", proto.Size(msg)) + t.Log("Client Sending", msg.XXX_Size()) err = s.Send(msg) require.NoError(t, err) @@ -247,7 +245,7 @@ func (f halfEcho) Process(server middleware_test.EchoServer_ProcessServer) error // Half the body msg.Body = msg.Body[:len(msg.Body)/2] - f.log("Server Sending", proto.Size(msg)) + f.log("Server Sending", msg.XXX_Size()) err = server.Send(msg) if err != nil { return err diff --git a/middleware/logging_test.go b/middleware/logging_test.go index c282064c..2c44718b 100644 --- a/middleware/logging_test.go +++ b/middleware/logging_test.go @@ -38,7 +38,8 @@ func TestBadWriteLogging(t *testing.T) { Log: logging.Logrus(logrusLogger), } handler := func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Hello World!") + _, err := io.WriteString(w, "Hello World!") + require.NoError(t, err) } loggingHandler := loggingMiddleware.Wrap(http.HandlerFunc(handler)) @@ -83,7 +84,8 @@ func TestDisabledSuccessfulRequestsLogging(t *testing.T) { } handler := func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Hello World!") //nolint:errcheck + _, err := io.WriteString(w, "Hello World!") //nolint:errcheck + require.NoError(t, err) } loggingHandler := loggingMiddleware.Wrap(http.HandlerFunc(handler)) @@ -127,7 +129,8 @@ func TestLoggingRequestsAtInfoLevel(t *testing.T) { LogRequestAtInfoLevel: true, } handler := func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "Hello World!") + _, err := io.WriteString(w, "Hello World!") + require.NoError(t, err) } loggingHandler := loggingMiddleware.Wrap(http.HandlerFunc(handler)) diff --git a/middleware/response.go b/middleware/response.go index 2655003c..652c33f7 100644 --- a/middleware/response.go +++ b/middleware/response.go @@ -72,7 +72,10 @@ func (b *nonFlushingBadResponseLoggingWriter) Write(data []byte) (int, error) { } n, err := b.rw.Write(data) if b.logBody { - b.captureResponseBody(data) + err := b.captureResponseBody(data) + if err != nil { + return n, err + } } if err != nil { b.writeError = err @@ -106,16 +109,23 @@ func (b *nonFlushingBadResponseLoggingWriter) getWriteError() error { return b.writeError } -func (b *nonFlushingBadResponseLoggingWriter) captureResponseBody(data []byte) { +func (b *nonFlushingBadResponseLoggingWriter) captureResponseBody(data []byte) error { if len(data) > b.bodyBytesLeft { - b.buffer.Write(data[:b.bodyBytesLeft]) - io.WriteString(b.buffer, "...") + if _, err := b.buffer.Write(data[:b.bodyBytesLeft]); err != nil { + return err + } + if _, err := io.WriteString(b.buffer, "..."); err != nil { + return err + } b.bodyBytesLeft = 0 b.logBody = false } else { - b.buffer.Write(data) + if _, err := b.buffer.Write(data); err != nil { + return err + } b.bodyBytesLeft -= len(data) } + return nil } func (b *flushingBadResponseLoggingWriter) Flush() { diff --git a/middleware/response_test.go b/middleware/response_test.go index 47d381b7..a94fe77f 100644 --- a/middleware/response_test.go +++ b/middleware/response_test.go @@ -2,6 +2,7 @@ package middleware import ( "bytes" + "github.com/stretchr/testify/require" "net/http" "net/http/httptest" "testing" @@ -27,7 +28,8 @@ func TestBadResponseLoggingWriter(t *testing.T) { wrapped.WriteHeader(tc.statusCode) case tc.statusCode < 300 && tc.data != "": wrapped.WriteHeader(tc.statusCode) - wrapped.Write([]byte(tc.data)) + _, err := wrapped.Write([]byte(tc.data)) + require.NoError(t, err) default: http.Error(wrapped, tc.data, tc.statusCode) } diff --git a/server/server.go b/server/server.go index 26eed4ea..a3e108b6 100644 --- a/server/server.go +++ b/server/server.go @@ -555,6 +555,9 @@ func (s *Server) Shutdown() { ctx, cancel := context.WithTimeout(context.Background(), s.cfg.ServerGracefulShutdownTimeout) defer cancel() // releases resources if httpServer.Shutdown completes before timeout elapses - s.HTTPServer.Shutdown(ctx) + if err := s.HTTPServer.Shutdown(ctx); err != nil { + s.Log.Warnf("Failed to shit down server: %v", err) + } + s.GRPC.GracefulStop() } diff --git a/server/server_test.go b/server/server_test.go index f8492cca..a8395eb7 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -10,7 +10,6 @@ import ( "net/http" "os" "os/exec" - "strconv" "testing" "time" @@ -37,7 +36,7 @@ func (f FakeServer) FailWithError(_ context.Context, _ *protobuf.Empty) (*protob } func (f FakeServer) FailWithHTTPError(_ context.Context, req *FailWithHTTPErrorRequest) (*protobuf.Empty, error) { - return nil, httpgrpc.Errorf(int(req.Code), strconv.Itoa(int(req.Code))) + return nil, httpgrpc.Errorf(int(req.Code), "%v", req.Code) } func (f FakeServer) Succeed(_ context.Context, _ *protobuf.Empty) (*protobuf.Empty, error) { @@ -126,12 +125,12 @@ func TestDefaultAddresses(t *testing.T) { w.WriteHeader(204) }) - go server.Run() + go require.NoError(t, server.Run()) defer server.Shutdown() conn, err := grpc.Dial("localhost:9095", grpc.WithTransportCredentials(insecure.NewCredentials())) require.NoError(t, err) - defer conn.Close() + defer require.NoError(t, conn.Close()) empty := protobuf.Empty{} client := NewFakeServerClient(conn) @@ -168,11 +167,11 @@ func TestErrorInstrumentationMiddleware(t *testing.T) { w.WriteHeader(http.StatusNotFound) }) - go server.Run() + go require.NoError(t, server.Run()) conn, err := grpc.Dial("localhost:1234", grpc.WithTransportCredentials(insecure.NewCredentials())) require.NoError(t, err) - defer conn.Close() + defer require.NoError(t, conn.Close()) empty := protobuf.Empty{} client := NewFakeServerClient(conn) @@ -307,7 +306,7 @@ func TestHTTPInstrumentationMetrics(t *testing.T) { _ = cancelableSleep(r.Context(), time.Second*10) }) - go server.Run() + go require.NoError(t, server.Run()) callThenCancel := func(f func(ctx context.Context) error) error { ctx, cancel := context.WithCancel(context.Background()) @@ -502,7 +501,7 @@ func TestMiddlewareLogging(t *testing.T) { w.WriteHeader(500) }) - go server.Run() + go require.NoError(t, server.Run()) defer server.Shutdown() req, err := http.NewRequest("GET", "http://127.0.0.1:9192/error500", nil) @@ -544,13 +543,14 @@ func TestTLSServer(t *testing.T) { require.NoError(t, err) server.HTTP.HandleFunc("/testhttps", func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte("Hello World!")) + _, err := w.Write([]byte("Hello World!")) + require.NoError(t, err) }) fakeServer := FakeServer{} RegisterFakeServerServer(server.GRPC, fakeServer) - go server.Run() + go require.NoError(t, server.Run()) defer server.Shutdown() clientCert, err := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key") @@ -574,7 +574,7 @@ func TestTLSServer(t *testing.T) { client := &http.Client{Transport: tr} res, err := client.Get("https://localhost:9193/testhttps") require.NoError(t, err) - defer res.Body.Close() + defer require.NoError(t, res.Body.Close()) require.Equal(t, res.StatusCode, http.StatusOK) @@ -585,7 +585,7 @@ func TestTLSServer(t *testing.T) { conn, err := grpc.Dial("localhost:9194", grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig))) require.NoError(t, err) - defer conn.Close() + defer require.NoError(t, conn.Close()) empty := protobuf.Empty{} grpcClient := NewFakeServerClient(conn) @@ -645,7 +645,7 @@ func TestLogSourceIPs(t *testing.T) { w.WriteHeader(500) }) - go server.Run() + go require.NoError(t, server.Run()) defer server.Shutdown() require.Empty(t, fake.sourceIPs) diff --git a/signals/signals.go b/signals/signals.go index 29d45fc8..81cb9b6d 100644 --- a/signals/signals.go +++ b/signals/signals.go @@ -54,7 +54,9 @@ func (h *Handler) Loop() { case syscall.SIGINT, syscall.SIGTERM: h.log.Infof("=== received SIGINT/SIGTERM ===\n*** exiting") for _, subsystem := range h.receivers { - subsystem.Stop() + if err := subsystem.Stop(); err != nil { + h.log.Errorf("Error stopping subsystem: %v", err) + } } return case syscall.SIGQUIT: diff --git a/test/exec/exec.go b/test/exec/exec.go index a18f1182..03a5de06 100644 --- a/test/exec/exec.go +++ b/test/exec/exec.go @@ -3,7 +3,6 @@ package exec import ( "bytes" "io" - "io/ioutil" "github.com/weaveworks/common/exec" ) @@ -20,7 +19,7 @@ func NewMockCmdString(s string) exec.Cmd { io.Closer }{ bytes.NewBufferString(s), - ioutil.NopCloser(nil), + io.NopCloser(nil), }, } } @@ -45,7 +44,7 @@ func (c *mockCmd) StdoutPipe() (io.ReadCloser, error) { } func (c *mockCmd) StderrPipe() (io.ReadCloser, error) { - return ioutil.NopCloser(bytes.NewReader(nil)), nil + return io.NopCloser(bytes.NewReader(nil)), nil } func (c *mockCmd) Kill() error { @@ -53,7 +52,7 @@ func (c *mockCmd) Kill() error { } func (c *mockCmd) Output() ([]byte, error) { - return ioutil.ReadAll(c.ReadCloser) + return io.ReadAll(c.ReadCloser) } func (c *mockCmd) Run() error { diff --git a/test/fs/fs.go b/test/fs/fs.go index 2f1717f1..afe3350c 100644 --- a/test/fs/fs.go +++ b/test/fs/fs.go @@ -4,7 +4,6 @@ import ( "bytes" "fmt" "io" - "io/ioutil" "os" "strings" "syscall" @@ -19,7 +18,6 @@ type dir struct { mockInode name string entries map[string]Entry - stat syscall.Stat_t } // File is a mock file @@ -35,7 +33,7 @@ type File struct { // Entry is an entry in the mock filesystem type Entry interface { - os.FileInfo + os.DirEntry fs.Interface Add(path string, e Entry) error Remove(path string) error @@ -76,9 +74,9 @@ func (mockInode) Sys() interface{} { return nil } func (p dir) Name() string { return p.name } func (p dir) IsDir() bool { return true } -func (p dir) ReadDir(path string) ([]os.FileInfo, error) { +func (p dir) ReadDir(path string) ([]os.DirEntry, error) { if path == "/" { - result := []os.FileInfo{} + result := []os.DirEntry{} for _, v := range p.entries { result = append(result, v) } @@ -94,6 +92,16 @@ func (p dir) ReadDir(path string) ([]os.FileInfo, error) { return fs.ReadDir(tail) } +func (p dir) Type() os.FileMode { + //TODO implement me + panic("implement me") +} + +func (p dir) Info() (os.FileInfo, error) { + //TODO implement me + panic("implement me") +} + func (p dir) ReadDirNames(path string) ([]string, error) { if path == "/" { result := []string{} @@ -232,7 +240,7 @@ func (p File) ReadFile(path string) ([]byte, error) { return nil, fmt.Errorf("I'm a file") } if p.FReader != nil { - return ioutil.ReadAll(p.FReader) + return io.ReadAll(p.FReader) } return []byte(p.FContents), nil } @@ -266,7 +274,7 @@ func (p File) Open(path string) (io.ReadWriteCloser, error) { io.Writer io.Closer }{ - buf, buf, ioutil.NopCloser(nil), + buf, buf, io.NopCloser(nil), } if p.FReader != nil { s.Reader = p.FReader diff --git a/tools/socks/main.go b/tools/socks/main.go index 2f16d167..14e91d8a 100644 --- a/tools/socks/main.go +++ b/tools/socks/main.go @@ -63,7 +63,10 @@ func main() { t := template.Must(template.New("pacfile").Parse(pacfile)) http.HandleFunc("/proxy.pac", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig") - t.Execute(w, pacFileParameters{hostMatch, socksDestination, aliases}) + err := t.Execute(w, pacFileParameters{hostMatch, socksDestination, aliases}) + if err != nil { + panic(err) + } }) if err := http.ListenAndServe(":8080", nil); err != nil {