From 9c26efade01345890e75f4edd8b58f1de349cfe4 Mon Sep 17 00:00:00 2001 From: Michelle Nguyen Date: Mon, 5 Apr 2021 16:56:20 -0700 Subject: [PATCH] Fix error checking to enable golint errcheck in CLI Summary: This is one diff in a series of diffs to fix the error checking in our golang code so that we can ultimately enable golint's errcheck. this lint rule requires errors to be handled, whether that is just a log or returning the error, etc. this part mainly tackles the CLI. Test Plan: unit tests pass, also ran CLI Reviewers: zasgar, vihang, nserrino Reviewed By: vihang Differential Revision: https://phab.corp.pixielabs.ai/D7963 GitOrigin-RevId: 8e16396798461f2c93eb307e3088eb7e90f94b70 --- .golangci.yaml | 4 +++- src/cloud/api/ptproxy/vizier_pt_proxy_test.go | 2 +- src/cloud/vzmgr/controller/server.go | 7 ++++++- src/e2e_test/cli/cli_e2e_test.go | 5 ++++- src/pixie_cli/pkg/auth/login.go | 16 ++++++++++++--- src/pixie_cli/pkg/cmd/demo.go | 6 +++++- src/pixie_cli/pkg/cmd/deploy.go | 7 ++++++- src/pixie_cli/pkg/cmd/root.go | 1 + src/pixie_cli/pkg/cmd/script_utils.go | 5 ++++- src/pixie_cli/pkg/live/live.go | 2 +- src/pixie_cli/pkg/live/new_autocomplete.go | 5 ++++- src/pixie_cli/pkg/live/utils.go | 5 ++++- src/pixie_cli/pkg/pxconfig/config.go | 5 ++++- src/pixie_cli/pkg/script/flagset_test.go | 3 ++- src/pixie_cli/pkg/vizier/data_formatter.go | 5 ++++- src/pixie_cli/pkg/vizier/script.go | 20 +++++++++++++++---- src/shared/services/healthz/healthz.go | 5 ++++- src/shared/services/msgbus/nats_test.go | 3 ++- src/shared/services/msgbus/stan_test.go | 7 +++++-- src/shared/services/pgtest/pgtest.go | 5 ++++- .../services/server/grpc_server_test.go | 17 ++++++++++++---- .../http/testing/go_http_server/main.go | 5 ++++- .../http2/testing/go_grpc_client/main.go | 5 ++++- .../http2/testing/go_grpc_server/main.go | 10 ++++++++-- .../protocols/pgsql/testing/demo.go | 10 ++++++++-- .../artifacts/artifact_db_updater/main.go | 5 ++++- src/utils/clutils.go | 10 ++++++++-- src/utils/dev_dns_updater/dev_dns_updater.go | 10 ++++++++-- src/utils/shared/certs/certs.go | 10 ++++++++-- src/utils/shared/k8s/apply.go | 15 +++++++++++--- src/utils/shared/k8s/logs.go | 17 +++++++++++++--- src/utils/shared/k8s/secrets.go | 12 +++++++++-- src/utils/uuid_test.go | 6 +++--- 33 files changed, 197 insertions(+), 53 deletions(-) diff --git a/.golangci.yaml b/.golangci.yaml index 09ffdd89544..a1ba759a0cf 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -45,7 +45,9 @@ linters: linters-settings: errcheck: - ignore: github.com/spf13/viper:BindPFlag + # yamllint disable + ignore: github.com/spf13/pflag:MarkHidden,github.com/spf13/viper:BindPFlag,github.com/spf13/cobra:(Help|MarkFlagRequired|Usage),gopkg.in/segmentio/analytics-go.v3:Enqueue,database/sql:Rollback,github.com/nats-io/stan.go:Unsubscribe,github.com/nats-io/nats.go:Unsubscribe + # yamllint enable goimports: local-prefixes: pixielabs.ai nakedret: diff --git a/src/cloud/api/ptproxy/vizier_pt_proxy_test.go b/src/cloud/api/ptproxy/vizier_pt_proxy_test.go index 4c7dd725aa1..a0a0f05acd8 100644 --- a/src/cloud/api/ptproxy/vizier_pt_proxy_test.go +++ b/src/cloud/api/ptproxy/vizier_pt_proxy_test.go @@ -531,7 +531,7 @@ func TestVizierPassThroughProxy_DebugLog(t *testing.T) { } } }) - eg.Wait() + err = eg.Wait() if err != nil { t.Fatal(err) } diff --git a/src/cloud/vzmgr/controller/server.go b/src/cloud/vzmgr/controller/server.go index a0556f46542..7faa9d8ff9b 100644 --- a/src/cloud/vzmgr/controller/server.go +++ b/src/cloud/vzmgr/controller/server.go @@ -836,7 +836,12 @@ func (s *Server) HandleVizierHeartbeat(v2cMsg *cvmsgspb.V2CMessage) { } // If we reach this point, the cluster is in bootstrap mode and needs to be deployed. - go s.updater.UpdateOrInstallVizier(vizierID, req.BootstrapVersion, false) + go func() { + _, err := s.updater.UpdateOrInstallVizier(vizierID, req.BootstrapVersion, false) + if err != nil { + log.WithError(err).Error("Failed to update or install vizier") + } + }() } // HandleSSLRequest registers certs for the vizier cluster. diff --git a/src/e2e_test/cli/cli_e2e_test.go b/src/e2e_test/cli/cli_e2e_test.go index 5e96e278a2f..8bd0398dc40 100644 --- a/src/e2e_test/cli/cli_e2e_test.go +++ b/src/e2e_test/cli/cli_e2e_test.go @@ -70,7 +70,10 @@ func cliExecStdoutBytes(t *testing.T, args ...string) (*bytes.Buffer, error) { var buf bytes.Buffer go func() { - io.Copy(&buf, r) + _, err := io.Copy(&buf, r) + if err != nil { + log.WithError(err).Error("Failed to copy") + } }() if err := c.Run(); err != nil { diff --git a/src/pixie_cli/pkg/auth/login.go b/src/pixie_cli/pkg/auth/login.go index d1275a1f702..62cb12d8e5a 100644 --- a/src/pixie_cli/pkg/auth/login.go +++ b/src/pixie_cli/pkg/auth/login.go @@ -48,7 +48,10 @@ func EnsureDefaultAuthFilePath() (string, error) { pixieDirPath := filepath.Join(u.HomeDir, pixieAuthPath) if _, err := os.Stat(pixieDirPath); os.IsNotExist(err) { - os.Mkdir(pixieDirPath, 0744) + err := os.Mkdir(pixieDirPath, 0744) + if err != nil { + return "", err + } } pixieAuthFilePath := filepath.Join(pixieDirPath, pixieAuthFile) @@ -300,7 +303,11 @@ func (p *PixieCloudLogin) tryBrowserAuth() (*RefreshToken, error) { ctx, cancel := context.WithTimeout(context.Background(), time.Minute*2) defer cancel() - defer h.Shutdown(ctx) + defer func() { + err := h.Shutdown(ctx) + log.WithError(err).Error("Failed to shutdown server") + }() + for { select { case <-ctx.Done(): @@ -329,7 +336,10 @@ func (p *PixieCloudLogin) getAuthStringManually() (string, error) { // fmt.Printf appears to escape % (as desired) so we use it here instead of the cli logger. fmt.Printf("\nPlease Visit: \n \t %s\n\n", authURL.String()) f := bufio.NewWriter(os.Stdout) - f.WriteString("Copy and paste token here: ") + _, err := f.WriteString("Copy and paste token here: ") + if err != nil { + return "", err + } f.Flush() r := bufio.NewReader(os.Stdin) diff --git a/src/pixie_cli/pkg/cmd/demo.go b/src/pixie_cli/pkg/cmd/demo.go index af994e3f8e4..3bf77c19391 100644 --- a/src/pixie_cli/pkg/cmd/demo.go +++ b/src/pixie_cli/pkg/cmd/demo.go @@ -144,7 +144,11 @@ func listCmd(cmd *cobra.Command, args []string) { for app, appSpec := range manifest { // When a demo app is deprecated, its contents will be set to null in manifest.json. if appSpec != nil { - w.Write([]interface{}{app}) + err = w.Write([]interface{}{app}) + if err != nil { + log.WithError(err).Error("Failed to write demo app") + continue + } } } } diff --git a/src/pixie_cli/pkg/cmd/deploy.go b/src/pixie_cli/pkg/cmd/deploy.go index 87e25b50165..796594f8cca 100644 --- a/src/pixie_cli/pkg/cmd/deploy.go +++ b/src/pixie_cli/pkg/cmd/deploy.go @@ -325,7 +325,12 @@ func runDeployCmd(cmd *cobra.Command, args []string) { // Using log.Fatal rather than CLI log in order to track this unexpected error in Sentry. log.WithError(err).Fatal("Failed to generate deployment key") } - defer deleteDeployKey(cloudAddr, uuid.FromStringOrNil(deployKeyID)) + defer func() { + err := deleteDeployKey(cloudAddr, uuid.FromStringOrNil(deployKeyID)) + if err != nil { + log.WithError(err).Info("Failed to delete generated deploy key") + } + }() } kubeConfig := k8s.GetConfig() diff --git a/src/pixie_cli/pkg/cmd/root.go b/src/pixie_cli/pkg/cmd/root.go index a5766569943..e54ac3dc3d9 100644 --- a/src/pixie_cli/pkg/cmd/root.go +++ b/src/pixie_cli/pkg/cmd/root.go @@ -53,6 +53,7 @@ func init() { RootCmd.PersistentFlags().MarkHidden("cloud_addr") } +// nolint:errcheck func printTestingBanner() { r := color.New(color.Bold, color.FgRed).Fprintf r(os.Stderr, "*******************************\n") diff --git a/src/pixie_cli/pkg/cmd/script_utils.go b/src/pixie_cli/pkg/cmd/script_utils.go index bb342670cfe..d669cd02d9f 100644 --- a/src/pixie_cli/pkg/cmd/script_utils.go +++ b/src/pixie_cli/pkg/cmd/script_utils.go @@ -59,7 +59,10 @@ func listBundleScripts(br *script.BundleManager, format string) { if script.Hidden { continue } - w.Write([]interface{}{script.ScriptName, script.ShortDoc}) + err := w.Write([]interface{}{script.ScriptName, script.ShortDoc}) + if err != nil { + log.WithError(err).Error("Failed to write to stream") + } } } diff --git a/src/pixie_cli/pkg/live/live.go b/src/pixie_cli/pkg/live/live.go index 6356e18f3b2..b8068e45b0c 100644 --- a/src/pixie_cli/pkg/live/live.go +++ b/src/pixie_cli/pkg/live/live.go @@ -487,7 +487,7 @@ func (v *View) showScriptView() { v.pages.AddAndSwitchToPage("script", tv, true) if v.s.execScript != nil { highlighted := strings.Builder{} - quick.Highlight(&highlighted, v.s.execScript.ScriptString, "python", + quick.Highlight(&highlighted, v.s.execScript.ScriptString, "python", // nolint: errcheck "terminal16m", "monokai") fmt.Fprintf(tv, "%s :\n\n", withAccent("Script View")) fmt.Fprint(tv, tview.TranslateANSI(highlighted.String())) diff --git a/src/pixie_cli/pkg/live/new_autocomplete.go b/src/pixie_cli/pkg/live/new_autocomplete.go index bee39a0c9f4..d81420b30b3 100644 --- a/src/pixie_cli/pkg/live/new_autocomplete.go +++ b/src/pixie_cli/pkg/live/new_autocomplete.go @@ -174,7 +174,10 @@ func (m *tabAutocompleteModal) parseCommand() (*script.ExecutableScript, error) return nil, err } } - es.UpdateFlags(fs) + err = es.UpdateFlags(fs) + if err != nil { + return nil, err + } return es, nil } diff --git a/src/pixie_cli/pkg/live/utils.go b/src/pixie_cli/pkg/live/utils.go index a514e2ec370..258ff6f5a38 100644 --- a/src/pixie_cli/pkg/live/utils.go +++ b/src/pixie_cli/pkg/live/utils.go @@ -47,7 +47,10 @@ func tryJSONHighlight(s string) string { } highlighted := strings.Builder{} - quick.Highlight(&highlighted, string(parsed), "json", "terminal16m", "monokai") + err = quick.Highlight(&highlighted, string(parsed), "json", "terminal16m", "monokai") + if err != nil { + return s + } return highlighted.String() } diff --git a/src/pixie_cli/pkg/pxconfig/config.go b/src/pixie_cli/pkg/pxconfig/config.go index 717f96790f9..d32f718ad57 100644 --- a/src/pixie_cli/pkg/pxconfig/config.go +++ b/src/pixie_cli/pkg/pxconfig/config.go @@ -37,7 +37,10 @@ func ensureDefaultConfigFilePath() (string, error) { pixieDirPath := filepath.Join(u.HomeDir, pixieDotPath) if _, err := os.Stat(pixieDirPath); os.IsNotExist(err) { - os.Mkdir(pixieDirPath, 0744) + err = os.Mkdir(pixieDirPath, 0744) + if err != nil { + return "", err + } } pixieConfigFilePath := filepath.Join(pixieDirPath, pixieConfigFile) diff --git a/src/pixie_cli/pkg/script/flagset_test.go b/src/pixie_cli/pkg/script/flagset_test.go index 4ab292463ab..a2b286cab6f 100644 --- a/src/pixie_cli/pkg/script/flagset_test.go +++ b/src/pixie_cli/pkg/script/flagset_test.go @@ -64,7 +64,8 @@ func TestSetFlag(t *testing.T) { assert.Nil(t, flags.Parse(flagVals)) - flags.Set("f3", "555") + err := flags.Set("f3", "555") + require.NoError(t, err) f3, err := flags.Lookup("f3") require.NoError(t, err) diff --git a/src/pixie_cli/pkg/vizier/data_formatter.go b/src/pixie_cli/pkg/vizier/data_formatter.go index 2acc1707614..949cea25c25 100644 --- a/src/pixie_cli/pkg/vizier/data_formatter.go +++ b/src/pixie_cli/pkg/vizier/data_formatter.go @@ -237,7 +237,10 @@ func (d *dataFormatterImpl) formatKV(valueDataType public_vizierapipb.DataType, return toString(val) } var result map[string]interface{} - json.Unmarshal([]byte(strVal), &result) + err := json.Unmarshal([]byte(strVal), &result) + if err != nil { + return toString(val) + } var keys []string for k := range result { diff --git a/src/pixie_cli/pkg/vizier/script.go b/src/pixie_cli/pkg/vizier/script.go index 370820e6079..8391c2cb980 100644 --- a/src/pixie_cli/pkg/vizier/script.go +++ b/src/pixie_cli/pkg/vizier/script.go @@ -50,7 +50,10 @@ func RunScriptAndOutputResults(ctx context.Context, conns []*Connector, execScri tw, err := runScript(ctx, conns, execScript, format) if err == nil { // Script ran successfully. - tw.Finish() + err = tw.Finish() + if err != nil { + return err + } return nil } @@ -62,7 +65,10 @@ func RunScriptAndOutputResults(ctx context.Context, conns []*Connector, execScri mutationInfo, _ := tw.MutationInfo() if mutationInfo == nil || (mutationInfo.Status.Code != int32(codes.Unavailable)) { // There is no mutation in the script, or the mutation is complete. - tw.Finish() + err = tw.Finish() + if err != nil { + return err + } return err } @@ -138,9 +144,15 @@ func RunScriptAndOutputResults(ctx context.Context, conns []*Connector, execScri } }() - vzJr.RunAndMonitor() + err = vzJr.RunAndMonitor() + if err != nil { + return err + } if tw != nil { - tw.Finish() + err = tw.Finish() + if err != nil { + return err + } } return err } diff --git a/src/shared/services/healthz/healthz.go b/src/shared/services/healthz/healthz.go index 18d79034c07..fb2b0323b00 100644 --- a/src/shared/services/healthz/healthz.go +++ b/src/shared/services/healthz/healthz.go @@ -123,7 +123,10 @@ func registerRootHealthzChecks(checks ...Checker) http.HandlerFunc { } fmt.Fprint(w, "OK\n") - verboseOut.WriteTo(w) + _, err := verboseOut.WriteTo(w) + if err != nil { + log.WithError(err).Error("Failed to write to response") + } fmt.Fprint(w, "healthz check passed\n") }) } diff --git a/src/shared/services/msgbus/nats_test.go b/src/shared/services/msgbus/nats_test.go index 0949f751c54..d471d500f08 100644 --- a/src/shared/services/msgbus/nats_test.go +++ b/src/shared/services/msgbus/nats_test.go @@ -23,7 +23,8 @@ func TestMustConnectNATS(t *testing.T) { ch := make(chan *nats.Msg) _, err := nc.ChanSubscribe(sub, ch) require.NoError(t, err) - nc.Publish(sub, msg) + err = nc.Publish(sub, msg) + require.NoError(t, err) natsMsg := <-ch assert.Equal(t, natsMsg.Data, msg) } diff --git a/src/shared/services/msgbus/stan_test.go b/src/shared/services/msgbus/stan_test.go index 0c2eb896df3..73ed34e2856 100644 --- a/src/shared/services/msgbus/stan_test.go +++ b/src/shared/services/msgbus/stan_test.go @@ -6,6 +6,7 @@ import ( "github.com/nats-io/stan.go" "github.com/spf13/viper" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "pixielabs.ai/pixielabs/src/shared/services/msgbus" "pixielabs.ai/pixielabs/src/utils/testingutils" @@ -24,10 +25,12 @@ func TestMustConnectSTAN(t *testing.T) { sub := "abc" data := []byte("123") ch := make(chan *stan.Msg) - sc.Subscribe(sub, func(msg *stan.Msg) { + _, err := sc.Subscribe(sub, func(msg *stan.Msg) { ch <- msg }) - sc.Publish(sub, data) + require.NoError(t, err) + err = sc.Publish(sub, data) + require.NoError(t, err) msg := <-ch assert.Equal(t, msg.Data, data) } diff --git a/src/shared/services/pgtest/pgtest.go b/src/shared/services/pgtest/pgtest.go index db762e99b80..a110e42771a 100644 --- a/src/shared/services/pgtest/pgtest.go +++ b/src/shared/services/pgtest/pgtest.go @@ -52,7 +52,10 @@ func SetupTestDB(schemaSource *bindata.AssetSource) (*sqlx.DB, func(), error) { return nil, nil, fmt.Errorf("Failed to run docker pool: %w", err) } // Set a 5 minute expiration on resources. - resource.Expire(300) + err = resource.Expire(300) + if err != nil { + return nil, nil, err + } viper.Set("postgres_port", resource.GetPort("5432/tcp")) viper.Set("postgres_hostname", "localhost") diff --git a/src/shared/services/server/grpc_server_test.go b/src/shared/services/server/grpc_server_test.go index 4a056cd49b3..fe4259d9e5a 100644 --- a/src/shared/services/server/grpc_server_test.go +++ b/src/shared/services/server/grpc_server_test.go @@ -36,7 +36,10 @@ func (s *testserver) Ping(ctx context.Context, in *ping.PingRequest) (*ping.Ping } func (s *testserver) PingServerStream(in *ping.PingRequest, srv ping.PingService_PingServerStreamServer) error { - srv.Send(&ping.PingReply{Reply: "test reply"}) + err := srv.Send(&ping.PingReply{Reply: "test reply"}) + if err != nil { + return err + } return nil } @@ -48,7 +51,10 @@ func (s *testserver) PingClientStream(srv ping.PingService_PingClientStreamServe if msg == nil { return fmt.Errorf("Got a nil message") } - srv.SendAndClose(&ping.PingReply{Reply: "test reply"}) + err = srv.SendAndClose(&ping.PingReply{Reply: "test reply"}) + if err != nil { + return err + } return nil } @@ -104,12 +110,15 @@ func makeTestClientStreamRequest(ctx context.Context, t *testing.T, lis *bufconn c := ping.NewPingServiceClient(conn) stream, err := c.PingClientStream(ctx) - stream.Send(&ping.PingRequest{Req: "hello"}) - if err != nil { t.Fatalf("Could not create stream") } + err = stream.Send(&ping.PingRequest{Req: "hello"}) + if err != nil { + t.Fatalf("Could not send on stream") + } + return stream.CloseAndRecv() } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http/testing/go_http_server/main.go b/src/stirling/source_connectors/socket_tracer/protocols/http/testing/go_http_server/main.go index 00d3c2fbe30..751b579deab 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http/testing/go_http_server/main.go +++ b/src/stirling/source_connectors/socket_tracer/protocols/http/testing/go_http_server/main.go @@ -22,7 +22,10 @@ func sayHello(w http.ResponseWriter, r *http.Request) { name = nameArgs[0] } reply := helloReply{Greeter: "Hello " + name + "!"} - json.NewEncoder(w).Encode(reply) + err := json.NewEncoder(w).Encode(reply) + if err != nil { + log.Fatal(err) + } } func main() { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_client/main.go b/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_client/main.go index e6e3c57e6a1..ac2703857d5 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_client/main.go +++ b/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_client/main.go @@ -116,7 +116,10 @@ func bidirStreamGreet(address string, https bool, names []string) { } log.Println(reply.Message) } - stream.CloseSend() + err = stream.CloseSend() + if err != nil { + log.Fatalf("Failed to close send") + } } func connectAndGreet(address string, https bool, name string) { diff --git a/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_server/main.go b/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_server/main.go index 9d0019cbe76..4e813fed61a 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_server/main.go +++ b/src/stirling/source_connectors/socket_tracer/protocols/http2/testing/go_grpc_server/main.go @@ -48,7 +48,10 @@ func (s *server) SayHelloServerStreaming(in *pb.HelloRequest, srv pb.StreamingGr // Send 3 responses each time. We do not care much about the exact number of responses, this is for executing the // server streaming mechanism and observe the underlying HTTP2 framing data. for i := 0; i < 3; i++ { - srv.Send(&pb.HelloReply{Message: "Hello " + in.Name}) + err := srv.Send(&pb.HelloReply{Message: "Hello " + in.Name}) + if err != nil { + return err + } } return nil } @@ -62,7 +65,10 @@ func (s *server) SayHelloBidirStreaming(stream pb.StreamingGreeter_SayHelloBidir if err != nil { return err } - stream.Send(&pb.HelloReply{Message: "Hello " + helloReq.Name}) + err = stream.Send(&pb.HelloReply{Message: "Hello " + helloReq.Name}) + if err != nil { + return err + } } } diff --git a/src/stirling/source_connectors/socket_tracer/protocols/pgsql/testing/demo.go b/src/stirling/source_connectors/socket_tracer/protocols/pgsql/testing/demo.go index 7e162c7e9c1..9b32f33c129 100644 --- a/src/stirling/source_connectors/socket_tracer/protocols/pgsql/testing/demo.go +++ b/src/stirling/source_connectors/socket_tracer/protocols/pgsql/testing/demo.go @@ -56,11 +56,17 @@ func main() { tx := db.MustBegin() tx.MustExec("INSERT INTO person (first_name, last_name, email) VALUES ($1, $2, $3)", "Jason", "Moiron", "jmoiron@jmoiron.net") // Named queries can use structs, so if you have an existing struct (i.e. person := &person{}) that you have populated, you can pass it in as &person - tx.Commit() + err := tx.Commit() + if err != nil { + log.Fatalln(err) + } // You can also get a single result, a la QueryRow jason := person{} - db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason") + err = db.Get(&jason, "SELECT * FROM person WHERE first_name=$1", "Jason") + if err != nil { + log.Fatalln(err) + } fmt.Printf("%#v\n", jason) time.Sleep(1 * time.Second) } diff --git a/src/utils/artifacts/artifact_db_updater/main.go b/src/utils/artifacts/artifact_db_updater/main.go index e43c00e00cb..175873807ad 100644 --- a/src/utils/artifacts/artifact_db_updater/main.go +++ b/src/utils/artifacts/artifact_db_updater/main.go @@ -132,7 +132,10 @@ func main() { // Print out latest artifact info to Stdout. latestArtifact := versionData.Artifact[0] m := jsonpb.Marshaler{} - m.Marshal(os.Stdout, latestArtifact) + err := m.Marshal(os.Stdout, latestArtifact) + if err != nil { + log.WithError(err).Error("Failed to marshal artifact") + } if viper.GetBool("check_only") { syscall.Exit(0) diff --git a/src/utils/clutils.go b/src/utils/clutils.go index 3ebedcad51a..1d97aefd7b0 100644 --- a/src/utils/clutils.go +++ b/src/utils/clutils.go @@ -72,9 +72,15 @@ func RunCmd(cmd *exec.Cmd) error { // special kill switch in case keyboard interrupt is hit 3 times. // otherwise, allow for graceful cleanup of command // via keyboard interrupt - cmd.Process.Signal(syscall.SIGINT) + err := cmd.Process.Signal(syscall.SIGINT) + if err != nil { + log.WithError(err).Error("Failed to signal SIGINT") + } if counter > 3 { - cmd.Process.Kill() + err = cmd.Process.Kill() + if err != nil { + log.WithError(err).Error("Failed to signal SIGINT") + } } counter++ }) diff --git a/src/utils/dev_dns_updater/dev_dns_updater.go b/src/utils/dev_dns_updater/dev_dns_updater.go index f4ab346db95..c732d929fd2 100644 --- a/src/utils/dev_dns_updater/dev_dns_updater.go +++ b/src/utils/dev_dns_updater/dev_dns_updater.go @@ -176,7 +176,10 @@ func updateHostsFile(svcInfoCh <-chan svcInfo) error { hosts.RemoveHosts(entries) hosts.AddHosts(s.Addr, entries) } - hosts.Save() + err = hosts.Save() + if err != nil { + return err + } } return nil } @@ -191,7 +194,10 @@ func cleanup() { for _, dnsEntries := range dnsEntriesByService { hosts.RemoveHosts(dnsEntries) } - hosts.Save() + err = hosts.Save() + if err != nil { + log.WithError(err).Fatal("Failed to save hosts file") + } } func copyFile(src, dst string) error { diff --git a/src/utils/shared/certs/certs.go b/src/utils/shared/certs/certs.go index d385b3dfd9f..1916cf54d73 100644 --- a/src/utils/shared/certs/certs.go +++ b/src/utils/shared/certs/certs.go @@ -123,7 +123,10 @@ func signCertificate(certPath string, certName string, cert *x509.Certificate, c if err != nil { return err } - pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certB}) + err = pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: certB}) + if err != nil { + return err + } certOut.Close() // Generate key. @@ -131,7 +134,10 @@ func signCertificate(certPath string, certName string, cert *x509.Certificate, c if err != nil { return err } - pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) + err = pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}) + if err != nil { + return err + } keyOut.Close() return nil } diff --git a/src/utils/shared/k8s/apply.go b/src/utils/shared/k8s/apply.go index 5c267b6211d..1e9e2020855 100644 --- a/src/utils/shared/k8s/apply.go +++ b/src/utils/shared/k8s/apply.go @@ -28,9 +28,18 @@ import ( func init() { // Suppress k8s log output. klog.InitFlags(nil) - flag.Set("logtostderr", "false") - flag.Set("v", "9") - flag.Set("alsologtostderr", "false") + err := flag.Set("logtostderr", "false") + if err != nil { + log.WithError(err).Error("Failed to set flag") + } + err = flag.Set("v", "9") + if err != nil { + log.WithError(err).Error("Failed to set flag") + } + err = flag.Set("alsologtostderr", "false") + if err != nil { + log.WithError(err).Error("Failed to set flag") + } // Suppress k8s log output. klog.SetOutput(ioutil.Discard) diff --git a/src/utils/shared/k8s/logs.go b/src/utils/shared/k8s/logs.go index 8eecb96b1ba..97c0799eb00 100644 --- a/src/utils/shared/k8s/logs.go +++ b/src/utils/shared/k8s/logs.go @@ -62,7 +62,10 @@ func (c *LogCollector) logPodInfoToZipFile(zf *zip.Writer, pod v12.Pod, containe return err } defer podLogs.Close() - io.Copy(w, podLogs) + _, err = io.Copy(w, podLogs) + if err != nil { + return err + } return nil } @@ -80,8 +83,16 @@ func (c *LogCollector) logKubeCmd(zf *zip.Writer, fName string, arg ...string) e return err } - cmd.Start() - go io.Copy(w, stdoutPipe) + err = cmd.Start() + if err != nil { + return err + } + go func() { + _, err := io.Copy(w, stdoutPipe) + if err != nil { + log.WithError(err).Error("Failed to copy stdout") + } + }() return cmd.Wait() } diff --git a/src/utils/shared/k8s/secrets.go b/src/utils/shared/k8s/secrets.go index 37b32b1be99..538d2615749 100644 --- a/src/utils/shared/k8s/secrets.go +++ b/src/utils/shared/k8s/secrets.go @@ -10,6 +10,8 @@ import ( "io/ioutil" "strings" + log "github.com/sirupsen/logrus" + v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation" @@ -18,7 +20,10 @@ import ( // DeleteSecret deletes the given secret in kubernetes. func DeleteSecret(clientset *kubernetes.Clientset, namespace, name string) { - clientset.CoreV1().Secrets(namespace).Delete(context.Background(), name, metav1.DeleteOptions{}) + err := clientset.CoreV1().Secrets(namespace).Delete(context.Background(), name, metav1.DeleteOptions{}) + if err != nil { + log.WithError(err).Error("Failed to delete secret") + } } // GetSecret gets the secret in kubernetes. @@ -139,7 +144,10 @@ func CreateDockerConfigJSONSecret(namespace, name, credsData string) (*v1.Secret credsBytes := []byte(encodedCredsData) encodedCreds := new(bytes.Buffer) encoder := base64.NewEncoder(base64.StdEncoding, encodedCreds) - encoder.Write(credsBytes) + _, err := encoder.Write(credsBytes) + if err != nil { + return nil, err + } encoder.Close() s := dockerConfig{ diff --git a/src/utils/uuid_test.go b/src/utils/uuid_test.go index d9fde9eaa07..378d07fc718 100644 --- a/src/utils/uuid_test.go +++ b/src/utils/uuid_test.go @@ -19,7 +19,7 @@ const lo uint64 = 0xb127d50e5b6e2645 var enc = binary.BigEndian func TestProtoFromUUID_BaseCaseValidUUID(t *testing.T) { - u, _ := uuid.FromString(uuidStr) + u := uuid.FromStringOrNil(uuidStr) proto := utils.ProtoFromUUID(u) assert.Equal(t, hi, proto.HighBits) @@ -89,7 +89,7 @@ func TestUUIDFromProto_ZeroUUID(t *testing.T) { func BenchmarkUUIDFromString(b *testing.B) { for i := 0; i < b.N; i++ { - uuid.FromString(uuidStr) + uuid.FromStringOrNil(uuidStr) } } @@ -98,7 +98,7 @@ func BenchmarkUUIDFromBytes(b *testing.B) { data := make([]byte, 16) enc.PutUint64(data[0:], hi) enc.PutUint64(data[8:], lo) - uuid.FromBytes(data) + uuid.FromBytesOrNil(data) } }