From f0c5fdd42b52ca817c84677601d8daac7d0fd1f0 Mon Sep 17 00:00:00 2001 From: Matthieu MOREL Date: Thu, 17 Oct 2024 22:21:33 +0200 Subject: [PATCH] fix: enable gofumpt instead of gofmt linter in contrib, etcdctl and etcdutl Signed-off-by: Matthieu MOREL --- contrib/raftexample/raft.go | 7 +- etcdctl/ctlv3/command/check.go | 4 +- etcdctl/ctlv3/command/elect_command.go | 4 +- etcdctl/ctlv3/command/ep_command.go | 6 +- etcdctl/ctlv3/command/lease_command.go | 4 +- etcdctl/ctlv3/command/printer.go | 13 +- etcdctl/ctlv3/command/printer_fields.go | 3 + etcdctl/ctlv3/command/printer_simple.go | 2 + etcdctl/ctlv3/command/printer_table.go | 3 + etcdctl/ctlv3/command/snapshot_command.go | 4 +- etcdctl/ctlv3/command/user_command.go | 4 +- etcdctl/ctlv3/ctl.go | 5 +- etcdutl/ctl.go | 12 +- etcdutl/etcdutl/defrag_command.go | 4 +- etcdutl/etcdutl/hashkv_command.go | 4 +- etcdutl/etcdutl/printer.go | 4 +- etcdutl/etcdutl/printer_simple.go | 3 +- etcdutl/etcdutl/snapshot_command.go | 3 +- etcdutl/snapshot/v3_snapshot.go | 4 +- etcdutl/snapshot/v3_snapshot_test.go | 6 +- pkg/expect/expect.go | 4 +- pkg/featuregate/feature_gate_test.go | 6 +- pkg/netutil/netutil_test.go | 1 + pkg/netutil/routes_linux.go | 8 +- pkg/osutil/osutil.go | 6 +- pkg/traceutil/trace.go | 6 +- server/auth/jwt.go | 3 +- server/auth/jwt_test.go | 2 +- server/auth/nop.go | 2 + server/auth/options.go | 6 +- server/auth/range_perm_cache.go | 3 +- server/auth/range_perm_cache_test.go | 12 +- server/auth/store.go | 5 +- server/auth/store_test.go | 5 +- server/embed/serve.go | 3 +- server/etcdmain/gateway.go | 12 +- server/etcdserver/api/etcdhttp/health_test.go | 1 - server/etcdserver/api/etcdhttp/peer_test.go | 3 + server/etcdserver/api/membership/cluster.go | 2 +- .../api/membership/membership_test.go | 9 +- .../etcdserver/api/rafthttp/pipeline_test.go | 1 + .../api/rafthttp/snapshot_sender.go | 6 +- server/etcdserver/api/rafthttp/stream.go | 10 +- server/etcdserver/api/rafthttp/stream_test.go | 1 + server/etcdserver/api/rafthttp/util.go | 3 +- server/etcdserver/api/snap/snapshotter.go | 2 +- .../etcdserver/api/snap/snapshotter_test.go | 22 +- server/etcdserver/api/v2error/error.go | 2 +- server/etcdserver/api/v2stats/queue.go | 2 +- server/etcdserver/api/v2store/event_queue.go | 2 +- server/etcdserver/api/v2store/store.go | 9 +- server/etcdserver/api/v2store/watcher_hub.go | 1 - .../etcdserver/api/v3discovery/discovery.go | 1 + .../api/v3discovery/discovery_test.go | 2 +- server/etcdserver/api/v3rpc/interceptor.go | 6 +- server/etcdserver/api/v3rpc/lease.go | 1 - server/etcdserver/api/v3rpc/watch.go | 3 +- server/etcdserver/apply/apply.go | 6 +- server/etcdserver/apply/apply_auth_test.go | 307 +++++++++--------- server/etcdserver/apply/metrics.go | 16 +- server/etcdserver/apply/uber_applier.go | 6 +- server/etcdserver/apply/uber_applier_test.go | 11 +- server/etcdserver/bootstrap_test.go | 4 +- server/etcdserver/cindex/cindex.go | 4 +- server/etcdserver/corrupt_test.go | 6 +- server/etcdserver/raft_test.go | 42 ++- server/etcdserver/server_test.go | 19 +- server/mock/mockstore/store_recorder.go | 11 + server/mock/mockwait/wait_recorder.go | 1 + .../adapter/election_client_adapter.go | 2 + .../grpcproxy/adapter/lease_client_adapter.go | 2 + .../adapter/maintenance_client_adapter.go | 2 + .../grpcproxy/adapter/watch_client_adapter.go | 2 + server/proxy/grpcproxy/watch_broadcast.go | 1 + server/storage/backend/backend.go | 7 +- server/storage/mvcc/hash_test.go | 2 +- server/storage/mvcc/key_index.go | 4 +- server/storage/mvcc/kv_test.go | 3 +- server/storage/mvcc/kvstore.go | 8 +- server/storage/mvcc/kvstore_test.go | 13 +- server/storage/mvcc/watcher_group.go | 10 +- server/storage/schema/actions.go | 3 +- server/storage/schema/auth.go | 6 +- server/storage/schema/schema.go | 2 +- server/storage/schema/version_test.go | 2 +- server/storage/wal/wal_test.go | 10 +- server/storage/wal/walpb/record.go | 4 +- tests/common/auth_test.go | 8 +- tests/common/compact_test.go | 2 +- tests/common/defrag_test.go | 2 +- tests/e2e/corrupt_test.go | 2 +- tests/e2e/ctl_v3_auth_no_proxy_test.go | 2 + tests/e2e/ctl_v3_auth_test.go | 1 + tests/e2e/ctl_v3_completion_test.go | 2 +- tests/e2e/ctl_v3_defrag_test.go | 2 +- tests/e2e/ctl_v3_kv_test.go | 18 +- tests/e2e/ctl_v3_lease_test.go | 3 + tests/e2e/ctl_v3_member_test.go | 3 + tests/e2e/ctl_v3_snapshot_test.go | 9 +- tests/e2e/ctl_v3_watch_no_cov_test.go | 3 + tests/e2e/discovery_v3_test.go | 4 + tests/e2e/etcd_grpcproxy_test.go | 3 +- tests/e2e/etcd_release_upgrade_test.go | 1 - tests/e2e/gateway_test.go | 4 +- tests/e2e/http_health_check_test.go | 50 ++- tests/e2e/v2store_deprecation_test.go | 5 +- tests/e2e/v3_curl_auth_test.go | 7 +- tests/e2e/v3_curl_lease_test.go | 3 + tests/framework/e2e/curl.go | 4 +- tests/framework/e2e/etcd_process.go | 6 +- tests/framework/e2e/lazyfs.go | 6 +- tests/framework/integration/cluster.go | 4 +- tests/framework/integration/testing.go | 6 +- .../clientv3/concurrency/session_test.go | 3 +- .../experimental/recipes/v3_queue_test.go | 1 + .../clientv3/naming/endpoints_test.go | 3 +- .../integration/clientv3/ordering_kv_test.go | 4 +- tests/integration/clientv3/util.go | 1 - tests/integration/clientv3/watch_test.go | 6 +- tests/integration/embed/embed_test.go | 14 +- tests/integration/metrics_test.go | 3 +- .../proxy/grpcproxy/cluster_test.go | 8 +- .../integration/snapshot/v3_snapshot_test.go | 3 +- tests/integration/testing_test.go | 1 - tests/integration/tracing_test.go | 8 +- tests/integration/v2store/main_test.go | 2 - tests/integration/v3_failover_test.go | 2 - tests/integration/v3_grpc_test.go | 135 +++++--- tests/integration/v3_kv_test.go | 2 +- tests/integration/v3_leadership_test.go | 1 - tests/integration/v3_lease_test.go | 4 +- tests/integration/v3_watch_restore_test.go | 3 +- tests/integration/v3_watch_test.go | 91 ++++-- tests/robustness/client/watch.go | 2 +- tests/robustness/failpoint/cluster.go | 4 +- tests/robustness/failpoint/failpoint.go | 36 +- tests/robustness/failpoint/kill.go | 4 +- tests/robustness/model/deterministic.go | 15 +- tests/robustness/model/history.go | 2 +- tests/robustness/report/client.go | 10 +- tests/robustness/report/report.go | 2 +- tests/robustness/traffic/etcd.go | 2 +- tests/robustness/traffic/kubernetes.go | 24 +- tools/.golangci.yaml | 2 +- tools/benchmark/cmd/lease.go | 4 +- tools/etcd-dump-db/backend.go | 4 +- tools/etcd-dump-db/main.go | 8 +- tools/etcd-dump-db/page.go | 8 +- tools/etcd-dump-logs/etcd-dump-log_test.go | 13 +- tools/etcd-dump-logs/main.go | 13 +- tools/local-tester/bridge/bridge.go | 6 +- tools/proto-annotations/cmd/etcd_version.go | 24 +- 152 files changed, 795 insertions(+), 631 deletions(-) diff --git a/contrib/raftexample/raft.go b/contrib/raftexample/raft.go index 2c4ae9cf4b5..22408317bc4 100644 --- a/contrib/raftexample/raft.go +++ b/contrib/raftexample/raft.go @@ -85,7 +85,8 @@ var defaultSnapshotCount uint64 = 10000 // commit channel, followed by a nil message (to indicate the channel is // current), then new log entries. To shutdown, close proposeC and read errorC. func newRaftNode(id int, peers []string, join bool, getSnapshot func() ([]byte, error), proposeC <-chan string, - confChangeC <-chan raftpb.ConfChange) (<-chan *commit, <-chan error, <-chan *snap.Snapshotter) { + confChangeC <-chan raftpb.ConfChange, +) (<-chan *commit, <-chan error, <-chan *snap.Snapshotter) { commitC := make(chan *commit) errorC := make(chan error) @@ -217,7 +218,7 @@ func (rc *raftNode) loadSnapshot() *raftpb.Snapshot { // openWAL returns a WAL ready for reading. func (rc *raftNode) openWAL(snapshot *raftpb.Snapshot) *wal.WAL { if !wal.Exist(rc.waldir) { - if err := os.Mkdir(rc.waldir, 0750); err != nil { + if err := os.Mkdir(rc.waldir, 0o750); err != nil { log.Fatalf("raftexample: cannot create dir for wal (%v)", err) } @@ -272,7 +273,7 @@ func (rc *raftNode) writeError(err error) { func (rc *raftNode) startRaft() { if !fileutil.Exist(rc.snapdir) { - if err := os.Mkdir(rc.snapdir, 0750); err != nil { + if err := os.Mkdir(rc.snapdir, 0o750); err != nil { log.Fatalf("raftexample: cannot create dir for snapshot (%v)", err) } } diff --git a/etcdctl/ctlv3/command/check.go b/etcdctl/ctlv3/command/check.go index 8d5906449cb..3678f32c0aa 100644 --- a/etcdctl/ctlv3/command/check.go +++ b/etcdctl/ctlv3/command/check.go @@ -139,7 +139,7 @@ func NewCheckPerfCommand() *cobra.Command { // newCheckPerfCommand executes the "check perf" command. func newCheckPerfCommand(cmd *cobra.Command, args []string) { - var checkPerfAlias = map[string]string{ + checkPerfAlias := map[string]string{ "s": "s", "small": "s", "m": "m", "medium": "m", "l": "l", "large": "l", @@ -312,7 +312,7 @@ func NewCheckDatascaleCommand() *cobra.Command { // newCheckDatascaleCommand executes the "check datascale" command. func newCheckDatascaleCommand(cmd *cobra.Command, args []string) { - var checkDatascaleAlias = map[string]string{ + checkDatascaleAlias := map[string]string{ "s": "s", "small": "s", "m": "m", "medium": "m", "l": "l", "large": "l", diff --git a/etcdctl/ctlv3/command/elect_command.go b/etcdctl/ctlv3/command/elect_command.go index 2e9a32b3f0d..eee4289e710 100644 --- a/etcdctl/ctlv3/command/elect_command.go +++ b/etcdctl/ctlv3/command/elect_command.go @@ -28,9 +28,7 @@ import ( "go.etcd.io/etcd/pkg/v3/cobrautl" ) -var ( - electListen bool -) +var electListen bool // NewElectCommand returns the cobra command for "elect". func NewElectCommand() *cobra.Command { diff --git a/etcdctl/ctlv3/command/ep_command.go b/etcdctl/ctlv3/command/ep_command.go index 22968ab057a..65df3dff372 100644 --- a/etcdctl/ctlv3/command/ep_command.go +++ b/etcdctl/ctlv3/command/ep_command.go @@ -32,8 +32,10 @@ import ( "go.etcd.io/etcd/pkg/v3/flags" ) -var epClusterEndpoints bool -var epHashKVRev int64 +var ( + epClusterEndpoints bool + epHashKVRev int64 +) // NewEndpointCommand returns the cobra command for "endpoint". func NewEndpointCommand() *cobra.Command { diff --git a/etcdctl/ctlv3/command/lease_command.go b/etcdctl/ctlv3/command/lease_command.go index 3d5094b3512..8e70670b638 100644 --- a/etcdctl/ctlv3/command/lease_command.go +++ b/etcdctl/ctlv3/command/lease_command.go @@ -151,9 +151,7 @@ func leaseListCommandFunc(cmd *cobra.Command, args []string) { display.Leases(*resp) } -var ( - leaseKeepAliveOnce bool -) +var leaseKeepAliveOnce bool // NewLeaseKeepAliveCommand returns the cobra command for "lease keep-alive". func NewLeaseKeepAliveCommand() *cobra.Command { diff --git a/etcdctl/ctlv3/command/printer.go b/etcdctl/ctlv3/command/printer.go index 75ee6324126..90a76ebfc31 100644 --- a/etcdctl/ctlv3/command/printer.go +++ b/etcdctl/ctlv3/command/printer.go @@ -111,9 +111,11 @@ func (p *printerRPC) MemberAdd(r v3.MemberAddResponse) { p.p((*pb.MemberAddRespo func (p *printerRPC) MemberRemove(id uint64, r v3.MemberRemoveResponse) { p.p((*pb.MemberRemoveResponse)(&r)) } + func (p *printerRPC) MemberUpdate(id uint64, r v3.MemberUpdateResponse) { p.p((*pb.MemberUpdateResponse)(&r)) } + func (p *printerRPC) MemberPromote(id uint64, r v3.MemberPromoteResponse) { p.p((*pb.MemberPromoteResponse)(&r)) } @@ -134,6 +136,7 @@ func (p *printerRPC) RoleList(r v3.AuthRoleListResponse) { p.p((*pb.AuthRoleList func (p *printerRPC) RoleGrantPermission(_ string, r v3.AuthRoleGrantPermissionResponse) { p.p((*pb.AuthRoleGrantPermissionResponse)(&r)) } + func (p *printerRPC) RoleRevokePermission(_ string, _ string, _ string, r v3.AuthRoleRevokePermissionResponse) { p.p((*pb.AuthRoleRevokePermissionResponse)(&r)) } @@ -143,15 +146,19 @@ func (p *printerRPC) UserList(r v3.AuthUserListResponse) { p.p((*pb.Auth func (p *printerRPC) UserChangePassword(r v3.AuthUserChangePasswordResponse) { p.p((*pb.AuthUserChangePasswordResponse)(&r)) } + func (p *printerRPC) UserGrantRole(_ string, _ string, r v3.AuthUserGrantRoleResponse) { p.p((*pb.AuthUserGrantRoleResponse)(&r)) } + func (p *printerRPC) UserRevokeRole(_ string, _ string, r v3.AuthUserRevokeRoleResponse) { p.p((*pb.AuthUserRevokeRoleResponse)(&r)) } + func (p *printerRPC) UserDelete(_ string, r v3.AuthUserDeleteResponse) { p.p((*pb.AuthUserDeleteResponse)(&r)) } + func (p *printerRPC) AuthStatus(r v3.AuthStatusResponse) { p.p((*pb.AuthStatusResponse)(&r)) } @@ -211,8 +218,10 @@ func makeEndpointHealthTable(healthList []epHealth) (hdr []string, rows [][]stri } func makeEndpointStatusTable(statusList []epStatus) (hdr []string, rows [][]string) { - hdr = []string{"endpoint", "ID", "version", "storage version", "db size", "in use", "percentage not in use", "quota", "is leader", "is learner", "raft term", - "raft index", "raft applied index", "errors"} + hdr = []string{ + "endpoint", "ID", "version", "storage version", "db size", "in use", "percentage not in use", "quota", "is leader", "is learner", "raft term", + "raft index", "raft applied index", "errors", + } for _, status := range statusList { rows = append(rows, []string{ status.Ep, diff --git a/etcdctl/ctlv3/command/printer_fields.go b/etcdctl/ctlv3/command/printer_fields.go index 5e7d9258425..86f1c70d71e 100644 --- a/etcdctl/ctlv3/command/printer_fields.go +++ b/etcdctl/ctlv3/command/printer_fields.go @@ -248,9 +248,11 @@ func (p *fieldsPrinter) RoleList(r v3.AuthRoleListResponse) { } fmt.Println() } + func (p *fieldsPrinter) RoleGrantPermission(role string, r v3.AuthRoleGrantPermissionResponse) { p.hdr(r.Header) } + func (p *fieldsPrinter) RoleRevokePermission(role string, key string, end string, r v3.AuthRoleRevokePermissionResponse) { p.hdr(r.Header) } @@ -259,6 +261,7 @@ func (p *fieldsPrinter) UserChangePassword(r v3.AuthUserChangePasswordResponse) func (p *fieldsPrinter) UserGrantRole(user string, role string, r v3.AuthUserGrantRoleResponse) { p.hdr(r.Header) } + func (p *fieldsPrinter) UserRevokeRole(user string, role string, r v3.AuthUserRevokeRoleResponse) { p.hdr(r.Header) } diff --git a/etcdctl/ctlv3/command/printer_simple.go b/etcdctl/ctlv3/command/printer_simple.go index 1da5e2c6ab5..c7e4fab725e 100644 --- a/etcdctl/ctlv3/command/printer_simple.go +++ b/etcdctl/ctlv3/command/printer_simple.go @@ -183,9 +183,11 @@ func (s *simplePrinter) MoveLeader(leader, target uint64, r v3.MoveLeaderRespons func (s *simplePrinter) DowngradeValidate(r v3.DowngradeResponse) { fmt.Printf("Downgrade validate success, cluster version %s\n", r.Version) } + func (s *simplePrinter) DowngradeEnable(r v3.DowngradeResponse) { fmt.Printf("Downgrade enable success, cluster version %s\n", r.Version) } + func (s *simplePrinter) DowngradeCancel(r v3.DowngradeResponse) { fmt.Printf("Downgrade cancel success, cluster version %s\n", r.Version) } diff --git a/etcdctl/ctlv3/command/printer_table.go b/etcdctl/ctlv3/command/printer_table.go index b617744649f..c576231ed5b 100644 --- a/etcdctl/ctlv3/command/printer_table.go +++ b/etcdctl/ctlv3/command/printer_table.go @@ -34,6 +34,7 @@ func (tp *tablePrinter) MemberList(r v3.MemberListResponse) { table.SetAlignment(tablewriter.ALIGN_RIGHT) table.Render() } + func (tp *tablePrinter) EndpointHealth(r []epHealth) { hdr, rows := makeEndpointHealthTable(r) table := tablewriter.NewWriter(os.Stdout) @@ -44,6 +45,7 @@ func (tp *tablePrinter) EndpointHealth(r []epHealth) { table.SetAlignment(tablewriter.ALIGN_RIGHT) table.Render() } + func (tp *tablePrinter) EndpointStatus(r []epStatus) { hdr, rows := makeEndpointStatusTable(r) table := tablewriter.NewWriter(os.Stdout) @@ -54,6 +56,7 @@ func (tp *tablePrinter) EndpointStatus(r []epStatus) { table.SetAlignment(tablewriter.ALIGN_RIGHT) table.Render() } + func (tp *tablePrinter) EndpointHashKV(r []epHashKV) { hdr, rows := makeEndpointHashKVTable(r) table := tablewriter.NewWriter(os.Stdout) diff --git a/etcdctl/ctlv3/command/snapshot_command.go b/etcdctl/ctlv3/command/snapshot_command.go index 983cf93ad16..66934bede37 100644 --- a/etcdctl/ctlv3/command/snapshot_command.go +++ b/etcdctl/ctlv3/command/snapshot_command.go @@ -27,8 +27,7 @@ import ( "go.etcd.io/etcd/pkg/v3/cobrautl" ) -var ( - snapshotExample = util.Normalize(` +var snapshotExample = util.Normalize(` # Save snapshot to a given file etcdctl snapshot save /backup/etcd-snapshot.db @@ -46,7 +45,6 @@ var ( # Save snapshot with desirable time format etcdctl snapshot save /mnt/backup/etcd/backup_$(date +%Y%m%d_%H%M%S).db`) -) // NewSnapshotCommand returns the cobra command for "snapshot". func NewSnapshotCommand() *cobra.Command { diff --git a/etcdctl/ctlv3/command/user_command.go b/etcdctl/ctlv3/command/user_command.go index 9aec9fab5dc..f3e59a7048b 100644 --- a/etcdctl/ctlv3/command/user_command.go +++ b/etcdctl/ctlv3/command/user_command.go @@ -26,9 +26,7 @@ import ( "go.etcd.io/etcd/pkg/v3/cobrautl" ) -var ( - userShowDetail bool -) +var userShowDetail bool // NewUserCommand returns the cobra command for "user". func NewUserCommand() *cobra.Command { diff --git a/etcdctl/ctlv3/ctl.go b/etcdctl/ctlv3/ctl.go index 59b6e002c51..168386fb0a7 100644 --- a/etcdctl/ctlv3/ctl.go +++ b/etcdctl/ctlv3/ctl.go @@ -38,10 +38,7 @@ const ( var ( globalFlags = command.GlobalFlags{} -) - -var ( - rootCmd = &cobra.Command{ + rootCmd = &cobra.Command{ Use: cliName, Short: cliDescription, SuggestFor: []string{"etcdctl"}, diff --git a/etcdutl/ctl.go b/etcdutl/ctl.go index e4106634744..8418729bfd1 100644 --- a/etcdutl/ctl.go +++ b/etcdutl/ctl.go @@ -26,13 +26,11 @@ const ( cliDescription = "An administrative command line tool for etcd3." ) -var ( - rootCmd = &cobra.Command{ - Use: cliName, - Short: cliDescription, - SuggestFor: []string{"etcdutl"}, - } -) +var rootCmd = &cobra.Command{ + Use: cliName, + Short: cliDescription, + SuggestFor: []string{"etcdutl"}, +} func init() { rootCmd.PersistentFlags().StringVarP(&etcdutl.OutputFormat, "write-out", "w", "simple", "set the output format (fields, json, protobuf, simple, table)") diff --git a/etcdutl/etcdutl/defrag_command.go b/etcdutl/etcdutl/defrag_command.go index 0d100025954..5135f5f5eb8 100644 --- a/etcdutl/etcdutl/defrag_command.go +++ b/etcdutl/etcdutl/defrag_command.go @@ -26,9 +26,7 @@ import ( "go.etcd.io/etcd/server/v3/storage/datadir" ) -var ( - defragDataDir string -) +var defragDataDir string // NewDefragCommand returns the cobra command for "Defrag". func NewDefragCommand() *cobra.Command { diff --git a/etcdutl/etcdutl/hashkv_command.go b/etcdutl/etcdutl/hashkv_command.go index 36db0a43f75..20c47a51452 100644 --- a/etcdutl/etcdutl/hashkv_command.go +++ b/etcdutl/etcdutl/hashkv_command.go @@ -23,9 +23,7 @@ import ( "go.etcd.io/etcd/server/v3/storage/mvcc" ) -var ( - hashKVRevision int64 -) +var hashKVRevision int64 // NewHashKVCommand returns the cobra command for "hashkv". func NewHashKVCommand() *cobra.Command { diff --git a/etcdutl/etcdutl/printer.go b/etcdutl/etcdutl/printer.go index 5234891caa3..739928dc5ff 100644 --- a/etcdutl/etcdutl/printer.go +++ b/etcdutl/etcdutl/printer.go @@ -25,9 +25,7 @@ import ( "go.etcd.io/etcd/pkg/v3/cobrautl" ) -var ( - OutputFormat string -) +var OutputFormat string type printer interface { DBStatus(snapshot.Status) diff --git a/etcdutl/etcdutl/printer_simple.go b/etcdutl/etcdutl/printer_simple.go index 8982e366b2c..b55c501dcf5 100644 --- a/etcdutl/etcdutl/printer_simple.go +++ b/etcdutl/etcdutl/printer_simple.go @@ -21,8 +21,7 @@ import ( "go.etcd.io/etcd/etcdutl/v3/snapshot" ) -type simplePrinter struct { -} +type simplePrinter struct{} func (s *simplePrinter) DBStatus(ds snapshot.Status) { _, rows := makeDBStatusTable(ds) diff --git a/etcdutl/etcdutl/snapshot_command.go b/etcdutl/etcdutl/snapshot_command.go index 98958b8e084..52cb4a1bbdd 100644 --- a/etcdutl/etcdutl/snapshot_command.go +++ b/etcdutl/etcdutl/snapshot_command.go @@ -120,7 +120,8 @@ func SnapshotRestoreCommandFunc(restoreCluster string, initialMmapSize uint64, revisionBump uint64, markCompacted bool, - args []string) { + args []string, +) { if len(args) != 1 { err := fmt.Errorf("snapshot restore requires exactly one argument") cobrautl.ExitWithError(cobrautl.ExitBadArgs, err) diff --git a/etcdutl/snapshot/v3_snapshot.go b/etcdutl/snapshot/v3_snapshot.go index 45b58ec0810..3d17dcbae51 100644 --- a/etcdutl/snapshot/v3_snapshot.go +++ b/etcdutl/snapshot/v3_snapshot.go @@ -119,7 +119,7 @@ func (s *v3Manager) Status(dbPath string) (ds Status, err error) { return ds, err } - db, err := bolt.Open(dbPath, 0400, &bolt.Options{ReadOnly: true}) + db, err := bolt.Open(dbPath, 0o400, &bolt.Options{ReadOnly: true}) if err != nil { return ds, err } @@ -449,7 +449,7 @@ func (s *v3Manager) copyAndVerifyDB() error { outDbPath := s.outDbPath() - db, dberr := os.OpenFile(outDbPath, os.O_RDWR|os.O_CREATE, 0600) + db, dberr := os.OpenFile(outDbPath, os.O_RDWR|os.O_CREATE, 0o600) if dberr != nil { return dberr } diff --git a/etcdutl/snapshot/v3_snapshot_test.go b/etcdutl/snapshot/v3_snapshot_test.go index 6e235cffe67..c2b3d5202a1 100644 --- a/etcdutl/snapshot/v3_snapshot_test.go +++ b/etcdutl/snapshot/v3_snapshot_test.go @@ -52,7 +52,7 @@ func TestSnapshotStatus(t *testing.T) { func TestSnapshotStatusCorruptRevision(t *testing.T) { dbpath := createDB(t, insertKeys(t, 1, 0)) - db, err := bbolt.Open(dbpath, 0600, nil) + db, err := bbolt.Open(dbpath, 0o600, nil) require.NoError(t, err) defer db.Close() @@ -74,7 +74,7 @@ func TestSnapshotStatusCorruptRevision(t *testing.T) { func TestSnapshotStatusNegativeRevisionMain(t *testing.T) { dbpath := createDB(t, insertKeys(t, 1, 0)) - db, err := bbolt.Open(dbpath, 0666, nil) + db, err := bbolt.Open(dbpath, 0o666, nil) require.NoError(t, err) defer db.Close() @@ -98,7 +98,7 @@ func TestSnapshotStatusNegativeRevisionMain(t *testing.T) { func TestSnapshotStatusNegativeRevisionSub(t *testing.T) { dbpath := createDB(t, insertKeys(t, 1, 0)) - db, err := bbolt.Open(dbpath, 0666, nil) + db, err := bbolt.Open(dbpath, 0o666, nil) require.NoError(t, err) defer db.Close() diff --git a/pkg/expect/expect.go b/pkg/expect/expect.go index 1a0999c43b0..8aab16e52a4 100644 --- a/pkg/expect/expect.go +++ b/pkg/expect/expect.go @@ -34,9 +34,7 @@ import ( const debugLinesTail = 40 -var ( - ErrProcessRunning = fmt.Errorf("process is still running") -) +var ErrProcessRunning = fmt.Errorf("process is still running") type ExpectedResponse struct { Value string diff --git a/pkg/featuregate/feature_gate_test.go b/pkg/featuregate/feature_gate_test.go index 1981496715e..7411f363fa3 100644 --- a/pkg/featuregate/feature_gate_test.go +++ b/pkg/featuregate/feature_gate_test.go @@ -233,7 +233,7 @@ func TestFeatureGateOverride(t *testing.T) { const testBetaGate Feature = "TestBeta" // Don't parse the flag, assert defaults are used. - var f = New("test", zaptest.NewLogger(t)) + f := New("test", zaptest.NewLogger(t)) f.Add(map[Feature]FeatureSpec{ testAlphaGate: {Default: false, PreRelease: Alpha}, testBetaGate: {Default: false, PreRelease: Beta}, @@ -262,7 +262,7 @@ func TestFeatureGateFlagDefaults(t *testing.T) { const testBetaGate Feature = "TestBeta" // Don't parse the flag, assert defaults are used. - var f = New("test", zaptest.NewLogger(t)) + f := New("test", zaptest.NewLogger(t)) f.Add(map[Feature]FeatureSpec{ testAlphaGate: {Default: false, PreRelease: Alpha}, testBetaGate: {Default: true, PreRelease: Beta}, @@ -286,7 +286,7 @@ func TestFeatureGateKnownFeatures(t *testing.T) { ) // Don't parse the flag, assert defaults are used. - var f = New("test", zaptest.NewLogger(t)) + f := New("test", zaptest.NewLogger(t)) f.Add(map[Feature]FeatureSpec{ testAlphaGate: {Default: false, PreRelease: Alpha}, testBetaGate: {Default: true, PreRelease: Beta}, diff --git a/pkg/netutil/netutil_test.go b/pkg/netutil/netutil_test.go index 119d06a352c..5b4551e1fc7 100644 --- a/pkg/netutil/netutil_test.go +++ b/pkg/netutil/netutil_test.go @@ -318,6 +318,7 @@ func TestURLsEqual(t *testing.T) { } } } + func TestURLStringsEqual(t *testing.T) { defer func() { resolveTCPAddr = resolveTCPAddrDefault }() errOnResolve := func(ctx context.Context, addr string) (*net.TCPAddr, error) { diff --git a/pkg/netutil/routes_linux.go b/pkg/netutil/routes_linux.go index f55899b0bda..b00ce457ec7 100644 --- a/pkg/netutil/routes_linux.go +++ b/pkg/netutil/routes_linux.go @@ -27,9 +27,11 @@ import ( "go.etcd.io/etcd/pkg/v3/cpuutil" ) -var errNoDefaultRoute = fmt.Errorf("could not find default route") -var errNoDefaultHost = fmt.Errorf("could not find default host") -var errNoDefaultInterface = fmt.Errorf("could not find default interface") +var ( + errNoDefaultRoute = fmt.Errorf("could not find default route") + errNoDefaultHost = fmt.Errorf("could not find default host") + errNoDefaultInterface = fmt.Errorf("could not find default interface") +) // GetDefaultHost obtains the first IP address of machine from the routing table and returns the IP address as string. // An IPv4 address is preferred to an IPv6 address for backward compatibility. diff --git a/pkg/osutil/osutil.go b/pkg/osutil/osutil.go index c1405db7008..f79108a6870 100644 --- a/pkg/osutil/osutil.go +++ b/pkg/osutil/osutil.go @@ -15,7 +15,5 @@ // Package osutil implements operating system-related utility functions. package osutil -var ( - // support to override setting SIG_DFL so tests don't terminate early - setDflSignal = dflSignal -) +// support to override setting SIG_DFL so tests don't terminate early +var setDflSignal = dflSignal diff --git a/pkg/traceutil/trace.go b/pkg/traceutil/trace.go index 0f36323bd19..abf5cf1d229 100644 --- a/pkg/traceutil/trace.go +++ b/pkg/traceutil/trace.go @@ -211,12 +211,14 @@ func (t *Trace) logInfo(threshold time.Duration) (string, []zap.Field) { lastStepTime = tstep.time } - fs := []zap.Field{zap.String("detail", writeFields(t.fields)), + fs := []zap.Field{ + zap.String("detail", writeFields(t.fields)), zap.Duration("duration", totalDuration), zap.Time("start", t.startTime), zap.Time("end", endTime), zap.Strings("steps", steps), - zap.Int("step_count", len(steps))} + zap.Int("step_count", len(steps)), + } return msg, fs } diff --git a/server/auth/jwt.go b/server/auth/jwt.go index 18890de9c0b..4984dca62ee 100644 --- a/server/auth/jwt.go +++ b/server/auth/jwt.go @@ -61,7 +61,6 @@ func (t *tokenJWT) info(ctx context.Context, token string, rev uint64) (*AuthInf return t.key, nil } }) - if err != nil { t.lg.Warn( "failed to parse a JWT token", @@ -137,7 +136,7 @@ func newTokenProviderJWT(lg *zap.Logger, optMap map[string]string) (*tokenJWT, e return nil, ErrInvalidAuthOpts } - var keys = make([]string, 0, len(optMap)) + keys := make([]string, 0, len(optMap)) for k := range optMap { if !knownOptions[k] { keys = append(keys, k) diff --git a/server/auth/jwt_test.go b/server/auth/jwt_test.go index 90d9455f175..ff0e4c41989 100644 --- a/server/auth/jwt_test.go +++ b/server/auth/jwt_test.go @@ -220,7 +220,7 @@ func TestJWTTokenWithMissingFields(t *testing.T) { } func TestJWTBad(t *testing.T) { - var badCases = map[string]map[string]string{ + badCases := map[string]map[string]string{ "no options": {}, "invalid method": { "sign-method": "invalid", diff --git a/server/auth/nop.go b/server/auth/nop.go index d4378747bd8..8ba3f8c893c 100644 --- a/server/auth/nop.go +++ b/server/auth/nop.go @@ -27,9 +27,11 @@ func (t *tokenNop) genTokenPrefix() (string, error) { return "", nil } func (t *tokenNop) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) { return nil, false } + func (t *tokenNop) assign(ctx context.Context, username string, revision uint64) (string, error) { return "", ErrAuthFailed } + func newTokenProviderNop() (*tokenNop, error) { return &tokenNop{}, nil } diff --git a/server/auth/options.go b/server/auth/options.go index 7ed4bf2f002..6d554fbc45e 100644 --- a/server/auth/options.go +++ b/server/auth/options.go @@ -40,10 +40,8 @@ var knownOptions = map[string]bool{ optTTL: true, } -var ( - // DefaultTTL will be used when a 'ttl' is not specified - DefaultTTL = 5 * time.Minute -) +// DefaultTTL will be used when a 'ttl' is not specified +var DefaultTTL = 5 * time.Minute type jwtOptions struct { SignMethod jwt.SigningMethod diff --git a/server/auth/range_perm_cache.go b/server/auth/range_perm_cache.go index a540e121d0d..539ed290e68 100644 --- a/server/auth/range_perm_cache.go +++ b/server/auth/range_perm_cache.go @@ -74,7 +74,8 @@ func checkKeyInterval( lg *zap.Logger, cachedPerms *unifiedRangePermissions, key, rangeEnd []byte, - permtyp authpb.Permission_Type) bool { + permtyp authpb.Permission_Type, +) bool { if isOpenEnded(rangeEnd) { rangeEnd = nil // nil rangeEnd will be converetd to []byte{}, the largest element of BytesAffineComparable, diff --git a/server/auth/range_perm_cache_test.go b/server/auth/range_perm_cache_test.go index 8a11c7ac1da..4b39acbcb2f 100644 --- a/server/auth/range_perm_cache_test.go +++ b/server/auth/range_perm_cache_test.go @@ -47,22 +47,26 @@ func TestRangePermission(t *testing.T) { }, { []adt.Interval{adt.NewBytesAffineInterval([]byte("a"), []byte("d")), adt.NewBytesAffineInterval([]byte("a"), []byte("b")), adt.NewBytesAffineInterval([]byte("c"), []byte("f"))}, - []byte("a"), []byte{}, + []byte("a"), + []byte{}, false, }, { []adt.Interval{adt.NewBytesAffineInterval([]byte("a"), []byte{})}, - []byte("a"), []byte{}, + []byte("a"), + []byte{}, true, }, { []adt.Interval{adt.NewBytesAffineInterval([]byte{0x00}, []byte{})}, - []byte("a"), []byte{}, + []byte("a"), + []byte{}, true, }, { []adt.Interval{adt.NewBytesAffineInterval([]byte{0x00}, []byte{})}, - []byte{0x00}, []byte{}, + []byte{0x00}, + []byte{}, true, }, } diff --git a/server/auth/store.go b/server/auth/store.go index 387aa560494..ed302638378 100644 --- a/server/auth/store.go +++ b/server/auth/store.go @@ -1060,7 +1060,7 @@ func (as *authStore) AuthInfoFromCtx(ctx context.Context) (*AuthInfo, error) { return nil, nil } - //TODO(mitake|hexfusion) review unifying key names + // TODO(mitake|hexfusion) review unifying key names ts, ok := md[rpctypes.TokenFieldNameGRPC] if !ok { ts, ok = md[rpctypes.TokenFieldNameSwagger] @@ -1120,7 +1120,8 @@ func NewTokenProvider( lg *zap.Logger, tokenOpts string, indexWaiter func(uint64) <-chan struct{}, - TokenTTL time.Duration) (TokenProvider, error) { + TokenTTL time.Duration, +) (TokenProvider, error) { tokenType, typeSpecificOpts, err := decomposeOpts(lg, tokenOpts) if err != nil { return nil, ErrInvalidAuthOpts diff --git a/server/auth/store_test.go b/server/auth/store_test.go index fe426b4e1d4..c8cd5cad7cc 100644 --- a/server/auth/store_test.go +++ b/server/auth/store_test.go @@ -524,7 +524,6 @@ func TestRoleGrantPermission(t *testing.T) { Name: "role-test-1", Perm: perm, }) - if err != nil { t.Error(err) } @@ -704,7 +703,6 @@ func TestRootRoleGrantPermission(t *testing.T) { Name: "root", Perm: perm, }) - if err != nil { t.Error(err) } @@ -714,7 +712,7 @@ func TestRootRoleGrantPermission(t *testing.T) { t.Fatal(err) } - //whatever grant permission to root, it always return root permission. + // whatever grant permission to root, it always return root permission. expectPerm := &authpb.Permission{ PermType: authpb.READWRITE, Key: []byte{}, @@ -742,7 +740,6 @@ func TestRoleRevokePermission(t *testing.T) { Name: "role-test-1", Perm: perm, }) - if err != nil { t.Fatal(err) } diff --git a/server/embed/serve.go b/server/embed/serve.go index 7f1a221974f..c6c561149be 100644 --- a/server/embed/serve.go +++ b/server/embed/serve.go @@ -97,7 +97,8 @@ func (sctx *serveCtx) serve( errHandler func(error), grpcDialForRestGatewayBackends func(ctx context.Context) (*grpc.ClientConn, error), splitHTTP bool, - gopts ...grpc.ServerOption) (err error) { + gopts ...grpc.ServerOption, +) (err error) { logger := defaultLog.New(io.Discard, "etcdhttp", 0) <-s.ReadyNotify() diff --git a/server/etcdmain/gateway.go b/server/etcdmain/gateway.go index 3f5774f573f..cda7fd7ee3e 100644 --- a/server/etcdmain/gateway.go +++ b/server/etcdmain/gateway.go @@ -38,13 +38,11 @@ var ( gatewayCA string ) -var ( - rootCmd = &cobra.Command{ - Use: "etcd", - Short: "etcd server", - SuggestFor: []string{"etcd"}, - } -) +var rootCmd = &cobra.Command{ + Use: "etcd", + Short: "etcd server", + SuggestFor: []string{"etcd"}, +} func init() { rootCmd.AddCommand(newGatewayCommand()) diff --git a/server/etcdserver/api/etcdhttp/health_test.go b/server/etcdserver/api/etcdhttp/health_test.go index c3ff411ad25..a5f64061996 100644 --- a/server/etcdserver/api/etcdhttp/health_test.go +++ b/server/etcdserver/api/etcdhttp/health_test.go @@ -346,7 +346,6 @@ func TestLinearizableReadCheck(t *testing.T) { func checkHTTPResponse(t *testing.T, ts *httptest.Server, url string, expectStatusCode int, inResult []string, notInResult []string) { res, err := ts.Client().Do(&http.Request{Method: http.MethodGet, URL: testutil.MustNewURL(t, ts.URL+url)}) - if err != nil { t.Fatalf("fail serve http request %s %v", url, err) } diff --git a/server/etcdserver/api/etcdhttp/peer_test.go b/server/etcdserver/api/etcdhttp/peer_test.go index d42eb783d0d..224079960a9 100644 --- a/server/etcdserver/api/etcdhttp/peer_test.go +++ b/server/etcdserver/api/etcdhttp/peer_test.go @@ -64,12 +64,15 @@ type fakeServer struct { func (s *fakeServer) AddMember(ctx context.Context, memb membership.Member) ([]*membership.Member, error) { return nil, fmt.Errorf("AddMember not implemented in fakeServer") } + func (s *fakeServer) RemoveMember(ctx context.Context, id uint64) ([]*membership.Member, error) { return nil, fmt.Errorf("RemoveMember not implemented in fakeServer") } + func (s *fakeServer) UpdateMember(ctx context.Context, updateMemb membership.Member) ([]*membership.Member, error) { return nil, fmt.Errorf("UpdateMember not implemented in fakeServer") } + func (s *fakeServer) PromoteMember(ctx context.Context, id uint64) ([]*membership.Member, error) { return nil, fmt.Errorf("PromoteMember not implemented in fakeServer") } diff --git a/server/etcdserver/api/membership/cluster.go b/server/etcdserver/api/membership/cluster.go index e35375a22c6..9d62db12154 100644 --- a/server/etcdserver/api/membership/cluster.go +++ b/server/etcdserver/api/membership/cluster.go @@ -907,7 +907,7 @@ func (c *RaftCluster) Store(store v2store.Store) { ) } for id := range c.removed { - //We do not need to delete the member since the store is empty. + // We do not need to delete the member since the store is empty. mustAddToRemovedMembersInStore(c.lg, store, id) } if c.version != nil { diff --git a/server/etcdserver/api/membership/membership_test.go b/server/etcdserver/api/membership/membership_test.go index 3abc97a2c6c..77be3bba255 100644 --- a/server/etcdserver/api/membership/membership_test.go +++ b/server/etcdserver/api/membership/membership_test.go @@ -44,8 +44,10 @@ func TestAddRemoveMember(t *testing.T) { c2 := newTestCluster(t, nil) c2.SetBackend(be) c2.Recover(func(*zap.Logger, *semver.Version) {}) - assert.Equal(t, []*Member{{ID: types.ID(19), - Attributes: Attributes{Name: "node19"}}}, c2.Members()) + assert.Equal(t, []*Member{{ + ID: types.ID(19), + Attributes: Attributes{Name: "node19"}, + }}, c2.Members()) assert.True(t, c2.IsIDRemoved(17)) assert.True(t, c2.IsIDRemoved(18)) assert.False(t, c2.IsIDRemoved(19)) @@ -78,14 +80,17 @@ func (b *backendMock) MustSaveClusterVersionToBackend(version *semver.Version) { func (b *backendMock) MustReadMembersFromBackend() (x map[types.ID]*Member, y map[types.ID]bool) { return b.members, b.removed } + func (b *backendMock) MustSaveMemberToBackend(m *Member) { b.members[m.ID] = m } + func (b *backendMock) TrimMembershipFromBackend() error { b.members = make(map[types.ID]*Member) b.removed = make(map[types.ID]bool) return nil } + func (b *backendMock) MustDeleteMemberFromBackend(id types.ID) { delete(b.members, id) b.removed[id] = true diff --git a/server/etcdserver/api/rafthttp/pipeline_test.go b/server/etcdserver/api/rafthttp/pipeline_test.go index 42a73c98363..316918ba5b6 100644 --- a/server/etcdserver/api/rafthttp/pipeline_test.go +++ b/server/etcdserver/api/rafthttp/pipeline_test.go @@ -272,6 +272,7 @@ type respRoundTripper struct { func newRespRoundTripper(code int, err error) *respRoundTripper { return &respRoundTripper{code: code, err: err} } + func (t *respRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { t.mu.Lock() defer t.mu.Unlock() diff --git a/server/etcdserver/api/rafthttp/snapshot_sender.go b/server/etcdserver/api/rafthttp/snapshot_sender.go index 07971cbbddc..8dbc11724b3 100644 --- a/server/etcdserver/api/rafthttp/snapshot_sender.go +++ b/server/etcdserver/api/rafthttp/snapshot_sender.go @@ -32,10 +32,8 @@ import ( "go.etcd.io/raft/v3" ) -var ( - // timeout for reading snapshot response body - snapResponseReadTimeout = 5 * time.Second -) +// timeout for reading snapshot response body +var snapResponseReadTimeout = 5 * time.Second type snapshotSender struct { from, to types.ID diff --git a/server/etcdserver/api/rafthttp/stream.go b/server/etcdserver/api/rafthttp/stream.go index e823c4770f4..fa02f42b9b9 100644 --- a/server/etcdserver/api/rafthttp/stream.go +++ b/server/etcdserver/api/rafthttp/stream.go @@ -90,12 +90,10 @@ func (t streamType) String() string { } } -var ( - // linkHeartbeatMessage is a special message used as heartbeat message in - // link layer. It never conflicts with messages from raft because raft - // doesn't send out messages without From and To fields. - linkHeartbeatMessage = raftpb.Message{Type: raftpb.MsgHeartbeat} -) +// linkHeartbeatMessage is a special message used as heartbeat message in +// link layer. It never conflicts with messages from raft because raft +// doesn't send out messages without From and To fields. +var linkHeartbeatMessage = raftpb.Message{Type: raftpb.MsgHeartbeat} func isLinkHeartbeatMessage(m *raftpb.Message) bool { return m.Type == raftpb.MsgHeartbeat && m.From == 0 && m.To == 0 diff --git a/server/etcdserver/api/rafthttp/stream_test.go b/server/etcdserver/api/rafthttp/stream_test.go index 428010286d9..a50961b96f0 100644 --- a/server/etcdserver/api/rafthttp/stream_test.go +++ b/server/etcdserver/api/rafthttp/stream_test.go @@ -234,6 +234,7 @@ func (wrc *waitReadCloser) Read(p []byte) (int, error) { <-wrc.closec return 0, io.EOF } + func (wrc *waitReadCloser) Close() error { close(wrc.closec) return nil diff --git a/server/etcdserver/api/rafthttp/util.go b/server/etcdserver/api/rafthttp/util.go index 5fe0728218b..5057f539af9 100644 --- a/server/etcdserver/api/rafthttp/util.go +++ b/server/etcdserver/api/rafthttp/util.go @@ -169,7 +169,8 @@ func minClusterVersion(h http.Header) *semver.Version { func checkVersionCompatibility(name string, server, minCluster *semver.Version) ( localServer *semver.Version, localMinCluster *semver.Version, - err error) { + err error, +) { localServer = semver.Must(semver.NewVersion(version.Version)) localMinCluster = semver.Must(semver.NewVersion(version.MinClusterVersion)) if compareMajorMinorVersion(server, localMinCluster) == -1 { diff --git a/server/etcdserver/api/snap/snapshotter.go b/server/etcdserver/api/snap/snapshotter.go index 2ae2b002341..0de6f9b91ea 100644 --- a/server/etcdserver/api/snap/snapshotter.go +++ b/server/etcdserver/api/snap/snapshotter.go @@ -88,7 +88,7 @@ func (s *Snapshotter) save(snapshot *raftpb.Snapshot) error { spath := filepath.Join(s.dir, fname) fsyncStart := time.Now() - err = pioutil.WriteAndSyncFile(spath, d, 0666) + err = pioutil.WriteAndSyncFile(spath, d, 0o666) snapFsyncSec.Observe(time.Since(fsyncStart).Seconds()) if err != nil { diff --git a/server/etcdserver/api/snap/snapshotter_test.go b/server/etcdserver/api/snap/snapshotter_test.go index cad3059fb18..51d0ac0443a 100644 --- a/server/etcdserver/api/snap/snapshotter_test.go +++ b/server/etcdserver/api/snap/snapshotter_test.go @@ -43,7 +43,7 @@ var testSnap = &raftpb.Snapshot{ func TestSaveAndLoad(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -65,7 +65,7 @@ func TestSaveAndLoad(t *testing.T) { func TestBadCRC(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -88,14 +88,14 @@ func TestBadCRC(t *testing.T) { func TestFailback(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } defer os.RemoveAll(dir) large := fmt.Sprintf("%016x-%016x-%016x.snap", 0xFFFF, 0xFFFF, 0xFFFF) - err = os.WriteFile(filepath.Join(dir, large), []byte("bad data"), 0666) + err = os.WriteFile(filepath.Join(dir, large), []byte("bad data"), 0o666) if err != nil { t.Fatal(err) } @@ -122,7 +122,7 @@ func TestFailback(t *testing.T) { func TestSnapNames(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -151,7 +151,7 @@ func TestSnapNames(t *testing.T) { func TestLoadNewestSnap(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -215,7 +215,7 @@ func TestLoadNewestSnap(t *testing.T) { func TestNoSnapshot(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -229,7 +229,7 @@ func TestNoSnapshot(t *testing.T) { func TestEmptySnapshot(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -250,7 +250,7 @@ func TestEmptySnapshot(t *testing.T) { // ErrNoSnapshot if all the snapshots are broken. func TestAllSnapshotBroken(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -270,7 +270,7 @@ func TestAllSnapshotBroken(t *testing.T) { func TestReleaseSnapDBs(t *testing.T) { dir := filepath.Join(os.TempDir(), "snapshot") - err := os.Mkdir(dir, 0700) + err := os.Mkdir(dir, 0o700) if err != nil { t.Fatal(err) } @@ -279,7 +279,7 @@ func TestReleaseSnapDBs(t *testing.T) { snapIndices := []uint64{100, 200, 300, 400} for _, index := range snapIndices { filename := filepath.Join(dir, fmt.Sprintf("%016x.snap.db", index)) - if err := os.WriteFile(filename, []byte("snap file\n"), 0644); err != nil { + if err := os.WriteFile(filename, []byte("snap file\n"), 0o644); err != nil { t.Fatal(err) } } diff --git a/server/etcdserver/api/v2error/error.go b/server/etcdserver/api/v2error/error.go index 0cbf2bf6930..168796e8357 100644 --- a/server/etcdserver/api/v2error/error.go +++ b/server/etcdserver/api/v2error/error.go @@ -27,7 +27,7 @@ import ( var errors = map[int]string{ // command related errors EcodeKeyNotFound: "Key not found", - EcodeTestFailed: "Compare failed", //test and set + EcodeTestFailed: "Compare failed", // test and set EcodeNotFile: "Not a file", ecodeNoMorePeer: "Reached the max number of peers in the cluster", EcodeNotDir: "Not a directory", diff --git a/server/etcdserver/api/v2stats/queue.go b/server/etcdserver/api/v2stats/queue.go index 9db8a14bcae..e16cec159c7 100644 --- a/server/etcdserver/api/v2stats/queue.go +++ b/server/etcdserver/api/v2stats/queue.go @@ -65,7 +65,7 @@ func (q *statsQueue) Insert(p *RequestStats) { q.back = (q.back + 1) % queueCapacity - if q.size == queueCapacity { //dequeue + if q.size == queueCapacity { // dequeue q.totalReqSize -= q.items[q.front].Size q.front = (q.back + 1) % queueCapacity } else { diff --git a/server/etcdserver/api/v2store/event_queue.go b/server/etcdserver/api/v2store/event_queue.go index 7ea03de8c9a..aa2a645d6ff 100644 --- a/server/etcdserver/api/v2store/event_queue.go +++ b/server/etcdserver/api/v2store/event_queue.go @@ -26,7 +26,7 @@ func (eq *eventQueue) insert(e *Event) { eq.Events[eq.Back] = e eq.Back = (eq.Back + 1) % eq.Capacity - if eq.Size == eq.Capacity { //dequeue + if eq.Size == eq.Capacity { // dequeue eq.Front = (eq.Front + 1) % eq.Capacity } else { eq.Size++ diff --git a/server/etcdserver/api/v2store/store.go b/server/etcdserver/api/v2store/store.go index 117f1c03e14..0c6f7b516e1 100644 --- a/server/etcdserver/api/v2store/store.go +++ b/server/etcdserver/api/v2store/store.go @@ -257,7 +257,8 @@ func getCompareFailCause(n *node, which int, prevValue string, prevIndex uint64) } func (s *store) CompareAndSwap(nodePath string, prevValue string, prevIndex uint64, - value string, expireOpts TTLOptionSet) (*Event, error) { + value string, expireOpts TTLOptionSet, +) (*Event, error) { var err *v2error.Error s.worldLock.Lock() @@ -563,7 +564,8 @@ func (s *store) Update(nodePath string, newValue string, expireOpts TTLOptionSet } func (s *store) internalCreate(nodePath string, dir bool, value string, unique, replace bool, - expireTime time.Time, action string) (*Event, *v2error.Error) { + expireTime time.Time, action string, +) (*Event, *v2error.Error) { currIndex, nextIndex := s.CurrentIndex, s.CurrentIndex+1 if unique { // append unique item under the node path @@ -587,7 +589,6 @@ func (s *store) internalCreate(nodePath string, dir bool, value string, unique, // walk through the nodePath, create dirs and get the last directory node d, err := s.walk(dirName, s.checkDir) - if err != nil { s.Stats.Inc(SetFail) reportWriteFailure(action) @@ -664,7 +665,6 @@ func (s *store) internalGet(nodePath string) (*node, *v2error.Error) { } f, err := s.walk(nodePath, walkFunc) - if err != nil { return nil, err } @@ -771,7 +771,6 @@ func (s *store) Recovery(state []byte) error { s.worldLock.Lock() defer s.worldLock.Unlock() err := json.Unmarshal(state, s) - if err != nil { return err } diff --git a/server/etcdserver/api/v2store/watcher_hub.go b/server/etcdserver/api/v2store/watcher_hub.go index dc5c8f2bb57..df5ae78b07d 100644 --- a/server/etcdserver/api/v2store/watcher_hub.go +++ b/server/etcdserver/api/v2store/watcher_hub.go @@ -59,7 +59,6 @@ func newWatchHub(capacity int) *watcherHub { func (wh *watcherHub) watch(key string, recursive, stream bool, index, storeIndex uint64) (Watcher, *v2error.Error) { reportWatchRequest() event, err := wh.EventHistory.scan(key, recursive, index) - if err != nil { err.Index = storeIndex return nil, err diff --git a/server/etcdserver/api/v3discovery/discovery.go b/server/etcdserver/api/v3discovery/discovery.go index 028876cd190..3bfd4c9cbd0 100644 --- a/server/etcdserver/api/v3discovery/discovery.go +++ b/server/etcdserver/api/v3discovery/discovery.go @@ -436,6 +436,7 @@ func (cls *clusterInfo) Len() int { return len(cls.members) } func (cls *clusterInfo) Less(i, j int) bool { return cls.members[i].createRev < cls.members[j].createRev } + func (cls *clusterInfo) Swap(i, j int) { cls.members[i], cls.members[j] = cls.members[j], cls.members[i] } diff --git a/server/etcdserver/api/v3discovery/discovery_test.go b/server/etcdserver/api/v3discovery/discovery_test.go index 89b4d3cbbef..a442ba9bcf0 100644 --- a/server/etcdserver/api/v3discovery/discovery_test.go +++ b/server/etcdserver/api/v3discovery/discovery_test.go @@ -708,7 +708,7 @@ func TestGetInitClusterStr(t *testing.T) { peerURLsMap: "infra2=http://192.168.0.102:2380", }, { - peerURLsMap: "infra3=http://192.168.0.103", //not host:port + peerURLsMap: "infra3=http://192.168.0.103", // not host:port }, }, clusterSize: 2, diff --git a/server/etcdserver/api/v3rpc/interceptor.go b/server/etcdserver/api/v3rpc/interceptor.go index 65e068ebbfc..697d0b075ed 100644 --- a/server/etcdserver/api/v3rpc/interceptor.go +++ b/server/etcdserver/api/v3rpc/interceptor.go @@ -181,7 +181,8 @@ func logUnaryRequestStats(ctx context.Context, lg *zap.Logger, warnLatency time. } func logGenericRequestStats(lg *zap.Logger, startTime time.Time, duration time.Duration, remote string, responseType string, - reqCount int64, reqSize int, respCount int64, respSize int, reqContent string) { + reqCount int64, reqSize int, respCount int64, respSize int, reqContent string, +) { lg.Debug("request stats", zap.Time("start time", startTime), zap.Duration("time spent", duration), @@ -196,7 +197,8 @@ func logGenericRequestStats(lg *zap.Logger, startTime time.Time, duration time.D } func logExpensiveRequestStats(lg *zap.Logger, startTime time.Time, duration time.Duration, remote string, responseType string, - reqCount int64, reqSize int, respCount int64, respSize int, reqContent string) { + reqCount int64, reqSize int, respCount int64, respSize int, reqContent string, +) { lg.Warn("request stats", zap.Time("start time", startTime), zap.Duration("time spent", duration), diff --git a/server/etcdserver/api/v3rpc/lease.go b/server/etcdserver/api/v3rpc/lease.go index 4d215e6308f..f51334eadeb 100644 --- a/server/etcdserver/api/v3rpc/lease.go +++ b/server/etcdserver/api/v3rpc/lease.go @@ -43,7 +43,6 @@ func NewLeaseServer(s *etcdserver.EtcdServer) pb.LeaseServer { func (ls *LeaseServer) LeaseGrant(ctx context.Context, cr *pb.LeaseGrantRequest) (*pb.LeaseGrantResponse, error) { resp, err := ls.le.LeaseGrant(ctx, cr) - if err != nil { return nil, togRPCError(err) } diff --git a/server/etcdserver/api/v3rpc/watch.go b/server/etcdserver/api/v3rpc/watch.go index fab02f56746..49bf81fcae6 100644 --- a/server/etcdserver/api/v3rpc/watch.go +++ b/server/etcdserver/api/v3rpc/watch.go @@ -545,7 +545,8 @@ func IsCreateEvent(e mvccpb.Event) bool { func sendFragments( wr *pb.WatchResponse, maxRequestBytes int, - sendFunc func(*pb.WatchResponse) error) error { + sendFunc func(*pb.WatchResponse) error, +) error { // no need to fragment if total request size is smaller // than max request limit or response contains only one event if wr.Size() < maxRequestBytes || len(wr.Events) < 2 { diff --git a/server/etcdserver/apply/apply.go b/server/etcdserver/apply/apply.go index 7629787dbbb..e45d53e17b1 100644 --- a/server/etcdserver/apply/apply.go +++ b/server/etcdserver/apply/apply.go @@ -132,7 +132,8 @@ func newApplierV3Backend( raftStatus RaftStatusGetter, snapshotServer SnapshotServer, consistentIndex cindex.ConsistentIndexer, - txnModeWriteWithSharedBuffer bool) applierV3 { + txnModeWriteWithSharedBuffer bool, +) applierV3 { return &applierV3backend{ lg: lg, kv: kv, @@ -143,7 +144,8 @@ func newApplierV3Backend( raftStatus: raftStatus, snapshotServer: snapshotServer, consistentIndex: consistentIndex, - txnModeWriteWithSharedBuffer: txnModeWriteWithSharedBuffer} + txnModeWriteWithSharedBuffer: txnModeWriteWithSharedBuffer, + } } func (a *applierV3backend) Apply(r *pb.InternalRaftRequest, applyFunc applyFunc) *Result { diff --git a/server/etcdserver/apply/apply_auth_test.go b/server/etcdserver/apply/apply_auth_test.go index ae12a04454d..cbd1893266c 100644 --- a/server/etcdserver/apply/apply_auth_test.go +++ b/server/etcdserver/apply/apply_auth_test.go @@ -53,15 +53,19 @@ type fakeRaftStatusGetter struct{} func (*fakeRaftStatusGetter) MemberID() types.ID { return 0 } + func (*fakeRaftStatusGetter) Leader() types.ID { return 0 } + func (*fakeRaftStatusGetter) CommittedIndex() uint64 { return 0 } + func (*fakeRaftStatusGetter) AppliedIndex() uint64 { return 0 } + func (*fakeRaftStatusGetter) Term() uint64 { return 0 } @@ -222,158 +226,157 @@ func TestAuthApplierV3_Apply(t *testing.T) { // TestAuthApplierV3_AdminPermission ensures the admin permission is checked for certain // operations func TestAuthApplierV3_AdminPermission(t *testing.T) { - tcs := - []struct { - name string - request *pb.InternalRaftRequest - adminPermissionNeeded bool - }{ - { - name: "Range does not need admin permission", - request: &pb.InternalRaftRequest{Range: &pb.RangeRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "Put does not need admin permission", - request: &pb.InternalRaftRequest{Put: &pb.PutRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "DeleteRange does not need admin permission", - request: &pb.InternalRaftRequest{DeleteRange: &pb.DeleteRangeRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "Txn does not need admin permission", - request: &pb.InternalRaftRequest{Txn: &pb.TxnRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "Compaction does not need admin permission", - request: &pb.InternalRaftRequest{Compaction: &pb.CompactionRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "LeaseGrant does not need admin permission", - request: &pb.InternalRaftRequest{LeaseGrant: &pb.LeaseGrantRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "LeaseRevoke does not need admin permission", - request: &pb.InternalRaftRequest{LeaseRevoke: &pb.LeaseRevokeRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "Alarm does not need admin permission", - request: &pb.InternalRaftRequest{Alarm: &pb.AlarmRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "LeaseCheckpoint does not need admin permission", - request: &pb.InternalRaftRequest{LeaseCheckpoint: &pb.LeaseCheckpointRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "Authenticate does not need admin permission", - request: &pb.InternalRaftRequest{Authenticate: &pb.InternalAuthenticateRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "ClusterVersionSet does not need admin permission", - request: &pb.InternalRaftRequest{ClusterVersionSet: &membershippb.ClusterVersionSetRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "ClusterMemberAttrSet does not need admin permission", - request: &pb.InternalRaftRequest{ClusterMemberAttrSet: &membershippb.ClusterMemberAttrSetRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "DowngradeInfoSet does not need admin permission", - request: &pb.InternalRaftRequest{DowngradeInfoSet: &membershippb.DowngradeInfoSetRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "AuthUserGet does not need admin permission", - request: &pb.InternalRaftRequest{AuthUserGet: &pb.AuthUserGetRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "AuthRoleGet does not need admin permission", - request: &pb.InternalRaftRequest{AuthRoleGet: &pb.AuthRoleGetRequest{}}, - adminPermissionNeeded: false, - }, - { - name: "AuthEnable needs admin permission", - request: &pb.InternalRaftRequest{AuthEnable: &pb.AuthEnableRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthDisable needs admin permission", - request: &pb.InternalRaftRequest{AuthDisable: &pb.AuthDisableRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthStatus needs admin permission", - request: &pb.InternalRaftRequest{AuthStatus: &pb.AuthStatusRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthUserAdd needs admin permission", - request: &pb.InternalRaftRequest{AuthUserAdd: &pb.AuthUserAddRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthUserDelete needs admin permission", - request: &pb.InternalRaftRequest{AuthUserDelete: &pb.AuthUserDeleteRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthUserChangePassword needs admin permission", - request: &pb.InternalRaftRequest{AuthUserChangePassword: &pb.AuthUserChangePasswordRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthUserGrantRole needs admin permission", - request: &pb.InternalRaftRequest{AuthUserGrantRole: &pb.AuthUserGrantRoleRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthUserRevokeRole needs admin permission", - request: &pb.InternalRaftRequest{AuthUserRevokeRole: &pb.AuthUserRevokeRoleRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthUserList needs admin permission", - request: &pb.InternalRaftRequest{AuthUserList: &pb.AuthUserListRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthRoleList needs admin permission", - request: &pb.InternalRaftRequest{AuthRoleList: &pb.AuthRoleListRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthRoleAdd needs admin permission", - request: &pb.InternalRaftRequest{AuthRoleAdd: &pb.AuthRoleAddRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthRoleDelete needs admin permission", - request: &pb.InternalRaftRequest{AuthRoleDelete: &pb.AuthRoleDeleteRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthRoleGrantPermission needs admin permission", - request: &pb.InternalRaftRequest{AuthRoleGrantPermission: &pb.AuthRoleGrantPermissionRequest{}}, - adminPermissionNeeded: true, - }, - { - name: "AuthRoleRevokePermission needs admin permission", - request: &pb.InternalRaftRequest{AuthRoleRevokePermission: &pb.AuthRoleRevokePermissionRequest{}}, - adminPermissionNeeded: true, - }, - } + tcs := []struct { + name string + request *pb.InternalRaftRequest + adminPermissionNeeded bool + }{ + { + name: "Range does not need admin permission", + request: &pb.InternalRaftRequest{Range: &pb.RangeRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "Put does not need admin permission", + request: &pb.InternalRaftRequest{Put: &pb.PutRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "DeleteRange does not need admin permission", + request: &pb.InternalRaftRequest{DeleteRange: &pb.DeleteRangeRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "Txn does not need admin permission", + request: &pb.InternalRaftRequest{Txn: &pb.TxnRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "Compaction does not need admin permission", + request: &pb.InternalRaftRequest{Compaction: &pb.CompactionRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "LeaseGrant does not need admin permission", + request: &pb.InternalRaftRequest{LeaseGrant: &pb.LeaseGrantRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "LeaseRevoke does not need admin permission", + request: &pb.InternalRaftRequest{LeaseRevoke: &pb.LeaseRevokeRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "Alarm does not need admin permission", + request: &pb.InternalRaftRequest{Alarm: &pb.AlarmRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "LeaseCheckpoint does not need admin permission", + request: &pb.InternalRaftRequest{LeaseCheckpoint: &pb.LeaseCheckpointRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "Authenticate does not need admin permission", + request: &pb.InternalRaftRequest{Authenticate: &pb.InternalAuthenticateRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "ClusterVersionSet does not need admin permission", + request: &pb.InternalRaftRequest{ClusterVersionSet: &membershippb.ClusterVersionSetRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "ClusterMemberAttrSet does not need admin permission", + request: &pb.InternalRaftRequest{ClusterMemberAttrSet: &membershippb.ClusterMemberAttrSetRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "DowngradeInfoSet does not need admin permission", + request: &pb.InternalRaftRequest{DowngradeInfoSet: &membershippb.DowngradeInfoSetRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "AuthUserGet does not need admin permission", + request: &pb.InternalRaftRequest{AuthUserGet: &pb.AuthUserGetRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "AuthRoleGet does not need admin permission", + request: &pb.InternalRaftRequest{AuthRoleGet: &pb.AuthRoleGetRequest{}}, + adminPermissionNeeded: false, + }, + { + name: "AuthEnable needs admin permission", + request: &pb.InternalRaftRequest{AuthEnable: &pb.AuthEnableRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthDisable needs admin permission", + request: &pb.InternalRaftRequest{AuthDisable: &pb.AuthDisableRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthStatus needs admin permission", + request: &pb.InternalRaftRequest{AuthStatus: &pb.AuthStatusRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthUserAdd needs admin permission", + request: &pb.InternalRaftRequest{AuthUserAdd: &pb.AuthUserAddRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthUserDelete needs admin permission", + request: &pb.InternalRaftRequest{AuthUserDelete: &pb.AuthUserDeleteRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthUserChangePassword needs admin permission", + request: &pb.InternalRaftRequest{AuthUserChangePassword: &pb.AuthUserChangePasswordRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthUserGrantRole needs admin permission", + request: &pb.InternalRaftRequest{AuthUserGrantRole: &pb.AuthUserGrantRoleRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthUserRevokeRole needs admin permission", + request: &pb.InternalRaftRequest{AuthUserRevokeRole: &pb.AuthUserRevokeRoleRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthUserList needs admin permission", + request: &pb.InternalRaftRequest{AuthUserList: &pb.AuthUserListRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthRoleList needs admin permission", + request: &pb.InternalRaftRequest{AuthRoleList: &pb.AuthRoleListRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthRoleAdd needs admin permission", + request: &pb.InternalRaftRequest{AuthRoleAdd: &pb.AuthRoleAddRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthRoleDelete needs admin permission", + request: &pb.InternalRaftRequest{AuthRoleDelete: &pb.AuthRoleDeleteRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthRoleGrantPermission needs admin permission", + request: &pb.InternalRaftRequest{AuthRoleGrantPermission: &pb.AuthRoleGrantPermissionRequest{}}, + adminPermissionNeeded: true, + }, + { + name: "AuthRoleRevokePermission needs admin permission", + request: &pb.InternalRaftRequest{AuthRoleRevokePermission: &pb.AuthRoleRevokePermissionRequest{}}, + adminPermissionNeeded: true, + }, + } authApplier := defaultAuthApplierV3(t) mustCreateRolesAndEnableAuth(t, authApplier) for _, tc := range tcs { diff --git a/server/etcdserver/apply/metrics.go b/server/etcdserver/apply/metrics.go index 34578578b4a..c6b43864633 100644 --- a/server/etcdserver/apply/metrics.go +++ b/server/etcdserver/apply/metrics.go @@ -16,15 +16,13 @@ package apply import "github.com/prometheus/client_golang/prometheus" -var ( - alarms = prometheus.NewGaugeVec(prometheus.GaugeOpts{ - Namespace: "etcd_debugging", - Subsystem: "server", - Name: "alarms", - Help: "Alarms for every member in cluster. 1 for 'server_id' label with current ID. 2 for 'alarm_type' label with type of this alarm", - }, - []string{"server_id", "alarm_type"}) -) +var alarms = prometheus.NewGaugeVec(prometheus.GaugeOpts{ + Namespace: "etcd_debugging", + Subsystem: "server", + Name: "alarms", + Help: "Alarms for every member in cluster. 1 for 'server_id' label with current ID. 2 for 'alarm_type' label with type of this alarm", +}, + []string{"server_id", "alarm_type"}) func init() { prometheus.MustRegister(alarms) diff --git a/server/etcdserver/apply/uber_applier.go b/server/etcdserver/apply/uber_applier.go index 9862d7d3d39..ec7e2aae663 100644 --- a/server/etcdserver/apply/uber_applier.go +++ b/server/etcdserver/apply/uber_applier.go @@ -61,7 +61,8 @@ func NewUberApplier( consistentIndex cindex.ConsistentIndexer, warningApplyDuration time.Duration, txnModeWriteWithSharedBuffer bool, - quotaBackendBytesCfg int64) UberApplier { + quotaBackendBytesCfg int64, +) UberApplier { applyV3base := newApplierV3(lg, be, kv, alarmStore, authStore, lessor, cluster, raftStatus, snapshotServer, consistentIndex, txnModeWriteWithSharedBuffer, quotaBackendBytesCfg) ua := &uberApplier{ @@ -87,7 +88,8 @@ func newApplierV3( snapshotServer SnapshotServer, consistentIndex cindex.ConsistentIndexer, txnModeWriteWithSharedBuffer bool, - quotaBackendBytesCfg int64) applierV3 { + quotaBackendBytesCfg int64, +) applierV3 { applierBackend := newApplierV3Backend(lg, kv, alarmStore, authStore, lessor, cluster, raftStatus, snapshotServer, consistentIndex, txnModeWriteWithSharedBuffer) return newAuthApplierV3( authStore, diff --git a/server/etcdserver/apply/uber_applier_test.go b/server/etcdserver/apply/uber_applier_test.go index 5be9b504056..086db23c6cf 100644 --- a/server/etcdserver/apply/uber_applier_test.go +++ b/server/etcdserver/apply/uber_applier_test.go @@ -73,7 +73,7 @@ func defaultUberApplier(t *testing.T) UberApplier { consistentIndex, 1*time.Hour, false, - 16*1024*1024, //16MB + 16*1024*1024, // 16MB ) } @@ -165,7 +165,8 @@ func TestUberApplier_Alarm_Quota(t *testing.T) { }, }, }, - }}}, + }, + }}, expectError: errors.ErrNoSpace, }, { @@ -179,7 +180,8 @@ func TestUberApplier_Alarm_Quota(t *testing.T) { }, }, }, - }}}, + }, + }}, expectError: nil, }, { @@ -210,7 +212,8 @@ func TestUberApplier_Alarm_Quota(t *testing.T) { }, }, }, - }}}, + }, + }}, expectError: nil, }, { diff --git a/server/etcdserver/bootstrap_test.go b/server/etcdserver/bootstrap_test.go index 83d28e3a1fa..a692a68566c 100644 --- a/server/etcdserver/bootstrap_test.go +++ b/server/etcdserver/bootstrap_test.go @@ -225,12 +225,12 @@ func createDataDir(t *testing.T) (string, error) { dataDir := t.TempDir() // create ${dataDir}/member/snap - if err = os.MkdirAll(datadir.ToSnapDir(dataDir), 0700); err != nil { + if err = os.MkdirAll(datadir.ToSnapDir(dataDir), 0o700); err != nil { return "", err } // create ${dataDir}/member/wal - err = os.MkdirAll(datadir.ToWALDir(dataDir), 0700) + err = os.MkdirAll(datadir.ToWALDir(dataDir), 0o700) if err != nil { return "", err } diff --git a/server/etcdserver/cindex/cindex.go b/server/etcdserver/cindex/cindex.go index 200008ff9b3..b865742014d 100644 --- a/server/etcdserver/cindex/cindex.go +++ b/server/etcdserver/cindex/cindex.go @@ -28,7 +28,6 @@ type Backend interface { // ConsistentIndexer is an interface that wraps the Get/Set/Save method for consistentIndex. type ConsistentIndexer interface { - // ConsistentIndex returns the consistent index of current executing entry. ConsistentIndex() uint64 @@ -150,9 +149,11 @@ type fakeConsistentIndex struct { func (f *fakeConsistentIndex) ConsistentIndex() uint64 { return atomic.LoadUint64(&f.index) } + func (f *fakeConsistentIndex) ConsistentApplyingIndex() (uint64, uint64) { return atomic.LoadUint64(&f.index), atomic.LoadUint64(&f.term) } + func (f *fakeConsistentIndex) UnsafeConsistentIndex() uint64 { return atomic.LoadUint64(&f.index) } @@ -161,6 +162,7 @@ func (f *fakeConsistentIndex) SetConsistentIndex(index uint64, term uint64) { atomic.StoreUint64(&f.index, index) atomic.StoreUint64(&f.term, term) } + func (f *fakeConsistentIndex) SetConsistentApplyingIndex(index uint64, term uint64) { atomic.StoreUint64(&f.index, index) atomic.StoreUint64(&f.term, term) diff --git a/server/etcdserver/corrupt_test.go b/server/etcdserver/corrupt_test.go index 56967021a2d..6001542d348 100644 --- a/server/etcdserver/corrupt_test.go +++ b/server/etcdserver/corrupt_test.go @@ -507,9 +507,9 @@ func (f *fakeHasher) TriggerCorruptAlarm(memberID types.ID) { } func TestHashKVHandler(t *testing.T) { - var remoteClusterID = 111195 - var localClusterID = 111196 - var revision = 1 + remoteClusterID := 111195 + localClusterID := 111196 + revision := 1 etcdSrv := &EtcdServer{} etcdSrv.cluster = newTestCluster(t) diff --git a/server/etcdserver/raft_test.go b/server/etcdserver/raft_test.go index cce1ac872b1..2cfa4816232 100644 --- a/server/etcdserver/raft_test.go +++ b/server/etcdserver/raft_test.go @@ -50,18 +50,36 @@ func TestGetIDs(t *testing.T) { widSet []uint64 }{ {nil, []raftpb.Entry{}, []uint64{}}, - {&raftpb.ConfState{Voters: []uint64{1}}, - []raftpb.Entry{}, []uint64{1}}, - {&raftpb.ConfState{Voters: []uint64{1}}, - []raftpb.Entry{addEntry}, []uint64{1, 2}}, - {&raftpb.ConfState{Voters: []uint64{1}}, - []raftpb.Entry{addEntry, removeEntry}, []uint64{1}}, - {&raftpb.ConfState{Voters: []uint64{1}}, - []raftpb.Entry{addEntry, normalEntry}, []uint64{1, 2}}, - {&raftpb.ConfState{Voters: []uint64{1}}, - []raftpb.Entry{addEntry, normalEntry, updateEntry}, []uint64{1, 2}}, - {&raftpb.ConfState{Voters: []uint64{1}}, - []raftpb.Entry{addEntry, removeEntry, normalEntry}, []uint64{1}}, + { + &raftpb.ConfState{Voters: []uint64{1}}, + []raftpb.Entry{}, + []uint64{1}, + }, + { + &raftpb.ConfState{Voters: []uint64{1}}, + []raftpb.Entry{addEntry}, + []uint64{1, 2}, + }, + { + &raftpb.ConfState{Voters: []uint64{1}}, + []raftpb.Entry{addEntry, removeEntry}, + []uint64{1}, + }, + { + &raftpb.ConfState{Voters: []uint64{1}}, + []raftpb.Entry{addEntry, normalEntry}, + []uint64{1, 2}, + }, + { + &raftpb.ConfState{Voters: []uint64{1}}, + []raftpb.Entry{addEntry, normalEntry, updateEntry}, + []uint64{1, 2}, + }, + { + &raftpb.ConfState{Voters: []uint64{1}}, + []raftpb.Entry{addEntry, removeEntry, normalEntry}, + []uint64{1}, + }, } for i, tt := range tests { diff --git a/server/etcdserver/server_test.go b/server/etcdserver/server_test.go index 688d71be264..0275390be44 100644 --- a/server/etcdserver/server_test.go +++ b/server/etcdserver/server_test.go @@ -583,7 +583,8 @@ func TestApplyMultiConfChangeShouldStop(t *testing.T) { Data: pbutil.MustMarshal( &raftpb.ConfChange{ Type: raftpb.ConfChangeRemoveNode, - NodeID: uint64(i)}), + NodeID: uint64(i), + }), } ents = append(ents, ent) } @@ -674,7 +675,7 @@ func TestSnapshotOrdering(t *testing.T) { testdir := t.TempDir() snapdir := filepath.Join(testdir, "member", "snap") - if err := os.MkdirAll(snapdir, 0755); err != nil { + if err := os.MkdirAll(snapdir, 0o755); err != nil { t.Fatalf("couldn't make snap dir (%v)", err) } @@ -765,7 +766,7 @@ func TestConcurrentApplyAndSnapshotV3(t *testing.T) { cl.SetBackend(schema.NewMembershipBackend(lg, be)) testdir := t.TempDir() - if err := os.MkdirAll(testdir+"/member/snap", 0755); err != nil { + if err := os.MkdirAll(testdir+"/member/snap", 0o755); err != nil { t.Fatalf("Couldn't make snap dir (%v)", err) } @@ -1105,7 +1106,8 @@ func TestPublishV3(t *testing.T) { t.Fatalf("unmarshal request error: %v", err) } assert.Equal(t, &membershippb.ClusterMemberAttrSetRequest{Member_ID: 0x1, MemberAttributes: &membershippb.Attributes{ - Name: "node1", ClientUrls: []string{"http://a", "http://b"}}}, r.ClusterMemberAttrSet) + Name: "node1", ClientUrls: []string{"http://a", "http://b"}, + }}, r.ClusterMemberAttrSet) } // TestPublishV3Stopped tests that publish will be stopped if server is stopped. @@ -1307,14 +1309,17 @@ func (n *nodeRecorder) Campaign(ctx context.Context) error { n.Record(testutil.Action{Name: "Campaign"}) return nil } + func (n *nodeRecorder) Propose(ctx context.Context, data []byte) error { n.Record(testutil.Action{Name: "Propose", Params: []any{data}}) return nil } + func (n *nodeRecorder) ProposeConfChange(ctx context.Context, conf raftpb.ConfChangeI) error { n.Record(testutil.Action{Name: "ProposeConfChange"}) return nil } + func (n *nodeRecorder) Step(ctx context.Context, msg raftpb.Message) error { n.Record(testutil.Action{Name: "Step"}) return nil @@ -1354,8 +1359,10 @@ type readyNode struct { func newReadyNode() *readyNode { return &readyNode{ nodeRecorder{testutil.NewRecorderStream()}, - make(chan raft.Ready, 1)} + make(chan raft.Ready, 1), + } } + func newNopReadyNode() *readyNode { return &readyNode{*newNodeRecorder(), make(chan raft.Ready, 1)} } @@ -1401,9 +1408,11 @@ func (n *nodeConfChangeCommitterRecorder) ProposeConfChange(ctx context.Context, n.readyc <- raft.Ready{CommittedEntries: []raftpb.Entry{{Index: n.index, Type: typ, Data: data}}} return nil } + func (n *nodeConfChangeCommitterRecorder) Ready() <-chan raft.Ready { return n.readyc } + func (n *nodeConfChangeCommitterRecorder) ApplyConfChange(conf raftpb.ConfChangeI) *raftpb.ConfState { n.Record(testutil.Action{Name: "ApplyConfChange:" + confChangeActionName(conf)}) return &raftpb.ConfState{} diff --git a/server/mock/mockstore/store_recorder.go b/server/mock/mockstore/store_recorder.go index b92d0d0e360..9edade1f29d 100644 --- a/server/mock/mockstore/store_recorder.go +++ b/server/mock/mockstore/store_recorder.go @@ -40,6 +40,7 @@ func NewRecorder() *StoreRecorder { sr := &storeRecorder{Recorder: &testutil.RecorderBuffered{}} return &StoreRecorder{Store: sr, Recorder: sr.Recorder} } + func NewRecorderStream() *StoreRecorder { sr := &storeRecorder{Recorder: testutil.NewRecorderStream()} return &StoreRecorder{Store: sr, Recorder: sr.Recorder} @@ -54,6 +55,7 @@ func (s *storeRecorder) Get(path string, recursive, sorted bool) (*v2store.Event }) return &v2store.Event{}, nil } + func (s *storeRecorder) Set(path string, dir bool, val string, expireOpts v2store.TTLOptionSet) (*v2store.Event, error) { s.Record(testutil.Action{ Name: "Set", @@ -61,6 +63,7 @@ func (s *storeRecorder) Set(path string, dir bool, val string, expireOpts v2stor }) return &v2store.Event{}, nil } + func (s *storeRecorder) Update(path, val string, expireOpts v2store.TTLOptionSet) (*v2store.Event, error) { s.Record(testutil.Action{ Name: "Update", @@ -68,6 +71,7 @@ func (s *storeRecorder) Update(path, val string, expireOpts v2store.TTLOptionSet }) return &v2store.Event{}, nil } + func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, expireOpts v2store.TTLOptionSet) (*v2store.Event, error) { s.Record(testutil.Action{ Name: "Create", @@ -75,6 +79,7 @@ func (s *storeRecorder) Create(path string, dir bool, val string, uniq bool, exp }) return &v2store.Event{}, nil } + func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val string, expireOpts v2store.TTLOptionSet) (*v2store.Event, error) { s.Record(testutil.Action{ Name: "CompareAndSwap", @@ -82,6 +87,7 @@ func (s *storeRecorder) CompareAndSwap(path, prevVal string, prevIdx uint64, val }) return &v2store.Event{}, nil } + func (s *storeRecorder) Delete(path string, dir, recursive bool) (*v2store.Event, error) { s.Record(testutil.Action{ Name: "Delete", @@ -89,6 +95,7 @@ func (s *storeRecorder) Delete(path string, dir, recursive bool) (*v2store.Event }) return &v2store.Event{}, nil } + func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) (*v2store.Event, error) { s.Record(testutil.Action{ Name: "CompareAndDelete", @@ -96,14 +103,17 @@ func (s *storeRecorder) CompareAndDelete(path, prevVal string, prevIdx uint64) ( }) return &v2store.Event{}, nil } + func (s *storeRecorder) Watch(_ string, _, _ bool, _ uint64) (v2store.Watcher, error) { s.Record(testutil.Action{Name: "Watch"}) return v2store.NewNopWatcher(), nil } + func (s *storeRecorder) Save() ([]byte, error) { s.Record(testutil.Action{Name: "Save"}) return nil, nil } + func (s *storeRecorder) Recovery(b []byte) error { s.Record(testutil.Action{Name: "Recovery"}) return nil @@ -155,6 +165,7 @@ func (s *errStoreRecorder) Get(path string, recursive, sorted bool) (*v2store.Ev s.storeRecorder.Get(path, recursive, sorted) return nil, s.err } + func (s *errStoreRecorder) Watch(path string, recursive, sorted bool, index uint64) (v2store.Watcher, error) { s.storeRecorder.Watch(path, recursive, sorted, index) return nil, s.err diff --git a/server/mock/mockwait/wait_recorder.go b/server/mock/mockwait/wait_recorder.go index 9f5baac6a5f..608ea73f501 100644 --- a/server/mock/mockwait/wait_recorder.go +++ b/server/mock/mockwait/wait_recorder.go @@ -38,6 +38,7 @@ func (w *waitRecorder) Register(id uint64) <-chan any { w.Record(testutil.Action{Name: "Register"}) return nil } + func (w *waitRecorder) Trigger(id uint64, x any) { w.Record(testutil.Action{Name: "Trigger"}) } diff --git a/server/proxy/grpcproxy/adapter/election_client_adapter.go b/server/proxy/grpcproxy/adapter/election_client_adapter.go index b1266318f9a..c7edaf70a47 100644 --- a/server/proxy/grpcproxy/adapter/election_client_adapter.go +++ b/server/proxy/grpcproxy/adapter/election_client_adapter.go @@ -60,6 +60,7 @@ type es2ecServerStream struct{ chanServerStream } func (s *es2ecClientStream) Send(rr *v3electionpb.LeaderRequest) error { return s.SendMsg(rr) } + func (s *es2ecClientStream) Recv() (*v3electionpb.LeaderResponse, error) { var v any if err := s.RecvMsg(&v); err != nil { @@ -71,6 +72,7 @@ func (s *es2ecClientStream) Recv() (*v3electionpb.LeaderResponse, error) { func (s *es2ecServerStream) Send(rr *v3electionpb.LeaderResponse) error { return s.SendMsg(rr) } + func (s *es2ecServerStream) Recv() (*v3electionpb.LeaderRequest, error) { var v any if err := s.RecvMsg(&v); err != nil { diff --git a/server/proxy/grpcproxy/adapter/lease_client_adapter.go b/server/proxy/grpcproxy/adapter/lease_client_adapter.go index 4369c3052f5..bf76a5563e5 100644 --- a/server/proxy/grpcproxy/adapter/lease_client_adapter.go +++ b/server/proxy/grpcproxy/adapter/lease_client_adapter.go @@ -62,6 +62,7 @@ type ls2lcServerStream struct{ chanServerStream } func (s *ls2lcClientStream) Send(rr *pb.LeaseKeepAliveRequest) error { return s.SendMsg(rr) } + func (s *ls2lcClientStream) Recv() (*pb.LeaseKeepAliveResponse, error) { var v any if err := s.RecvMsg(&v); err != nil { @@ -73,6 +74,7 @@ func (s *ls2lcClientStream) Recv() (*pb.LeaseKeepAliveResponse, error) { func (s *ls2lcServerStream) Send(rr *pb.LeaseKeepAliveResponse) error { return s.SendMsg(rr) } + func (s *ls2lcServerStream) Recv() (*pb.LeaseKeepAliveRequest, error) { var v any if err := s.RecvMsg(&v); err != nil { diff --git a/server/proxy/grpcproxy/adapter/maintenance_client_adapter.go b/server/proxy/grpcproxy/adapter/maintenance_client_adapter.go index d3bb805a1f6..7b204451681 100644 --- a/server/proxy/grpcproxy/adapter/maintenance_client_adapter.go +++ b/server/proxy/grpcproxy/adapter/maintenance_client_adapter.go @@ -72,6 +72,7 @@ type ss2scServerStream struct{ chanServerStream } func (s *ss2scClientStream) Send(rr *pb.SnapshotRequest) error { return s.SendMsg(rr) } + func (s *ss2scClientStream) Recv() (*pb.SnapshotResponse, error) { var v any if err := s.RecvMsg(&v); err != nil { @@ -83,6 +84,7 @@ func (s *ss2scClientStream) Recv() (*pb.SnapshotResponse, error) { func (s *ss2scServerStream) Send(rr *pb.SnapshotResponse) error { return s.SendMsg(rr) } + func (s *ss2scServerStream) Recv() (*pb.SnapshotRequest, error) { var v any if err := s.RecvMsg(&v); err != nil { diff --git a/server/proxy/grpcproxy/adapter/watch_client_adapter.go b/server/proxy/grpcproxy/adapter/watch_client_adapter.go index 43f2ab7677d..828ed1b7e60 100644 --- a/server/proxy/grpcproxy/adapter/watch_client_adapter.go +++ b/server/proxy/grpcproxy/adapter/watch_client_adapter.go @@ -47,6 +47,7 @@ type ws2wcServerStream struct{ chanServerStream } func (s *ws2wcClientStream) Send(wr *pb.WatchRequest) error { return s.SendMsg(wr) } + func (s *ws2wcClientStream) Recv() (*pb.WatchResponse, error) { var v any if err := s.RecvMsg(&v); err != nil { @@ -58,6 +59,7 @@ func (s *ws2wcClientStream) Recv() (*pb.WatchResponse, error) { func (s *ws2wcServerStream) Send(wr *pb.WatchResponse) error { return s.SendMsg(wr) } + func (s *ws2wcServerStream) Recv() (*pb.WatchRequest, error) { var v any if err := s.RecvMsg(&v); err != nil { diff --git a/server/proxy/grpcproxy/watch_broadcast.go b/server/proxy/grpcproxy/watch_broadcast.go index 1f07f6ac5e2..5a395df08a0 100644 --- a/server/proxy/grpcproxy/watch_broadcast.go +++ b/server/proxy/grpcproxy/watch_broadcast.go @@ -126,6 +126,7 @@ func (wb *watchBroadcast) add(w *watcher) bool { return true } + func (wb *watchBroadcast) delete(w *watcher) { wb.mu.Lock() defer wb.mu.Unlock() diff --git a/server/storage/backend/backend.go b/server/storage/backend/backend.go index 95f5cf96fc8..19f9e4a15c7 100644 --- a/server/storage/backend/backend.go +++ b/server/storage/backend/backend.go @@ -194,7 +194,7 @@ func newBackend(bcfg BackendConfig) *backend { bopts.Mlock = bcfg.Mlock bopts.Logger = newBoltLoggerZap(bcfg) - db, err := bolt.Open(bcfg.Path, 0600, bopts) + db, err := bolt.Open(bcfg.Path, 0o600, bopts) if err != nil { bcfg.Logger.Panic("failed to open database", zap.String("path", bcfg.Path), zap.Error(err)) } @@ -407,7 +407,6 @@ func (b *backend) Hash(ignores func(bucketName, keyName []byte) bool) (uint32, e } return nil }) - if err != nil { return 0, err } @@ -498,7 +497,7 @@ func (b *backend) defrag() error { // Don't load tmp db into memory regardless of opening options options.Mlock = false tdbp := temp.Name() - tmpdb, err := bolt.Open(tdbp, 0600, &options) + tmpdb, err := bolt.Open(tdbp, 0o600, &options) if err != nil { return err } @@ -539,7 +538,7 @@ func (b *backend) defrag() error { b.lg.Fatal("failed to rename tmp database", zap.Error(err)) } - b.db, err = bolt.Open(dbp, 0600, b.bopts) + b.db, err = bolt.Open(dbp, 0o600, b.bopts) if err != nil { b.lg.Fatal("failed to open database", zap.String("path", dbp), zap.Error(err)) } diff --git a/server/storage/mvcc/hash_test.go b/server/storage/mvcc/hash_test.go index 8ba41ecf8a0..d08b3ad1982 100644 --- a/server/storage/mvcc/hash_test.go +++ b/server/storage/mvcc/hash_test.go @@ -214,7 +214,7 @@ func TestHasherStoreFull(t *testing.T) { defer store.Close() var minRevision int64 = 100 - var maxRevision = minRevision + hashStorageMaxSize + maxRevision := minRevision + hashStorageMaxSize for i := 0; i < hashStorageMaxSize; i++ { s.Store(KeyValueHash{Revision: int64(i) + minRevision}) } diff --git a/server/storage/mvcc/key_index.go b/server/storage/mvcc/key_index.go index 6ba7d2732ee..27b22fd4899 100644 --- a/server/storage/mvcc/key_index.go +++ b/server/storage/mvcc/key_index.go @@ -22,9 +22,7 @@ import ( "go.uber.org/zap" ) -var ( - ErrRevisionNotFound = errors.New("mvcc: revision not found") -) +var ErrRevisionNotFound = errors.New("mvcc: revision not found") // keyIndex stores the revisions of a key in the backend. // Each keyIndex has at least one key generation. diff --git a/server/storage/mvcc/kv_test.go b/server/storage/mvcc/kv_test.go index 0a3a2ad736f..71a9953f743 100644 --- a/server/storage/mvcc/kv_test.go +++ b/server/storage/mvcc/kv_test.go @@ -766,7 +766,8 @@ func TestWatchableKVWatch(t *testing.T) { wid, _ := w.Watch(0, []byte("foo"), []byte("fop"), 0) wev := []mvccpb.Event{ - {Type: mvccpb.PUT, + { + Type: mvccpb.PUT, Kv: &mvccpb.KeyValue{ Key: []byte("foo"), Value: []byte("bar"), diff --git a/server/storage/mvcc/kvstore.go b/server/storage/mvcc/kvstore.go index 9ee73cce2e9..3e1226c9174 100644 --- a/server/storage/mvcc/kvstore.go +++ b/server/storage/mvcc/kvstore.go @@ -38,9 +38,11 @@ var ( ErrFutureRev = errors.New("mvcc: required revision is a future revision") ) -var restoreChunkKeys = 10000 // non-const for testing -var defaultCompactionBatchLimit = 1000 -var defaultCompactionSleepInterval = 10 * time.Millisecond +var ( + restoreChunkKeys = 10000 // non-const for testing + defaultCompactionBatchLimit = 1000 + defaultCompactionSleepInterval = 10 * time.Millisecond +) type StoreConfig struct { CompactionBatchLimit int diff --git a/server/storage/mvcc/kvstore_test.go b/server/storage/mvcc/kvstore_test.go index e7906df5da8..65ad4f240ec 100644 --- a/server/storage/mvcc/kvstore_test.go +++ b/server/storage/mvcc/kvstore_test.go @@ -914,7 +914,8 @@ func newTestBucketKeyBytes(rev BucketKey) []byte { func newFakeStore(lg *zap.Logger) *store { b := &fakeBackend{&fakeBatchTx{ Recorder: &testutil.RecorderBuffered{}, - rangeRespc: make(chan rangeResp, 5)}} + rangeRespc: make(chan rangeResp, 5), + }} s := &store{ cfg: StoreConfig{ CompactionBatchLimit: 10000, @@ -965,17 +966,21 @@ func (b *fakeBatchTx) UnsafeDeleteBucket(bucket backend.Bucket) {} func (b *fakeBatchTx) UnsafePut(bucket backend.Bucket, key []byte, value []byte) { b.Recorder.Record(testutil.Action{Name: "put", Params: []any{bucket, key, value}}) } + func (b *fakeBatchTx) UnsafeSeqPut(bucket backend.Bucket, key []byte, value []byte) { b.Recorder.Record(testutil.Action{Name: "seqput", Params: []any{bucket, key, value}}) } + func (b *fakeBatchTx) UnsafeRange(bucket backend.Bucket, key, endKey []byte, limit int64) (keys [][]byte, vals [][]byte) { b.Recorder.Record(testutil.Action{Name: "range", Params: []any{bucket, key, endKey, limit}}) r := <-b.rangeRespc return r.keys, r.vals } + func (b *fakeBatchTx) UnsafeDelete(bucket backend.Bucket, key []byte) { b.Recorder.Record(testutil.Action{Name: "delete", Params: []any{bucket, key}}) } + func (b *fakeBatchTx) UnsafeForEach(bucket backend.Bucket, visitor func(k, v []byte) error) error { return nil } @@ -1041,27 +1046,33 @@ func (i *fakeIndex) Get(key []byte, atRev int64) (rev, created Revision, ver int r := <-i.indexGetRespc return r.rev, r.created, r.ver, r.err } + func (i *fakeIndex) Range(key, end []byte, atRev int64) ([][]byte, []Revision) { i.Recorder.Record(testutil.Action{Name: "range", Params: []any{key, end, atRev}}) r := <-i.indexRangeRespc return r.keys, r.revs } + func (i *fakeIndex) Put(key []byte, rev Revision) { i.Recorder.Record(testutil.Action{Name: "put", Params: []any{key, rev}}) } + func (i *fakeIndex) Tombstone(key []byte, rev Revision) error { i.Recorder.Record(testutil.Action{Name: "tombstone", Params: []any{key, rev}}) return nil } + func (i *fakeIndex) RangeSince(key, end []byte, rev int64) []Revision { i.Recorder.Record(testutil.Action{Name: "rangeEvents", Params: []any{key, end, rev}}) r := <-i.indexRangeEventsRespc return r.revs } + func (i *fakeIndex) Compact(rev int64) map[Revision]struct{} { i.Recorder.Record(testutil.Action{Name: "compact", Params: []any{rev}}) return <-i.indexCompactRespc } + func (i *fakeIndex) Keep(rev int64) map[Revision]struct{} { i.Recorder.Record(testutil.Action{Name: "keep", Params: []any{rev}}) return <-i.indexCompactRespc diff --git a/server/storage/mvcc/watcher_group.go b/server/storage/mvcc/watcher_group.go index 356b49e6413..c9db0e2bd9b 100644 --- a/server/storage/mvcc/watcher_group.go +++ b/server/storage/mvcc/watcher_group.go @@ -22,12 +22,10 @@ import ( "go.etcd.io/etcd/pkg/v3/adt" ) -var ( - // watchBatchMaxRevs is the maximum distinct revisions that - // may be sent to an unsynced watcher at a time. Declared as - // var instead of const for testing purposes. - watchBatchMaxRevs = 1000 -) +// watchBatchMaxRevs is the maximum distinct revisions that +// may be sent to an unsynced watcher at a time. Declared as +// var instead of const for testing purposes. +var watchBatchMaxRevs = 1000 type eventBatch struct { // evs is a batch of revision-ordered events diff --git a/server/storage/schema/actions.go b/server/storage/schema/actions.go index 415ffcd792f..8d18cee8638 100644 --- a/server/storage/schema/actions.go +++ b/server/storage/schema/actions.go @@ -69,10 +69,9 @@ type ActionList []action // unsafeExecute executes actions one by one. If one of actions returns error, // it will revert them. func (as ActionList) unsafeExecute(lg *zap.Logger, tx backend.UnsafeReadWriter) error { - var revertActions = make(ActionList, 0, len(as)) + revertActions := make(ActionList, 0, len(as)) for _, a := range as { revert, err := a.unsafeDo(tx) - if err != nil { revertActions.unsafeExecuteInReversedOrder(lg, tx) return err diff --git a/server/storage/schema/auth.go b/server/storage/schema/auth.go index 3bff8412c9f..96ca881c5c8 100644 --- a/server/storage/schema/auth.go +++ b/server/storage/schema/auth.go @@ -78,8 +78,10 @@ type authBatchTx struct { lg *zap.Logger } -var _ auth.AuthReadTx = (*authReadTx)(nil) -var _ auth.AuthBatchTx = (*authBatchTx)(nil) +var ( + _ auth.AuthReadTx = (*authReadTx)(nil) + _ auth.AuthBatchTx = (*authBatchTx)(nil) +) func (atx *authBatchTx) UnsafeSaveAuthEnabled(enabled bool) { if enabled { diff --git a/server/storage/schema/schema.go b/server/storage/schema/schema.go index 6165d33d644..0f54c04fabe 100644 --- a/server/storage/schema/schema.go +++ b/server/storage/schema/schema.go @@ -108,7 +108,7 @@ func UnsafeDetectSchemaVersion(lg *zap.Logger, tx backend.UnsafeReader) (v semve func schemaChangesForVersion(v semver.Version, isUpgrade bool) ([]schemaChange, error) { // changes should be taken from higher version - var higherV = v + higherV := v if isUpgrade { higherV = semver.Version{Major: v.Major, Minor: v.Minor + 1} } diff --git a/server/storage/schema/version_test.go b/server/storage/schema/version_test.go index 48d12d3d2ab..63442fc24d5 100644 --- a/server/storage/schema/version_test.go +++ b/server/storage/schema/version_test.go @@ -114,7 +114,7 @@ func TestVersionSnapshot(t *testing.T) { tx.Unlock() be.ForceCommit() be.Close() - db, err := bbolt.Open(tmpPath, 0400, &bbolt.Options{ReadOnly: true}) + db, err := bbolt.Open(tmpPath, 0o400, &bbolt.Options{ReadOnly: true}) if err != nil { t.Fatal(err) } diff --git a/server/storage/wal/wal_test.go b/server/storage/wal/wal_test.go index 4a9269ba44a..a9e6dc84910 100644 --- a/server/storage/wal/wal_test.go +++ b/server/storage/wal/wal_test.go @@ -39,12 +39,10 @@ import ( "go.etcd.io/raft/v3/raftpb" ) -var ( - confState = raftpb.ConfState{ - Voters: []uint64{0x00ffca74}, - AutoLeave: false, - } -) +var confState = raftpb.ConfState{ + Voters: []uint64{0x00ffca74}, + AutoLeave: false, +} func TestNew(t *testing.T) { p := t.TempDir() diff --git a/server/storage/wal/walpb/record.go b/server/storage/wal/walpb/record.go index 693deab113d..30e6c061366 100644 --- a/server/storage/wal/walpb/record.go +++ b/server/storage/wal/walpb/record.go @@ -19,9 +19,7 @@ import ( "fmt" ) -var ( - ErrCRCMismatch = errors.New("walpb: crc mismatch") -) +var ErrCRCMismatch = errors.New("walpb: crc mismatch") func (rec *Record) Validate(crc uint32) error { if rec.Crc == crc { diff --git a/tests/common/auth_test.go b/tests/common/auth_test.go index afeca9245c6..c734543611a 100644 --- a/tests/common/auth_test.go +++ b/tests/common/auth_test.go @@ -28,9 +28,11 @@ import ( "go.etcd.io/etcd/tests/v3/framework/testutils" ) -var tokenTTL = time.Second * 3 -var defaultAuthToken = fmt.Sprintf("jwt,pub-key=%s,priv-key=%s,sign-method=RS256,ttl=%s", - mustAbsPath("../fixtures/server.crt"), mustAbsPath("../fixtures/server.key.insecure"), tokenTTL) +var ( + tokenTTL = time.Second * 3 + defaultAuthToken = fmt.Sprintf("jwt,pub-key=%s,priv-key=%s,sign-method=RS256,ttl=%s", + mustAbsPath("../fixtures/server.crt"), mustAbsPath("../fixtures/server.key.insecure"), tokenTTL) +) const ( PermissionDenied = "etcdserver: permission denied" diff --git a/tests/common/compact_test.go b/tests/common/compact_test.go index 642038dcd9e..3c1f6daadc9 100644 --- a/tests/common/compact_test.go +++ b/tests/common/compact_test.go @@ -49,7 +49,7 @@ func TestCompact(t *testing.T) { defer clus.Close() cc := testutils.MustClient(clus.Client()) testutils.ExecuteUntil(ctx, t, func() { - var kvs = []testutils.KV{{Key: "key", Val: "val1"}, {Key: "key", Val: "val2"}, {Key: "key", Val: "val3"}} + kvs := []testutils.KV{{Key: "key", Val: "val1"}, {Key: "key", Val: "val2"}, {Key: "key", Val: "val3"}} for i := range kvs { if err := cc.Put(ctx, kvs[i].Key, kvs[i].Val, config.PutOptions{}); err != nil { t.Fatalf("compactTest #%d: put kv error (%v)", i, err) diff --git a/tests/common/defrag_test.go b/tests/common/defrag_test.go index 0197ced3756..4509ad51d97 100644 --- a/tests/common/defrag_test.go +++ b/tests/common/defrag_test.go @@ -32,7 +32,7 @@ func TestDefragOnline(t *testing.T) { cc := testutils.MustClient(clus.Client()) testutils.ExecuteUntil(ctx, t, func() { defer clus.Close() - var kvs = []testutils.KV{{Key: "key", Val: "val1"}, {Key: "key", Val: "val2"}, {Key: "key", Val: "val3"}} + kvs := []testutils.KV{{Key: "key", Val: "val1"}, {Key: "key", Val: "val2"}, {Key: "key", Val: "val3"}} for i := range kvs { if err := cc.Put(ctx, kvs[i].Key, kvs[i].Val, config.PutOptions{}); err != nil { t.Fatalf("compactTest #%d: put kv error (%v)", i, err) diff --git a/tests/e2e/corrupt_test.go b/tests/e2e/corrupt_test.go index 204de050ff7..b02b74a9115 100644 --- a/tests/e2e/corrupt_test.go +++ b/tests/e2e/corrupt_test.go @@ -119,7 +119,7 @@ func TestInPlaceRecovery(t *testing.T) { }) t.Log("old cluster started.") - //Put some data into the old cluster, so that after recovering from a blank db, the hash diverges. + // Put some data into the old cluster, so that after recovering from a blank db, the hash diverges. t.Log("putting 10 keys...") oldCc, err := e2e.NewEtcdctl(epcOld.Cfg.Client, epcOld.EndpointsGRPC()) assert.NoError(t, err) diff --git a/tests/e2e/ctl_v3_auth_no_proxy_test.go b/tests/e2e/ctl_v3_auth_no_proxy_test.go index 840307ec3b6..8529ff38dc9 100644 --- a/tests/e2e/ctl_v3_auth_no_proxy_test.go +++ b/tests/e2e/ctl_v3_auth_no_proxy_test.go @@ -32,9 +32,11 @@ import ( func TestCtlV3AuthCertCN(t *testing.T) { testCtl(t, authTestCertCN, withCfg(*e2e.NewConfigClientTLSCertAuth())) } + func TestCtlV3AuthCertCNAndUsername(t *testing.T) { testCtl(t, authTestCertCNAndUsername, withCfg(*e2e.NewConfigClientTLSCertAuth())) } + func TestCtlV3AuthCertCNAndUsernameNoPassword(t *testing.T) { testCtl(t, authTestCertCNAndUsernameNoPassword, withCfg(*e2e.NewConfigClientTLSCertAuth())) } diff --git a/tests/e2e/ctl_v3_auth_test.go b/tests/e2e/ctl_v3_auth_test.go index 6c252e9c202..e587c069276 100644 --- a/tests/e2e/ctl_v3_auth_test.go +++ b/tests/e2e/ctl_v3_auth_test.go @@ -39,6 +39,7 @@ func TestCtlV3AuthEndpointHealth(t *testing.T) { // TestCtlV3AuthSnapshot TODO fill up common/maintenance_auth_test.go when Snapshot API is added in interfaces.Client func TestCtlV3AuthSnapshot(t *testing.T) { testCtl(t, authTestSnapshot) } + func TestCtlV3AuthSnapshotJWT(t *testing.T) { testCtl(t, authTestSnapshot, withCfg(*e2e.NewConfigJWT())) } diff --git a/tests/e2e/ctl_v3_completion_test.go b/tests/e2e/ctl_v3_completion_test.go index 462bb14ec55..8057c0c1e21 100644 --- a/tests/e2e/ctl_v3_completion_test.go +++ b/tests/e2e/ctl_v3_completion_test.go @@ -52,7 +52,7 @@ func testShellCompletion(t *testing.T, binPath, shellName string) { require.NoError(t, completionCmd.Run()) filename := fmt.Sprintf("etcdctl-%s.completion", shellName) - require.NoError(t, os.WriteFile(filename, stdout.Bytes(), 0644)) + require.NoError(t, os.WriteFile(filename, stdout.Bytes(), 0o644)) shellCmd := exec.Command(shellName, "-c", "source "+filename) require.NoError(t, shellCmd.Run()) diff --git a/tests/e2e/ctl_v3_defrag_test.go b/tests/e2e/ctl_v3_defrag_test.go index 479ba1a284a..e4723710ba8 100644 --- a/tests/e2e/ctl_v3_defrag_test.go +++ b/tests/e2e/ctl_v3_defrag_test.go @@ -26,7 +26,7 @@ func TestCtlV3DefragOffline(t *testing.T) { } func maintenanceInitKeys(cx ctlCtx) { - var kvs = []kv{{"key", "val1"}, {"key", "val2"}, {"key", "val3"}} + kvs := []kv{{"key", "val1"}, {"key", "val2"}, {"key", "val3"}} for i := range kvs { if err := ctlV3Put(cx, kvs[i].key, kvs[i].val, ""); err != nil { cx.t.Fatal(err) diff --git a/tests/e2e/ctl_v3_kv_test.go b/tests/e2e/ctl_v3_kv_test.go index 719efc464a4..0ad173e78e4 100644 --- a/tests/e2e/ctl_v3_kv_test.go +++ b/tests/e2e/ctl_v3_kv_test.go @@ -191,9 +191,7 @@ func getFormatTest(cx ctlCtx) { } func getRevTest(cx ctlCtx) { - var ( - kvs = []kv{{"key", "val1"}, {"key", "val2"}, {"key", "val3"}} - ) + kvs := []kv{{"key", "val1"}, {"key", "val2"}, {"key", "val3"}} for i := range kvs { if err := ctlV3Put(cx, kvs[i].key, kvs[i].val, ""); err != nil { cx.t.Fatalf("getRevTest #%d: ctlV3Put error (%v)", i, err) @@ -218,14 +216,12 @@ func getRevTest(cx ctlCtx) { } func getMinMaxCreateModRevTest(cx ctlCtx) { - var ( - kvs = []kv{ // revision: store | key create | key modify - {"key1", "val1"}, // 2 2 2 - {"key2", "val2"}, // 3 3 3 - {"key1", "val3"}, // 4 2 4 - {"key4", "val4"}, // 5 5 5 - } - ) + kvs := []kv{ // revision: store | key create | key modify + {"key1", "val1"}, // 2 2 2 + {"key2", "val2"}, // 3 3 3 + {"key1", "val3"}, // 4 2 4 + {"key4", "val4"}, // 5 5 5 + } for i := range kvs { if err := ctlV3Put(cx, kvs[i].key, kvs[i].val, ""); err != nil { cx.t.Fatalf("getRevTest #%d: ctlV3Put error (%v)", i, err) diff --git a/tests/e2e/ctl_v3_lease_test.go b/tests/e2e/ctl_v3_lease_test.go index e556798745f..0ac6d1b32bd 100644 --- a/tests/e2e/ctl_v3_lease_test.go +++ b/tests/e2e/ctl_v3_lease_test.go @@ -28,12 +28,15 @@ func TestCtlV3LeaseKeepAlive(t *testing.T) { testCtl(t, leaseTestKeepAlive) } func TestCtlV3LeaseKeepAliveNoTLS(t *testing.T) { testCtl(t, leaseTestKeepAlive, withCfg(*e2e.NewConfigNoTLS())) } + func TestCtlV3LeaseKeepAliveClientTLS(t *testing.T) { testCtl(t, leaseTestKeepAlive, withCfg(*e2e.NewConfigClientTLS())) } + func TestCtlV3LeaseKeepAliveClientAutoTLS(t *testing.T) { testCtl(t, leaseTestKeepAlive, withCfg(*e2e.NewConfigClientAutoTLS())) } + func TestCtlV3LeaseKeepAlivePeerTLS(t *testing.T) { testCtl(t, leaseTestKeepAlive, withCfg(*e2e.NewConfigPeerTLS())) } diff --git a/tests/e2e/ctl_v3_member_test.go b/tests/e2e/ctl_v3_member_test.go index e10836eae3a..56d8a8f3c95 100644 --- a/tests/e2e/ctl_v3_member_test.go +++ b/tests/e2e/ctl_v3_member_test.go @@ -50,12 +50,15 @@ func TestCtlV3MemberUpdate(t *testing.T) { testCtl(t, memberUpdateTest) } func TestCtlV3MemberUpdateNoTLS(t *testing.T) { testCtl(t, memberUpdateTest, withCfg(*e2e.NewConfigNoTLS())) } + func TestCtlV3MemberUpdateClientTLS(t *testing.T) { testCtl(t, memberUpdateTest, withCfg(*e2e.NewConfigClientTLS())) } + func TestCtlV3MemberUpdateClientAutoTLS(t *testing.T) { testCtl(t, memberUpdateTest, withCfg(*e2e.NewConfigClientAutoTLS())) } + func TestCtlV3MemberUpdatePeerTLS(t *testing.T) { testCtl(t, memberUpdateTest, withCfg(*e2e.NewConfigPeerTLS())) } diff --git a/tests/e2e/ctl_v3_snapshot_test.go b/tests/e2e/ctl_v3_snapshot_test.go index 66f2dbf574e..c4747b7e3b0 100644 --- a/tests/e2e/ctl_v3_snapshot_test.go +++ b/tests/e2e/ctl_v3_snapshot_test.go @@ -224,7 +224,8 @@ func testIssue6361(t *testing.T) { "--initial-cluster", epc.Procs[0].Config().InitialCluster, "--initial-cluster-token", epc.Procs[0].Config().InitialToken, "--initial-advertise-peer-urls", epc.Procs[0].Config().PeerURL.String(), - "--data-dir", newDataDir}, + "--data-dir", newDataDir, + }, expect.ExpectedResponse{Value: "added member"}) if err != nil { t.Fatal(err) @@ -264,10 +265,12 @@ func testIssue6361(t *testing.T) { t.Log("Starting the new member") // start the new member var nepc *expect.ExpectProcess - nepc, err = e2e.SpawnCmd([]string{epc.Procs[0].Config().ExecPath, "--name", name2, + nepc, err = e2e.SpawnCmd([]string{ + epc.Procs[0].Config().ExecPath, "--name", name2, "--listen-client-urls", clientURL, "--advertise-client-urls", clientURL, "--listen-peer-urls", peerURL, "--initial-advertise-peer-urls", peerURL, - "--initial-cluster", initialCluster2, "--initial-cluster-state", "existing", "--data-dir", newDataDir2}, nil) + "--initial-cluster", initialCluster2, "--initial-cluster-state", "existing", "--data-dir", newDataDir2, + }, nil) if err != nil { t.Fatal(err) } diff --git a/tests/e2e/ctl_v3_watch_no_cov_test.go b/tests/e2e/ctl_v3_watch_no_cov_test.go index b139deedae9..9df7cc60078 100644 --- a/tests/e2e/ctl_v3_watch_no_cov_test.go +++ b/tests/e2e/ctl_v3_watch_no_cov_test.go @@ -30,12 +30,15 @@ func TestCtlV3WatchTimeout(t *testing.T) { testCtl(t, watchTest, withDefaultDi func TestCtlV3WatchInteractive(t *testing.T) { testCtl(t, watchTest, withInteractive()) } + func TestCtlV3WatchInteractiveNoTLS(t *testing.T) { testCtl(t, watchTest, withInteractive(), withCfg(*e2e.NewConfigNoTLS())) } + func TestCtlV3WatchInteractiveClientTLS(t *testing.T) { testCtl(t, watchTest, withInteractive(), withCfg(*e2e.NewConfigClientTLS())) } + func TestCtlV3WatchInteractivePeerTLS(t *testing.T) { testCtl(t, watchTest, withInteractive(), withCfg(*e2e.NewConfigPeerTLS())) } diff --git a/tests/e2e/discovery_v3_test.go b/tests/e2e/discovery_v3_test.go index b74666fb8a0..e7603d1a07b 100644 --- a/tests/e2e/discovery_v3_test.go +++ b/tests/e2e/discovery_v3_test.go @@ -28,9 +28,11 @@ import ( func TestClusterOf1UsingV3Discovery_1endpoint(t *testing.T) { testClusterUsingV3Discovery(t, 1, 1, e2e.ClientNonTLS, false) } + func TestClusterOf3UsingV3Discovery_1endpoint(t *testing.T) { testClusterUsingV3Discovery(t, 1, 3, e2e.ClientTLS, true) } + func TestTLSClusterOf5UsingV3Discovery_1endpoint(t *testing.T) { testClusterUsingV3Discovery(t, 1, 5, e2e.ClientTLS, false) } @@ -38,9 +40,11 @@ func TestTLSClusterOf5UsingV3Discovery_1endpoint(t *testing.T) { func TestClusterOf1UsingV3Discovery_3endpoints(t *testing.T) { testClusterUsingV3Discovery(t, 3, 1, e2e.ClientNonTLS, false) } + func TestClusterOf3UsingV3Discovery_3endpoints(t *testing.T) { testClusterUsingV3Discovery(t, 3, 3, e2e.ClientTLS, true) } + func TestTLSClusterOf5UsingV3Discovery_3endpoints(t *testing.T) { testClusterUsingV3Discovery(t, 3, 5, e2e.ClientTLS, false) } diff --git a/tests/e2e/etcd_grpcproxy_test.go b/tests/e2e/etcd_grpcproxy_test.go index fd3353ce6af..beb279553a7 100644 --- a/tests/e2e/etcd_grpcproxy_test.go +++ b/tests/e2e/etcd_grpcproxy_test.go @@ -48,7 +48,8 @@ func TestGrpcProxyAutoSync(t *testing.T) { ) // Run independent grpc-proxy instance - proxyProc, err := e2e.SpawnCmd([]string{e2e.BinPath.Etcd, "grpc-proxy", "start", + proxyProc, err := e2e.SpawnCmd([]string{ + e2e.BinPath.Etcd, "grpc-proxy", "start", "--advertise-client-url", proxyClientURL, "--listen-addr", proxyClientURL, "--endpoints", node1ClientURL, "--endpoints-auto-sync-interval", "1s", diff --git a/tests/e2e/etcd_release_upgrade_test.go b/tests/e2e/etcd_release_upgrade_test.go index afc73974980..cf12cbadf69 100644 --- a/tests/e2e/etcd_release_upgrade_test.go +++ b/tests/e2e/etcd_release_upgrade_test.go @@ -123,7 +123,6 @@ func TestReleaseUpgradeWithRestart(t *testing.T) { e2e.WithSnapshotCount(10), e2e.WithBasePeerScheme("unix"), ) - if err != nil { t.Fatalf("could not start etcd process cluster (%v)", err) } diff --git a/tests/e2e/gateway_test.go b/tests/e2e/gateway_test.go index aefe3d4a713..268e20f7ea5 100644 --- a/tests/e2e/gateway_test.go +++ b/tests/e2e/gateway_test.go @@ -23,9 +23,7 @@ import ( "go.etcd.io/etcd/tests/v3/framework/e2e" ) -var ( - defaultGatewayEndpoint = "127.0.0.1:23790" -) +var defaultGatewayEndpoint = "127.0.0.1:23790" func TestGateway(t *testing.T) { ec, err := e2e.NewEtcdProcessCluster(context.TODO(), t) diff --git a/tests/e2e/http_health_check_test.go b/tests/e2e/http_health_check_test.go index 8aa2694344f..9dbad81a235 100644 --- a/tests/e2e/http_health_check_test.go +++ b/tests/e2e/http_health_check_test.go @@ -172,33 +172,31 @@ func TestHTTPHealthHandler(t *testing.T) { } } -var ( - defaultHealthCheckConfigs = []healthCheckConfig{ - { - url: "/livez", - expectedStatusCode: http.StatusOK, - expectedRespSubStrings: []string{`ok`}, - }, - { - url: "/readyz", - expectedStatusCode: http.StatusOK, - expectedRespSubStrings: []string{`ok`}, +var defaultHealthCheckConfigs = []healthCheckConfig{ + { + url: "/livez", + expectedStatusCode: http.StatusOK, + expectedRespSubStrings: []string{`ok`}, + }, + { + url: "/readyz", + expectedStatusCode: http.StatusOK, + expectedRespSubStrings: []string{`ok`}, + }, + { + url: "/livez?verbose=true", + expectedStatusCode: http.StatusOK, + expectedRespSubStrings: []string{`[+]serializable_read ok`}, + }, + { + url: "/readyz?verbose=true", + expectedStatusCode: http.StatusOK, + expectedRespSubStrings: []string{ + `[+]serializable_read ok`, + `[+]data_corruption ok`, }, - { - url: "/livez?verbose=true", - expectedStatusCode: http.StatusOK, - expectedRespSubStrings: []string{`[+]serializable_read ok`}, - }, - { - url: "/readyz?verbose=true", - expectedStatusCode: http.StatusOK, - expectedRespSubStrings: []string{ - `[+]serializable_read ok`, - `[+]data_corruption ok`, - }, - }, - } -) + }, +} func TestHTTPLivezReadyzHandler(t *testing.T) { e2e.BeforeTest(t) diff --git a/tests/e2e/v2store_deprecation_test.go b/tests/e2e/v2store_deprecation_test.go index a36a2269b85..5306344daa3 100644 --- a/tests/e2e/v2store_deprecation_test.go +++ b/tests/e2e/v2store_deprecation_test.go @@ -42,7 +42,8 @@ func writeCustomV2Data(t testing.TB, epc *e2e.EtcdProcessCluster, count int) { for i := 0; i < count; i++ { if err := e2e.CURLPut(epc, e2e.CURLReq{ Endpoint: "/v2/keys/foo", Value: "bar" + fmt.Sprint(i), - Expected: expect.ExpectedResponse{Value: `{"action":"set","node":{"key":"/foo","value":"bar` + fmt.Sprint(i)}}); err != nil { + Expected: expect.ExpectedResponse{Value: `{"action":"set","node":{"key":"/foo","value":"bar` + fmt.Sprint(i)}, + }); err != nil { t.Fatalf("failed put with curl (%v)", err) } } @@ -275,7 +276,7 @@ func assertMembershipEqual(t testing.TB, firstStore v2store.Store, secondStore v rc2.SetStore(secondStore) rc2.Recover(func(lg *zap.Logger, v *semver.Version) { return }) - //membership should match + // membership should match if !reflect.DeepEqual(rc1.Members(), rc2.Members()) { t.Logf("memberids_from_last_version = %+v, member_ids_from_current_version = %+v", rc1.MemberIDs(), rc2.MemberIDs()) t.Errorf("members_from_last_version_snapshot = %+v, members_from_current_version_snapshot %+v", rc1.Members(), rc2.Members()) diff --git a/tests/e2e/v3_curl_auth_test.go b/tests/e2e/v3_curl_auth_test.go index 04f07b48013..0ea8cd7fd2a 100644 --- a/tests/e2e/v3_curl_auth_test.go +++ b/tests/e2e/v3_curl_auth_test.go @@ -34,6 +34,7 @@ import ( func TestCurlV3Auth(t *testing.T) { testCtl(t, testCurlV3Auth) } + func TestCurlV3AuthClientTLSCertAuth(t *testing.T) { testCtl(t, testCurlV3Auth, withCfg(*e2e.NewConfigClientTLSCertAuthWithNoCN())) } @@ -89,7 +90,7 @@ func testCurlV3Auth(cx ctlCtx) { cx.t.Fatalf("testCurlV3Auth failed to create role (%v)", err) } - //grant root role + // grant root role for i := 0; i < len(usernames); i++ { grantroleroot, merr := json.Marshal(&pb.AuthUserGrantRoleRequest{User: usernames[i], Role: "root"}) assert.NoError(cx.t, merr) @@ -378,9 +379,7 @@ func testCurlV3AuthRoleBasicOperations(cx ctlCtx) { } func testCurlV3AuthRoleManagePermission(cx ctlCtx) { - var ( - rolename = "role1" - ) + rolename := "role1" // create a role role, err := json.Marshal(&pb.AuthRoleAddRequest{Name: rolename}) diff --git a/tests/e2e/v3_curl_lease_test.go b/tests/e2e/v3_curl_lease_test.go index 67ef64e2240..343830ff4cf 100644 --- a/tests/e2e/v3_curl_lease_test.go +++ b/tests/e2e/v3_curl_lease_test.go @@ -25,12 +25,15 @@ import ( func TestCurlV3LeaseGrantNoTLS(t *testing.T) { testCtl(t, testCurlV3LeaseGrant, withCfg(*e2e.NewConfigNoTLS())) } + func TestCurlV3LeaseRevokeNoTLS(t *testing.T) { testCtl(t, testCurlV3LeaseRevoke, withCfg(*e2e.NewConfigNoTLS())) } + func TestCurlV3LeaseLeasesNoTLS(t *testing.T) { testCtl(t, testCurlV3LeaseLeases, withCfg(*e2e.NewConfigNoTLS())) } + func TestCurlV3LeaseKeepAliveNoTLS(t *testing.T) { testCtl(t, testCurlV3LeaseKeepAlive, withCfg(*e2e.NewConfigNoTLS())) } diff --git a/tests/framework/e2e/curl.go b/tests/framework/e2e/curl.go index 16c2c39cf3f..a6a9ee35fc4 100644 --- a/tests/framework/e2e/curl.go +++ b/tests/framework/e2e/curl.go @@ -59,9 +59,7 @@ func CURLPrefixArgsCluster(cfg *EtcdProcessClusterConfig, member EtcdProcess, me } func CURLPrefixArgs(clientURL string, cfg ClientConfig, CN bool, method string, req CURLReq) []string { - var ( - cmdArgs = []string{"curl"} - ) + cmdArgs := []string{"curl"} if req.HTTPVersion != "" { cmdArgs = append(cmdArgs, "--http"+req.HTTPVersion) } diff --git a/tests/framework/e2e/etcd_process.go b/tests/framework/e2e/etcd_process.go index b55ef9e90a6..022d86a6c7b 100644 --- a/tests/framework/e2e/etcd_process.go +++ b/tests/framework/e2e/etcd_process.go @@ -37,9 +37,7 @@ import ( "go.etcd.io/etcd/tests/v3/framework/config" ) -var ( - EtcdServerReadyLines = []string{"ready to serve client requests"} -) +var EtcdServerReadyLines = []string{"ready to serve client requests"} // EtcdProcess is a process that serves etcd requests. type EtcdProcess interface { @@ -112,7 +110,7 @@ func NewEtcdServerProcess(t testing.TB, cfg *EtcdServerProcessConfig) (*EtcdServ if err := os.RemoveAll(cfg.DataDirPath); err != nil { return nil, err } - if err := os.Mkdir(cfg.DataDirPath, 0700); err != nil { + if err := os.Mkdir(cfg.DataDirPath, 0o700); err != nil { return nil, err } } diff --git a/tests/framework/e2e/lazyfs.go b/tests/framework/e2e/lazyfs.go index fb17b203b34..98bfc69dc79 100644 --- a/tests/framework/e2e/lazyfs.go +++ b/tests/framework/e2e/lazyfs.go @@ -50,12 +50,12 @@ func (fs *LazyFS) Start(ctx context.Context) (err error) { if fs.ep != nil { return nil } - err = os.WriteFile(fs.configPath(), fs.config(), 0666) + err = os.WriteFile(fs.configPath(), fs.config(), 0o666) if err != nil { return err } dataPath := filepath.Join(fs.LazyFSDir, "data") - err = os.Mkdir(dataPath, 0700) + err = os.Mkdir(dataPath, 0o700) if err != nil { return err } @@ -103,7 +103,7 @@ func (fs *LazyFS) Stop() error { } func (fs *LazyFS) ClearCache(ctx context.Context) error { - err := os.WriteFile(fs.socketPath(), []byte("lazyfs::clear-cache\n"), 0666) + err := os.WriteFile(fs.socketPath(), []byte("lazyfs::clear-cache\n"), 0o666) if err != nil { return err } diff --git a/tests/framework/integration/cluster.go b/tests/framework/integration/cluster.go index 95b5c88d9f8..b41a010433c 100644 --- a/tests/framework/integration/cluster.go +++ b/tests/framework/integration/cluster.go @@ -975,9 +975,7 @@ func (m *Member) Launch() error { } if m.GRPCListener != nil { - var ( - tlscfg *tls.Config - ) + var tlscfg *tls.Config if m.ClientTLSInfo != nil && !m.ClientTLSInfo.Empty() { tlscfg, err = m.ClientTLSInfo.ServerConfig() if err != nil { diff --git a/tests/framework/integration/testing.go b/tests/framework/integration/testing.go index a211973ddc7..a4d03c53212 100644 --- a/tests/framework/integration/testing.go +++ b/tests/framework/integration/testing.go @@ -31,8 +31,10 @@ import ( gofail "go.etcd.io/gofail/runtime" ) -var grpcLogger grpclogsettable.SettableLoggerV2 -var insideTestContext bool +var ( + grpcLogger grpclogsettable.SettableLoggerV2 + insideTestContext bool +) func init() { grpcLogger = grpclogsettable.ReplaceGrpcLoggerV2() diff --git a/tests/integration/clientv3/concurrency/session_test.go b/tests/integration/clientv3/concurrency/session_test.go index 37fc1899b0f..dff508972a2 100644 --- a/tests/integration/clientv3/concurrency/session_test.go +++ b/tests/integration/clientv3/concurrency/session_test.go @@ -50,6 +50,7 @@ func TestSessionOptions(t *testing.T) { t.Fatal("session did not get orphaned as expected") } } + func TestSessionTTLOptions(t *testing.T) { cli, err := integration2.NewClient(t, clientv3.Config{Endpoints: exampleEndpoints()}) if err != nil { @@ -57,7 +58,7 @@ func TestSessionTTLOptions(t *testing.T) { } defer cli.Close() - var setTTL = 90 + setTTL := 90 s, err := concurrency.NewSession(cli, concurrency.WithTTL(setTTL)) if err != nil { t.Fatal(err) diff --git a/tests/integration/clientv3/experimental/recipes/v3_queue_test.go b/tests/integration/clientv3/experimental/recipes/v3_queue_test.go index 7ace22eb8f6..73ed5552fe2 100644 --- a/tests/integration/clientv3/experimental/recipes/v3_queue_test.go +++ b/tests/integration/clientv3/experimental/recipes/v3_queue_test.go @@ -234,6 +234,7 @@ func (q *flatPriorityQueue) Enqueue(val string) error { // randomized to stress dequeuing logic; order isn't important return q.PriorityQueue.Enqueue(val, uint16(rand.Intn(2))) } + func (q *flatPriorityQueue) Dequeue() (string, error) { return q.PriorityQueue.Dequeue() } diff --git a/tests/integration/clientv3/naming/endpoints_test.go b/tests/integration/clientv3/naming/endpoints_test.go index 8677e9732cd..3c93c6c7d19 100644 --- a/tests/integration/clientv3/naming/endpoints_test.go +++ b/tests/integration/clientv3/naming/endpoints_test.go @@ -102,7 +102,8 @@ func TestEndpointManagerAtomicity(t *testing.T) { err = em.Update(context.TODO(), []*endpoints.UpdateWithOpts{ endpoints.NewAddUpdateOpts("foo/host", endpoints.Endpoint{Addr: "127.0.0.1:2000"}), - endpoints.NewAddUpdateOpts("foo/host2", endpoints.Endpoint{Addr: "127.0.0.1:2001"})}) + endpoints.NewAddUpdateOpts("foo/host2", endpoints.Endpoint{Addr: "127.0.0.1:2001"}), + }) require.NoError(t, err) ctx, watchCancel := context.WithCancel(context.Background()) diff --git a/tests/integration/clientv3/ordering_kv_test.go b/tests/integration/clientv3/ordering_kv_test.go index 1d667b44dac..7775197ec47 100644 --- a/tests/integration/clientv3/ordering_kv_test.go +++ b/tests/integration/clientv3/ordering_kv_test.go @@ -28,7 +28,7 @@ import ( ) func TestDetectKvOrderViolation(t *testing.T) { - var errOrderViolation = errors.New("DetectedOrderViolation") + errOrderViolation := errors.New("DetectedOrderViolation") integration2.BeforeTest(t) clus := integration2.NewCluster(t, &integration2.ClusterConfig{Size: 3, UseBridge: true}) @@ -95,7 +95,7 @@ func TestDetectKvOrderViolation(t *testing.T) { } func TestDetectTxnOrderViolation(t *testing.T) { - var errOrderViolation = errors.New("DetectedOrderViolation") + errOrderViolation := errors.New("DetectedOrderViolation") integration2.BeforeTest(t) clus := integration2.NewCluster(t, &integration2.ClusterConfig{Size: 3, UseBridge: true}) diff --git a/tests/integration/clientv3/util.go b/tests/integration/clientv3/util.go index 623e575be11..0e84115704c 100644 --- a/tests/integration/clientv3/util.go +++ b/tests/integration/clientv3/util.go @@ -114,7 +114,6 @@ func populateDataIntoCluster(t *testing.T, cluster *integration2.Cluster, numKey for i := 0; i < numKeys; i++ { _, err := cluster.RandClient().Put(ctx, fmt.Sprintf("%s-%v", t.Name(), i), strings.Repeat("a", valueSize)) - if err != nil { t.Errorf("populating data expected no error, but got %v", err) } diff --git a/tests/integration/clientv3/watch_test.go b/tests/integration/clientv3/watch_test.go index 090e473d065..b06f3e34916 100644 --- a/tests/integration/clientv3/watch_test.go +++ b/tests/integration/clientv3/watch_test.go @@ -576,8 +576,10 @@ func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) { t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision) } if watchOnPut { // wait for put if watch on the put key - ev := []*clientv3.Event{{Type: clientv3.EventTypePut, - Kv: &mvccpb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}} + ev := []*clientv3.Event{{ + Type: clientv3.EventTypePut, + Kv: &mvccpb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}, + }} if !reflect.DeepEqual(ev, resp.Events) { t.Fatalf("expected %+v, got %+v", ev, resp.Events) } diff --git a/tests/integration/embed/embed_test.go b/tests/integration/embed/embed_test.go index ade0504b783..2cf8fd6bb0e 100644 --- a/tests/integration/embed/embed_test.go +++ b/tests/integration/embed/embed_test.go @@ -40,14 +40,12 @@ import ( "go.etcd.io/etcd/tests/v3/framework/testutils" ) -var ( - testTLSInfo = transport.TLSInfo{ - KeyFile: testutils.MustAbsPath("../../fixtures/server.key.insecure"), - CertFile: testutils.MustAbsPath("../../fixtures/server.crt"), - TrustedCAFile: testutils.MustAbsPath("../../fixtures/ca.crt"), - ClientCertAuth: true, - } -) +var testTLSInfo = transport.TLSInfo{ + KeyFile: testutils.MustAbsPath("../../fixtures/server.key.insecure"), + CertFile: testutils.MustAbsPath("../../fixtures/server.crt"), + TrustedCAFile: testutils.MustAbsPath("../../fixtures/ca.crt"), + ClientCertAuth: true, +} func TestEmbedEtcd(t *testing.T) { testutil.SkipTestIfShortMode(t, "Cannot start embedded cluster in --short tests") diff --git a/tests/integration/metrics_test.go b/tests/integration/metrics_test.go index 047b57ef150..e6f5a3f3e9c 100644 --- a/tests/integration/metrics_test.go +++ b/tests/integration/metrics_test.go @@ -222,7 +222,8 @@ func TestMetricsRangeDurationSeconds(t *testing.T) { client := clus.RandClient() keys := []string{ - "my-namespace/foobar", "my-namespace/foobar1", "namespace/foobar1"} + "my-namespace/foobar", "my-namespace/foobar1", "namespace/foobar1", + } for _, key := range keys { _, err := client.Put(context.Background(), key, "data") require.NoError(t, err) diff --git a/tests/integration/proxy/grpcproxy/cluster_test.go b/tests/integration/proxy/grpcproxy/cluster_test.go index 58ea4e4bd95..ca2fcb506b3 100644 --- a/tests/integration/proxy/grpcproxy/cluster_test.go +++ b/tests/integration/proxy/grpcproxy/cluster_test.go @@ -74,13 +74,13 @@ func TestClusterProxyMemberList(t *testing.T) { } assert.Contains(t, mresp.Members, &pb.Member{Name: hostname, ClientURLs: []string{cts.caddr}}) - //test proxy member add + // test proxy member add newMemberAddr := "127.0.0.2:6789" grpcproxy.Register(lg, cts.c, prefix, newMemberAddr, 7) // wait some time for proxy update members time.Sleep(200 * time.Millisecond) - //check add member succ + // check add member succ mresp, err = client.Cluster.MemberList(context.Background()) if err != nil { t.Fatalf("err %v, want nil", err) @@ -90,12 +90,12 @@ func TestClusterProxyMemberList(t *testing.T) { } assert.Contains(t, mresp.Members, &pb.Member{Name: hostname, ClientURLs: []string{newMemberAddr}}) - //test proxy member delete + // test proxy member delete deregisterMember(cts.c, prefix, newMemberAddr, t) // wait some time for proxy update members time.Sleep(200 * time.Millisecond) - //check delete member succ + // check delete member succ mresp, err = client.Cluster.MemberList(context.Background()) if err != nil { t.Fatalf("err %v, want nil", err) diff --git a/tests/integration/snapshot/v3_snapshot_test.go b/tests/integration/snapshot/v3_snapshot_test.go index b9739e2ab1c..893fa4fd038 100644 --- a/tests/integration/snapshot/v3_snapshot_test.go +++ b/tests/integration/snapshot/v3_snapshot_test.go @@ -205,7 +205,8 @@ const testClusterTkn = "tkn" func restoreCluster(t *testing.T, clusterN int, dbPath string) ( cURLs []url.URL, pURLs []url.URL, - srvs []*embed.Etcd) { + srvs []*embed.Etcd, +) { urls := newEmbedURLs(t, clusterN*2) cURLs, pURLs = urls[:clusterN], urls[clusterN:] diff --git a/tests/integration/testing_test.go b/tests/integration/testing_test.go index dfd75e89344..f49e58d83d7 100644 --- a/tests/integration/testing_test.go +++ b/tests/integration/testing_test.go @@ -24,6 +24,5 @@ func TestBeforeTestWithoutLeakDetection(t *testing.T) { integration2.BeforeTest(t, integration2.WithoutGoLeakDetection(), integration2.WithoutSkipInShort()) // Intentional leak that should get ignored go func() { - }() } diff --git a/tests/integration/tracing_test.go b/tests/integration/tracing_test.go index 744028322d3..5b87208848a 100644 --- a/tests/integration/tracing_test.go +++ b/tests/integration/tracing_test.go @@ -50,7 +50,8 @@ func TestTracing(t *testing.T) { srv := grpc.NewServer() traceservice.RegisterTraceServiceServer(srv, &traceServer{ traceFound: traceFound, - filterFunc: containsNodeListSpan}) + filterFunc: containsNodeListSpan, + }) go srv.Serve(listener) defer srv.Stop() @@ -92,7 +93,8 @@ func TestTracing(t *testing.T) { dialOptions := []grpc.DialOption{ grpc.WithUnaryInterceptor(otelgrpc.UnaryClientInterceptor(tracingOpts...)), - grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor(tracingOpts...))} + grpc.WithStreamInterceptor(otelgrpc.StreamClientInterceptor(tracingOpts...)), + } ccfg := clientv3.Config{DialOptions: dialOptions, Endpoints: []string{cfg.AdvertiseClientUrls[0].String()}} cli, err := integration.NewClient(t, ccfg) if err != nil { @@ -141,7 +143,7 @@ type traceServer struct { } func (t *traceServer) Export(ctx context.Context, req *traceservice.ExportTraceServiceRequest) (*traceservice.ExportTraceServiceResponse, error) { - var emptyValue = traceservice.ExportTraceServiceResponse{} + emptyValue := traceservice.ExportTraceServiceResponse{} if t.filterFunc(req) { t.traceFound <- struct{}{} } diff --git a/tests/integration/v2store/main_test.go b/tests/integration/v2store/main_test.go index 89026c5a773..b5534268a0b 100644 --- a/tests/integration/v2store/main_test.go +++ b/tests/integration/v2store/main_test.go @@ -20,8 +20,6 @@ import ( "go.etcd.io/etcd/client/pkg/v3/testutil" ) -//var endpoints []string - func TestMain(m *testing.M) { //cfg := integration.ClusterConfig{Size: 1} //clus := integration.NewClusterV3(nil, &cfg) diff --git a/tests/integration/v3_failover_test.go b/tests/integration/v3_failover_test.go index d71dd267b85..b4ce09e1a38 100644 --- a/tests/integration/v3_failover_test.go +++ b/tests/integration/v3_failover_test.go @@ -120,7 +120,6 @@ func putWithRetries(t *testing.T, cli *clientv3.Client, key, val string, retryCo } return nil }() - if err != nil { retryCount-- if shouldRetry(err) { @@ -153,7 +152,6 @@ func getWithRetries(t *testing.T, cli *clientv3.Client, key, val string, retryCo } return nil }() - if err != nil { retryCount-- if shouldRetry(err) { diff --git a/tests/integration/v3_grpc_test.go b/tests/integration/v3_grpc_test.go index 61fef15d8cd..17f103d27ae 100644 --- a/tests/integration/v3_grpc_test.go +++ b/tests/integration/v3_grpc_test.go @@ -253,9 +253,10 @@ func TestV3TxnTooManyOps(t *testing.T) { newTxn := &pb.TxnRequest{} addSuccessOps(newTxn) txn.Success = append(txn.Success, - &pb.RequestOp{Request: &pb.RequestOp_RequestTxn{ - RequestTxn: newTxn, - }, + &pb.RequestOp{ + Request: &pb.RequestOp_RequestTxn{ + RequestTxn: newTxn, + }, }, ) } @@ -286,44 +287,53 @@ func TestV3TxnDuplicateKeys(t *testing.T) { defer clus.Terminate(t) putreq := &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: &pb.PutRequest{Key: []byte("abc"), Value: []byte("def")}}} - delKeyReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{ - RequestDeleteRange: &pb.DeleteRangeRequest{ - Key: []byte("abc"), + delKeyReq := &pb.RequestOp{ + Request: &pb.RequestOp_RequestDeleteRange{ + RequestDeleteRange: &pb.DeleteRangeRequest{ + Key: []byte("abc"), + }, }, - }, } - delInRangeReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{ - RequestDeleteRange: &pb.DeleteRangeRequest{ - Key: []byte("a"), RangeEnd: []byte("b"), + delInRangeReq := &pb.RequestOp{ + Request: &pb.RequestOp_RequestDeleteRange{ + RequestDeleteRange: &pb.DeleteRangeRequest{ + Key: []byte("a"), RangeEnd: []byte("b"), + }, }, - }, } - delOutOfRangeReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{ - RequestDeleteRange: &pb.DeleteRangeRequest{ - Key: []byte("abb"), RangeEnd: []byte("abc"), + delOutOfRangeReq := &pb.RequestOp{ + Request: &pb.RequestOp_RequestDeleteRange{ + RequestDeleteRange: &pb.DeleteRangeRequest{ + Key: []byte("abb"), RangeEnd: []byte("abc"), + }, }, - }, } - txnDelReq := &pb.RequestOp{Request: &pb.RequestOp_RequestTxn{ - RequestTxn: &pb.TxnRequest{Success: []*pb.RequestOp{delInRangeReq}}, - }, + txnDelReq := &pb.RequestOp{ + Request: &pb.RequestOp_RequestTxn{ + RequestTxn: &pb.TxnRequest{Success: []*pb.RequestOp{delInRangeReq}}, + }, } - txnDelReqTwoSide := &pb.RequestOp{Request: &pb.RequestOp_RequestTxn{ - RequestTxn: &pb.TxnRequest{ - Success: []*pb.RequestOp{delInRangeReq}, - Failure: []*pb.RequestOp{delInRangeReq}}, - }, + txnDelReqTwoSide := &pb.RequestOp{ + Request: &pb.RequestOp_RequestTxn{ + RequestTxn: &pb.TxnRequest{ + Success: []*pb.RequestOp{delInRangeReq}, + Failure: []*pb.RequestOp{delInRangeReq}, + }, + }, } - txnPutReq := &pb.RequestOp{Request: &pb.RequestOp_RequestTxn{ - RequestTxn: &pb.TxnRequest{Success: []*pb.RequestOp{putreq}}, - }, + txnPutReq := &pb.RequestOp{ + Request: &pb.RequestOp_RequestTxn{ + RequestTxn: &pb.TxnRequest{Success: []*pb.RequestOp{putreq}}, + }, } - txnPutReqTwoSide := &pb.RequestOp{Request: &pb.RequestOp_RequestTxn{ - RequestTxn: &pb.TxnRequest{ - Success: []*pb.RequestOp{putreq}, - Failure: []*pb.RequestOp{putreq}}, - }, + txnPutReqTwoSide := &pb.RequestOp{ + Request: &pb.RequestOp_RequestTxn{ + RequestTxn: &pb.TxnRequest{ + Success: []*pb.RequestOp{putreq}, + Failure: []*pb.RequestOp{putreq}, + }, + }, } kvc := integration.ToGRPC(clus.RandClient()).KV @@ -473,7 +483,8 @@ func TestV3TxnCmpHeaderRev(t *testing.T) { // The read-only txn uses the optimized readindex server path. txnget := &pb.RequestOp{Request: &pb.RequestOp_RequestRange{ - RequestRange: &pb.RangeRequest{Key: []byte("k")}}} + RequestRange: &pb.RangeRequest{Key: []byte("k")}, + }} txn := &pb.TxnRequest{Success: []*pb.RequestOp{txnget}} // i = 0 /\ Succeeded => put followed txn cmp := &pb.Compare{ @@ -709,7 +720,8 @@ func TestV3PutIgnoreValue(t *testing.T) { preq.IgnoreValue = true txn := &pb.TxnRequest{} txn.Success = append(txn.Success, &pb.RequestOp{ - Request: &pb.RequestOp_RequestPut{RequestPut: &preq}}) + Request: &pb.RequestOp_RequestPut{RequestPut: &preq}, + }) _, err := kvc.Txn(context.TODO(), txn) return err }, @@ -732,7 +744,8 @@ func TestV3PutIgnoreValue(t *testing.T) { preq.IgnoreValue = true txn := &pb.TxnRequest{} txn.Success = append(txn.Success, &pb.RequestOp{ - Request: &pb.RequestOp_RequestPut{RequestPut: &preq}}) + Request: &pb.RequestOp_RequestPut{RequestPut: &preq}, + }) _, err := kvc.Txn(context.TODO(), txn) return err }, @@ -844,7 +857,8 @@ func TestV3PutIgnoreLease(t *testing.T) { preq.IgnoreLease = true txn := &pb.TxnRequest{} txn.Success = append(txn.Success, &pb.RequestOp{ - Request: &pb.RequestOp_RequestPut{RequestPut: &preq}}) + Request: &pb.RequestOp_RequestPut{RequestPut: &preq}, + }) _, err := kvc.Txn(context.TODO(), txn) return err }, @@ -870,7 +884,8 @@ func TestV3PutIgnoreLease(t *testing.T) { preq.IgnoreLease = true txn := &pb.TxnRequest{} txn.Success = append(txn.Success, &pb.RequestOp{ - Request: &pb.RequestOp_RequestPut{RequestPut: &preq}}) + Request: &pb.RequestOp_RequestPut{RequestPut: &preq}, + }) _, err := kvc.Txn(context.TODO(), txn) return err }, @@ -960,7 +975,9 @@ func TestV3PutMissingLease(t *testing.T) { txn := &pb.TxnRequest{} txn.Success = append(txn.Success, &pb.RequestOp{ Request: &pb.RequestOp_RequestPut{ - RequestPut: preq}}) + RequestPut: preq, + }, + }) if tresp, err := kvc.Txn(context.TODO(), txn); err == nil { t.Errorf("succeeded txn success. req: %v. resp: %v", txn, tresp) } @@ -970,7 +987,9 @@ func TestV3PutMissingLease(t *testing.T) { txn := &pb.TxnRequest{} txn.Failure = append(txn.Failure, &pb.RequestOp{ Request: &pb.RequestOp_RequestPut{ - RequestPut: preq}}) + RequestPut: preq, + }, + }) cmp := &pb.Compare{ Result: pb.Compare_GREATER, Target: pb.Compare_CREATE, @@ -987,10 +1006,14 @@ func TestV3PutMissingLease(t *testing.T) { rreq := &pb.RangeRequest{Key: []byte("bar")} txn.Success = append(txn.Success, &pb.RequestOp{ Request: &pb.RequestOp_RequestRange{ - RequestRange: rreq}}) + RequestRange: rreq, + }, + }) txn.Failure = append(txn.Failure, &pb.RequestOp{ Request: &pb.RequestOp_RequestPut{ - RequestPut: preq}}) + RequestPut: preq, + }, + }) if tresp, err := kvc.Txn(context.TODO(), txn); err != nil { t.Errorf("failed good txn. req: %v. resp: %v", txn, tresp) } @@ -1028,43 +1051,50 @@ func TestV3DeleteRange(t *testing.T) { "delete middle", []string{"foo", "foo/abc", "fop"}, "foo/", "fop", false, - [][]byte{[]byte("foo"), []byte("fop")}, 1, + [][]byte{[]byte("foo"), []byte("fop")}, + 1, }, { "no delete", []string{"foo", "foo/abc", "fop"}, "foo/", "foo/", false, - [][]byte{[]byte("foo"), []byte("foo/abc"), []byte("fop")}, 0, + [][]byte{[]byte("foo"), []byte("foo/abc"), []byte("fop")}, + 0, }, { "delete first", []string{"foo", "foo/abc", "fop"}, "fo", "fop", false, - [][]byte{[]byte("fop")}, 2, + [][]byte{[]byte("fop")}, + 2, }, { "delete tail", []string{"foo", "foo/abc", "fop"}, "foo/", "fos", false, - [][]byte{[]byte("foo")}, 2, + [][]byte{[]byte("foo")}, + 2, }, { "delete exact", []string{"foo", "foo/abc", "fop"}, "foo/abc", "", false, - [][]byte{[]byte("foo"), []byte("fop")}, 1, + [][]byte{[]byte("foo"), []byte("fop")}, + 1, }, { "delete none [x,x)", []string{"foo"}, "foo", "foo", false, - [][]byte{[]byte("foo")}, 0, + [][]byte{[]byte("foo")}, + 0, }, { "delete middle with preserveKVs set", []string{"foo", "foo/abc", "fop"}, "foo/", "fop", true, - [][]byte{[]byte("foo"), []byte("fop")}, 1, + [][]byte{[]byte("foo"), []byte("fop")}, + 1, }, } @@ -1147,12 +1177,16 @@ func TestV3TxnInvalidRange(t *testing.T) { txn := &pb.TxnRequest{} txn.Success = append(txn.Success, &pb.RequestOp{ Request: &pb.RequestOp_RequestPut{ - RequestPut: preq}}) + RequestPut: preq, + }, + }) rreq := &pb.RangeRequest{Key: []byte("foo"), Revision: 100} txn.Success = append(txn.Success, &pb.RequestOp{ Request: &pb.RequestOp_RequestRange{ - RequestRange: rreq}}) + RequestRange: rreq, + }, + }) if _, err := kvc.Txn(context.TODO(), txn); !eqErrGRPC(err, rpctypes.ErrGRPCFutureRev) { t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCFutureRev) @@ -1717,7 +1751,8 @@ func testTLSReload( cloneFunc func() transport.TLSInfo, replaceFunc func(), revertFunc func(), - useIP bool) { + useIP bool, +) { integration.BeforeTest(t) // 1. separate copies for TLS assets modification diff --git a/tests/integration/v3_kv_test.go b/tests/integration/v3_kv_test.go index 2cf8acf7ab9..eacb821af60 100644 --- a/tests/integration/v3_kv_test.go +++ b/tests/integration/v3_kv_test.go @@ -64,7 +64,7 @@ func TestKVWithEmptyValue(t *testing.T) { t.Log(string(kv.Key), "=", string(kv.Value)) } - //Remove all keys without WithFromKey/WithPrefix func + // Remove all keys without WithFromKey/WithPrefix func _, err = client.Delete(context.Background(), "") if err == nil { // fatal error duo to without WithFromKey/WithPrefix func called. diff --git a/tests/integration/v3_leadership_test.go b/tests/integration/v3_leadership_test.go index aa1cd8ddc9c..2054acbade6 100644 --- a/tests/integration/v3_leadership_test.go +++ b/tests/integration/v3_leadership_test.go @@ -203,7 +203,6 @@ func TestFirstCommitNotification(t *testing.T) { } _, err := oldLeaderClient.MoveLeader(context.Background(), newLeaderID) - if err != nil { t.Errorf("got error during leadership transfer: %v", err) } diff --git a/tests/integration/v3_lease_test.go b/tests/integration/v3_lease_test.go index 2ec93a3ac84..c26d74b8923 100644 --- a/tests/integration/v3_lease_test.go +++ b/tests/integration/v3_lease_test.go @@ -249,7 +249,9 @@ func TestV3LeaseExpire(t *testing.T) { wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo"), StartRevision: 1}}} + Key: []byte("foo"), StartRevision: 1, + }, + }} if err := wStream.Send(wreq); err != nil { return err } diff --git a/tests/integration/v3_watch_restore_test.go b/tests/integration/v3_watch_restore_test.go index f7e2e4b4730..b9b6afccb38 100644 --- a/tests/integration/v3_watch_restore_test.go +++ b/tests/integration/v3_watch_restore_test.go @@ -69,7 +69,8 @@ func TestV3WatchRestoreSnapshotUnsync(t *testing.T) { t.Fatal(errW) } if err := wStream.Send(&pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 5}}}); err != nil { + CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 5}, + }}); err != nil { t.Fatalf("wStream.Send error: %v", err) } wresp, errR := wStream.Recv() diff --git a/tests/integration/v3_watch_test.go b/tests/integration/v3_watch_test.go index e60805b3761..d9bc3e70eab 100644 --- a/tests/integration/v3_watch_test.go +++ b/tests/integration/v3_watch_test.go @@ -54,7 +54,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { []string{"foo"}, &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo")}}}, + Key: []byte("foo"), + }, + }}, []*pb.WatchResponse{ { @@ -74,7 +76,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { []string{"foo"}, &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("helloworld")}}}, + Key: []byte("helloworld"), + }, + }}, []*pb.WatchResponse{}, }, @@ -84,7 +88,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ Key: []byte("foo"), - RangeEnd: []byte("fop")}}}, + RangeEnd: []byte("fop"), + }, + }}, []*pb.WatchResponse{ { @@ -105,7 +111,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ Key: []byte("helloworld"), - RangeEnd: []byte("helloworle")}}}, + RangeEnd: []byte("helloworle"), + }, + }}, []*pb.WatchResponse{}, }, @@ -115,7 +123,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ Key: []byte(""), - RangeEnd: []byte("\x00")}}}, + RangeEnd: []byte("\x00"), + }, + }}, []*pb.WatchResponse{ { @@ -135,7 +145,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { []string{"foo", "foo", "foo"}, &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo")}}}, + Key: []byte("foo"), + }, + }}, []*pb.WatchResponse{ { @@ -176,7 +188,9 @@ func TestV3WatchFromCurrentRevision(t *testing.T) { &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ Key: []byte("foo"), - RangeEnd: []byte("fop")}}}, + RangeEnd: []byte("fop"), + }, + }}, []*pb.WatchResponse{ { @@ -316,7 +330,8 @@ func TestV3WatchFutureRevision(t *testing.T) { wkey := []byte("foo") wrev := int64(10) req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: &pb.WatchCreateRequest{Key: wkey, StartRevision: wrev}}} + CreateRequest: &pb.WatchCreateRequest{Key: wkey, StartRevision: wrev}, + }} err = wStream.Send(req) if err != nil { t.Fatalf("wStream.Send error: %v", err) @@ -385,7 +400,8 @@ func TestV3WatchWrongRange(t *testing.T) { } for i, tt := range tests { if err := wStream.Send(&pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: &pb.WatchCreateRequest{Key: tt.key, RangeEnd: tt.end, StartRevision: 1}}}); err != nil { + CreateRequest: &pb.WatchCreateRequest{Key: tt.key, RangeEnd: tt.end, StartRevision: 1}, + }}); err != nil { t.Fatalf("#%d: wStream.Send error: %v", i, err) } cresp, err := wStream.Recv() @@ -429,7 +445,9 @@ func testV3WatchCancel(t *testing.T, startRev int64) { wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo"), StartRevision: startRev}}} + Key: []byte("foo"), StartRevision: startRev, + }, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("wStream.Send error: %v", err) } @@ -444,7 +462,9 @@ func testV3WatchCancel(t *testing.T, startRev int64) { creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{ CancelRequest: &pb.WatchCancelRequest{ - WatchId: wresp.WatchId}}} + WatchId: wresp.WatchId, + }, + }} if err := wStream.Send(creq); err != nil { t.Fatalf("wStream.Send error: %v", err) } @@ -503,7 +523,8 @@ func TestV3WatchCurrentPutOverlap(t *testing.T) { progress := make(map[int64]int64) wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), RangeEnd: []byte("fop")}}} + CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), RangeEnd: []byte("fop")}, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("first watch request failed (%v)", err) } @@ -570,7 +591,9 @@ func TestV3WatchEmptyKey(t *testing.T) { } req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo")}}} + Key: []byte("foo"), + }, + }} if err := ws.Send(req); err != nil { t.Fatal(err) } @@ -634,11 +657,15 @@ func testV3WatchMultipleWatchers(t *testing.T, startRev int64) { if i < watchKeyN { wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo"), StartRevision: startRev}}} + Key: []byte("foo"), StartRevision: startRev, + }, + }} } else { wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("fo"), RangeEnd: []byte("fp"), StartRevision: startRev}}} + Key: []byte("fo"), RangeEnd: []byte("fp"), StartRevision: startRev, + }, + }} } if err := wStream.Send(wreq); err != nil { t.Fatalf("wStream.Send error: %v", err) @@ -730,7 +757,9 @@ func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) { wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: startRev}}} + Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: startRev, + }, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("wStream.Send error: %v", err) } @@ -744,7 +773,9 @@ func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) { ru := &pb.RequestOp{} ru.Request = &pb.RequestOp_RequestPut{ RequestPut: &pb.PutRequest{ - Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}} + Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar"), + }, + } txn.Success = append(txn.Success, ru) } @@ -822,7 +853,9 @@ func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) { wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: 1}}} + Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: 1, + }, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("wStream.Send error: %v", err) } @@ -1012,7 +1045,9 @@ func testV3WatchMultipleStreams(t *testing.T, startRev int64) { } wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ CreateRequest: &pb.WatchCreateRequest{ - Key: []byte("foo"), StartRevision: startRev}}} + Key: []byte("foo"), StartRevision: startRev, + }, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("wStream.Send error: %v", err) } @@ -1111,12 +1146,14 @@ func TestWatchWithProgressNotify(t *testing.T) { // create two watchers, one with progressNotify set. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1, ProgressNotify: true}}} + CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1, ProgressNotify: true}, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("watch request failed (%v)", err) } wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}}} + CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}, + }} if err := wStream.Send(wreq); err != nil { t.Fatalf("watch request failed (%v)", err) } @@ -1171,7 +1208,9 @@ func TestV3WatchClose(t *testing.T) { cr := &pb.WatchCreateRequest{Key: []byte("a")} req := &pb.WatchRequest{ RequestUnion: &pb.WatchRequest_CreateRequest{ - CreateRequest: cr}} + CreateRequest: cr, + }, + } ws.Send(req) ws.Recv() }() @@ -1199,7 +1238,8 @@ func TestV3WatchWithFilter(t *testing.T) { CreateRequest: &pb.WatchCreateRequest{ Key: []byte("foo"), Filters: []pb.WatchCreateRequest_FilterType{pb.WatchCreateRequest_NOPUT}, - }}} + }, + }} if err := ws.Send(req); err != nil { t.Fatal(err) } @@ -1287,7 +1327,8 @@ func TestV3WatchWithPrevKV(t *testing.T) { Key: []byte(tt.key), RangeEnd: []byte(tt.end), PrevKv: true, - }}} + }, + }} err = ws.Send(req) require.NoError(t, err) _, err = ws.Recv() @@ -1434,7 +1475,7 @@ func TestV3WatchProgressWaitsForSync(t *testing.T) { // Immediately request a progress notification. As the client // is unsynchronised, the server will not sent any notification, - //as client can infer progress from events. + // as client can infer progress from events. err := client.RequestProgress(ctx) require.NoError(t, err) diff --git a/tests/robustness/client/watch.go b/tests/robustness/client/watch.go index ca7ce9f9f9a..c980fdfba05 100644 --- a/tests/robustness/client/watch.go +++ b/tests/robustness/client/watch.go @@ -124,7 +124,7 @@ resetWatch: } func ValidateGotAtLeastOneProgressNotify(t *testing.T, reports []report.ClientReport, expectProgressNotify bool) { - var gotProgressNotify = false + gotProgressNotify := false external: for _, r := range reports { for _, op := range r.Watch { diff --git a/tests/robustness/failpoint/cluster.go b/tests/robustness/failpoint/cluster.go index f756e814b42..58ffd96d8cd 100644 --- a/tests/robustness/failpoint/cluster.go +++ b/tests/robustness/failpoint/cluster.go @@ -35,9 +35,7 @@ import ( "go.etcd.io/etcd/tests/v3/robustness/traffic" ) -var ( - MemberReplace Failpoint = memberReplace{} -) +var MemberReplace Failpoint = memberReplace{} type memberReplace struct{} diff --git a/tests/robustness/failpoint/failpoint.go b/tests/robustness/failpoint/failpoint.go index 235f13debb2..1463b53d85e 100644 --- a/tests/robustness/failpoint/failpoint.go +++ b/tests/robustness/failpoint/failpoint.go @@ -35,25 +35,23 @@ const ( triggerTimeout = time.Minute ) -var ( - allFailpoints = []Failpoint{ - KillFailpoint, BeforeCommitPanic, AfterCommitPanic, RaftBeforeSavePanic, RaftAfterSavePanic, - DefragBeforeCopyPanic, DefragBeforeRenamePanic, BackendBeforePreCommitHookPanic, BackendAfterPreCommitHookPanic, - BackendBeforeStartDBTxnPanic, BackendAfterStartDBTxnPanic, BackendBeforeWritebackBufPanic, - BackendAfterWritebackBufPanic, CompactBeforeCommitScheduledCompactPanic, CompactAfterCommitScheduledCompactPanic, - CompactBeforeSetFinishedCompactPanic, CompactAfterSetFinishedCompactPanic, CompactBeforeCommitBatchPanic, - CompactAfterCommitBatchPanic, RaftBeforeLeaderSendPanic, BlackholePeerNetwork, DelayPeerNetwork, - RaftBeforeFollowerSendPanic, RaftBeforeApplySnapPanic, RaftAfterApplySnapPanic, RaftAfterWALReleasePanic, - RaftBeforeSaveSnapPanic, RaftAfterSaveSnapPanic, BlackholeUntilSnapshot, - BeforeApplyOneConfChangeSleep, - MemberReplace, - DropPeerNetwork, - RaftBeforeSaveSleep, - RaftAfterSaveSleep, - ApplyBeforeOpenSnapshot, - SleepBeforeSendWatchResponse, - } -) +var allFailpoints = []Failpoint{ + KillFailpoint, BeforeCommitPanic, AfterCommitPanic, RaftBeforeSavePanic, RaftAfterSavePanic, + DefragBeforeCopyPanic, DefragBeforeRenamePanic, BackendBeforePreCommitHookPanic, BackendAfterPreCommitHookPanic, + BackendBeforeStartDBTxnPanic, BackendAfterStartDBTxnPanic, BackendBeforeWritebackBufPanic, + BackendAfterWritebackBufPanic, CompactBeforeCommitScheduledCompactPanic, CompactAfterCommitScheduledCompactPanic, + CompactBeforeSetFinishedCompactPanic, CompactAfterSetFinishedCompactPanic, CompactBeforeCommitBatchPanic, + CompactAfterCommitBatchPanic, RaftBeforeLeaderSendPanic, BlackholePeerNetwork, DelayPeerNetwork, + RaftBeforeFollowerSendPanic, RaftBeforeApplySnapPanic, RaftAfterApplySnapPanic, RaftAfterWALReleasePanic, + RaftBeforeSaveSnapPanic, RaftAfterSaveSnapPanic, BlackholeUntilSnapshot, + BeforeApplyOneConfChangeSleep, + MemberReplace, + DropPeerNetwork, + RaftBeforeSaveSleep, + RaftAfterSaveSleep, + ApplyBeforeOpenSnapshot, + SleepBeforeSendWatchResponse, +} func PickRandom(clus *e2e.EtcdProcessCluster, profile traffic.Profile) (Failpoint, error) { availableFailpoints := make([]Failpoint, 0, len(allFailpoints)) diff --git a/tests/robustness/failpoint/kill.go b/tests/robustness/failpoint/kill.go index d046ae580e7..c905019cbf7 100644 --- a/tests/robustness/failpoint/kill.go +++ b/tests/robustness/failpoint/kill.go @@ -30,9 +30,7 @@ import ( "go.etcd.io/etcd/tests/v3/robustness/traffic" ) -var ( - KillFailpoint Failpoint = killFailpoint{} -) +var KillFailpoint Failpoint = killFailpoint{} type killFailpoint struct{} diff --git a/tests/robustness/model/deterministic.go b/tests/robustness/model/deterministic.go index 7a17da11884..6f570ce0825 100644 --- a/tests/robustness/model/deterministic.go +++ b/tests/robustness/model/deterministic.go @@ -181,10 +181,10 @@ func (s EtcdState) Step(request EtcdRequest) (EtcdState, MaybeEtcdResponse) { newState.Leases[request.LeaseGrant.LeaseID] = lease return newState, MaybeEtcdResponse{EtcdResponse: EtcdResponse{Revision: newState.Revision, LeaseGrant: &LeaseGrantReponse{}}} case LeaseRevoke: - //Delete the keys attached to the lease + // Delete the keys attached to the lease keyDeleted := false for key := range newState.Leases[request.LeaseRevoke.LeaseID].Keys { - //same as delete. + // same as delete. if _, ok := newState.KeyValues[key]; ok { if !keyDeleted { keyDeleted = true @@ -193,7 +193,7 @@ func (s EtcdState) Step(request EtcdRequest) (EtcdState, MaybeEtcdResponse) { delete(newState.KeyLeases, key) } } - //delete the lease + // delete the lease delete(newState.Leases, request.LeaseRevoke.LeaseID) if keyDeleted { newState.Revision++ @@ -402,8 +402,10 @@ type RangeResponse struct { type LeaseGrantReponse struct { LeaseID int64 } -type LeaseRevokeResponse struct{} -type DefragmentResponse struct{} +type ( + LeaseRevokeResponse struct{} + DefragmentResponse struct{} +) type EtcdOperationResult struct { RangeResponse @@ -451,8 +453,7 @@ func ToValueOrHash(value string) ValueOrHash { return v } -type CompactResponse struct { -} +type CompactResponse struct{} type CompactRequest struct { Revision int64 diff --git a/tests/robustness/model/history.go b/tests/robustness/model/history.go index fd1b051294c..20ebd1c7cff 100644 --- a/tests/robustness/model/history.go +++ b/tests/robustness/model/history.go @@ -481,7 +481,7 @@ func (h History) Len() int { func (h History) Operations() []porcupine.Operation { operations := make([]porcupine.Operation, 0, len(h.operations)) - var maxTime = h.lastObservedTime() + maxTime := h.lastObservedTime() for _, op := range h.operations { // Failed requests don't have a known return time. if op.Return == -1 { diff --git a/tests/robustness/report/client.go b/tests/robustness/report/client.go index b2ae5a6b261..48d29b8ae81 100644 --- a/tests/robustness/report/client.go +++ b/tests/robustness/report/client.go @@ -53,7 +53,7 @@ func persistClientReports(t *testing.T, lg *zap.Logger, path string, reports []C }) for _, r := range reports { clientDir := filepath.Join(path, fmt.Sprintf("client-%d", r.ClientID)) - err := os.MkdirAll(clientDir, 0700) + err := os.MkdirAll(clientDir, 0o700) require.NoError(t, err) if len(r.Watch) != 0 { persistWatchOperations(t, lg, filepath.Join(clientDir, "watch.json"), r.Watch) @@ -115,7 +115,7 @@ func loadWatchOperations(path string) (operations []model.WatchOperation, err er } return nil, fmt.Errorf("failed to open watch operation file: %q, err: %w", path, err) } - file, err := os.OpenFile(path, os.O_RDONLY, 0755) + file, err := os.OpenFile(path, os.O_RDONLY, 0o755) if err != nil { return nil, fmt.Errorf("failed to open watch operation file: %q, err: %w", path, err) } @@ -140,7 +140,7 @@ func loadKeyValueOperations(path string) (operations []porcupine.Operation, err } return nil, fmt.Errorf("failed to open watch operation file: %q, err: %w", path, err) } - file, err := os.OpenFile(path, os.O_RDONLY, 0755) + file, err := os.OpenFile(path, os.O_RDONLY, 0o755) if err != nil { return nil, fmt.Errorf("failed to open watch operation file: %q, err: %w", path, err) } @@ -171,7 +171,7 @@ func loadKeyValueOperations(path string) (operations []porcupine.Operation, err func persistWatchOperations(t *testing.T, lg *zap.Logger, path string, responses []model.WatchOperation) { lg.Info("Saving watch operations", zap.String("path", path)) - file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755) + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755) if err != nil { t.Errorf("Failed to save watch operations: %v", err) return @@ -188,7 +188,7 @@ func persistWatchOperations(t *testing.T, lg *zap.Logger, path string, responses func persistKeyValueOperations(t *testing.T, lg *zap.Logger, path string, operations []porcupine.Operation) { lg.Info("Saving operation history", zap.String("path", path)) - file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755) + file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755) if err != nil { t.Errorf("Failed to save operation history: %v", err) return diff --git a/tests/robustness/report/report.go b/tests/robustness/report/report.go index 162d2dcb4f8..b3d3d5a5e32 100644 --- a/tests/robustness/report/report.go +++ b/tests/robustness/report/report.go @@ -49,7 +49,7 @@ func testResultsDirectory(t *testing.T) string { require.NoError(t, err) err = os.RemoveAll(path) require.NoError(t, err) - err = os.MkdirAll(path, 0700) + err = os.MkdirAll(path, 0o700) require.NoError(t, err) return path } diff --git a/tests/robustness/traffic/etcd.go b/tests/robustness/traffic/etcd.go index b09c076e6d8..6210ee93d59 100644 --- a/tests/robustness/traffic/etcd.go +++ b/tests/robustness/traffic/etcd.go @@ -255,7 +255,7 @@ func (c etcdTrafficClient) Request(ctx context.Context, request etcdRequestType, if leaseID != 0 { var resp *clientv3.LeaseRevokeResponse resp, err = c.client.LeaseRevoke(opCtx, leaseID) - //if LeaseRevoke has failed, do not remove the mapping. + // if LeaseRevoke has failed, do not remove the mapping. if err == nil { c.leaseStorage.RemoveLeaseID(c.client.ID) } diff --git a/tests/robustness/traffic/kubernetes.go b/tests/robustness/traffic/kubernetes.go index ff0886d54b6..52dfe5cc8f5 100644 --- a/tests/robustness/traffic/kubernetes.go +++ b/tests/robustness/traffic/kubernetes.go @@ -32,19 +32,17 @@ import ( "go.etcd.io/etcd/tests/v3/robustness/random" ) -var ( - Kubernetes Traffic = kubernetesTraffic{ - averageKeyCount: 10, - resource: "pods", - namespace: "default", - // Please keep the sum of weights equal 1000. - writeChoices: []random.ChoiceWeight[KubernetesRequestType]{ - {Choice: KubernetesUpdate, Weight: 90}, - {Choice: KubernetesDelete, Weight: 5}, - {Choice: KubernetesCreate, Weight: 5}, - }, - } -) +var Kubernetes Traffic = kubernetesTraffic{ + averageKeyCount: 10, + resource: "pods", + namespace: "default", + // Please keep the sum of weights equal 1000. + writeChoices: []random.ChoiceWeight[KubernetesRequestType]{ + {Choice: KubernetesUpdate, Weight: 90}, + {Choice: KubernetesDelete, Weight: 5}, + {Choice: KubernetesCreate, Weight: 5}, + }, +} type kubernetesTraffic struct { averageKeyCount int diff --git a/tools/.golangci.yaml b/tools/.golangci.yaml index 39358b0d83d..51ed2a3e894 100644 --- a/tools/.golangci.yaml +++ b/tools/.golangci.yaml @@ -18,7 +18,7 @@ linters: # - deadcode # - structcheck # - varcheck - - gofmt + - gofumpt - goimports - ineffassign - nakedret diff --git a/tools/benchmark/cmd/lease.go b/tools/benchmark/cmd/lease.go index 2b91c35b21f..5ed3dbe4b3e 100644 --- a/tools/benchmark/cmd/lease.go +++ b/tools/benchmark/cmd/lease.go @@ -33,9 +33,7 @@ var leaseKeepaliveCmd = &cobra.Command{ Run: leaseKeepaliveFunc, } -var ( - leaseKeepaliveTotal int -) +var leaseKeepaliveTotal int func init() { RootCmd.AddCommand(leaseKeepaliveCmd) diff --git a/tools/etcd-dump-db/backend.go b/tools/etcd-dump-db/backend.go index 6d64c005b75..2cc8285a679 100644 --- a/tools/etcd-dump-db/backend.go +++ b/tools/etcd-dump-db/backend.go @@ -35,7 +35,7 @@ func snapDir(dataDir string) string { } func getBuckets(dbPath string) (buckets []string, err error) { - db, derr := bolt.Open(dbPath, 0600, &bolt.Options{Timeout: flockTimeout}) + db, derr := bolt.Open(dbPath, 0o600, &bolt.Options{Timeout: flockTimeout}) if derr != nil { return nil, fmt.Errorf("failed to open bolt DB %v", derr) } @@ -132,7 +132,7 @@ func metaDecoder(k, v []byte) { } func iterateBucket(dbPath, bucket string, limit uint64, decode bool) (err error) { - db, err := bolt.Open(dbPath, 0600, &bolt.Options{Timeout: flockTimeout}) + db, err := bolt.Open(dbPath, 0o600, &bolt.Options{Timeout: flockTimeout}) if err != nil { return fmt.Errorf("failed to open bolt DB %v", err) } diff --git a/tools/etcd-dump-db/main.go b/tools/etcd-dump-db/main.go index 89c2f2137e6..6be6d83ac73 100644 --- a/tools/etcd-dump-db/main.go +++ b/tools/etcd-dump-db/main.go @@ -53,9 +53,11 @@ var ( } ) -var flockTimeout time.Duration -var iterateBucketLimit uint64 -var iterateBucketDecode bool +var ( + flockTimeout time.Duration + iterateBucketLimit uint64 + iterateBucketDecode bool +) func init() { rootCommand.PersistentFlags().DurationVar(&flockTimeout, "timeout", 10*time.Second, "time to wait to obtain a file lock on db file, 0 to block indefinitely") diff --git a/tools/etcd-dump-db/page.go b/tools/etcd-dump-db/page.go index 0b6c9c67b19..298bdacadbb 100644 --- a/tools/etcd-dump-db/page.go +++ b/tools/etcd-dump-db/page.go @@ -16,9 +16,11 @@ package main import "unsafe" -const pageHeaderSize = unsafe.Sizeof(page{}) -const leafPageElementSize = unsafe.Sizeof(leafPageElement{}) -const pageMaxAllocSize = 0xFFFFFFF +const ( + pageHeaderSize = unsafe.Sizeof(page{}) + leafPageElementSize = unsafe.Sizeof(leafPageElement{}) + pageMaxAllocSize = 0xFFFFFFF +) const ( leafPageFlag = 0x02 diff --git a/tools/etcd-dump-logs/etcd-dump-log_test.go b/tools/etcd-dump-logs/etcd-dump-log_test.go index c71866c9c64..05af6935ad2 100644 --- a/tools/etcd-dump-logs/etcd-dump-log_test.go +++ b/tools/etcd-dump-logs/etcd-dump-log_test.go @@ -92,7 +92,7 @@ func TestEtcdDumpLogEntryType(t *testing.T) { func mustCreateWALLog(t *testing.T, path string) { memberdir := filepath.Join(path, "member") - err := os.Mkdir(memberdir, 0744) + err := os.Mkdir(memberdir, 0o744) require.NoError(t, err) waldir := walDir(path) snapdir := snapDir(path) @@ -100,7 +100,7 @@ func mustCreateWALLog(t *testing.T, path string) { w, err := wal.Create(zaptest.NewLogger(t), waldir, nil) require.NoError(t, err) - err = os.Mkdir(snapdir, 0744) + err = os.Mkdir(snapdir, 0o744) require.NoError(t, err) ents := make([]raftpb.Entry, 0) @@ -162,11 +162,12 @@ func appendNormalIRREnts(ents *[]raftpb.Entry) { irrdeleterange := &etcdserverpb.DeleteRangeRequest{Key: []byte("0"), RangeEnd: []byte("9"), PrevKv: true} - delInRangeReq := &etcdserverpb.RequestOp{Request: &etcdserverpb.RequestOp_RequestDeleteRange{ - RequestDeleteRange: &etcdserverpb.DeleteRangeRequest{ - Key: []byte("a"), RangeEnd: []byte("b"), + delInRangeReq := &etcdserverpb.RequestOp{ + Request: &etcdserverpb.RequestOp_RequestDeleteRange{ + RequestDeleteRange: &etcdserverpb.DeleteRangeRequest{ + Key: []byte("a"), RangeEnd: []byte("b"), + }, }, - }, } irrtxn := &etcdserverpb.TxnRequest{Success: []*etcdserverpb.RequestOp{delInRangeReq}, Failure: []*etcdserverpb.RequestOp{delInRangeReq}} diff --git a/tools/etcd-dump-logs/main.go b/tools/etcd-dump-logs/main.go index a13669ccc2e..45ceaba1db1 100644 --- a/tools/etcd-dump-logs/main.go +++ b/tools/etcd-dump-logs/main.go @@ -309,7 +309,8 @@ func evaluateEntrytypeFlag(entrytype string) []EntryFilter { entrytypelist = strings.Split(entrytype, ",") } - validRequest := map[string][]EntryFilter{"ConfigChange": {passConfChange}, + validRequest := map[string][]EntryFilter{ + "ConfigChange": {passConfChange}, "Normal": {passInternalRaftRequest, passRequest, passUnknownNormal}, "Request": {passRequest}, "InternalRaftRequest": {passInternalRaftRequest}, @@ -341,10 +342,12 @@ IRRCompaction, IRRLeaseGrant, IRRLeaseRevoke, IRRLeaseCheckpoint`, et) // listEntriesType filters and prints entries based on the entry-type flag, func listEntriesType(entrytype string, streamdecoder string, ents []raftpb.Entry) { entryFilters := evaluateEntrytypeFlag(entrytype) - printerMap := map[string]EntryPrinter{"InternalRaftRequest": printInternalRaftRequest, - "Request": printRequest, - "ConfigChange": printConfChange, - "UnknownNormal": printUnknownNormal} + printerMap := map[string]EntryPrinter{ + "InternalRaftRequest": printInternalRaftRequest, + "Request": printRequest, + "ConfigChange": printConfChange, + "UnknownNormal": printUnknownNormal, + } var stderr strings.Builder args := strings.Split(streamdecoder, " ") cmd := exec.Command(args[0], args[1:]...) diff --git a/tools/local-tester/bridge/bridge.go b/tools/local-tester/bridge/bridge.go index 86d33780508..25ca7e01568 100644 --- a/tools/local-tester/bridge/bridge.go +++ b/tools/local-tester/bridge/bridge.go @@ -186,8 +186,10 @@ type config struct { rxDelay string } -type acceptFaultFunc func() -type connFaultFunc func(*bridgeConn) +type ( + acceptFaultFunc func() + connFaultFunc func(*bridgeConn) +) func main() { var cfg config diff --git a/tools/proto-annotations/cmd/etcd_version.go b/tools/proto-annotations/cmd/etcd_version.go index a7d5a89b660..86766466adb 100644 --- a/tools/proto-annotations/cmd/etcd_version.go +++ b/tools/proto-annotations/cmd/etcd_version.go @@ -27,19 +27,17 @@ import ( "go.etcd.io/etcd/server/v3/storage/wal" ) -var ( - // externalPackages that are not expected to have etcd version annotation. - externalPackages = []string{ - "io.prometheus.client", - "grpc.binarylog.v1", - "google.protobuf", - "google.rpc", - "google.api", - "raftpb", - "grpc.gateway.protoc_gen_swagger.options", - "grpc.gateway.protoc_gen_openapiv2.options", - } -) +// externalPackages that are not expected to have etcd version annotation. +var externalPackages = []string{ + "io.prometheus.client", + "grpc.binarylog.v1", + "google.protobuf", + "google.rpc", + "google.api", + "raftpb", + "grpc.gateway.protoc_gen_swagger.options", + "grpc.gateway.protoc_gen_openapiv2.options", +} // printEtcdVersion writes etcd_version proto annotation to stdout and returns any errors encountered when reading annotation. func printEtcdVersion() []error {