diff --git a/Dockerfile b/Dockerfile index edd41b1c86459..cc9ae08ad600b 100644 --- a/Dockerfile +++ b/Dockerfile @@ -176,8 +176,8 @@ COPY hack/dockerfile/install/install.sh ./install.sh COPY hack/dockerfile/install/$INSTALL_BINARY_NAME.installer ./ RUN PREFIX=/build ./install.sh $INSTALL_BINARY_NAME -FROM base AS gometalinter -ENV INSTALL_BINARY_NAME=gometalinter +FROM base AS golangci_lint +ENV INSTALL_BINARY_NAME=golangci_lint COPY hack/dockerfile/install/install.sh ./install.sh COPY hack/dockerfile/install/$INSTALL_BINARY_NAME.installer ./ RUN PREFIX=/build ./install.sh $INSTALL_BINARY_NAME @@ -265,7 +265,7 @@ RUN pip3 install yamllint==1.16.0 COPY --from=swagger /build/swagger* /usr/local/bin/ COPY --from=frozen-images /build/ /docker-frozen-images -COPY --from=gometalinter /build/ /usr/local/bin/ +COPY --from=golangci_lint /build/ /usr/local/bin/ COPY --from=gotestsum /build/ /usr/local/bin/ COPY --from=tomlv /build/ /usr/local/bin/ COPY --from=vndr /build/ /usr/local/bin/ diff --git a/api/server/httputils/httputils.go b/api/server/httputils/httputils.go index d344562cf7aeb..accbb06eb3235 100644 --- a/api/server/httputils/httputils.go +++ b/api/server/httputils/httputils.go @@ -31,7 +31,7 @@ func HijackConnection(w http.ResponseWriter) (io.ReadCloser, io.Writer, error) { return nil, nil, err } // Flush the options to make sure the client sets the raw mode - conn.Write([]byte{}) + _, _ = conn.Write([]byte{}) return conn, conn, nil } @@ -41,9 +41,9 @@ func CloseStreams(streams ...interface{}) { if tcpc, ok := stream.(interface { CloseWrite() error }); ok { - tcpc.CloseWrite() + _ = tcpc.CloseWrite() } else if closer, ok := stream.(io.Closer); ok { - closer.Close() + _ = closer.Close() } } } @@ -102,7 +102,7 @@ func MakeErrorHandler(err error) http.HandlerFunc { response := &types.ErrorResponse{ Message: err.Error(), } - WriteJSON(w, statusCode, response) + _ = WriteJSON(w, statusCode, response) } else { http.Error(w, status.Convert(err).Message(), statusCode) } diff --git a/api/server/httputils/write_log_stream.go b/api/server/httputils/write_log_stream.go index 9e769c8b4d583..22be5bb1c3364 100644 --- a/api/server/httputils/write_log_stream.go +++ b/api/server/httputils/write_log_stream.go @@ -51,10 +51,10 @@ func WriteLogStream(_ context.Context, w io.Writer, msgs <-chan *backend.LogMess logLine = append([]byte(msg.Timestamp.Format(jsonmessage.RFC3339NanoFixed)+" "), logLine...) } if msg.Source == "stdout" && config.ShowStdout { - outStream.Write(logLine) + _, _ = outStream.Write(logLine) } if msg.Source == "stderr" && config.ShowStderr { - errStream.Write(logLine) + _, _ = errStream.Write(logLine) } } } diff --git a/api/server/router/build/build_routes.go b/api/server/router/build/build_routes.go index 57d9fc8c46d9b..fb67534af2a4b 100644 --- a/api/server/router/build/build_routes.go +++ b/api/server/router/build/build_routes.go @@ -176,7 +176,7 @@ func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r * if err := httputils.ParseForm(r); err != nil { return err } - filters, err := filters.FromJSON(r.Form.Get("filters")) + fltrs, err := filters.FromJSON(r.Form.Get("filters")) if err != nil { return errors.Wrap(err, "could not parse filters") } @@ -191,7 +191,7 @@ func (br *buildRouter) postPrune(ctx context.Context, w http.ResponseWriter, r * opts := types.BuildCachePruneOptions{ All: httputils.BoolValue(r, "all"), - Filters: filters, + Filters: fltrs, KeepStorage: int64(ks), } @@ -234,12 +234,12 @@ func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * } output := ioutils.NewWriteFlusher(ww) - defer output.Close() + defer func() { _ = output.Close() }() errf := func(err error) error { if httputils.BoolValue(r, "q") && notVerboseBuffer.Len() > 0 { - output.Write(notVerboseBuffer.Bytes()) + _, _ = output.Write(notVerboseBuffer.Bytes()) } // Do not write the error in the http output if it's still empty. @@ -290,7 +290,7 @@ func (br *buildRouter) postBuild(ctx context.Context, w http.ResponseWriter, r * // Everything worked so if -q was provided the output from the daemon // should be just the image ID and we'll print that to stdout. if buildOptions.SuppressOutput { - fmt.Fprintln(streamformatter.NewStdoutWriter(output), imgID) + _, _ = fmt.Fprintln(streamformatter.NewStdoutWriter(output), imgID) } return nil } @@ -306,7 +306,7 @@ func getAuthConfigs(header http.Header) map[string]types.AuthConfig { authConfigsJSON := base64.NewDecoder(base64.URLEncoding, strings.NewReader(authConfigsEncoded)) // Pulling an image does not error when no auth is provided so to remain // consistent with the existing api decode errors are ignored - json.NewDecoder(authConfigsJSON).Decode(&authConfigs) + _ = json.NewDecoder(authConfigsJSON).Decode(&authConfigs) return authConfigs } @@ -428,7 +428,7 @@ func (w *wcf) notify() { w.mu.Lock() if !w.ready { if w.buf.Len() > 0 { - io.Copy(w.Writer, w.buf) + _, _ = io.Copy(w.Writer, w.buf) } if w.flushed { w.flusher.Flush() diff --git a/api/server/router/distribution/distribution_routes.go b/api/server/router/distribution/distribution_routes.go index d285728382772..6e5ee2d80c8fe 100644 --- a/api/server/router/distribution/distribution_routes.go +++ b/api/server/router/distribution/distribution_routes.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/api/types" registrytypes "github.com/docker/docker/api/types/registry" "github.com/docker/docker/errdefs" - "github.com/opencontainers/image-spec/specs-go/v1" + v1 "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" ) diff --git a/api/server/router/image/image_routes.go b/api/server/router/image/image_routes.go index 41994bbef9d4d..1f7d81adfaf72 100644 --- a/api/server/router/image/image_routes.go +++ b/api/server/router/image/image_routes.go @@ -91,7 +91,7 @@ func (s *imageRouter) postImagesCreate(ctx context.Context, w http.ResponseWrite if !output.Flushed() { return err } - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil @@ -136,7 +136,7 @@ func (s *imageRouter) postImagesPush(ctx context.Context, w http.ResponseWriter, if !output.Flushed() { return err } - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil } @@ -161,7 +161,7 @@ func (s *imageRouter) getImagesGet(ctx context.Context, w http.ResponseWriter, r if !output.Flushed() { return err } - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil } @@ -177,7 +177,7 @@ func (s *imageRouter) postImagesLoad(ctx context.Context, w http.ResponseWriter, output := ioutils.NewWriteFlusher(w) defer output.Close() if err := s.backend.LoadImage(r.Body, output, quiet); err != nil { - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil } diff --git a/api/server/router/plugin/plugin_routes.go b/api/server/router/plugin/plugin_routes.go index 9508ca8c9d673..31b2c30215319 100644 --- a/api/server/router/plugin/plugin_routes.go +++ b/api/server/router/plugin/plugin_routes.go @@ -123,7 +123,7 @@ func (pr *pluginRouter) upgradePlugin(ctx context.Context, w http.ResponseWriter if !output.Flushed() { return err } - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil @@ -162,7 +162,7 @@ func (pr *pluginRouter) pullPlugin(ctx context.Context, w http.ResponseWriter, r if !output.Flushed() { return err } - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil @@ -270,7 +270,7 @@ func (pr *pluginRouter) pushPlugin(ctx context.Context, w http.ResponseWriter, r if !output.Flushed() { return err } - output.Write(streamformatter.FormatError(err)) + _, _ = output.Write(streamformatter.FormatError(err)) } return nil } diff --git a/api/server/router/system/system.go b/api/server/router/system/system.go index 459ee50bf762e..4c3c039f04542 100644 --- a/api/server/router/system/system.go +++ b/api/server/router/system/system.go @@ -2,7 +2,7 @@ package system // import "github.com/docker/docker/api/server/router/system" import ( "github.com/docker/docker/api/server/router" - "github.com/docker/docker/builder/builder-next" + buildkit "github.com/docker/docker/builder/builder-next" "github.com/docker/docker/builder/fscache" ) diff --git a/api/types/container/host_config.go b/api/types/container/host_config.go index 654c88106c684..209f33eb91768 100644 --- a/api/types/container/host_config.go +++ b/api/types/container/host_config.go @@ -7,7 +7,7 @@ import ( "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/strslice" "github.com/docker/go-connections/nat" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) // CgroupnsMode represents the cgroup namespace mode of the container diff --git a/api/types/filters/parse.go b/api/types/filters/parse.go index 1f75403f78da7..2e24e769c10ea 100644 --- a/api/types/filters/parse.go +++ b/api/types/filters/parse.go @@ -57,7 +57,7 @@ func ToJSON(a Args) (string, error) { // then the encoded format will use an older legacy format where the values are a // list of strings, instead of a set. // -// Deprecated: Use ToJSON +// Deprecated: do not use in any new code; use ToJSON instead func ToParamWithVersion(version string, a Args) (string, error) { if a.Len() == 0 { return "", nil diff --git a/api/types/filters/parse_test.go b/api/types/filters/parse_test.go index 6bca7d87218a4..aadea040d8d37 100644 --- a/api/types/filters/parse_test.go +++ b/api/types/filters/parse_test.go @@ -337,14 +337,17 @@ func TestWalkValues(t *testing.T) { f.Add("status", "running") f.Add("status", "paused") - f.WalkValues("status", func(value string) error { + err := f.WalkValues("status", func(value string) error { if value != "running" && value != "paused" { t.Fatalf("Unexpected value %s", value) } return nil }) + if err != nil { + t.Fatalf("Expected no error, got %v", err) + } - err := f.WalkValues("status", func(value string) error { + err = f.WalkValues("status", func(value string) error { return errors.New("return") }) if err == nil { diff --git a/api/types/registry/registry.go b/api/types/registry/registry.go index 8789ad3b32101..53e47084c8d5e 100644 --- a/api/types/registry/registry.go +++ b/api/types/registry/registry.go @@ -4,7 +4,7 @@ import ( "encoding/json" "net" - "github.com/opencontainers/image-spec/specs-go/v1" + v1 "github.com/opencontainers/image-spec/specs-go/v1" ) // ServiceConfig stores daemon registry services configuration. diff --git a/builder/builder-next/adapters/containerimage/pull.go b/builder/builder-next/adapters/containerimage/pull.go index 729ef52ae8653..43b84919c7f07 100644 --- a/builder/builder-next/adapters/containerimage/pull.go +++ b/builder/builder-next/adapters/containerimage/pull.go @@ -37,7 +37,7 @@ import ( "github.com/moby/buildkit/util/progress" "github.com/moby/buildkit/util/resolver" "github.com/moby/buildkit/util/tracing" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/opencontainers/image-spec/identity" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" @@ -275,7 +275,7 @@ func (p *puller) resolve(ctx context.Context) error { ref, err := distreference.ParseNormalizedNamed(p.src.Reference.String()) if err != nil { p.resolveErr = err - resolveProgressDone(err) + _ = resolveProgressDone(err) return } @@ -283,7 +283,7 @@ func (p *puller) resolve(ctx context.Context) error { origRef, desc, err := p.resolver.Resolve(ctx, ref.String()) if err != nil { p.resolveErr = err - resolveProgressDone(err) + _ = resolveProgressDone(err) return } @@ -300,19 +300,19 @@ func (p *puller) resolve(ctx context.Context) error { ref, err := distreference.WithDigest(ref, p.desc.Digest) if err != nil { p.resolveErr = err - resolveProgressDone(err) + _ = resolveProgressDone(err) return } _, dt, err := p.is.ResolveImageConfig(ctx, ref.String(), gw.ResolveImageConfigOpt{Platform: &p.platform, ResolveMode: resolveModeToString(p.src.ResolveMode)}, p.sm) if err != nil { p.resolveErr = err - resolveProgressDone(err) + _ = resolveProgressDone(err) return } p.config = dt } - resolveProgressDone(nil) + _ = resolveProgressDone(nil) }) return p.resolveErr } @@ -509,7 +509,7 @@ func (p *puller) Snapshot(ctx context.Context) (cache.ImmutableRef, error) { tm := time.Now() end = &tm } - pw.Write("extracting "+p.ID, progress.Status{ + _ = pw.Write("extracting "+p.ID, progress.Status{ Action: "extract", Started: &st.st, Completed: end, @@ -672,7 +672,7 @@ func showProgress(ctx context.Context, ongoing *jobs, cs content.Store, pw progr refKey := remotes.MakeRefKey(ctx, j.Descriptor) if a, ok := actives[refKey]; ok { started := j.started - pw.Write(j.Digest.String(), progress.Status{ + _ = pw.Write(j.Digest.String(), progress.Status{ Action: a.Status, Total: int(a.Total), Current: int(a.Offset), @@ -685,7 +685,7 @@ func showProgress(ctx context.Context, ongoing *jobs, cs content.Store, pw progr info, err := cs.Info(context.TODO(), j.Digest) if err != nil { if containerderrors.IsNotFound(err) { - // pw.Write(j.Digest.String(), progress.Status{ + // _ = pw.Write(j.Digest.String(), progress.Status{ // Action: "waiting", // }) continue @@ -697,7 +697,7 @@ func showProgress(ctx context.Context, ongoing *jobs, cs content.Store, pw progr if done || j.done { started := j.started createdAt := info.CreatedAt - pw.Write(j.Digest.String(), progress.Status{ + _ = pw.Write(j.Digest.String(), progress.Status{ Action: "done", Current: int(info.Size), Total: int(info.Size), @@ -783,13 +783,13 @@ func oneOffProgress(ctx context.Context, id string) func(err error) error { st := progress.Status{ Started: &now, } - pw.Write(id, st) + _ = pw.Write(id, st) return func(err error) error { // TODO: set error on status now := time.Now() st.Completed = &now - pw.Write(id, st) - pw.Close() + _ = pw.Write(id, st) + _ = pw.Close() return err } } diff --git a/builder/builder-next/exporter/export.go b/builder/builder-next/exporter/export.go index d82a6a5635752..4e0ba0214a03a 100644 --- a/builder/builder-next/exporter/export.go +++ b/builder/builder-next/exporter/export.go @@ -130,7 +130,7 @@ func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source) diffs[i] = digest.Digest(diffIDs[i]) } - layersDone(nil) + _ = layersDone(nil) } if len(config) == 0 { @@ -160,7 +160,7 @@ func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source) if err != nil { return nil, configDone(err) } - configDone(nil) + _ = configDone(nil) if e.opt.ReferenceStore != nil { for _, targetName := range e.targetNames { @@ -169,7 +169,7 @@ func (e *imageExporterInstance) Export(ctx context.Context, inp exporter.Source) if err := e.opt.ReferenceStore.AddTag(targetName, digest.Digest(id), true); err != nil { return nil, tagDone(err) } - tagDone(nil) + _ = tagDone(nil) } } diff --git a/builder/builder-next/exporter/writer.go b/builder/builder-next/exporter/writer.go index b0f51c6ff577a..64d260f230ec3 100644 --- a/builder/builder-next/exporter/writer.go +++ b/builder/builder-next/exporter/writer.go @@ -78,9 +78,9 @@ func patchImageConfig(dt []byte, dps []digest.Digest, history []ocispec.History, } if cache != nil { - dt, err := json.Marshal(cache) + dt, err = json.Marshal(cache) if err != nil { - return nil, err + return nil, errors.Wrap(err, "failed to marshal cache") } m["moby.buildkit.cache.v0"] = dt } @@ -204,13 +204,13 @@ func oneOffProgress(ctx context.Context, id string) func(err error) error { st := progress.Status{ Started: &now, } - pw.Write(id, st) + _ = pw.Write(id, st) return func(err error) error { // TODO: set error on status now := time.Now() st.Completed = &now - pw.Write(id, st) - pw.Close() + _ = pw.Write(id, st) + _ = pw.Close() return err } } diff --git a/builder/builder-next/worker/worker.go b/builder/builder-next/worker/worker.go index 40d9a2e23fd21..a47ded37f41e3 100644 --- a/builder/builder-next/worker/worker.go +++ b/builder/builder-next/worker/worker.go @@ -394,7 +394,7 @@ func (ld *layerDescriptor) Download(ctx context.Context, progressOutput pkgprogr if err := contentutil.Copy(ctx, ld.w.ContentStore, ld.provider, ld.desc); err != nil { return nil, 0, done(err) } - done(nil) + _ = done(nil) ra, err := ld.w.ContentStore.ReaderAt(ctx, ld.desc) if err != nil { @@ -443,13 +443,13 @@ func oneOffProgress(ctx context.Context, id string) func(err error) error { st := progress.Status{ Started: &now, } - pw.Write(id, st) + _ = pw.Write(id, st) return func(err error) error { // TODO: set error on status now := time.Now() st.Completed = &now - pw.Write(id, st) - pw.Close() + _ = pw.Write(id, st) + _ = pw.Close() return err } } diff --git a/builder/dockerfile/copy_unix.go b/builder/dockerfile/copy_unix.go index 770226444545a..d2a16e022087a 100644 --- a/builder/dockerfile/copy_unix.go +++ b/builder/dockerfile/copy_unix.go @@ -25,7 +25,7 @@ func fixPermissions(source, destination string, identity idtools.Identity, overr // We Walk on the source rather than on the destination because we don't // want to change permissions on things we haven't created or modified. - return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error { + return filepath.Walk(source, func(fullpath string, _ os.FileInfo, _ error) error { // Do not alter the walk root iff. it existed before, as it doesn't fall under // the domain of "things we should chown". if skipChownRoot && source == fullpath { diff --git a/builder/dockerfile/copy_windows.go b/builder/dockerfile/copy_windows.go index 59c1a4b7c37bb..82e801ae4ce86 100644 --- a/builder/dockerfile/copy_windows.go +++ b/builder/dockerfile/copy_windows.go @@ -6,7 +6,7 @@ import ( "path/filepath" "strings" - "github.com/Microsoft/go-winio" + winio "github.com/Microsoft/go-winio" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/reexec" "github.com/docker/docker/pkg/system" diff --git a/builder/dockerfile/imagecontext.go b/builder/dockerfile/imagecontext.go index 08cb396a2bdfb..6e5ddb9bc2edd 100644 --- a/builder/dockerfile/imagecontext.go +++ b/builder/dockerfile/imagecontext.go @@ -88,9 +88,8 @@ func (m *imageSources) Add(im *imageMount) { // imageMount is a reference to an image that can be used as a builder.Source type imageMount struct { - image builder.Image - source builder.Source - layer builder.ROLayer + image builder.Image + layer builder.ROLayer } func newImageMount(image builder.Image, layer builder.ROLayer) *imageMount { diff --git a/builder/dockerfile/metrics.go b/builder/dockerfile/metrics.go index ceafa7ad629e5..eb5b5562f3742 100644 --- a/builder/dockerfile/metrics.go +++ b/builder/dockerfile/metrics.go @@ -1,7 +1,7 @@ package dockerfile // import "github.com/docker/docker/builder/dockerfile" import ( - "github.com/docker/go-metrics" + metrics "github.com/docker/go-metrics" ) var ( diff --git a/builder/fscache/fscache.go b/builder/fscache/fscache.go index 8897fe16d89bf..4c3b9a6cd5643 100644 --- a/builder/fscache/fscache.go +++ b/builder/fscache/fscache.go @@ -497,6 +497,7 @@ type sourceMeta struct { Size int64 } +//nolint:structcheck type cachedSource struct { sourceMeta refs map[*cachedSourceRef]struct{} diff --git a/builder/remotecontext/git/gitutils.go b/builder/remotecontext/git/gitutils.go index 6213963db2e11..cfcf6487250f2 100644 --- a/builder/remotecontext/git/gitutils.go +++ b/builder/remotecontext/git/gitutils.go @@ -142,9 +142,9 @@ func supportsShallowClone(remoteURL string) bool { serviceURL := remoteURL + "/info/refs?service=git-upload-pack" // Try a HEAD request and fallback to a Get request on error - res, err := http.Head(serviceURL) + res, err := http.Head(serviceURL) // #nosec G107 if err != nil || res.StatusCode != http.StatusOK { - res, err = http.Get(serviceURL) + res, err = http.Get(serviceURL) // #nosec G107 if err == nil { res.Body.Close() } diff --git a/builder/remotecontext/remote.go b/builder/remotecontext/remote.go index 1fb80549b8b26..8047494c9d87b 100644 --- a/builder/remotecontext/remote.go +++ b/builder/remotecontext/remote.go @@ -45,6 +45,7 @@ func downloadRemote(remoteURL string) (string, io.ReadCloser, error) { // GetWithStatusError does an http.Get() and returns an error if the // status code is 4xx or 5xx. func GetWithStatusError(address string) (resp *http.Response, err error) { + // #nosec G107 if resp, err = http.Get(address); err != nil { if uerr, ok := err.(*url.Error); ok { if derr, ok := uerr.Err.(*net.DNSError); ok && !derr.IsTimeout { diff --git a/builder/remotecontext/tarsum.go b/builder/remotecontext/tarsum.go index b809cfb78b4f8..9e8c7d6072bde 100644 --- a/builder/remotecontext/tarsum.go +++ b/builder/remotecontext/tarsum.go @@ -6,7 +6,7 @@ import ( "github.com/docker/docker/pkg/containerfs" iradix "github.com/hashicorp/go-immutable-radix" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/tonistiigi/fsutil" ) diff --git a/client/container_list.go b/client/container_list.go index 1e7a63a9c0665..c099d80e2a24e 100644 --- a/client/container_list.go +++ b/client/container_list.go @@ -35,6 +35,7 @@ func (cli *Client) ContainerList(ctx context.Context, options types.ContainerLis } if options.Filters.Len() > 0 { + //lint:ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) if err != nil { diff --git a/client/events.go b/client/events.go index 6e56538955ee6..f347cadf1450d 100644 --- a/client/events.go +++ b/client/events.go @@ -90,6 +90,7 @@ func buildEventsQueryParams(cliVersion string, options types.EventsOptions) (url } if options.Filters.Len() > 0 { + //lint:ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cliVersion, options.Filters) if err != nil { return nil, err diff --git a/client/hijack.go b/client/hijack.go index e9c9a752f83fe..e77084af64d78 100644 --- a/client/hijack.go +++ b/client/hijack.go @@ -87,6 +87,8 @@ func (cli *Client) setupHijackConn(ctx context.Context, req *http.Request, proto // Server hijacks the connection, error 'connection closed' expected resp, err := clientconn.Do(req) + + //lint:ignore SA1019 for connecting to old (pre go1.8) daemons if err != httputil.ErrPersistEOF { if err != nil { return nil, err diff --git a/client/image_build_test.go b/client/image_build_test.go index 6cc14145ac10c..353bc12eb1577 100644 --- a/client/image_build_test.go +++ b/client/image_build_test.go @@ -13,7 +13,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/errdefs" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) func TestImageBuildError(t *testing.T) { diff --git a/client/image_list.go b/client/image_list.go index 4fa8c006b2ea9..a5bc4b095f7ba 100644 --- a/client/image_list.go +++ b/client/image_list.go @@ -24,6 +24,7 @@ func (cli *Client) ImageList(ctx context.Context, options types.ImageListOptions } } if optionFilters.Len() > 0 { + //lint:ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cli.version, optionFilters) if err != nil { return images, err diff --git a/client/network_list.go b/client/network_list.go index 7130c1364eb28..8ca7eb6128e6c 100644 --- a/client/network_list.go +++ b/client/network_list.go @@ -13,6 +13,7 @@ import ( func (cli *Client) NetworkList(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) { query := url.Values{} if options.Filters.Len() > 0 { + //lint:ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cli.version, options.Filters) if err != nil { return nil, err diff --git a/client/plugin_list.go b/client/plugin_list.go index 8285cecd6e176..a51c930e6d53c 100644 --- a/client/plugin_list.go +++ b/client/plugin_list.go @@ -15,6 +15,7 @@ func (cli *Client) PluginList(ctx context.Context, filter filters.Args) (types.P query := url.Values{} if filter.Len() > 0 { + //lint:ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cli.version, filter) if err != nil { return plugins, err diff --git a/client/request.go b/client/request.go index 2610338da616f..144c4163695d3 100644 --- a/client/request.go +++ b/client/request.go @@ -50,15 +50,6 @@ func (cli *Client) postRaw(ctx context.Context, path string, query url.Values, b return cli.sendRequest(ctx, "POST", path, query, body, headers) } -// put sends an http request to the docker API using the method PUT. -func (cli *Client) put(ctx context.Context, path string, query url.Values, obj interface{}, headers map[string][]string) (serverResponse, error) { - body, headers, err := encodeBody(obj, headers) - if err != nil { - return serverResponse{}, err - } - return cli.sendRequest(ctx, "PUT", path, query, body, headers) -} - // putRaw sends an http request to the docker API using the method PUT. func (cli *Client) putRaw(ctx context.Context, path string, query url.Values, body io.Reader, headers map[string][]string) (serverResponse, error) { return cli.sendRequest(ctx, "PUT", path, query, body, headers) diff --git a/client/service_create.go b/client/service_create.go index 620fc6cff7579..56bfe55b71018 100644 --- a/client/service_create.go +++ b/client/service_create.go @@ -9,7 +9,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" ) diff --git a/client/service_create_test.go b/client/service_create_test.go index df836ae2af1bd..ef792a38e2f9e 100644 --- a/client/service_create_test.go +++ b/client/service_create_test.go @@ -14,8 +14,8 @@ import ( registrytypes "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/errdefs" - "github.com/opencontainers/go-digest" - "github.com/opencontainers/image-spec/specs-go/v1" + digest "github.com/opencontainers/go-digest" + v1 "github.com/opencontainers/image-spec/specs-go/v1" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) diff --git a/client/volume_list.go b/client/volume_list.go index 2380d56382150..d68fc2b9860de 100644 --- a/client/volume_list.go +++ b/client/volume_list.go @@ -15,6 +15,7 @@ func (cli *Client) VolumeList(ctx context.Context, filter filters.Args) (volumet query := url.Values{} if filter.Len() > 0 { + //lint:ignore SA1019 for old code filterJSON, err := filters.ToParamWithVersion(cli.version, filter) if err != nil { return volumes, err diff --git a/cmd/dockerd/config.go b/cmd/dockerd/config.go index c6c6b8a7a1c73..baf672cbf7ee2 100644 --- a/cmd/dockerd/config.go +++ b/cmd/dockerd/config.go @@ -47,12 +47,12 @@ func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { // "--graph" is "soft-deprecated" in favor of "data-root". This flag was added // before Docker 1.0, so won't be removed, only hidden, to discourage its usage. - flags.MarkHidden("graph") + _ = flags.MarkHidden("graph") flags.StringVar(&conf.Root, "data-root", defaultDataRoot, "Root directory of persistent Docker state") flags.BoolVarP(&conf.AutoRestart, "restart", "r", true, "--restart on the daemon has been deprecated in favor of --restart policies on docker run") - flags.MarkDeprecated("restart", "Please use a restart policy on docker run") + _ = flags.MarkDeprecated("restart", "Please use a restart policy on docker run") // Windows doesn't support setting the storage driver - there is no choice as to which ones to use. if runtime.GOOS != "windows" { @@ -75,7 +75,7 @@ func installCommonConfigFlags(conf *config.Config, flags *pflag.FlagSet) error { flags.IntVar(&maxConcurrentUploads, "max-concurrent-uploads", config.DefaultMaxConcurrentUploads, "Set the max concurrent uploads for each push") flags.IntVar(&conf.ShutdownTimeout, "shutdown-timeout", defaultShutdownTimeout, "Set the default shutdown timeout") flags.IntVar(&conf.NetworkDiagnosticPort, "network-diagnostic-port", 0, "TCP port number of the network diagnostic server") - flags.MarkHidden("network-diagnostic-port") + _ = flags.MarkHidden("network-diagnostic-port") flags.StringVar(&conf.SwarmDefaultAdvertiseAddr, "swarm-default-advertise-addr", "", "Set default address or interface for swarm advertised address") flags.BoolVar(&conf.Experimental, "experimental", false, "Enable experimental features") diff --git a/cmd/dockerd/config_unix.go b/cmd/dockerd/config_unix.go index 4be15b329af3d..1817c1da271d9 100644 --- a/cmd/dockerd/config_unix.go +++ b/cmd/dockerd/config_unix.go @@ -8,7 +8,7 @@ import ( "github.com/docker/docker/daemon/config" "github.com/docker/docker/opts" "github.com/docker/docker/rootless" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/pkg/errors" "github.com/spf13/pflag" ) diff --git a/cmd/dockerd/metrics.go b/cmd/dockerd/metrics.go index 1bfa37ea824a5..2b3c90578ea69 100644 --- a/cmd/dockerd/metrics.go +++ b/cmd/dockerd/metrics.go @@ -4,7 +4,7 @@ import ( "net" "net/http" - "github.com/docker/go-metrics" + metrics "github.com/docker/go-metrics" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/cmd/dockerd/service_windows.go b/cmd/dockerd/service_windows.go index 07977d95c9069..83218e4815654 100644 --- a/cmd/dockerd/service_windows.go +++ b/cmd/dockerd/service_windows.go @@ -52,7 +52,7 @@ func installServiceFlags(flags *pflag.FlagSet) { flRegisterService = flags.Bool("register-service", false, "Register the service and exit") flUnregisterService = flags.Bool("unregister-service", false, "Unregister the service and exit") flRunService = flags.Bool("run-service", false, "") - flags.MarkHidden("run-service") + _ = flags.MarkHidden("run-service") } type handler struct { diff --git a/container/container.go b/container/container.go index 71a8a1b42c825..031ee974dcbeb 100644 --- a/container/container.go +++ b/container/container.go @@ -36,7 +36,7 @@ import ( "github.com/docker/docker/restartmanager" "github.com/docker/docker/volume" volumemounts "github.com/docker/docker/volume/mounts" - "github.com/docker/go-units" + units "github.com/docker/go-units" agentexec "github.com/docker/swarmkit/agent/exec" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/container/state.go b/container/state.go index 59eafc9171748..11f8e4828398c 100644 --- a/container/state.go +++ b/container/state.go @@ -8,7 +8,7 @@ import ( "time" "github.com/docker/docker/api/types" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) // State holds the current container state, and has methods to get and diff --git a/container/view.go b/container/view.go index aabb01923d876..962a20b9e1cd6 100644 --- a/container/view.go +++ b/container/view.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/network" "github.com/docker/go-connections/nat" - "github.com/hashicorp/go-memdb" + memdb "github.com/hashicorp/go-memdb" "github.com/sirupsen/logrus" ) diff --git a/contrib/docker-device-tool/device_tool.go b/contrib/docker-device-tool/device_tool.go index d3ec46a8b4d2d..b256a3669bb7e 100644 --- a/contrib/docker-device-tool/device_tool.go +++ b/contrib/docker-device-tool/device_tool.go @@ -38,7 +38,7 @@ func byteSizeFromString(arg string) (int64, error) { rest = strings.ToLower(strings.TrimSpace(rest)) - var multiplier int64 = 1 + var multiplier int64 switch rest { case "": multiplier = 1 diff --git a/daemon/checkpoint.go b/daemon/checkpoint.go index 1c850b335b7d9..3ec581e5fcd25 100644 --- a/daemon/checkpoint.go +++ b/daemon/checkpoint.go @@ -35,16 +35,16 @@ func getCheckpointDir(checkDir, checkpointID, ctrName, ctrID, ctrCheckpointDir s err2 = os.MkdirAll(checkpointAbsDir, 0700) case err != nil: err2 = err - case err == nil: + default: err2 = fmt.Errorf("%s exists and is not a directory", checkpointAbsDir) } } else { switch { case err != nil: err2 = fmt.Errorf("checkpoint %s does not exist for container %s", checkpointID, ctrName) - case err == nil && stat.IsDir(): + case stat.IsDir(): err2 = nil - case err == nil: + default: err2 = fmt.Errorf("%s exists and is not a directory", checkpointAbsDir) } } diff --git a/daemon/cluster/controllers/plugin/controller.go b/daemon/cluster/controllers/plugin/controller.go index f10747e39af28..bad3d7243e701 100644 --- a/daemon/cluster/controllers/plugin/controller.go +++ b/daemon/cluster/controllers/plugin/controller.go @@ -11,7 +11,7 @@ import ( "github.com/docker/docker/api/types/swarm/runtime" "github.com/docker/docker/errdefs" "github.com/docker/docker/plugin" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" "github.com/docker/swarmkit/api" "github.com/gogo/protobuf/proto" "github.com/pkg/errors" @@ -34,7 +34,6 @@ type Controller struct { pluginID string serviceID string - taskID string // hook used to signal tests that `Wait()` is actually ready and waiting signalWaitReady func() diff --git a/daemon/cluster/controllers/plugin/controller_test.go b/daemon/cluster/controllers/plugin/controller_test.go index 8329d44766d18..0611d59d9c6a8 100644 --- a/daemon/cluster/controllers/plugin/controller_test.go +++ b/daemon/cluster/controllers/plugin/controller_test.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/api/types/swarm/runtime" "github.com/docker/docker/pkg/pubsub" "github.com/docker/docker/plugin" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" "github.com/sirupsen/logrus" ) diff --git a/daemon/cluster/executor/container/adapter.go b/daemon/cluster/executor/container/adapter.go index 720b8447fc803..664740f06ebc1 100644 --- a/daemon/cluster/executor/container/adapter.go +++ b/daemon/cluster/executor/container/adapter.go @@ -26,7 +26,7 @@ import ( "github.com/docker/swarmkit/api" "github.com/docker/swarmkit/log" gogotypes "github.com/gogo/protobuf/types" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/time/rate" diff --git a/daemon/cluster/executor/container/container.go b/daemon/cluster/executor/container/container.go index 8748ea7ad33e1..8ad12d6e5ddd5 100644 --- a/daemon/cluster/executor/container/container.go +++ b/daemon/cluster/executor/container/container.go @@ -98,10 +98,6 @@ func (c *containerConfig) taskID() string { return c.task.ID } -func (c *containerConfig) endpoint() *api.Endpoint { - return c.task.Endpoint -} - func (c *containerConfig) spec() *api.ContainerSpec { return c.task.Spec.GetContainer() } diff --git a/daemon/cluster/executor/container/controller.go b/daemon/cluster/executor/container/controller.go index 4ef22490fcd36..56c23113e5a9e 100644 --- a/daemon/cluster/executor/container/controller.go +++ b/daemon/cluster/executor/container/controller.go @@ -637,7 +637,7 @@ func parsePortMap(portMap nat.PortMap) ([]*api.PortConfig, error) { return nil, err } - protocol := api.ProtocolTCP + var protocol api.PortConfig_Protocol switch strings.ToLower(parts[1]) { case "tcp": protocol = api.ProtocolTCP diff --git a/daemon/cluster/nodes.go b/daemon/cluster/nodes.go index dffd7556f0bbd..f0d70fe1ff6c6 100644 --- a/daemon/cluster/nodes.go +++ b/daemon/cluster/nodes.go @@ -66,7 +66,7 @@ func (c *Cluster) GetNode(input string) (types.Node, error) { // UpdateNode updates existing nodes properties. func (c *Cluster) UpdateNode(input string, version uint64, spec types.NodeSpec) error { - return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { + return c.lockedManagerAction(func(_ context.Context, state nodeState) error { nodeSpec, err := convert.NodeSpecToGRPC(spec) if err != nil { return errdefs.InvalidParameter(err) diff --git a/daemon/config/config_unix.go b/daemon/config/config_unix.go index ff8f78d3bfd1a..92076d4d7faa9 100644 --- a/daemon/config/config_unix.go +++ b/daemon/config/config_unix.go @@ -7,7 +7,7 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/opts" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) const ( diff --git a/daemon/config/config_unix_test.go b/daemon/config/config_unix_test.go index 529b6777050e7..3824918f5ee43 100644 --- a/daemon/config/config_unix_test.go +++ b/daemon/config/config_unix_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/docker/docker/opts" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/spf13/pflag" "gotest.tools/assert" is "gotest.tools/assert/cmp" diff --git a/daemon/events/metrics.go b/daemon/events/metrics.go index 199858d6e0bdc..bf939004bf618 100644 --- a/daemon/events/metrics.go +++ b/daemon/events/metrics.go @@ -1,6 +1,6 @@ package events // import "github.com/docker/docker/daemon/events" -import "github.com/docker/go-metrics" +import metrics "github.com/docker/go-metrics" var ( eventsCounter metrics.Counter diff --git a/daemon/exec.go b/daemon/exec.go index 5fdba72a09d71..d477a3672046a 100644 --- a/daemon/exec.go +++ b/daemon/exec.go @@ -17,7 +17,7 @@ import ( "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/signal" "github.com/docker/docker/pkg/term" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/daemon/exec_linux.go b/daemon/exec_linux.go index f712dd31dfa48..2df28cb3b8c4c 100644 --- a/daemon/exec_linux.go +++ b/daemon/exec_linux.go @@ -7,7 +7,7 @@ import ( "github.com/docker/docker/daemon/exec" "github.com/docker/docker/oci/caps" "github.com/opencontainers/runc/libcontainer/apparmor" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) func (daemon *Daemon) execSetPlatformOpt(c *container.Container, ec *exec.Config, p *specs.Process) error { diff --git a/daemon/exec_linux_test.go b/daemon/exec_linux_test.go index 0db7f080db106..9e2f829eb76a0 100644 --- a/daemon/exec_linux_test.go +++ b/daemon/exec_linux_test.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/container" "github.com/docker/docker/daemon/exec" "github.com/opencontainers/runc/libcontainer/apparmor" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "gotest.tools/assert" ) diff --git a/daemon/graphdriver/btrfs/btrfs.go b/daemon/graphdriver/btrfs/btrfs.go index fcaedc6eab18f..a20875eb9181a 100644 --- a/daemon/graphdriver/btrfs/btrfs.go +++ b/daemon/graphdriver/btrfs/btrfs.go @@ -32,7 +32,7 @@ import ( "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/system" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/opencontainers/selinux/go-selinux/label" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/daemon/graphdriver/copy/copy.go b/daemon/graphdriver/copy/copy.go index 62d42433fd3d3..7577d0a7756e7 100644 --- a/daemon/graphdriver/copy/copy.go +++ b/daemon/graphdriver/copy/copy.go @@ -133,9 +133,6 @@ func DirCopy(srcDir, dstDir string, copyMode Mode, copyXattrs bool) error { } dstPath := filepath.Join(dstDir, relPath) - if err != nil { - return err - } stat, ok := f.Sys().(*syscall.Stat_t) if !ok { diff --git a/daemon/graphdriver/devmapper/deviceset.go b/daemon/graphdriver/devmapper/deviceset.go index 30bbfd8533634..5ab70503b11a0 100644 --- a/daemon/graphdriver/devmapper/deviceset.go +++ b/daemon/graphdriver/devmapper/deviceset.go @@ -27,7 +27,7 @@ import ( "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/kernel" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/opencontainers/selinux/go-selinux/label" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/daemon/graphdriver/devmapper/devmapper_test.go b/daemon/graphdriver/devmapper/devmapper_test.go index bda907a5d6748..4fb3dc0a605ed 100644 --- a/daemon/graphdriver/devmapper/devmapper_test.go +++ b/daemon/graphdriver/devmapper/devmapper_test.go @@ -40,7 +40,7 @@ func initLoopbacks() error { // only create new loopback files if they don't exist if _, err := os.Stat(loopPath); err != nil { if mkerr := syscall.Mknod(loopPath, - uint32(statT.Mode|syscall.S_IFBLK), int((7<<8)|(i&0xff)|((i&0xfff00)<<12))); mkerr != nil { + uint32(statT.Mode|syscall.S_IFBLK), int((7<<8)|(i&0xff)|((i&0xfff00)<<12))); mkerr != nil { // nolint: unconvert return mkerr } os.Chown(loopPath, int(statT.Uid), int(statT.Gid)) diff --git a/daemon/graphdriver/devmapper/driver.go b/daemon/graphdriver/devmapper/driver.go index a42a03ba90555..400cfe05fba69 100644 --- a/daemon/graphdriver/devmapper/driver.go +++ b/daemon/graphdriver/devmapper/driver.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/locker" "github.com/docker/docker/pkg/mount" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" ) diff --git a/daemon/graphdriver/graphtest/graphbench_unix.go b/daemon/graphdriver/graphtest/graphbench_unix.go index 22de8d17813ad..44e36b1b12889 100644 --- a/daemon/graphdriver/graphtest/graphbench_unix.go +++ b/daemon/graphdriver/graphtest/graphbench_unix.go @@ -172,6 +172,10 @@ func DriverBenchDiffApplyN(b *testing.B, fileCount int, drivername string, drive b.StopTimer() arch.Close() + // suppressing "SA9003: empty branch (staticcheck)" instead of commenting-out/removing + // these lines because removing/commenting these lines causes a ripple effect + // of changes, and there's still a to-do below + //nolint:staticcheck if applyDiffSize != diffSize { // TODO: enforce this //b.Fatalf("Apply diff size different, got %d, expected %s", applyDiffSize, diffSize) diff --git a/daemon/graphdriver/graphtest/graphtest_unix.go b/daemon/graphdriver/graphtest/graphtest_unix.go index e83d0bb2ad77e..348fc8692d3e0 100644 --- a/daemon/graphdriver/graphtest/graphtest_unix.go +++ b/daemon/graphdriver/graphtest/graphtest_unix.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/daemon/graphdriver" "github.com/docker/docker/daemon/graphdriver/quota" "github.com/docker/docker/pkg/stringid" - "github.com/docker/go-units" + units "github.com/docker/go-units" "golang.org/x/sys/unix" "gotest.tools/assert" is "gotest.tools/assert/cmp" diff --git a/daemon/graphdriver/overlay2/overlay.go b/daemon/graphdriver/overlay2/overlay.go index eedf5b73ae2c0..71bb4e6295ff4 100644 --- a/daemon/graphdriver/overlay2/overlay.go +++ b/daemon/graphdriver/overlay2/overlay.go @@ -31,7 +31,7 @@ import ( "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/parsers/kernel" "github.com/docker/docker/pkg/system" - "github.com/docker/go-units" + units "github.com/docker/go-units" rsystem "github.com/opencontainers/runc/libcontainer/system" "github.com/opencontainers/selinux/go-selinux/label" "github.com/sirupsen/logrus" diff --git a/daemon/graphdriver/plugin.go b/daemon/graphdriver/plugin.go index b0983c566797c..00f1dc9b6df1b 100644 --- a/daemon/graphdriver/plugin.go +++ b/daemon/graphdriver/plugin.go @@ -7,7 +7,7 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/plugins" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" "github.com/pkg/errors" ) diff --git a/daemon/graphdriver/vfs/driver.go b/daemon/graphdriver/vfs/driver.go index d7f14ecb622db..98824bb07ecd9 100644 --- a/daemon/graphdriver/vfs/driver.go +++ b/daemon/graphdriver/vfs/driver.go @@ -12,7 +12,7 @@ import ( "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/parsers" "github.com/docker/docker/pkg/system" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/opencontainers/selinux/go-selinux/label" "github.com/pkg/errors" ) diff --git a/daemon/graphdriver/vfs/quota_linux.go b/daemon/graphdriver/vfs/quota_linux.go index f579fc092b8b9..3af797819e7f3 100644 --- a/daemon/graphdriver/vfs/quota_linux.go +++ b/daemon/graphdriver/vfs/quota_linux.go @@ -5,6 +5,7 @@ import ( "github.com/sirupsen/logrus" ) +//nolint:structcheck type driverQuota struct { quotaCtl *quota.Control quotaOpt quota.Quota diff --git a/daemon/graphdriver/windows/windows.go b/daemon/graphdriver/windows/windows.go index 9b83e7975b21b..66d5af5bbbabc 100644 --- a/daemon/graphdriver/windows/windows.go +++ b/daemon/graphdriver/windows/windows.go @@ -19,7 +19,7 @@ import ( "time" "unsafe" - "github.com/Microsoft/go-winio" + winio "github.com/Microsoft/go-winio" "github.com/Microsoft/go-winio/archive/tar" "github.com/Microsoft/go-winio/backuptar" "github.com/Microsoft/go-winio/vhd" diff --git a/daemon/images/image_prune.go b/daemon/images/image_prune.go index 313494f2f48d0..aa8019b9a41bb 100644 --- a/daemon/images/image_prune.go +++ b/daemon/images/image_prune.go @@ -13,7 +13,7 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/image" "github.com/docker/docker/layer" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/daemon/images/image_pull.go b/daemon/images/image_pull.go index f2b689486193c..4eedfdddc171d 100644 --- a/daemon/images/image_pull.go +++ b/daemon/images/image_pull.go @@ -14,7 +14,7 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/pkg/progress" "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" ) diff --git a/daemon/images/locals.go b/daemon/images/locals.go index 5ffc460a09e9a..a57ea2da60957 100644 --- a/daemon/images/locals.go +++ b/daemon/images/locals.go @@ -3,7 +3,7 @@ package images // import "github.com/docker/docker/daemon/images" import ( "fmt" - "github.com/docker/go-metrics" + metrics "github.com/docker/go-metrics" ) type invalidFilter struct { diff --git a/daemon/images/service.go b/daemon/images/service.go index e8df5cb649858..56bfc441ce503 100644 --- a/daemon/images/service.go +++ b/daemon/images/service.go @@ -15,7 +15,7 @@ import ( dockerreference "github.com/docker/docker/reference" "github.com/docker/docker/registry" "github.com/docker/libtrust" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/daemon/info.go b/daemon/info.go index bfd8199edbc1a..7f92db12a2fc9 100644 --- a/daemon/info.go +++ b/daemon/info.go @@ -21,7 +21,7 @@ import ( "github.com/docker/docker/pkg/system" "github.com/docker/docker/registry" "github.com/docker/go-connections/sockets" - "github.com/docker/go-metrics" + metrics "github.com/docker/go-metrics" "github.com/sirupsen/logrus" ) diff --git a/daemon/info_unix_test.go b/daemon/info_unix_test.go index 7b619602627d7..92b3eafd2b832 100644 --- a/daemon/info_unix_test.go +++ b/daemon/info_unix_test.go @@ -39,7 +39,7 @@ func TestParseInitVersion(t *testing.T) { } for _, test := range tests { - version, commit, err := parseInitVersion(string(test.output)) + version, commit, err := parseInitVersion(test.output) if test.invalid { assert.Check(t, is.ErrorContains(err, "")) } else { @@ -91,7 +91,7 @@ spec: 1.0.0 } for _, test := range tests { - version, commit, err := parseRuncVersion(string(test.output)) + version, commit, err := parseRuncVersion(test.output) if test.invalid { assert.Check(t, is.ErrorContains(err, "")) } else { diff --git a/daemon/list_test.go b/daemon/list_test.go index c0a7290cd496d..4a8d4cc0b2c83 100644 --- a/daemon/list_test.go +++ b/daemon/list_test.go @@ -12,7 +12,7 @@ import ( "github.com/docker/docker/container" "github.com/docker/docker/image" "github.com/google/uuid" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) diff --git a/daemon/listeners/listeners_windows.go b/daemon/listeners/listeners_windows.go index 73f5f79e4b18c..b6d630445a714 100644 --- a/daemon/listeners/listeners_windows.go +++ b/daemon/listeners/listeners_windows.go @@ -6,7 +6,7 @@ import ( "net" "strings" - "github.com/Microsoft/go-winio" + winio "github.com/Microsoft/go-winio" "github.com/docker/go-connections/sockets" ) diff --git a/daemon/logger/copier_test.go b/daemon/logger/copier_test.go index d09450bd199b6..c01c4b0cf034c 100644 --- a/daemon/logger/copier_test.go +++ b/daemon/logger/copier_test.go @@ -3,7 +3,6 @@ package logger // import "github.com/docker/docker/daemon/logger" import ( "bytes" "encoding/json" - "fmt" "io" "os" "strings" @@ -453,9 +452,9 @@ func piped(b *testing.B, iterations int, delay time.Duration, buf []byte) io.Rea time.Sleep(delay) if n, err := w.Write(buf); err != nil || n != len(buf) { if err != nil { - b.Fatal(err) + b.Error(err) } - b.Fatal(fmt.Errorf("short write")) + b.Error("short write") } } w.Close() diff --git a/daemon/logger/factory.go b/daemon/logger/factory.go index 84b54b2794cb6..9723f7fc0ce69 100644 --- a/daemon/logger/factory.go +++ b/daemon/logger/factory.go @@ -7,7 +7,7 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/pkg/errors" ) diff --git a/daemon/logger/fluentd/fluentd.go b/daemon/logger/fluentd/fluentd.go index 2ed91df19fccd..cfa0ce5dc2e93 100644 --- a/daemon/logger/fluentd/fluentd.go +++ b/daemon/logger/fluentd/fluentd.go @@ -14,7 +14,7 @@ import ( "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/loggerutils" "github.com/docker/docker/pkg/urlutil" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/fluent/fluent-logger-golang/fluent" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/daemon/logger/journald/journald.go b/daemon/logger/journald/journald.go index 4d3952cba47a2..35985f0318fd1 100644 --- a/daemon/logger/journald/journald.go +++ b/daemon/logger/journald/journald.go @@ -18,7 +18,7 @@ import ( const name = "journald" type journald struct { - mu sync.Mutex + mu sync.Mutex //nolint:structcheck,unused vars map[string]string // additional variables and values to send to the journal along with the log message readers map[*logger.LogWatcher]struct{} } diff --git a/daemon/logger/jsonfilelog/jsonfilelog.go b/daemon/logger/jsonfilelog/jsonfilelog.go index e59f3bf6a55c4..e66a6b8266f43 100644 --- a/daemon/logger/jsonfilelog/jsonfilelog.go +++ b/daemon/logger/jsonfilelog/jsonfilelog.go @@ -13,7 +13,7 @@ import ( "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/jsonfilelog/jsonlog" "github.com/docker/docker/daemon/logger/loggerutils" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/daemon/logger/jsonfilelog/jsonfilelog_test.go b/daemon/logger/jsonfilelog/jsonfilelog_test.go index 97265a7fc77e0..155086dec6a60 100644 --- a/daemon/logger/jsonfilelog/jsonfilelog_test.go +++ b/daemon/logger/jsonfilelog/jsonfilelog_test.go @@ -188,15 +188,15 @@ func TestJSONFileLoggerWithOpts(t *testing.T) { } file, err := os.Open(filename + ".1.gz") - defer file.Close() if err != nil { t.Fatal(err) } + defer file.Close() zipReader, err := gzip.NewReader(file) - defer zipReader.Close() if err != nil { t.Fatal(err) } + defer zipReader.Close() penUlt, err = ioutil.ReadAll(zipReader) if err != nil { t.Fatal(err) @@ -204,15 +204,15 @@ func TestJSONFileLoggerWithOpts(t *testing.T) { } file, err := os.Open(filename + ".2.gz") - defer file.Close() if err != nil { t.Fatal(err) } + defer file.Close() zipReader, err := gzip.NewReader(file) - defer zipReader.Close() if err != nil { t.Fatal(err) } + defer zipReader.Close() antepenult, err := ioutil.ReadAll(zipReader) if err != nil { t.Fatal(err) diff --git a/daemon/logger/local/local.go b/daemon/logger/local/local.go index ba4aa096f7104..f8c58c6fca5ba 100644 --- a/daemon/logger/local/local.go +++ b/daemon/logger/local/local.go @@ -12,7 +12,7 @@ import ( "github.com/docker/docker/daemon/logger" "github.com/docker/docker/daemon/logger/loggerutils" "github.com/docker/docker/errdefs" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/daemon/logger/metrics.go b/daemon/logger/metrics.go index b7dfd38ec2061..05b557f8625ed 100644 --- a/daemon/logger/metrics.go +++ b/daemon/logger/metrics.go @@ -1,7 +1,7 @@ package logger // import "github.com/docker/docker/daemon/logger" import ( - "github.com/docker/go-metrics" + metrics "github.com/docker/go-metrics" ) var ( diff --git a/daemon/metrics.go b/daemon/metrics.go index f2548b6dfa919..c693b82709a95 100644 --- a/daemon/metrics.go +++ b/daemon/metrics.go @@ -6,7 +6,7 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/plugins" - "github.com/docker/go-metrics" + metrics "github.com/docker/go-metrics" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" diff --git a/daemon/metrics_unix.go b/daemon/metrics_unix.go index a9b5f810b0638..b131ebc3e1871 100644 --- a/daemon/metrics_unix.go +++ b/daemon/metrics_unix.go @@ -10,8 +10,8 @@ import ( "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/plugins" "github.com/docker/docker/plugin" - "github.com/docker/go-metrics" - "github.com/opencontainers/runtime-spec/specs-go" + metrics "github.com/docker/go-metrics" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" diff --git a/daemon/monitor.go b/daemon/monitor.go index c29474288414f..b8d32c39a974c 100644 --- a/daemon/monitor.go +++ b/daemon/monitor.go @@ -202,15 +202,13 @@ func (daemon *Daemon) autoRemove(c *container.Container) { return } - var err error - if err = daemon.ContainerRm(c.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err == nil { + err := daemon.ContainerRm(c.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}) + if err == nil { return } if c := daemon.containers.Get(c.ID); c == nil { return } - if err != nil { - logrus.WithError(err).WithField("container", c.ID).Error("error removing container") - } + logrus.WithError(err).WithField("container", c.ID).Error("error removing container") } diff --git a/daemon/network.go b/daemon/network.go index 01b5956adbba1..abbee5dc15703 100644 --- a/daemon/network.go +++ b/daemon/network.go @@ -960,12 +960,6 @@ func buildCreateEndpointOptions(c *container.Container, n libnetwork.Network, ep return createOptions, nil } -// getEndpointInNetwork returns the container's endpoint to the provided network. -func getEndpointInNetwork(name string, n libnetwork.Network) (libnetwork.Endpoint, error) { - endpointName := strings.TrimPrefix(name, "/") - return n.EndpointByName(endpointName) -} - // getSandboxPortMapInfo retrieves the current port-mapping programmed for the given sandbox func getSandboxPortMapInfo(sb libnetwork.Sandbox) nat.PortMap { pm := nat.PortMap{} diff --git a/daemon/network_windows.go b/daemon/network_windows.go new file mode 100644 index 0000000000000..a5a93bbb386c0 --- /dev/null +++ b/daemon/network_windows.go @@ -0,0 +1,13 @@ +package daemon + +import ( + "strings" + + "github.com/docker/libnetwork" +) + +// getEndpointInNetwork returns the container's endpoint to the provided network. +func getEndpointInNetwork(name string, n libnetwork.Network) (libnetwork.Endpoint, error) { + endpointName := strings.TrimPrefix(name, "/") + return n.EndpointByName(endpointName) +} diff --git a/daemon/nvidia_linux.go b/daemon/nvidia_linux.go index c136634e6ac30..9f1c9141465f4 100644 --- a/daemon/nvidia_linux.go +++ b/daemon/nvidia_linux.go @@ -8,7 +8,7 @@ import ( "github.com/containerd/containerd/contrib/nvidia" "github.com/docker/docker/pkg/capabilities" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" ) diff --git a/daemon/oci_linux.go b/daemon/oci_linux.go index 6f55a19c16930..a3864b9a83b3a 100644 --- a/daemon/oci_linux.go +++ b/daemon/oci_linux.go @@ -27,7 +27,7 @@ import ( "github.com/opencontainers/runc/libcontainer/devices" rsystem "github.com/opencontainers/runc/libcontainer/system" "github.com/opencontainers/runc/libcontainer/user" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" diff --git a/daemon/oci_utils.go b/daemon/oci_utils.go index 6058d86e4871d..2d833502bd3a9 100644 --- a/daemon/oci_utils.go +++ b/daemon/oci_utils.go @@ -2,7 +2,7 @@ package daemon // import "github.com/docker/docker/daemon" import ( "github.com/docker/docker/container" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) func setLinuxDomainname(c *container.Container, s *specs.Spec) { diff --git a/daemon/oci_windows.go b/daemon/oci_windows.go index 1d3b78a4ddee6..d5c1ab1c1d1c7 100644 --- a/daemon/oci_windows.go +++ b/daemon/oci_windows.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/oci/caps" "github.com/docker/docker/pkg/sysinfo" "github.com/docker/docker/pkg/system" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/windows/registry" diff --git a/daemon/oci_windows_test.go b/daemon/oci_windows_test.go index 370187afcb04d..c757536b402da 100644 --- a/daemon/oci_windows_test.go +++ b/daemon/oci_windows_test.go @@ -14,7 +14,7 @@ import ( "github.com/docker/docker/container" swarmagent "github.com/docker/swarmkit/agent" swarmapi "github.com/docker/swarmkit/api" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "golang.org/x/sys/windows/registry" "gotest.tools/assert" ) diff --git a/daemon/seccomp_linux.go b/daemon/seccomp_linux.go index 27461775d4385..eea1913189044 100644 --- a/daemon/seccomp_linux.go +++ b/daemon/seccomp_linux.go @@ -10,7 +10,7 @@ import ( coci "github.com/containerd/containerd/oci" "github.com/docker/docker/container" "github.com/docker/docker/profiles/seccomp" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/sirupsen/logrus" ) @@ -28,9 +28,9 @@ func WithSeccomp(daemon *Daemon, c *container.Container) coci.SpecOpts { if !daemon.seccompEnabled { if c.SeccompProfile != "" && c.SeccompProfile != "unconfined" { - return fmt.Errorf("Seccomp is not enabled in your kernel, cannot run a custom seccomp profile.") + return fmt.Errorf("seccomp is not enabled in your kernel, cannot run a custom seccomp profile") } - logrus.Warn("Seccomp is not enabled in your kernel, running container without default profile.") + logrus.Warn("seccomp is not enabled in your kernel, running container without default profile") c.SeccompProfile = "unconfined" } if c.SeccompProfile == "unconfined" { diff --git a/daemon/selinux_linux.go b/daemon/selinux_linux.go index f87b30b7387ce..1f7843ed1e9d0 100644 --- a/daemon/selinux_linux.go +++ b/daemon/selinux_linux.go @@ -1,6 +1,6 @@ package daemon // import "github.com/docker/docker/daemon" -import "github.com/opencontainers/selinux/go-selinux" +import selinux "github.com/opencontainers/selinux/go-selinux" func selinuxSetDisabled() { selinux.SetDisabled() diff --git a/daemon/top_windows.go b/daemon/top_windows.go index 23cb4d48bd7a8..010b426d3f297 100644 --- a/daemon/top_windows.go +++ b/daemon/top_windows.go @@ -7,7 +7,7 @@ import ( "time" containertypes "github.com/docker/docker/api/types/container" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) // ContainerTop handles `docker top` client requests. diff --git a/daemon/update_linux.go b/daemon/update_linux.go index 7dc1f33156ec4..c1d3684868db1 100644 --- a/daemon/update_linux.go +++ b/daemon/update_linux.go @@ -5,7 +5,7 @@ import ( "github.com/docker/docker/api/types/container" libcontainerdtypes "github.com/docker/docker/libcontainerd/types" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) func toContainerdResources(resources container.Resources) *libcontainerdtypes.Resources { diff --git a/distribution/config.go b/distribution/config.go index 438051c296e27..8e66d93cade7f 100644 --- a/distribution/config.go +++ b/distribution/config.go @@ -19,7 +19,7 @@ import ( refstore "github.com/docker/docker/reference" "github.com/docker/docker/registry" "github.com/docker/libtrust" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" ) diff --git a/distribution/errors.go b/distribution/errors.go index 9dc5955f26c7d..194287d8a2979 100644 --- a/distribution/errors.go +++ b/distribution/errors.go @@ -9,7 +9,7 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/reference" "github.com/docker/distribution/registry/api/errcode" - "github.com/docker/distribution/registry/api/v2" + v2 "github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/client" "github.com/docker/distribution/registry/client/auth" "github.com/docker/docker/distribution/xfer" diff --git a/distribution/errors_test.go b/distribution/errors_test.go index 7105bdb4d6079..87354bc22eb11 100644 --- a/distribution/errors_test.go +++ b/distribution/errors_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/docker/distribution/registry/api/errcode" - "github.com/docker/distribution/registry/api/v2" + v2 "github.com/docker/distribution/registry/api/v2" "github.com/docker/distribution/registry/client" ) diff --git a/distribution/metadata/v1_id_service.go b/distribution/metadata/v1_id_service.go index 5575c59b0e9a7..86c83f62ebf11 100644 --- a/distribution/metadata/v1_id_service.go +++ b/distribution/metadata/v1_id_service.go @@ -1,7 +1,7 @@ package metadata // import "github.com/docker/docker/distribution/metadata" import ( - "github.com/docker/docker/image/v1" + v1 "github.com/docker/docker/image/v1" "github.com/docker/docker/layer" "github.com/pkg/errors" ) diff --git a/distribution/metadata/v2_metadata_service.go b/distribution/metadata/v2_metadata_service.go index fe33498554148..482d2224ea54c 100644 --- a/distribution/metadata/v2_metadata_service.go +++ b/distribution/metadata/v2_metadata_service.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/layer" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) // V2MetadataService maps layer IDs to a set of known metadata for diff --git a/distribution/metadata/v2_metadata_service_test.go b/distribution/metadata/v2_metadata_service_test.go index cf24e0d85b637..c5f0a562ae80c 100644 --- a/distribution/metadata/v2_metadata_service_test.go +++ b/distribution/metadata/v2_metadata_service_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/docker/docker/layer" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) func TestV2MetadataService(t *testing.T) { diff --git a/distribution/pull.go b/distribution/pull.go index be366ce4a99b6..ecf2f981689d5 100644 --- a/distribution/pull.go +++ b/distribution/pull.go @@ -10,7 +10,7 @@ import ( "github.com/docker/docker/pkg/progress" refstore "github.com/docker/docker/reference" "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/distribution/pull_v2.go b/distribution/pull_v2.go index 77c5f645a0d3c..c81af5e6e73c6 100644 --- a/distribution/pull_v2.go +++ b/distribution/pull_v2.go @@ -31,7 +31,7 @@ import ( "github.com/docker/docker/pkg/system" refstore "github.com/docker/docker/reference" "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -200,7 +200,7 @@ func (ld *v2LayerDescriptor) Download(ctx context.Context, progressOutput progre } if offset != 0 { - _, err := layerDownload.Seek(offset, os.SEEK_SET) + _, err := layerDownload.Seek(offset, io.SeekStart) if err != nil { if err := ld.truncateDownloadFile(); err != nil { return nil, 0, xfer.DoNotRetry{Err: err} @@ -226,7 +226,7 @@ func (ld *v2LayerDescriptor) Download(ctx context.Context, progressOutput progre // Restore the seek offset either at the beginning of the // stream, or just after the last byte we have from previous // attempts. - _, err = layerDownload.Seek(offset, os.SEEK_SET) + _, err = layerDownload.Seek(offset, io.SeekStart) if err != nil { return nil, 0, err } @@ -272,7 +272,7 @@ func (ld *v2LayerDescriptor) Download(ctx context.Context, progressOutput progre logrus.Debugf("Downloaded %s to tempfile %s", ld.ID(), tmpFile.Name()) - _, err = tmpFile.Seek(0, os.SEEK_SET) + _, err = tmpFile.Seek(0, io.SeekStart) if err != nil { tmpFile.Close() if err := os.Remove(tmpFile.Name()); err != nil { @@ -310,7 +310,7 @@ func (ld *v2LayerDescriptor) truncateDownloadFile() error { // Need a new hash context since we will be redoing the download ld.verifier = nil - if _, err := ld.tmpFile.Seek(0, os.SEEK_SET); err != nil { + if _, err := ld.tmpFile.Seek(0, io.SeekStart); err != nil { logrus.Errorf("error seeking to beginning of download file: %v", err) return err } diff --git a/distribution/pull_v2_test.go b/distribution/pull_v2_test.go index 7c14d50026303..7e06abb42b068 100644 --- a/distribution/pull_v2_test.go +++ b/distribution/pull_v2_test.go @@ -12,7 +12,7 @@ import ( "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/reference" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -180,7 +180,7 @@ func TestValidateManifest(t *testing.T) { t.Fatal("error unmarshaling manifest:", err) } - verifiedManifest, err = verifySchema1Manifest(&badSignedManifest, expectedDigest) + _, err = verifySchema1Manifest(&badSignedManifest, expectedDigest) if err == nil || !strings.HasPrefix(err.Error(), "image verification failed for digest") { t.Fatal("expected validateManifest to fail with digest error") } diff --git a/distribution/pull_v2_windows.go b/distribution/pull_v2_windows.go index 1162e9a8bbf1d..52ab89074554d 100644 --- a/distribution/pull_v2_windows.go +++ b/distribution/pull_v2_windows.go @@ -4,8 +4,8 @@ import ( "context" "errors" "fmt" + "io" "net/http" - "os" "runtime" "sort" "strconv" @@ -41,7 +41,7 @@ func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekClo // We're done if the registry has this blob. if err == nil { // Seek does an HTTP GET. If it succeeds, the blob really is accessible. - if _, err = rsc.Seek(0, os.SEEK_SET); err == nil { + if _, err = rsc.Seek(0, io.SeekStart); err == nil { return rsc, nil } rsc.Close() @@ -53,7 +53,7 @@ func (ld *v2LayerDescriptor) open(ctx context.Context) (distribution.ReadSeekClo rsc = transport.NewHTTPReadSeeker(http.DefaultClient, url, nil) // Seek does an HTTP GET. If it succeeds, the blob really is accessible. - _, err = rsc.Seek(0, os.SEEK_SET) + _, err = rsc.Seek(0, io.SeekStart) if err == nil { break } diff --git a/distribution/push_v2.go b/distribution/push_v2.go index 06863ad0d7174..0bf39e22171d4 100644 --- a/distribution/push_v2.go +++ b/distribution/push_v2.go @@ -24,7 +24,7 @@ import ( "github.com/docker/docker/pkg/progress" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" ) diff --git a/distribution/push_v2_test.go b/distribution/push_v2_test.go index 436b4a1797fc0..9bf3675ece59c 100644 --- a/distribution/push_v2_test.go +++ b/distribution/push_v2_test.go @@ -17,7 +17,7 @@ import ( "github.com/docker/docker/pkg/progress" refstore "github.com/docker/docker/reference" "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) func TestGetRepositoryMountCandidates(t *testing.T) { diff --git a/distribution/xfer/download_test.go b/distribution/xfer/download_test.go index 4ab3705af6a1f..1262d24d695da 100644 --- a/distribution/xfer/download_test.go +++ b/distribution/xfer/download_test.go @@ -16,7 +16,7 @@ import ( "github.com/docker/docker/image" "github.com/docker/docker/layer" "github.com/docker/docker/pkg/progress" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) const maxDownloadConcurrency = 3 @@ -26,7 +26,6 @@ type mockLayer struct { diffID layer.DiffID chainID layer.ChainID parent layer.Layer - os string } func (ml *mockLayer) TarStream() (io.ReadCloser, error) { diff --git a/distribution/xfer/transfer_test.go b/distribution/xfer/transfer_test.go index a86e27959ea08..f8f8e96fe0fa3 100644 --- a/distribution/xfer/transfer_test.go +++ b/distribution/xfer/transfer_test.go @@ -10,11 +10,11 @@ import ( func TestTransfer(t *testing.T) { makeXferFunc := func(id string) DoFunc { - return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { + return func(progressChan chan<- progress.Progress, start <-chan struct{}, _ chan<- struct{}) Transfer { select { case <-start: default: - t.Fatalf("transfer function not started even though concurrency limit not reached") + t.Errorf("%s: transfer function not started even though concurrency limit not reached", id) } xfer := NewTransfer() @@ -38,7 +38,7 @@ func TestTransfer(t *testing.T) { for p := range progressChan { val, present := receivedProgress[p.ID] if present && p.Current <= val { - t.Fatalf("got unexpected progress value: %d (expected %d)", p.Current, val+1) + t.Errorf("%s: got unexpected progress value: %d (expected <= %d)", p.ID, p.Current, val) } receivedProgress[p.ID] = p.Current } @@ -72,13 +72,13 @@ func TestConcurrencyLimit(t *testing.T) { var runningJobs int32 makeXferFunc := func(id string) DoFunc { - return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { + return func(progressChan chan<- progress.Progress, start <-chan struct{}, _ chan<- struct{}) Transfer { xfer := NewTransfer() go func() { <-start totalJobs := atomic.AddInt32(&runningJobs, 1) if int(totalJobs) > concurrencyLimit { - t.Fatalf("too many jobs running") + t.Errorf("%s: too many jobs running (%d > %d)", id, totalJobs, concurrencyLimit) } for i := 0; i <= 10; i++ { progressChan <- progress.Progress{ID: id, Action: "testing", Current: int64(i), Total: 10} @@ -137,7 +137,7 @@ func TestInactiveJobs(t *testing.T) { <-start totalJobs := atomic.AddInt32(&runningJobs, 1) if int(totalJobs) > concurrencyLimit { - t.Fatalf("too many jobs running") + t.Errorf("%s: too many jobs running (%d > %d)", id, totalJobs, concurrencyLimit) } for i := 0; i <= 10; i++ { progressChan <- progress.Progress{ID: id, Action: "testing", Current: int64(i), Total: 10} @@ -191,7 +191,7 @@ func TestWatchRelease(t *testing.T) { ready := make(chan struct{}) makeXferFunc := func(id string) DoFunc { - return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { + return func(progressChan chan<- progress.Progress, start <-chan struct{}, _ chan<- struct{}) Transfer { xfer := NewTransfer() go func() { defer func() { @@ -280,7 +280,7 @@ func TestWatchRelease(t *testing.T) { func TestWatchFinishedTransfer(t *testing.T) { makeXferFunc := func(id string) DoFunc { - return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { + return func(progressChan chan<- progress.Progress, _ <-chan struct{}, _ chan<- struct{}) Transfer { xfer := NewTransfer() go func() { // Finish immediately @@ -322,7 +322,7 @@ func TestDuplicateTransfer(t *testing.T) { var xferFuncCalls int32 makeXferFunc := func(id string) DoFunc { - return func(progressChan chan<- progress.Progress, start <-chan struct{}, inactive chan<- struct{}) Transfer { + return func(progressChan chan<- progress.Progress, _ <-chan struct{}, _ chan<- struct{}) Transfer { atomic.AddInt32(&xferFuncCalls, 1) xfer := NewTransfer() go func() { diff --git a/hack/dockerfile/install/golangci_lint.installer b/hack/dockerfile/install/golangci_lint.installer new file mode 100755 index 0000000000000..198f8a76b2d59 --- /dev/null +++ b/hack/dockerfile/install/golangci_lint.installer @@ -0,0 +1,11 @@ +#!/bin/sh + +: "${GOLANGCI_LINT_COMMIT=v1.17.1}" + +install_golangci_lint() { + echo "Installing golangci-lint version ${GOLANGCI_LINT_COMMIT}" + go get -d github.com/golangci/golangci-lint/cmd/golangci-lint + cd "$GOPATH/src/github.com/golangci/golangci-lint/" || exit 1 + git checkout -q "${GOLANGCI_LINT_COMMIT}" + go build -buildmode=pie -o "${PREFIX}/golangci-lint" "github.com/golangci/golangci-lint/cmd/golangci-lint" +} diff --git a/hack/dockerfile/install/gometalinter.installer b/hack/dockerfile/install/gometalinter.installer deleted file mode 100755 index 461850f9360ed..0000000000000 --- a/hack/dockerfile/install/gometalinter.installer +++ /dev/null @@ -1,12 +0,0 @@ -#!/bin/sh - -GOMETALINTER_COMMIT=v2.0.6 - -install_gometalinter() { - echo "Installing gometalinter version $GOMETALINTER_COMMIT" - go get -d github.com/alecthomas/gometalinter - cd "$GOPATH/src/github.com/alecthomas/gometalinter" - git checkout -q "$GOMETALINTER_COMMIT" - go build -buildmode=pie -o "${PREFIX}/gometalinter" "github.com/alecthomas/gometalinter" - GOBIN=${PREFIX} "${PREFIX}/gometalinter" --install -} diff --git a/hack/validate/default b/hack/validate/default index 4266d1f82fd41..7d566f2a243d8 100755 --- a/hack/validate/default +++ b/hack/validate/default @@ -6,11 +6,11 @@ export SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" . ${SCRIPTDIR}/dco . ${SCRIPTDIR}/default-seccomp -. ${SCRIPTDIR}/gometalinter +. ${SCRIPTDIR}/golangci-lint . ${SCRIPTDIR}/pkg-imports . ${SCRIPTDIR}/swagger . ${SCRIPTDIR}/swagger-gen . ${SCRIPTDIR}/toml . ${SCRIPTDIR}/changelog-well-formed . ${SCRIPTDIR}/changelog-date-descending -. ${SCRIPTDIR}/deprecate-integration-cli +#. ${SCRIPTDIR}/deprecate-integration-cli diff --git a/hack/validate/golangci-lint b/hack/validate/golangci-lint new file mode 100755 index 0000000000000..41750f6e26499 --- /dev/null +++ b/hack/validate/golangci-lint @@ -0,0 +1,26 @@ +#!/usr/bin/env bash +set -e -o pipefail + +SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +# CI platforms differ, so per-platform GOLANGCI_LINT_OPTS can be set +# from a platform-specific Dockerfile, otherwise let's just set +# (somewhat pessimistic) default of 10 minutes. +: ${GOLANGCI_LINT_OPTS=--deadline=20m} + +[ -n "${TESTDEBUG}" ] && set -x + +# TODO find a way to share this code with hack/make.sh +if ${PKG_CONFIG} 'libsystemd >= 209' 2> /dev/null ; then + DOCKER_BUILDTAGS+=" journald" +elif ${PKG_CONFIG} 'libsystemd-journal' 2> /dev/null ; then + DOCKER_BUILDTAGS+=" journald journald_compat" +fi + +# TODO use --out-format=junit-xml and store artifacts +GOGC=20 golangci-lint run \ + ${GOLANGCI_LINT_OPTS} \ + --print-resources-usage \ + --build-tags="${DOCKER_BUILDTAGS}" \ + --verbose \ + --config ${SCRIPTDIR}/golangci-lint.yml diff --git a/hack/validate/golangci-lint.yml b/hack/validate/golangci-lint.yml new file mode 100644 index 0000000000000..938c53f78d2c2 --- /dev/null +++ b/hack/validate/golangci-lint.yml @@ -0,0 +1,76 @@ +linters: + enable: + - deadcode + - gofmt + - goimports + - golint + - gosec + - gosimple + - govet + - ineffassign + - misspell + - unconvert + + disable: + - errcheck + + run: + concurrency: 2 + modules-download-mode: vendor + + skip-dirs: + - docs + - integration-cli + + skip-files: + - ".*\\.pb\\.go" + - "dockerversion/version_autogen.go" + - "api/types/container/container_.*" + - "api/types/volume/volume_.*" + +linters-settings: + govet: + check-shadowing: false + +issues: + exclude-rules: + # Exclude some linters from running on tests files. + - path: _test\.go + linters: + - errcheck + - gosec + + - text: "G201: SQL string formatting" + linters: + - gosec + - text: "G202: SQL string concatenation" + linters: + - gosec + # FIXME temporarily suppress these. See #39925 + - text: "SA1019: base.Dial is deprecated" + linters: + - staticcheck + # FIXME temporarily suppress these. See #39928 + - text: "SA1019: grpc.WithDialer is deprecated" + linters: + - staticcheck + # FIXME temporarily suppress these. See #39924 + - text: "SA1019: h.Xattrs is deprecated: Use PAXRecords instead" + linters: + - staticcheck + # FIXME temporarily suppress these. See #39924 + - text: "SA1019: hdr.Xattrs is deprecated: Use PAXRecords instead" + linters: + - staticcheck + # FIXME temporarily suppress these. See #39929 + - text: "SA1019: http.CloseNotifier is deprecated" + linters: + - staticcheck + # FIXME temporarily suppress these. See #39926 + - text: "SA1019: httputil.NewClientConn is deprecated" + linters: + - staticcheck + # FIXME temporarily suppress these. See #39927 + - text: "SA1019: httputil.ClientConn is deprecated" + linters: + - staticcheck diff --git a/hack/validate/gometalinter b/hack/validate/gometalinter deleted file mode 100755 index 4300b67a11a63..0000000000000 --- a/hack/validate/gometalinter +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env bash -set -e -o pipefail - -SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -# CI platforms differ, so per-platform GOMETALINTER_OPTS can be set -# in the Jenkinsfile, otherwise let's just set a -# (somewhat pessimistic) default of 10 minutes. -: "${GOMETALINTER_OPTS=--deadline=10m}" - -# shellcheck disable=SC2086 -gometalinter \ - ${GOMETALINTER_OPTS} \ - --config "${SCRIPTDIR}/gometalinter.json" ./... diff --git a/hack/validate/gometalinter.json b/hack/validate/gometalinter.json deleted file mode 100644 index e36dd73306a24..0000000000000 --- a/hack/validate/gometalinter.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "Vendor": true, - "EnableGC": true, - "Sort": ["linter", "severity", "path"], - "Exclude": [ - ".*\\.pb\\.go", - "dockerversion/version_autogen.go", - "api/types/container/container_.*", - "api/types/volume/volume_.*", - "integration-cli/" - ], - "Skip": ["integration-cli/"], - - "Enable": [ - "deadcode", - "gofmt", - "goimports", - "golint", - "gosimple", - "ineffassign", - "unconvert", - "vet" - ], - - "LineLength": 200 -} diff --git a/image/fs.go b/image/fs.go index 7080c8c0155f6..8300c4188485f 100644 --- a/image/fs.go +++ b/image/fs.go @@ -8,7 +8,7 @@ import ( "sync" "github.com/docker/docker/pkg/ioutils" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/image/fs_test.go b/image/fs_test.go index 6290c2b66e841..a377e134e3bda 100644 --- a/image/fs_test.go +++ b/image/fs_test.go @@ -10,7 +10,7 @@ import ( "path/filepath" "testing" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) @@ -29,15 +29,13 @@ func TestFSGetInvalidData(t *testing.T) { store, cleanup := defaultFSStoreBackend(t) defer cleanup() - id, err := store.Set([]byte("foobar")) + dgst, err := store.Set([]byte("foobar")) assert.Check(t, err) - dgst := digest.Digest(id) - err = ioutil.WriteFile(filepath.Join(store.(*fs).root, contentDirName, string(dgst.Algorithm()), dgst.Hex()), []byte("foobar2"), 0600) assert.Check(t, err) - _, err = store.Get(id) + _, err = store.Get(dgst) assert.Check(t, is.ErrorContains(err, "failed to verify")) } @@ -172,7 +170,7 @@ func TestFSGetSet(t *testing.T) { }) for _, tc := range tcases { - id, err := store.Set([]byte(tc.input)) + id, err := store.Set(tc.input) assert.Check(t, err) assert.Check(t, is.Equal(tc.expected, id)) } diff --git a/image/image.go b/image/image.go index 079ecb813172a..f043b042cf035 100644 --- a/image/image.go +++ b/image/image.go @@ -11,7 +11,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/dockerversion" "github.com/docker/docker/layer" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) // ID is the content-addressable ID of an image. @@ -62,7 +62,7 @@ type V1Image struct { // Image stores the image configuration type Image struct { V1Image - Parent ID `json:"parent,omitempty"` + Parent ID `json:"parent,omitempty"` //nolint:govet RootFS *RootFS `json:"rootfs,omitempty"` History []History `json:"history,omitempty"` OSVersion string `json:"os.version,omitempty"` diff --git a/image/store.go b/image/store.go index 1a8a8a24516c2..0ad87f5c61def 100644 --- a/image/store.go +++ b/image/store.go @@ -9,7 +9,7 @@ import ( "github.com/docker/distribution/digestset" "github.com/docker/docker/layer" "github.com/docker/docker/pkg/system" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/image/store_test.go b/image/store_test.go index 0edf3282af471..f601285b6d946 100644 --- a/image/store_test.go +++ b/image/store_test.go @@ -6,7 +6,6 @@ import ( "testing" "github.com/docker/docker/layer" - "github.com/opencontainers/go-digest" "gotest.tools/assert" "gotest.tools/assert/cmp" ) @@ -60,11 +59,11 @@ func TestRestore(t *testing.T) { assert.NilError(t, err) assert.Check(t, cmp.Equal(ID(id1), sid1)) - sid1, err = is.Search(digest.Digest(id1).Hex()[:6]) + sid1, err = is.Search(id1.Hex()[:6]) assert.NilError(t, err) assert.Check(t, cmp.Equal(ID(id1), sid1)) - invalidPattern := digest.Digest(id1).Hex()[1:6] + invalidPattern := id1.Hex()[1:6] _, err = is.Search(invalidPattern) assert.ErrorContains(t, err, "No such image") } diff --git a/image/tarexport/load.go b/image/tarexport/load.go index 786214383eaf3..cc22127038f0e 100644 --- a/image/tarexport/load.go +++ b/image/tarexport/load.go @@ -15,7 +15,7 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/reference" "github.com/docker/docker/image" - "github.com/docker/docker/image/v1" + v1 "github.com/docker/docker/image/v1" "github.com/docker/docker/layer" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" @@ -24,7 +24,7 @@ import ( "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/symlink" "github.com/docker/docker/pkg/system" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" ) diff --git a/image/tarexport/save.go b/image/tarexport/save.go index 4e734b35038aa..0fb5986b72bb3 100644 --- a/image/tarexport/save.go +++ b/image/tarexport/save.go @@ -14,11 +14,11 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/reference" "github.com/docker/docker/image" - "github.com/docker/docker/image/v1" + v1 "github.com/docker/docker/image/v1" "github.com/docker/docker/layer" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/system" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" ) diff --git a/image/v1/imagev1.go b/image/v1/imagev1.go index c341ceaa77038..1eec8dfc8c00a 100644 --- a/image/v1/imagev1.go +++ b/image/v1/imagev1.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/image" "github.com/docker/docker/layer" "github.com/docker/docker/pkg/stringid" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" ) diff --git a/integration-cli/daemon/daemon.go b/integration-cli/daemon/daemon.go index d138f85ce535f..d9ff7e2150bc5 100644 --- a/integration-cli/daemon/daemon.go +++ b/integration-cli/daemon/daemon.go @@ -94,7 +94,7 @@ func (d *Daemon) CheckActiveContainerCount(c *testing.T) (interface{}, string) { if len(strings.TrimSpace(out)) == 0 { return 0, "" } - return len(strings.Split(strings.TrimSpace(out), "\n")), fmt.Sprintf("output: %q", string(out)) + return len(strings.Split(strings.TrimSpace(out), "\n")), fmt.Sprintf("output: %q", out) } // WaitRun waits for a container to be running for 10s diff --git a/integration-cli/docker_api_attach_test.go b/integration-cli/docker_api_attach_test.go index 59b550aa7ae57..e7c751c2e6279 100644 --- a/integration-cli/docker_api_attach_test.go +++ b/integration-cli/docker_api_attach_test.go @@ -27,7 +27,7 @@ func (s *DockerSuite) TestGetContainersAttachWebsocket(c *testing.T) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat") - rwc, err := request.SockConn(time.Duration(10*time.Second), request.DaemonHost()) + rwc, err := request.SockConn(10*time.Second, request.DaemonHost()) assert.NilError(c, err) cleanedContainerID := strings.TrimSpace(out) @@ -237,7 +237,7 @@ func sockRequestHijack(method, endpoint string, data io.Reader, ct string, daemo // Deprecated: Use New instead of NewRequestClient // Deprecated: use request.Do (or Get, Delete, Post) instead func newRequestClient(method, endpoint string, data io.Reader, ct, daemon string, modifiers ...func(*http.Request)) (*http.Request, *httputil.ClientConn, error) { - c, err := request.SockConn(time.Duration(10*time.Second), daemon) + c, err := request.SockConn(10*time.Second, daemon) if err != nil { return nil, nil, fmt.Errorf("could not dial docker daemon: %v", err) } diff --git a/integration-cli/docker_api_containers_test.go b/integration-cli/docker_api_containers_test.go index 19f8054568462..f58ecf16abc18 100644 --- a/integration-cli/docker_api_containers_test.go +++ b/integration-cli/docker_api_containers_test.go @@ -348,6 +348,7 @@ func (s *DockerSuite) TestGetStoppedContainerStats(c *testing.T) { defer cli.Close() resp, err := cli.ContainerStats(context.Background(), name, false) + assert.NilError(c, err) defer resp.Body.Close() chResp <- err }() @@ -394,7 +395,7 @@ func (s *DockerSuite) TestContainerAPIPause(c *testing.T) { func (s *DockerSuite) TestContainerAPITop(c *testing.T) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) assert.NilError(c, waitRun(id)) cli, err := client.NewClientWithOpts(client.FromEnv) @@ -417,7 +418,7 @@ func (s *DockerSuite) TestContainerAPITop(c *testing.T) { func (s *DockerSuite) TestContainerAPITopWindows(c *testing.T) { testRequires(c, DaemonIsWindows) out := runSleepingContainer(c, "-d") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) assert.NilError(c, waitRun(id)) cli, err := client.NewClientWithOpts(client.FromEnv) @@ -614,7 +615,7 @@ func UtilCreateNetworkMode(c *testing.T, networkMode containertypes.NetworkMode) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) assert.NilError(c, err) - assert.Equal(c, containerJSON.HostConfig.NetworkMode, containertypes.NetworkMode(networkMode), "Mismatched NetworkMode") + assert.Equal(c, containerJSON.HostConfig.NetworkMode, networkMode, "Mismatched NetworkMode") } func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *testing.T) { @@ -993,13 +994,13 @@ func (s *DockerSuite) TestContainerAPIWait(c *testing.T) { assert.NilError(c, err) defer cli.Close() - waitresC, errC := cli.ContainerWait(context.Background(), name, "") + waitResC, errC := cli.ContainerWait(context.Background(), name, "") select { case err = <-errC: assert.NilError(c, err) - case waitres := <-waitresC: - assert.Equal(c, waitres.StatusCode, int64(0)) + case waitRes := <-waitResC: + assert.Equal(c, waitRes.StatusCode, int64(0)) } } @@ -1941,7 +1942,7 @@ func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *testing.T) { tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind") assert.NilError(c, err) defer os.RemoveAll(tmpDir) - err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666) + err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 0666) assert.NilError(c, err) config := containertypes.Config{ Image: "busybox", @@ -2093,14 +2094,6 @@ func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *testing.T) { }...) } - type wrapper struct { - containertypes.Config - HostConfig containertypes.HostConfig - } - type createResp struct { - ID string `json:"Id"` - } - ctx := context.Background() apiclient := testEnv.APIClient() for i, x := range cases { diff --git a/integration-cli/docker_api_exec_resize_test.go b/integration-cli/docker_api_exec_resize_test.go index 146552bfbe8e9..8a64dfe307747 100644 --- a/integration-cli/docker_api_exec_resize_test.go +++ b/integration-cli/docker_api_exec_resize_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/api/types/versions" "github.com/docker/docker/testutil/request" + "github.com/pkg/errors" "gotest.tools/assert" ) @@ -46,7 +47,7 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *testing.T) { return err } if res.StatusCode != http.StatusCreated { - return fmt.Errorf("POST %s is expected to return %d, got %d", uri, http.StatusCreated, res.StatusCode) + return errors.Errorf("POST %s is expected to return %d, got %d", uri, http.StatusCreated, res.StatusCode) } buf, err := request.ReadBody(body) @@ -55,18 +56,18 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *testing.T) { out := map[string]string{} err = json.Unmarshal(buf, &out) if err != nil { - return fmt.Errorf("ExecCreate returned invalid json. Error: %q", err.Error()) + return errors.Wrap(err, "ExecCreate returned invalid json") } execID := out["Id"] if len(execID) < 1 { - return fmt.Errorf("ExecCreate got invalid execID") + return errors.New("ExecCreate got invalid execID") } payload := bytes.NewBufferString(`{"Tty":true}`) conn, _, err := sockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json", request.DaemonHost()) if err != nil { - return fmt.Errorf("Failed to start the exec: %q", err.Error()) + return errors.Wrap(err, "failed to start the exec") } defer conn.Close() @@ -74,10 +75,10 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *testing.T) { if err != nil { // It's probably a panic of the daemon if io.ErrUnexpectedEOF is returned. if err == io.ErrUnexpectedEOF { - return fmt.Errorf("The daemon might have crashed.") + return errors.New("the daemon might have crashed") } // Other error happened, should be reported. - return fmt.Errorf("Fail to exec resize immediately after start. Error: %q", err.Error()) + return errors.Wrap(err, "failed to exec resize immediately after start") } rc.Close() diff --git a/integration-cli/docker_api_images_test.go b/integration-cli/docker_api_images_test.go index c36fcf0c5bb24..e1b8199a121b0 100644 --- a/integration-cli/docker_api_images_test.go +++ b/integration-cli/docker_api_images_test.go @@ -84,7 +84,7 @@ func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *testing.T) { assert.Equal(c, res.StatusCode, http.StatusOK) inspectOut := cli.InspectCmd(c, id, cli.Format(".Id")).Combined() - assert.Equal(c, strings.TrimSpace(string(inspectOut)), id, "load did not work properly") + assert.Equal(c, strings.TrimSpace(inspectOut), id, "load did not work properly") } func (s *DockerSuite) TestAPIImagesDelete(c *testing.T) { diff --git a/integration-cli/docker_api_swarm_test.go b/integration-cli/docker_api_swarm_test.go index b443988b36f10..68b11525e19a0 100644 --- a/integration-cli/docker_api_swarm_test.go +++ b/integration-cli/docker_api_swarm_test.go @@ -595,7 +595,7 @@ func (s *DockerSwarmSuite) TestAPISwarmForceNewCluster(c *testing.T) { func simpleTestService(s *swarm.Service) { ureplicas := uint64(1) - restartDelay := time.Duration(100 * time.Millisecond) + restartDelay := 100 * time.Millisecond s.Spec = swarm.ServiceSpec{ TaskTemplate: swarm.TaskSpec{ @@ -618,7 +618,7 @@ func simpleTestService(s *swarm.Service) { func serviceForUpdate(s *swarm.Service) { ureplicas := uint64(1) - restartDelay := time.Duration(100 * time.Millisecond) + restartDelay := 100 * time.Millisecond s.Spec = swarm.ServiceSpec{ TaskTemplate: swarm.TaskSpec{ diff --git a/integration-cli/docker_cli_attach_test.go b/integration-cli/docker_cli_attach_test.go index b1ae40a72ad2f..a22ef105bde9c 100644 --- a/integration-cli/docker_cli_attach_test.go +++ b/integration-cli/docker_cli_attach_test.go @@ -51,24 +51,24 @@ func (s *DockerSuite) TestAttachMultipleAndRestart(c *testing.T) { out, err := cmd.StdoutPipe() if err != nil { - c.Fatal(err) + c.Error(err) } defer out.Close() if err := cmd.Start(); err != nil { - c.Fatal(err) + c.Error(err) } buf := make([]byte, 1024) if _, err := out.Read(buf); err != nil && err != io.EOF { - c.Fatal(err) + c.Error(err) } startGroup.Done() if !strings.Contains(string(buf), "hello") { - c.Fatalf("unexpected output %s expected hello\n", string(buf)) + c.Errorf("unexpected output %s expected hello\n", string(buf)) } }() } diff --git a/integration-cli/docker_cli_build_test.go b/integration-cli/docker_cli_build_test.go index 2f57f6e2423df..6ecfce4ed1291 100644 --- a/integration-cli/docker_cli_build_test.go +++ b/integration-cli/docker_cli_build_test.go @@ -26,7 +26,7 @@ import ( "github.com/docker/docker/testutil/fakegit" "github.com/docker/docker/testutil/fakestorage" "github.com/moby/buildkit/frontend/dockerfile/command" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" "gotest.tools/assert/cmp" "gotest.tools/icmd" @@ -998,7 +998,7 @@ func (s *DockerSuite) TestBuildAddBadLinks(c *testing.T) { } buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx)) - if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) { + if _, err := os.Stat(nonExistingFile); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile) } @@ -1039,7 +1039,7 @@ func (s *DockerSuite) TestBuildAddBadLinksVolume(c *testing.T) { } buildImageSuccessfully(c, "test-link-absolute-volume", build.WithExternalBuildContext(ctx)) - if _, err := os.Stat(nonExistingFile); err == nil || err != nil && !os.IsNotExist(err) { + if _, err := os.Stat(nonExistingFile); err == nil || !os.IsNotExist(err) { c.Fatalf("%s shouldn't have been written and it shouldn't exist", nonExistingFile) } @@ -2082,7 +2082,7 @@ CMD ["cat", "/foo"]`), }).Assert(c, icmd.Success) res := inspectField(c, name, "Config.Cmd") - assert.Equal(c, strings.TrimSpace(string(res)), `[cat /foo]`) + assert.Equal(c, strings.TrimSpace(res), `[cat /foo]`) } // FIXME(vdemeester) migrate to docker/cli tests (unit or e2e) @@ -3427,7 +3427,7 @@ func (s *DockerSuite) TestBuildLabelsCache(c *testing.T) { func (s *DockerSuite) TestBuildNotVerboseSuccess(c *testing.T) { // This test makes sure that -q works correctly when build is successful: // stdout has only the image ID (long image ID) and stderr is empty. - outRegexp := regexp.MustCompile("^(sha256:|)[a-z0-9]{64}\\n$") + outRegexp := regexp.MustCompile(`^(sha256:|)[a-z0-9]{64}\n$`) buildFlags := cli.WithFlags("-q") tt := []struct { diff --git a/integration-cli/docker_cli_build_unix_test.go b/integration-cli/docker_cli_build_unix_test.go index 2d56e2ac94f78..e0a9cc4138908 100644 --- a/integration-cli/docker_cli_build_unix_test.go +++ b/integration-cli/docker_cli_build_unix_test.go @@ -19,7 +19,7 @@ import ( "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/testutil/fakecontext" - "github.com/docker/go-units" + units "github.com/docker/go-units" "gotest.tools/assert" "gotest.tools/icmd" ) diff --git a/integration-cli/docker_cli_by_digest_test.go b/integration-cli/docker_cli_by_digest_test.go index 494ac50204da3..5c0f57b8742f5 100644 --- a/integration-cli/docker_cli_by_digest_test.go +++ b/integration-cli/docker_cli_by_digest_test.go @@ -14,7 +14,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) @@ -22,8 +22,8 @@ import ( var ( remoteRepoName = "dockercli/busybox-by-dgst" repoName = fmt.Sprintf("%s/%s", privateRegistryURL, remoteRepoName) - pushDigestRegex = regexp.MustCompile("[\\S]+: digest: ([\\S]+) size: [0-9]+") - digestRegex = regexp.MustCompile("Digest: ([\\S]+)") + pushDigestRegex = regexp.MustCompile(`[\S]+: digest: ([\S]+) size: [0-9]+`) + digestRegex = regexp.MustCompile(`Digest: ([\S]+)`) ) func setupImage(c *testing.T) (digest.Digest, error) { diff --git a/integration-cli/docker_cli_create_test.go b/integration-cli/docker_cli_create_test.go index 88c7b31f6ec32..87375a23424fb 100644 --- a/integration-cli/docker_cli_create_test.go +++ b/integration-cli/docker_cli_create_test.go @@ -7,7 +7,6 @@ import ( "reflect" "strings" "testing" - "time" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" @@ -28,11 +27,8 @@ func (s *DockerSuite) TestCreateArgs(c *testing.T) { out, _ = dockerCmd(c, "inspect", cleanedContainerID) var containers []struct { - ID string - Created time.Time - Path string - Args []string - Image string + Path string + Args []string } err := json.Unmarshal([]byte(out), &containers) @@ -40,7 +36,7 @@ func (s *DockerSuite) TestCreateArgs(c *testing.T) { assert.Equal(c, len(containers), 1) cont := containers[0] - assert.Equal(c, string(cont.Path), "command", fmt.Sprintf("Unexpected container path. Expected command, received: %s", cont.Path)) + assert.Equal(c, cont.Path, "command", fmt.Sprintf("Unexpected container path. Expected command, received: %s", cont.Path)) b := false expected := []string{"arg1", "arg2", "arg with space", "-c", "flags"} @@ -325,7 +321,7 @@ func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *testing.T) { // #20972 func (s *DockerSuite) TestCreate64ByteHexID(c *testing.T) { out := inspectField(c, "busybox", "Id") - imageID := strings.TrimPrefix(strings.TrimSpace(string(out)), "sha256:") + imageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:") dockerCmd(c, "create", imageID) } diff --git a/integration-cli/docker_cli_daemon_plugins_test.go b/integration-cli/docker_cli_daemon_plugins_test.go index a581d948c15ef..ee7fd9908baf9 100644 --- a/integration-cli/docker_cli_daemon_plugins_test.go +++ b/integration-cli/docker_cli_daemon_plugins_test.go @@ -6,7 +6,6 @@ import ( "strings" "testing" - "github.com/docker/docker/pkg/mount" "golang.org/x/sys/unix" "gotest.tools/assert" "gotest.tools/icmd" @@ -259,19 +258,6 @@ func (s *DockerDaemonSuite) TestPluginVolumeRemoveOnRestart(c *testing.T) { assert.NilError(c, err, out) } -func existsMountpointWithPrefix(mountpointPrefix string) (bool, error) { - mounts, err := mount.GetMounts(nil) - if err != nil { - return false, err - } - for _, mnt := range mounts { - if strings.HasPrefix(mnt.Mountpoint, mountpointPrefix) { - return true, nil - } - } - return false, nil -} - func (s *DockerDaemonSuite) TestPluginListFilterEnabled(c *testing.T) { testRequires(c, IsAmd64, Network) diff --git a/integration-cli/docker_cli_daemon_test.go b/integration-cli/docker_cli_daemon_test.go index 5182f91fc7497..6a874eb981ef3 100644 --- a/integration-cli/docker_cli_daemon_test.go +++ b/integration-cli/docker_cli_daemon_test.go @@ -34,7 +34,7 @@ import ( "github.com/docker/docker/opts" "github.com/docker/docker/pkg/mount" testdaemon "github.com/docker/docker/testutil/daemon" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/docker/libnetwork/iptables" "github.com/docker/libtrust" "golang.org/x/sys/unix" @@ -1750,7 +1750,7 @@ func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *testing.T break } ip, err := s.d.Cmd("inspect", "--format", "'{{.NetworkSettings.IPAddress}}'", contName) - assert.Assert(c, err == nil, "%s", ip) + assert.Assert(c, err == nil, ip) assert.Assert(c, ip != bridgeIP) cont++ @@ -1780,7 +1780,7 @@ func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *testing.T) { // pull a repository large enough to overfill the mounted filesystem pullOut, err := s.d.Cmd("pull", "debian:stretch") - assert.Assert(c, err != nil, "%s", pullOut) + assert.Assert(c, err != nil, pullOut) assert.Assert(c, strings.Contains(pullOut, "no space left on device")) } @@ -1854,11 +1854,11 @@ func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *testing.T) { out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup") assert.NilError(c, err) - cgroupPaths := ParseCgroupPaths(string(out)) - assert.Assert(c, len(cgroupPaths) != 0, "unexpected output - %q", string(out)) + cgroupPaths := ParseCgroupPaths(out) + assert.Assert(c, len(cgroupPaths) != 0, "unexpected output - %q", out) out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name) assert.NilError(c, err) - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) expectedCgroup := path.Join(cgroupParent, id) found := false for _, path := range cgroupPaths { @@ -1890,7 +1890,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *testing.T) { assert.NilError(c, err, out) out, err = s.d.Cmd("start", "-a", "test2") assert.NilError(c, err, out) - assert.Equal(c, strings.Contains(out, "1 packets transmitted, 1 packets received"), true, fmt.Sprintf("%s", out)) + assert.Equal(c, strings.Contains(out, "1 packets transmitted, 1 packets received"), true, out) } func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *testing.T) { @@ -2217,7 +2217,7 @@ func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *testing.T) err = configFile.Truncate(0) assert.NilError(c, err) - _, err = configFile.Seek(0, os.SEEK_SET) + _, err = configFile.Seek(0, io.SeekStart) assert.NilError(c, err) _, err = configFile.Write([]byte(daemonConfig)) diff --git a/integration-cli/docker_cli_external_volume_driver_test.go b/integration-cli/docker_cli_external_volume_driver_test.go index 35a5b0fd3532a..94144f85c9219 100644 --- a/integration-cli/docker_cli_external_volume_driver_test.go +++ b/integration-cli/docker_cli_external_volume_driver_test.go @@ -162,7 +162,6 @@ func newVolumePlugin(c *testing.T, name string) *volumePlugin { v.Mountpoint = hostVolumePath(pr.Name) send(w, map[string]vol{"Volume": v}) - return }) mux.HandleFunc("/VolumeDriver.Remove", func(w http.ResponseWriter, r *http.Request) { @@ -442,7 +441,7 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverBindExternalVolume(c } out := inspectFieldJSON(c, "testing", "Mounts") assert.Assert(c, json.NewDecoder(strings.NewReader(out)).Decode(&mounts) == nil) - assert.Equal(c, len(mounts), 1, fmt.Sprintf("%s", out)) + assert.Equal(c, len(mounts), 1, out) assert.Equal(c, mounts[0].Name, "foo") assert.Equal(c, mounts[0].Driver, volumePluginName) } @@ -598,9 +597,9 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnmountOnMountFail(c s.d.Cmd("volume", "create", "-d", "test-external-volume-driver", "--opt=invalidOption=1", "--name=testumount") out, _ := s.d.Cmd("run", "-v", "testumount:/foo", "busybox", "true") - assert.Equal(c, s.ec.unmounts, 0, fmt.Sprintf("%s", out)) + assert.Equal(c, s.ec.unmounts, 0, out) out, _ = s.d.Cmd("run", "-w", "/foo", "-v", "testumount:/foo", "busybox", "true") - assert.Equal(c, s.ec.unmounts, 0, fmt.Sprintf("%s", out)) + assert.Equal(c, s.ec.unmounts, 0, out) } func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnmountOnCp(c *testing.T) { @@ -608,12 +607,12 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnmountOnCp(c *testi s.d.Cmd("volume", "create", "-d", "test-external-volume-driver", "--name=test") out, _ := s.d.Cmd("run", "-d", "--name=test", "-v", "test:/foo", "busybox", "/bin/sh", "-c", "touch /test && top") - assert.Equal(c, s.ec.mounts, 1, fmt.Sprintf("%s", out)) + assert.Equal(c, s.ec.mounts, 1, out) out, _ = s.d.Cmd("cp", "test:/test", "/tmp/test") - assert.Equal(c, s.ec.mounts, 2, fmt.Sprintf("%s", out)) - assert.Equal(c, s.ec.unmounts, 1, fmt.Sprintf("%s", out)) + assert.Equal(c, s.ec.mounts, 2, out) + assert.Equal(c, s.ec.unmounts, 1, out) out, _ = s.d.Cmd("kill", "test") - assert.Equal(c, s.ec.unmounts, 2, fmt.Sprintf("%s", out)) + assert.Equal(c, s.ec.unmounts, 2, out) } diff --git a/integration-cli/docker_cli_images_test.go b/integration-cli/docker_cli_images_test.go index e9e728b10367e..d81bc39533db7 100644 --- a/integration-cli/docker_cli_images_test.go +++ b/integration-cli/docker_cli_images_test.go @@ -202,7 +202,7 @@ func (s *DockerSuite) TestImagesFilterSpaceTrimCase(c *testing.T) { "dangling = true", } - imageListings := make([][]string, 5, 5) + imageListings := make([][]string, 5) for idx, filter := range filters { out, _ := dockerCmd(c, "images", "-q", "-f", filter) listing := strings.Split(out, "\n") @@ -329,7 +329,7 @@ func (s *DockerSuite) TestImagesFormat(c *testing.T) { dockerCmd(c, "tag", "busybox", tag+":v2") out, _ := dockerCmd(c, "images", "--format", "{{.Repository}}", tag) - lines := strings.Split(strings.TrimSpace(string(out)), "\n") + lines := strings.Split(strings.TrimSpace(out), "\n") expected := []string{"myimage", "myimage"} var names []string diff --git a/integration-cli/docker_cli_import_test.go b/integration-cli/docker_cli_import_test.go index 3506c181885b7..1581e40273690 100644 --- a/integration-cli/docker_cli_import_test.go +++ b/integration-cli/docker_cli_import_test.go @@ -110,7 +110,7 @@ func (s *DockerSuite) TestImportFileWithMessage(c *testing.T) { split := strings.Split(out, "\n") assert.Equal(c, len(split), 3, "expected 3 lines from image history") - r := regexp.MustCompile("[\\s]{2,}") + r := regexp.MustCompile(`[\s]{2,}`) split = r.Split(split[1], -1) assert.Equal(c, message, split[3], "didn't get expected value in commit message") diff --git a/integration-cli/docker_cli_links_test.go b/integration-cli/docker_cli_links_test.go index 575d12c887c7f..9aed629b4b96f 100644 --- a/integration-cli/docker_cli_links_test.go +++ b/integration-cli/docker_cli_links_test.go @@ -161,7 +161,7 @@ func (s *DockerSuite) TestLinksUpdateOnRestart(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) dockerCmd(c, "run", "-d", "--name", "one", "busybox", "top") out, _ := dockerCmd(c, "run", "-d", "--name", "two", "--link", "one:onetwo", "--link", "one:one", "busybox", "top") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) realIP := inspectField(c, "one", "NetworkSettings.Networks.bridge.IPAddress") content := readContainerFileWithExec(c, id, "/etc/hosts") diff --git a/integration-cli/docker_cli_network_unix_test.go b/integration-cli/docker_cli_network_unix_test.go index 01f860e0ca911..e4f9246abb673 100644 --- a/integration-cli/docker_cli_network_unix_test.go +++ b/integration-cli/docker_cli_network_unix_test.go @@ -812,14 +812,14 @@ func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c * // verify first container's etc/hosts file has not changed after spawning the second named container hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile) assert.NilError(c, err) - assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second container creation", hostsFile)) + assert.Equal(c, hosts, hostsPost, fmt.Sprintf("Unexpected %s change on second container creation", hostsFile)) // stop container 2 and verify first container's etc/hosts has not changed _, err = s.d.Cmd("stop", cid2) assert.NilError(c, err) hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) assert.NilError(c, err) - assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second container creation", hostsFile)) + assert.Equal(c, hosts, hostsPost, fmt.Sprintf("Unexpected %s change on second container creation", hostsFile)) // but discovery is on when connecting to non default bridge network network := "anotherbridge" out, err = s.d.Cmd("network", "create", network) @@ -834,7 +834,7 @@ func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c * hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) assert.NilError(c, err) - assert.Equal(c, string(hosts), string(hostsPost), fmt.Sprintf("Unexpected %s change on second network connection", hostsFile)) + assert.Equal(c, hosts, hostsPost, fmt.Sprintf("Unexpected %s change on second network connection", hostsFile)) } func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *testing.T) { @@ -1683,7 +1683,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartRestoreBridgeNetwork(t *testing.T) // Cleanup because these containers will not be shut down by daemon out, err = s.d.Cmd("stop", newCon) if err != nil { - t.Fatalf("err: %v %v", err, string(out)) + t.Fatalf("err: %v %v", err, out) } _, err = s.d.Cmd("stop", strings.TrimSpace(id)) if err != nil { diff --git a/integration-cli/docker_cli_plugins_test.go b/integration-cli/docker_cli_plugins_test.go index 66b89c56ad1af..6f4664565a5c0 100644 --- a/integration-cli/docker_cli_plugins_test.go +++ b/integration-cli/docker_cli_plugins_test.go @@ -428,7 +428,7 @@ func (s *DockerSuite) TestPluginUpgrade(c *testing.T) { // make sure "v2" does not exists _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id, "rootfs", "v2")) - assert.Assert(c, os.IsNotExist(err), "%s", out) + assert.Assert(c, os.IsNotExist(err), out) dockerCmd(c, "plugin", "disable", "-f", plugin) dockerCmd(c, "plugin", "upgrade", "--grant-all-permissions", "--skip-remote-check", plugin, pluginV2) diff --git a/integration-cli/docker_cli_port_test.go b/integration-cli/docker_cli_port_test.go index dd751e3a982cf..163281ddb3083 100644 --- a/integration-cli/docker_cli_port_test.go +++ b/integration-cli/docker_cli_port_test.go @@ -173,33 +173,33 @@ func assertPortList(c *testing.T, out string, expected []string) error { return nil } -func assertPortRange(c *testing.T, out string, expectedTcp, expectedUdp []int) error { +func assertPortRange(c *testing.T, out string, expectedTCP, expectedUDP []int) error { lines := strings.Split(strings.Trim(out, "\n "), "\n") - var validTcp, validUdp bool + var validTCP, validUDP bool for _, l := range lines { // 80/tcp -> 0.0.0.0:8015 port, err := strconv.Atoi(strings.Split(l, ":")[1]) if err != nil { return err } - if strings.Contains(l, "tcp") && expectedTcp != nil { - if port < expectedTcp[0] || port > expectedTcp[1] { - return fmt.Errorf("tcp port (%d) not in range expected range %d-%d", port, expectedTcp[0], expectedTcp[1]) + if strings.Contains(l, "tcp") && expectedTCP != nil { + if port < expectedTCP[0] || port > expectedTCP[1] { + return fmt.Errorf("tcp port (%d) not in range expected range %d-%d", port, expectedTCP[0], expectedTCP[1]) } - validTcp = true + validTCP = true } - if strings.Contains(l, "udp") && expectedUdp != nil { - if port < expectedUdp[0] || port > expectedUdp[1] { - return fmt.Errorf("udp port (%d) not in range expected range %d-%d", port, expectedUdp[0], expectedUdp[1]) + if strings.Contains(l, "udp") && expectedUDP != nil { + if port < expectedUDP[0] || port > expectedUDP[1] { + return fmt.Errorf("udp port (%d) not in range expected range %d-%d", port, expectedUDP[0], expectedUDP[1]) } - validUdp = true + validUDP = true } } - if !validTcp { + if !validTCP { return fmt.Errorf("tcp port not found") } - if !validUdp { + if !validUDP { return fmt.Errorf("udp port not found") } return nil diff --git a/integration-cli/docker_cli_ps_test.go b/integration-cli/docker_cli_ps_test.go index aec67e1baba09..1bbf530744413 100644 --- a/integration-cli/docker_cli_ps_test.go +++ b/integration-cli/docker_cli_ps_test.go @@ -473,22 +473,22 @@ func (s *DockerSuite) TestPsRightTagName(c *testing.T) { var id1 string out := runSleepingContainer(c) - id1 = strings.TrimSpace(string(out)) + id1 = strings.TrimSpace(out) var id2 string out = runSleepingContainerInImage(c, tag) - id2 = strings.TrimSpace(string(out)) + id2 = strings.TrimSpace(out) var imageID string out = inspectField(c, "busybox", "Id") - imageID = strings.TrimSpace(string(out)) + imageID = strings.TrimSpace(out) var id3 string out = runSleepingContainerInImage(c, imageID) - id3 = strings.TrimSpace(string(out)) + id3 = strings.TrimSpace(out) out, _ = dockerCmd(c, "ps", "--no-trunc") - lines := strings.Split(strings.TrimSpace(string(out)), "\n") + lines := strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) // skip header lines = lines[1:] @@ -557,7 +557,7 @@ func (s *DockerSuite) TestPsImageIDAfterUpdate(c *testing.T) { result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc") result.Assert(c, icmd.Success) - lines := strings.Split(strings.TrimSpace(string(result.Combined())), "\n") + lines := strings.Split(strings.TrimSpace(result.Combined()), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) // skip header lines = lines[1:] @@ -574,7 +574,7 @@ func (s *DockerSuite) TestPsImageIDAfterUpdate(c *testing.T) { result = icmd.RunCommand(dockerBinary, "ps", "--no-trunc") result.Assert(c, icmd.Success) - lines = strings.Split(strings.TrimSpace(string(result.Combined())), "\n") + lines = strings.Split(strings.TrimSpace(result.Combined()), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) // skip header lines = lines[1:] @@ -592,7 +592,7 @@ func (s *DockerSuite) TestPsNotShowPortsOfStoppedContainer(c *testing.T) { dockerCmd(c, "run", "--name=foo", "-d", "-p", "5000:5000", "busybox", "top") assert.Assert(c, waitRun("foo") == nil) out, _ := dockerCmd(c, "ps") - lines := strings.Split(strings.TrimSpace(string(out)), "\n") + lines := strings.Split(strings.TrimSpace(out), "\n") expected := "0.0.0.0:5000->5000/tcp" fields := strings.Fields(lines[1]) assert.Equal(c, fields[len(fields)-2], expected, fmt.Sprintf("Expected: %v, got: %v", expected, fields[len(fields)-2])) @@ -600,7 +600,7 @@ func (s *DockerSuite) TestPsNotShowPortsOfStoppedContainer(c *testing.T) { dockerCmd(c, "kill", "foo") dockerCmd(c, "wait", "foo") out, _ = dockerCmd(c, "ps", "-l") - lines = strings.Split(strings.TrimSpace(string(out)), "\n") + lines = strings.Split(strings.TrimSpace(out), "\n") fields = strings.Fields(lines[1]) assert.Assert(c, fields[len(fields)-2] != expected, "Should not got %v", expected) } @@ -633,7 +633,7 @@ func (s *DockerSuite) TestPsShowMounts(c *testing.T) { out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}") - lines := strings.Split(strings.TrimSpace(string(out)), "\n") + lines := strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) assert.Equal(c, len(lines), 3) @@ -653,7 +653,7 @@ func (s *DockerSuite) TestPsShowMounts(c *testing.T) { // filter by volume name out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test") - lines = strings.Split(strings.TrimSpace(string(out)), "\n") + lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) assert.Equal(c, len(lines), 1) @@ -662,12 +662,12 @@ func (s *DockerSuite) TestPsShowMounts(c *testing.T) { // empty results filtering by unknown volume out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist") - assert.Equal(c, len(strings.TrimSpace(string(out))), 0) + assert.Equal(c, len(strings.TrimSpace(out)), 0) // filter by mount destination out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp) - lines = strings.Split(strings.TrimSpace(string(out)), "\n") + lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) assert.Equal(c, len(lines), 2) @@ -679,7 +679,7 @@ func (s *DockerSuite) TestPsShowMounts(c *testing.T) { // filter by bind mount source out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource) - lines = strings.Split(strings.TrimSpace(string(out)), "\n") + lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) assert.Equal(c, len(lines), 1) @@ -691,7 +691,7 @@ func (s *DockerSuite) TestPsShowMounts(c *testing.T) { // filter by bind mount destination out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination) - lines = strings.Split(strings.TrimSpace(string(out)), "\n") + lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) assert.Equal(c, len(lines), 1) @@ -702,7 +702,7 @@ func (s *DockerSuite) TestPsShowMounts(c *testing.T) { // empty results filtering by unknown mount point out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted") - assert.Equal(c, len(strings.TrimSpace(string(out))), 0) + assert.Equal(c, len(strings.TrimSpace(out)), 0) } func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) { @@ -718,7 +718,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) { // Filter docker ps on non existing network out, _ := dockerCmd(c, "ps", "--filter", "network=doesnotexist") - containerOut := strings.TrimSpace(string(out)) + containerOut := strings.TrimSpace(out) lines := strings.Split(containerOut, "\n") // skip header @@ -729,7 +729,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) { // Filter docker ps on network bridge out, _ = dockerCmd(c, "ps", "--filter", "network=bridge") - containerOut = strings.TrimSpace(string(out)) + containerOut = strings.TrimSpace(out) lines = strings.Split(containerOut, "\n") @@ -743,7 +743,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) { assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on network\n") // Filter docker ps on networks bridge and none out, _ = dockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none") - containerOut = strings.TrimSpace(string(out)) + containerOut = strings.TrimSpace(out) lines = strings.Split(containerOut, "\n") @@ -760,15 +760,15 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *testing.T) { // Filter by network ID out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID) - containerOut = strings.TrimSpace(string(out)) + containerOut = strings.TrimSpace(out) assert.Assert(c, is.Contains(containerOut, "onbridgenetwork")) // Filter by partial network ID - partialnwID := string(nwID[0:4]) + partialnwID := nwID[0:4] out, _ = dockerCmd(c, "ps", "--filter", "network="+partialnwID) - containerOut = strings.TrimSpace(string(out)) + containerOut = strings.TrimSpace(out) lines = strings.Split(containerOut, "\n") @@ -844,7 +844,7 @@ func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *testing.T) { dockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top") out, _ := dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}") - lines := strings.Split(strings.TrimSpace(string(out)), "\n") + lines := strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) expected := []string{"bbb", "aaa,bbb/aaa"} var names []string diff --git a/integration-cli/docker_cli_pull_local_test.go b/integration-cli/docker_cli_pull_local_test.go index 94df86d4c9915..94e973a1c4a4f 100644 --- a/integration-cli/docker_cli_pull_local_test.go +++ b/integration-cli/docker_cli_pull_local_test.go @@ -15,7 +15,7 @@ import ( "github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/schema2" "github.com/docker/docker/integration-cli/cli/build" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" "gotest.tools/icmd" ) @@ -107,11 +107,11 @@ func testConcurrentPullWholeRepo(c *testing.T) { } } -func (s *DockerRegistrySuite) testConcurrentPullWholeRepo(c *testing.T) { +func (s *DockerRegistrySuite) TestConcurrentPullWholeRepo(c *testing.T) { testConcurrentPullWholeRepo(c) } -func (s *DockerSchema1RegistrySuite) testConcurrentPullWholeRepo(c *testing.T) { +func (s *DockerSchema1RegistrySuite) TestConcurrentPullWholeRepo(c *testing.T) { testConcurrentPullWholeRepo(c) } @@ -138,11 +138,11 @@ func testConcurrentFailingPull(c *testing.T) { } } -func (s *DockerRegistrySuite) testConcurrentFailingPull(c *testing.T) { +func (s *DockerRegistrySuite) TestConcurrentFailingPull(c *testing.T) { testConcurrentFailingPull(c) } -func (s *DockerSchema1RegistrySuite) testConcurrentFailingPull(c *testing.T) { +func (s *DockerSchema1RegistrySuite) TestConcurrentFailingPull(c *testing.T) { testConcurrentFailingPull(c) } @@ -333,7 +333,7 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *testing.T) { err = os.MkdirAll(blobDir, 0755) assert.NilError(c, err, "error creating blob dir") blobPath := filepath.Join(blobDir, "data") - err = ioutil.WriteFile(blobPath, []byte(manifestListJSON), 0644) + err = ioutil.WriteFile(blobPath, manifestListJSON, 0644) assert.NilError(c, err, "error writing manifest list") // Add to revision store diff --git a/integration-cli/docker_cli_pull_test.go b/integration-cli/docker_cli_pull_test.go index 81f5b1fb874e4..871be9563d173 100644 --- a/integration-cli/docker_cli_pull_test.go +++ b/integration-cli/docker_cli_pull_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) diff --git a/integration-cli/docker_cli_push_test.go b/integration-cli/docker_cli_push_test.go index 53369c273cf9a..ce4ec7aaeb526 100644 --- a/integration-cli/docker_cli_push_test.go +++ b/integration-cli/docker_cli_push_test.go @@ -80,15 +80,13 @@ func testPushMultipleTags(c *testing.T) { repoTag2 := fmt.Sprintf("%v/dockercli/busybox:t2", privateRegistryURL) // tag the image and upload it to the private registry dockerCmd(c, "tag", "busybox", repoTag1) - dockerCmd(c, "tag", "busybox", repoTag2) - dockerCmd(c, "push", repoName) - // Ensure layer list is equivalent for repoTag1 and repoTag2 - out1, _ := dockerCmd(c, "pull", repoTag1) - imageAlreadyExists := ": Image already exists" + + // Ensure layer list is equivalent for repoTag1 and repoTag2 + out1, _ := dockerCmd(c, "push", repoTag1) var out1Lines []string for _, outputLine := range strings.Split(out1, "\n") { if strings.Contains(outputLine, imageAlreadyExists) { @@ -96,19 +94,14 @@ func testPushMultipleTags(c *testing.T) { } } - out2, _ := dockerCmd(c, "pull", repoTag2) - + out2, _ := dockerCmd(c, "push", repoTag2) var out2Lines []string for _, outputLine := range strings.Split(out2, "\n") { if strings.Contains(outputLine, imageAlreadyExists) { - out1Lines = append(out1Lines, outputLine) + out2Lines = append(out2Lines, outputLine) } } - assert.Equal(c, len(out2Lines), len(out1Lines)) - - for i := range out1Lines { - assert.Equal(c, out1Lines[i], out2Lines[i]) - } + assert.DeepEqual(c, out1Lines, out2Lines) } func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) { diff --git a/integration-cli/docker_cli_registry_user_agent_test.go b/integration-cli/docker_cli_registry_user_agent_test.go index 257a47fb477f6..b73d95a9dc180 100644 --- a/integration-cli/docker_cli_registry_user_agent_test.go +++ b/integration-cli/docker_cli_registry_user_agent_test.go @@ -18,13 +18,13 @@ func unescapeBackslashSemicolonParens(s string) string { ret := re.ReplaceAll([]byte(s), []byte(";")) re = regexp.MustCompile(`\\\(`) - ret = re.ReplaceAll([]byte(ret), []byte("(")) + ret = re.ReplaceAll(ret, []byte("(")) re = regexp.MustCompile(`\\\)`) - ret = re.ReplaceAll([]byte(ret), []byte(")")) + ret = re.ReplaceAll(ret, []byte(")")) re = regexp.MustCompile(`\\\\`) - ret = re.ReplaceAll([]byte(ret), []byte(`\`)) + ret = re.ReplaceAll(ret, []byte(`\`)) return string(ret) } @@ -45,7 +45,7 @@ func regexpCheckUA(c *testing.T, ua string) { // check upstreamUA looks correct // Expecting something like: Docker-Client/1.11.0-dev (linux) upstreamUA := unescapeBackslashSemicolonParens(upstreamUAEscaped) - reUpstreamUA := regexp.MustCompile("^\\(Docker-Client/[0-9A-Za-z+]") + reUpstreamUA := regexp.MustCompile(`^\(Docker-Client/[0-9A-Za-z+]`) bMatchUpstreamUA := reUpstreamUA.MatchString(upstreamUA) assert.Assert(c, bMatchUpstreamUA, "(Upstream) Docker Client User-Agent malformed") } @@ -75,8 +75,9 @@ func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *testing.T) { var ua string reg, err := registry.NewMock(c) - defer reg.Close() assert.NilError(c, err) + defer reg.Close() + registerUserAgentHandler(reg, &ua) repoName := fmt.Sprintf("%s/busybox", reg.URL()) diff --git a/integration-cli/docker_cli_restart_test.go b/integration-cli/docker_cli_restart_test.go index 9e1d99d3eb922..e6534539eb3e5 100644 --- a/integration-cli/docker_cli_restart_test.go +++ b/integration-cli/docker_cli_restart_test.go @@ -98,7 +98,7 @@ func (s *DockerSuite) TestRestartDisconnectedContainer(c *testing.T) { func (s *DockerSuite) TestRestartPolicyNO(c *testing.T) { out, _ := dockerCmd(c, "create", "--restart=no", "busybox") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") assert.Equal(c, name, "no") } @@ -106,7 +106,7 @@ func (s *DockerSuite) TestRestartPolicyNO(c *testing.T) { func (s *DockerSuite) TestRestartPolicyAlways(c *testing.T) { out, _ := dockerCmd(c, "create", "--restart=always", "busybox") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") assert.Equal(c, name, "always") @@ -123,7 +123,7 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) { out, _ = dockerCmd(c, "create", "--restart=on-failure:1", "busybox") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") @@ -132,7 +132,7 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) { out, _ = dockerCmd(c, "create", "--restart=on-failure:0", "busybox") - id = strings.TrimSpace(string(out)) + id = strings.TrimSpace(out) name = inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") @@ -141,7 +141,7 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) { out, _ = dockerCmd(c, "create", "--restart=on-failure", "busybox") - id = strings.TrimSpace(string(out)) + id = strings.TrimSpace(out) name = inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") @@ -154,7 +154,7 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *testing.T) { func (s *DockerSuite) TestRestartContainerwithGoodContainer(c *testing.T) { out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "true") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second) assert.NilError(c, err) @@ -281,8 +281,8 @@ func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *testing.T) { out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false") - id1 := strings.TrimSpace(string(out1)) - id2 := strings.TrimSpace(string(out2)) + id1 := strings.TrimSpace(out1) + id2 := strings.TrimSpace(out2) waitTimeout := 15 * time.Second if testEnv.OSType == "windows" { waitTimeout = 150 * time.Second @@ -311,7 +311,7 @@ func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *testing.T) { func (s *DockerSuite) TestRestartAutoRemoveContainer(c *testing.T) { out := runSleepingContainer(c, "--rm") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) dockerCmd(c, "restart", id) err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_run_test.go b/integration-cli/docker_cli_run_test.go index 3a431aaddd697..0f982403d24b6 100644 --- a/integration-cli/docker_cli_run_test.go +++ b/integration-cli/docker_cli_run_test.go @@ -1332,8 +1332,8 @@ func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) { var out string out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf") - if actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP); string(actualNameservers[0]) != "127.0.0.1" { - c.Fatalf("expected '127.0.0.1', but says: %q", string(actualNameservers[0])) + if actualNameservers := resolvconf.GetNameservers([]byte(out), types.IP); actualNameservers[0] != "127.0.0.1" { + c.Fatalf("expected '127.0.0.1', but says: %q", actualNameservers[0]) } actualSearch := resolvconf.GetSearchDomains([]byte(out)) @@ -1358,8 +1358,8 @@ func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) { } } - if actualSearch = resolvconf.GetSearchDomains([]byte(out)); string(actualSearch[0]) != "mydomain" { - c.Fatalf("expected 'mydomain', but says: %q", string(actualSearch[0])) + if actualSearch = resolvconf.GetSearchDomains([]byte(out)); actualSearch[0] != "mydomain" { + c.Fatalf("expected 'mydomain', but says: %q", actualSearch[0]) } // test with file @@ -1382,7 +1382,7 @@ func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) { hostSearch = resolvconf.GetSearchDomains(resolvConf) out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") - if actualNameservers = resolvconf.GetNameservers([]byte(out), types.IP); string(actualNameservers[0]) != "12.34.56.78" || len(actualNameservers) != 1 { + if actualNameservers = resolvconf.GetNameservers([]byte(out), types.IP); actualNameservers[0] != "12.34.56.78" || len(actualNameservers) != 1 { c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers) } @@ -1458,8 +1458,7 @@ func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { containerID1 := getIDByName(c, "first") // replace resolv.conf with our temporary copy - bytesResolvConf := []byte(tmpResolvConf) - if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { + if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { c.Fatal(err) } @@ -1468,7 +1467,7 @@ func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { // check for update in container containerResolv := readContainerFile(c, containerID1, "resolv.conf") - if !bytes.Equal(containerResolv, bytesResolvConf) { + if !bytes.Equal(containerResolv, tmpResolvConf) { c.Fatalf("Restarted container does not have updated resolv.conf; expected %q, got %q", tmpResolvConf, string(containerResolv)) } @@ -1500,13 +1499,13 @@ func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { runningContainerID := strings.TrimSpace(out) // replace resolv.conf - if err := ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { + if err := ioutil.WriteFile("/etc/resolv.conf", tmpResolvConf, 0644); err != nil { c.Fatal(err) } // check for update in container containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") - if bytes.Equal(containerResolv, bytesResolvConf) { + if bytes.Equal(containerResolv, tmpResolvConf) { c.Fatalf("Running container should not have updated resolv.conf; expected %q, got %q", string(resolvConfSystem), string(containerResolv)) } @@ -1516,16 +1515,15 @@ func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { // check for update in container containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") - if !bytes.Equal(containerResolv, bytesResolvConf) { - c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(bytesResolvConf), string(containerResolv)) + if !bytes.Equal(containerResolv, tmpResolvConf) { + c.Fatalf("Restarted container should have updated resolv.conf; expected %q, got %q", string(tmpResolvConf), string(containerResolv)) } //5. test that additions of a localhost resolver are cleaned from // host resolv.conf before updating container's resolv.conf copies // replace resolv.conf with a localhost-only nameserver copy - bytesResolvConf = []byte(tmpLocalhostResolvConf) - if err = ioutil.WriteFile("/etc/resolv.conf", bytesResolvConf, 0644); err != nil { + if err = ioutil.WriteFile("/etc/resolv.conf", tmpLocalhostResolvConf, 0644); err != nil { c.Fatal(err) } @@ -1553,8 +1551,7 @@ func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { containerID3 := getIDByName(c, "third") // Create a modified resolv.conf.aside and override resolv.conf with it - bytesResolvConf = []byte(tmpResolvConf) - if err := ioutil.WriteFile("/etc/resolv.conf.aside", bytesResolvConf, 0644); err != nil { + if err := ioutil.WriteFile("/etc/resolv.conf.aside", tmpResolvConf, 0644); err != nil { c.Fatal(err) } @@ -1568,7 +1565,7 @@ func (s *DockerSuite) TestRunResolvconfUpdate(c *testing.T) { // check for update in container containerResolv = readContainerFile(c, containerID3, "resolv.conf") - if !bytes.Equal(containerResolv, bytesResolvConf) { + if !bytes.Equal(containerResolv, tmpResolvConf) { c.Fatalf("Stopped container does not have updated resolv.conf; expected\n%q\n got\n%q", tmpResolvConf, string(containerResolv)) } @@ -2661,7 +2658,7 @@ func (s *DockerSuite) TestRunRestartMaxRetries(c *testing.T) { timeout = 120 * time.Second } - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil { c.Fatal(err) } @@ -2704,7 +2701,7 @@ func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *testing.T) { c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.") } expected := "type devpts (rw," - if !strings.Contains(string(out), expected) { + if !strings.Contains(out, expected) { c.Fatalf("expected output to contain %s but contains %s", expected, out) } } @@ -2739,7 +2736,7 @@ func (s *DockerSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContainer(c * dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts") - if !strings.Contains(string(out), "testlinked") { + if !strings.Contains(out, "testlinked") { c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled") } } @@ -2749,7 +2746,7 @@ func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *testing.T testRequires(c, DaemonIsLinux, UserNamespaceROMount) out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf") - if !strings.Contains(string(out), "1.1.1.1") { + if !strings.Contains(out, "1.1.1.1") { c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used") } } @@ -2759,7 +2756,7 @@ func (s *DockerSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c *testi testRequires(c, DaemonIsLinux, UserNamespaceROMount) out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts") - if !strings.Contains(string(out), "testreadonly") { + if !strings.Contains(out, "testreadonly") { c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used") } } @@ -3249,11 +3246,11 @@ func (s *DockerSuite) TestRunContainerWithCgroupParent(c *testing.T) { func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) { out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") if err != nil { - c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) + c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err) } - cgroupPaths := ParseCgroupPaths(string(out)) + cgroupPaths := ParseCgroupPaths(out) if len(cgroupPaths) == 0 { - c.Fatalf("unexpected output - %q", string(out)) + c.Fatalf("unexpected output - %q", out) } id := getIDByName(c, name) expectedCgroup := path.Join(cgroupParent, id) @@ -3283,7 +3280,7 @@ func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, n out, _, err := dockerCmdWithError("run", "--cgroup-parent", cgroupParent, "--name", name, "busybox", "cat", "/proc/self/cgroup") if err != nil { // XXX: This may include a daemon crash. - c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", string(out), err) + c.Fatalf("unexpected failure when running container with --cgroup-parent option - %s\n%v", out, err) } // We expect "/SHOULD_NOT_EXIST" to not exist. If not, we have a security issue. @@ -3291,9 +3288,9 @@ func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, n c.Fatalf("SECURITY: --cgroup-parent with ../../ relative paths cause files to be created in the host (this is bad) !!") } - cgroupPaths := ParseCgroupPaths(string(out)) + cgroupPaths := ParseCgroupPaths(out) if len(cgroupPaths) == 0 { - c.Fatalf("unexpected output - %q", string(out)) + c.Fatalf("unexpected output - %q", out) } id := getIDByName(c, name) expectedCgroup := path.Join(cleanCgroupParent, id) @@ -3947,11 +3944,11 @@ func (s *DockerSuite) TestRunAttachFailedNoLeak(c *testing.T) { assert.Assert(c, err != nil, "Command should have failed but succeeded with: %s\nContainer 'test' [%+v]: %s\nContainer 'fail' [%+v]: %s", out, err1, out1, err2, out2) // check for windows error as well // TODO Windows Post TP5. Fix the error message string - assert.Assert(c, strings.Contains(string(out), "port is already allocated") || - strings.Contains(string(out), "were not connected because a duplicate name exists") || - strings.Contains(string(out), "The specified port already exists") || - strings.Contains(string(out), "HNS failed with error : Failed to create endpoint") || - strings.Contains(string(out), "HNS failed with error : The object already exists"), fmt.Sprintf("Output: %s", out)) + assert.Assert(c, strings.Contains(out, "port is already allocated") || + strings.Contains(out, "were not connected because a duplicate name exists") || + strings.Contains(out, "The specified port already exists") || + strings.Contains(out, "HNS failed with error : Failed to create endpoint") || + strings.Contains(out, "HNS failed with error : The object already exists"), fmt.Sprintf("Output: %s", out)) dockerCmd(c, "rm", "-f", "test") // NGoroutines is not updated right away, so we need to wait before failing diff --git a/integration-cli/docker_cli_save_load_test.go b/integration-cli/docker_cli_save_load_test.go index 4bcd1d08314c5..59da3fec00275 100644 --- a/integration-cli/docker_cli_save_load_test.go +++ b/integration-cli/docker_cli_save_load_test.go @@ -17,7 +17,7 @@ import ( "time" "github.com/docker/docker/integration-cli/cli/build" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/icmd" @@ -236,7 +236,7 @@ func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *testing.T) { lines := strings.Split(strings.TrimSpace(out), "\n") var actual []string for _, l := range lines { - if regexp.MustCompile("^[a-f0-9]{64}\\.json$").Match([]byte(l)) { + if regexp.MustCompile(`^[a-f0-9]{64}\.json$`).Match([]byte(l)) { actual = append(actual, strings.TrimSuffix(l, ".json")) } } diff --git a/integration-cli/docker_cli_service_logs_test.go b/integration-cli/docker_cli_service_logs_test.go index 50857664f144b..9170878377328 100644 --- a/integration-cli/docker_cli_service_logs_test.go +++ b/integration-cli/docker_cli_service_logs_test.go @@ -65,7 +65,7 @@ func countLogLines(d *daemon.Daemon, name string) func(*testing.T) (interface{}, return 0, "Empty stdout" } lines := strings.Split(strings.TrimSpace(result.Stdout()), "\n") - return len(lines), fmt.Sprintf("output, %q", string(result.Stdout())) + return len(lines), fmt.Sprintf("output, %q", result.Stdout()) } } diff --git a/integration-cli/docker_cli_swarm_test.go b/integration-cli/docker_cli_swarm_test.go index e597a09fc4a12..c91f29e5dde6e 100644 --- a/integration-cli/docker_cli_swarm_test.go +++ b/integration-cli/docker_cli_swarm_test.go @@ -171,7 +171,7 @@ func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *testing.T) { func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *testing.T) { d := s.AddDaemon(c, true, true) hostname, err := d.Cmd("node", "inspect", "--format", "{{.Description.Hostname}}", "self") - assert.Assert(c, err == nil, "%s", hostname) + assert.Assert(c, err == nil, hostname) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "test", "--hostname", "{{.Service.Name}}-{{.Task.Slot}}-{{.Node.Hostname}}", "busybox", "top") assert.NilError(c, err, out) @@ -900,15 +900,15 @@ func (s *DockerSwarmSuite) TestSwarmServiceNetworkUpdate(c *testing.T) { result := icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "foo")) result.Assert(c, icmd.Success) - fooNetwork := strings.TrimSpace(string(result.Combined())) + fooNetwork := strings.TrimSpace(result.Combined()) result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "bar")) result.Assert(c, icmd.Success) - barNetwork := strings.TrimSpace(string(result.Combined())) + barNetwork := strings.TrimSpace(result.Combined()) result = icmd.RunCmd(d.Command("network", "create", "-d", "overlay", "baz")) result.Assert(c, icmd.Success) - bazNetwork := strings.TrimSpace(string(result.Combined())) + bazNetwork := strings.TrimSpace(result.Combined()) // Create a service name := "top" @@ -1043,7 +1043,7 @@ func (s *DockerSwarmSuite) TestSwarmInitLocked(c *testing.T) { d := s.AddDaemon(c, false, false) outs, err := d.Cmd("swarm", "init", "--autolock") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) unlockKey := getUnlockKey(d, c, outs) assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive) @@ -1068,15 +1068,15 @@ func (s *DockerSwarmSuite) TestSwarmInitLocked(c *testing.T) { assert.Equal(c, getNodeStatus(c, d), swarm.LocalNodeStateActive) outs, err = d.Cmd("node", "ls") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked")) outs, err = d.Cmd("swarm", "update", "--autolock=false") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) checkSwarmLockedToUnlocked(c, d) outs, err = d.Cmd("node", "ls") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked")) } @@ -1084,7 +1084,7 @@ func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *testing.T) { d := s.AddDaemon(c, false, false) outs, err := d.Cmd("swarm", "init", "--autolock") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) // It starts off locked d.RestartNode(c) @@ -1099,13 +1099,13 @@ func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *testing.T) { assert.Assert(c, strings.Contains(outs, "Swarm is encrypted and locked.")) // It is OK for user to leave a locked swarm with --force outs, err = d.Cmd("swarm", "leave", "--force") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) info = d.SwarmInfo(c) assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) outs, err = d.Cmd("swarm", "init") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) info = d.SwarmInfo(c) assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) @@ -1125,7 +1125,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *testing.T) { // enable autolock outs, err := d1.Cmd("swarm", "update", "--autolock") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) unlockKey := getUnlockKey(d1, c, outs) // The ones that got the cluster update should be set to locked @@ -1320,13 +1320,13 @@ func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *testing.T) { d3 := s.AddDaemon(c, true, true) outs, err := d1.Cmd("swarm", "update", "--autolock") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) unlockKey := getUnlockKey(d1, c, outs) // Rotate multiple times for i := 0; i != 3; i++ { outs, err = d1.Cmd("swarm", "unlock-key", "-q", "--rotate") - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) // Strip \n newUnlockKey := outs[:len(outs)-1] assert.Assert(c, newUnlockKey != "") @@ -1385,7 +1385,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *testing.T) { continue } } - assert.Assert(c, err == nil, "%s", outs) + assert.Assert(c, err == nil, outs) assert.Assert(c, !strings.Contains(outs, "Swarm is encrypted and needs to be unlocked")) break } @@ -1982,7 +1982,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsConfig(c *testing.T) { func getUnlockKey(d *daemon.Daemon, c *testing.T, autolockOutput string) string { unlockKey, err := d.Cmd("swarm", "unlock-key", "-q") - assert.Assert(c, err == nil, "%s", unlockKey) + assert.Assert(c, err == nil, unlockKey) unlockKey = strings.TrimSuffix(unlockKey, "\n") // Check that "docker swarm init --autolock" or "docker swarm update --autolock" diff --git a/integration-cli/docker_cli_swarm_unix_test.go b/integration-cli/docker_cli_swarm_unix_test.go index ea51256489e8c..35d0a5a3012df 100644 --- a/integration-cli/docker_cli_swarm_unix_test.go +++ b/integration-cli/docker_cli_swarm_unix_test.go @@ -50,7 +50,7 @@ func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *testing.T) { } assert.NilError(c, json.NewDecoder(strings.NewReader(out)).Decode(&mounts)) - assert.Equal(c, len(mounts), 1, string(out)) + assert.Equal(c, len(mounts), 1, out) assert.Equal(c, mounts[0].Name, "my-volume") assert.Equal(c, mounts[0].Driver, "customvolumedriver") } diff --git a/integration-cli/docker_cli_update_unix_test.go b/integration-cli/docker_cli_update_unix_test.go index ad5a7ab145d6b..95d02b7f5317c 100644 --- a/integration-cli/docker_cli_update_unix_test.go +++ b/integration-cli/docker_cli_update_unix_test.go @@ -271,7 +271,7 @@ func (s *DockerSuite) TestUpdateNotAffectMonitorRestartPolicy(c *testing.T) { testRequires(c, DaemonIsLinux, cpuShare) out, _ := dockerCmd(c, "run", "-tid", "--restart=always", "busybox", "sh") - id := strings.TrimSpace(string(out)) + id := strings.TrimSpace(out) dockerCmd(c, "update", "--cpu-shares", "512", id) cpty, tty, err := pty.Open() diff --git a/integration-cli/docker_cli_v2_only_test.go b/integration-cli/docker_cli_v2_only_test.go index f985a360f9309..d10ccd4ed3d6a 100644 --- a/integration-cli/docker_cli_v2_only_test.go +++ b/integration-cli/docker_cli_v2_only_test.go @@ -27,8 +27,8 @@ func makefile(path string, contents string) (string, error) { // attempt to contact any v1 registry endpoints. func (s *DockerRegistrySuite) TestV2Only(c *testing.T) { reg, err := registry.NewMock(c) - defer reg.Close() assert.NilError(c, err) + defer reg.Close() reg.RegisterHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) @@ -49,11 +49,10 @@ func (s *DockerRegistrySuite) TestV2Only(c *testing.T) { dockerfileName, err := makefile(tmp, fmt.Sprintf("FROM %s/busybox", reg.URL())) assert.NilError(c, err, "Unable to create test dockerfile") - s.d.Cmd("build", "--file", dockerfileName, tmp) - - s.d.Cmd("run", repoName) - s.d.Cmd("login", "-u", "richard", "-p", "testtest", reg.URL()) - s.d.Cmd("tag", "busybox", repoName) - s.d.Cmd("push", repoName) - s.d.Cmd("pull", repoName) + _, _ = s.d.Cmd("build", "--file", dockerfileName, tmp) + _, _ = s.d.Cmd("run", repoName) + _, _ = s.d.Cmd("login", "-u", "richard", "-p", "testtest", reg.URL()) + _, _ = s.d.Cmd("tag", "busybox", repoName) + _, _ = s.d.Cmd("push", repoName) + _, _ = s.d.Cmd("pull", repoName) } diff --git a/integration-cli/docker_cli_volume_test.go b/integration-cli/docker_cli_volume_test.go index f5fcf600d3160..3a74302c727ad 100644 --- a/integration-cli/docker_cli_volume_test.go +++ b/integration-cli/docker_cli_volume_test.go @@ -106,7 +106,7 @@ func (s *DockerSuite) TestVolumeLsFormatDefaultFormat(c *testing.T) { } func assertVolumesInList(c *testing.T, out string, expected []string) { - lines := strings.Split(strings.TrimSpace(string(out)), "\n") + lines := strings.Split(strings.TrimSpace(out), "\n") for _, expect := range expected { found := false for _, v := range lines { diff --git a/integration-cli/docker_utils_test.go b/integration-cli/docker_utils_test.go index 3ee6b7c098c75..f817681fcdefc 100644 --- a/integration-cli/docker_utils_test.go +++ b/integration-cli/docker_utils_test.go @@ -174,20 +174,6 @@ func inspectMountPointJSON(j, destination string) (types.MountPoint, error) { return *m, nil } -// Deprecated: use cli.Inspect -func inspectImage(c *testing.T, name, filter string) string { - c.Helper() - args := []string{"inspect", "--type", "image"} - if filter != "" { - format := fmt.Sprintf("{{%s}}", filter) - args = append(args, "-f", format) - } - args = append(args, name) - result := icmd.RunCommand(dockerBinary, args...) - result.Assert(c, icmd.Success) - return strings.TrimSpace(result.Combined()) -} - func getIDByName(c *testing.T, name string) string { c.Helper() id, err := inspectFieldWithError(name, "Id") diff --git a/integration-cli/events_utils_test.go b/integration-cli/events_utils_test.go index 0bd923d1488c3..a9116102a784c 100644 --- a/integration-cli/events_utils_test.go +++ b/integration-cli/events_utils_test.go @@ -192,15 +192,3 @@ func parseEvents(c *testing.T, out, match string) { assert.Assert(c, matched, "Matcher: %s did not match %s", match, matches["action"]) } } - -func parseEventsWithID(c *testing.T, out, match, id string) { - events := strings.Split(strings.TrimSpace(out), "\n") - for _, event := range events { - matches := eventstestutils.ScanMap(event) - assert.Assert(c, matchEventID(matches, id)) - - matched, err := regexp.MatchString(match, matches["action"]) - assert.NilError(c, err) - assert.Assert(c, matched, "Matcher: %s did not match %s", match, matches["action"]) - } -} diff --git a/integration-cli/fixtures_linux_daemon_test.go b/integration-cli/fixtures_linux_daemon_test.go index 2f38f3bae7c91..92a0ceadd266b 100644 --- a/integration-cli/fixtures_linux_daemon_test.go +++ b/integration-cli/fixtures_linux_daemon_test.go @@ -14,15 +14,6 @@ import ( "gotest.tools/assert" ) -type testingT interface { - logT - Fatalf(string, ...interface{}) -} - -type logT interface { - Logf(string, ...interface{}) -} - func ensureSyscallTest(c *testing.T) { defer testEnv.ProtectImage(c, "syscall-test:latest") @@ -61,7 +52,7 @@ func ensureSyscallTest(c *testing.T) { FROM debian:jessie COPY . /usr/bin/ `) - err = ioutil.WriteFile(dockerFile, content, 600) + err = ioutil.WriteFile(dockerFile, content, 0600) assert.NilError(c, err) var buildArgs []string @@ -116,7 +107,7 @@ func ensureNNPTest(c *testing.T) { COPY . /usr/bin RUN chmod +s /usr/bin/nnp-test ` - err = ioutil.WriteFile(dockerfile, []byte(content), 600) + err = ioutil.WriteFile(dockerfile, []byte(content), 0600) assert.NilError(c, err, "could not write Dockerfile for nnp-test image") var buildArgs []string diff --git a/integration-cli/requirements_test.go b/integration-cli/requirements_test.go index 9e4971451f162..c7d913d51b35b 100644 --- a/integration-cli/requirements_test.go +++ b/integration-cli/requirements_test.go @@ -82,8 +82,8 @@ func UnixCli() bool { func Network() bool { // Set a timeout on the GET at 15s - var timeout = time.Duration(15 * time.Second) - var url = "https://hub.docker.com" + const timeout = 15 * time.Second + const url = "https://hub.docker.com" client := http.Client{ Timeout: timeout, diff --git a/integration/container/create_test.go b/integration/container/create_test.go index 7be1cb6eacc72..769e673b9abf4 100644 --- a/integration/container/create_test.go +++ b/integration/container/create_test.go @@ -385,7 +385,6 @@ func TestCreateWithCustomReadonlyPaths(t *testing.T) { ctx := context.Background() testCases := []struct { - doc string readonlyPaths []string expected []string }{ diff --git a/integration/container/wait_test.go b/integration/container/wait_test.go index 57d83d7525f8f..061b426918fc6 100644 --- a/integration/container/wait_test.go +++ b/integration/container/wait_test.go @@ -42,12 +42,12 @@ func TestWaitNonBlocked(t *testing.T) { containerID := container.Run(ctx, t, cli, container.WithCmd("sh", "-c", tc.cmd)) poll.WaitOn(t, container.IsInState(ctx, cli, containerID, "exited"), poll.WithTimeout(30*time.Second), poll.WithDelay(100*time.Millisecond)) - waitresC, errC := cli.ContainerWait(ctx, containerID, "") + waitResC, errC := cli.ContainerWait(ctx, containerID, "") select { case err := <-errC: assert.NilError(t, err) - case waitres := <-waitresC: - assert.Check(t, is.Equal(tc.expectedCode, waitres.StatusCode)) + case waitRes := <-waitResC: + assert.Check(t, is.Equal(tc.expectedCode, waitRes.StatusCode)) } }) } @@ -84,7 +84,7 @@ func TestWaitBlocked(t *testing.T) { containerID := container.Run(ctx, t, cli, container.WithCmd("sh", "-c", tc.cmd)) poll.WaitOn(t, container.IsInState(ctx, cli, containerID, "running"), poll.WithTimeout(30*time.Second), poll.WithDelay(100*time.Millisecond)) - waitresC, errC := cli.ContainerWait(ctx, containerID, "") + waitResC, errC := cli.ContainerWait(ctx, containerID, "") err := cli.ContainerStop(ctx, containerID, nil) assert.NilError(t, err) @@ -92,8 +92,8 @@ func TestWaitBlocked(t *testing.T) { select { case err := <-errC: assert.NilError(t, err) - case waitres := <-waitresC: - assert.Check(t, is.Equal(tc.expectedCode, waitres.StatusCode)) + case waitRes := <-waitResC: + assert.Check(t, is.Equal(tc.expectedCode, waitRes.StatusCode)) case <-time.After(2 * time.Second): t.Fatal("timeout waiting for `docker wait`") } diff --git a/integration/image/remove_unix_test.go b/integration/image/remove_unix_test.go index 4dbd2eab9409a..aad281bc6e522 100644 --- a/integration/image/remove_unix_test.go +++ b/integration/image/remove_unix_test.go @@ -88,6 +88,6 @@ func TestRemoveImageGarbageCollector(t *testing.T) { // Run imageService.Cleanup() and make sure that layer was removed from disk i.Cleanup() - dir, err = os.Stat(data["UpperDir"]) - assert.ErrorContains(t, err, "no such file or directory") + _, err = os.Stat(data["UpperDir"]) + assert.Assert(t, os.IsNotExist(err)) } diff --git a/integration/network/ipvlan/main_test.go b/integration/network/ipvlan/main_test.go index 20d149bbaaba1..c235396da07c7 100644 --- a/integration/network/ipvlan/main_test.go +++ b/integration/network/ipvlan/main_test.go @@ -28,8 +28,3 @@ func TestMain(m *testing.M) { testEnv.Print() os.Exit(m.Run()) } - -func setupTest(t *testing.T) func() { - environment.ProtectAll(t, testEnv) - return func() { testEnv.Clean(t) } -} diff --git a/integration/network/macvlan/macvlan_test.go b/integration/network/macvlan/macvlan_test.go index f9d9e676d19fb..4caed271f1153 100644 --- a/integration/network/macvlan/macvlan_test.go +++ b/integration/network/macvlan/macvlan_test.go @@ -59,6 +59,9 @@ func TestDockerNetworkMacvlan(t *testing.T) { }, { name: "InternalMode", test: testMacvlanInternalMode, + }, { + name: "MultiSubnet", + test: testMacvlanMultiSubnet, }, { name: "Addressing", test: testMacvlanAddressing, @@ -237,7 +240,7 @@ func testMacvlanMultiSubnet(client client.APIClient) func(*testing.T) { // Inspect the v4 gateway to ensure the proper explicitly assigned default GW was assigned assert.Equal(t, c3.NetworkSettings.Networks["dualstackbridge"].Gateway, "172.28.102.254") // Inspect the v6 gateway to ensure the proper explicitly assigned default GW was assigned - assert.Equal(t, c3.NetworkSettings.Networks["dualstackbridge"].IPv6Gateway, "2001:db8.abc4::254") + assert.Equal(t, c3.NetworkSettings.Networks["dualstackbridge"].IPv6Gateway, "2001:db8:abc4::254") } } diff --git a/integration/network/macvlan/main_test.go b/integration/network/macvlan/main_test.go index 85e48500c4fa4..c18ef7b12e97f 100644 --- a/integration/network/macvlan/main_test.go +++ b/integration/network/macvlan/main_test.go @@ -28,8 +28,3 @@ func TestMain(m *testing.M) { testEnv.Print() os.Exit(m.Run()) } - -func setupTest(t *testing.T) func() { - environment.ProtectAll(t, testEnv) - return func() { testEnv.Clean(t) } -} diff --git a/integration/plugin/graphdriver/external_test.go b/integration/plugin/graphdriver/external_test.go index d72210be3efa1..dce8efc354b76 100644 --- a/integration/plugin/graphdriver/external_test.go +++ b/integration/plugin/graphdriver/external_test.go @@ -424,8 +424,8 @@ func TestGraphdriverPluginV2(t *testing.T) { RemoteRef: plugin, AcceptAllPermissions: true, }) - defer responseReader.Close() assert.NilError(t, err) + defer responseReader.Close() // ensure it's done by waiting for EOF on the response _, err = io.Copy(ioutil.Discard, responseReader) assert.NilError(t, err) diff --git a/integration/plugin/graphdriver/main_test.go b/integration/plugin/graphdriver/main_test.go index 21dd9beba0ab0..68fa02c81e9bf 100644 --- a/integration/plugin/graphdriver/main_test.go +++ b/integration/plugin/graphdriver/main_test.go @@ -17,8 +17,6 @@ func init() { reexec.Init() // This is required for external graphdriver tests } -const dockerdBinary = "dockerd" - func TestMain(m *testing.M) { var err error testEnv, err = environment.New() diff --git a/layer/empty_test.go b/layer/empty_test.go index ec9fbc1a3c352..d4671a1b07e1b 100644 --- a/layer/empty_test.go +++ b/layer/empty_test.go @@ -4,7 +4,7 @@ import ( "io" "testing" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) func TestEmptyLayer(t *testing.T) { diff --git a/layer/filestore_test.go b/layer/filestore_test.go index 878dc54e3616e..3af1904f48751 100644 --- a/layer/filestore_test.go +++ b/layer/filestore_test.go @@ -11,7 +11,7 @@ import ( "testing" "github.com/docker/docker/pkg/stringid" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) func randomLayerID(seed int64) ChainID { diff --git a/layer/layer.go b/layer/layer.go index 53923ad42af5e..7b7624f4fcbf3 100644 --- a/layer/layer.go +++ b/layer/layer.go @@ -16,7 +16,7 @@ import ( "github.com/docker/distribution" "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/containerfs" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" ) diff --git a/layer/layer_store.go b/layer/layer_store.go index 7b8c011f4c07c..dd766c9d55ae8 100644 --- a/layer/layer_store.go +++ b/layer/layer_store.go @@ -16,7 +16,7 @@ import ( "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/system" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" "github.com/vbatts/tar-split/tar/asm" "github.com/vbatts/tar-split/tar/storage" diff --git a/layer/layer_test.go b/layer/layer_test.go index 5c4e8fab190ad..9199b9c2dbca0 100644 --- a/layer/layer_test.go +++ b/layer/layer_test.go @@ -17,7 +17,7 @@ import ( "github.com/docker/docker/pkg/containerfs" "github.com/docker/docker/pkg/idtools" "github.com/docker/docker/pkg/stringid" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) func init() { @@ -171,10 +171,6 @@ func getCachedLayer(l Layer) *roLayer { return l.(*roLayer) } -func getMountLayer(l RWLayer) *mountedLayer { - return l.(*referencedRWLayer).mountedLayer -} - func createMetadata(layers ...Layer) []Metadata { metadata := make([]Metadata, len(layers)) for i := range layers { diff --git a/layer/migration.go b/layer/migration.go index 12500694f0a93..5834659433e61 100644 --- a/layer/migration.go +++ b/layer/migration.go @@ -6,7 +6,7 @@ import ( "io" "os" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/sirupsen/logrus" "github.com/vbatts/tar-split/tar/asm" "github.com/vbatts/tar-split/tar/storage" diff --git a/layer/mounted_layer.go b/layer/mounted_layer.go index 99bb10d42521e..f614fd571df2a 100644 --- a/layer/mounted_layer.go +++ b/layer/mounted_layer.go @@ -13,7 +13,6 @@ type mountedLayer struct { mountID string initID string parent *roLayer - path string layerStore *layerStore sync.Mutex diff --git a/layer/ro_layer.go b/layer/ro_layer.go index 3555e8b027994..15841d5bd2447 100644 --- a/layer/ro_layer.go +++ b/layer/ro_layer.go @@ -5,7 +5,7 @@ import ( "io" "github.com/docker/distribution" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" ) type roLayer struct { diff --git a/libcontainerd/remote/client_linux.go b/libcontainerd/remote/client_linux.go index 1c43ef61c361f..2389cbb69d437 100644 --- a/libcontainerd/remote/client_linux.go +++ b/libcontainerd/remote/client_linux.go @@ -12,7 +12,7 @@ import ( "github.com/containerd/containerd/containers" libcontainerdtypes "github.com/docker/docker/libcontainerd/types" "github.com/docker/docker/pkg/idtools" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/sirupsen/logrus" ) diff --git a/libcontainerd/types/types.go b/libcontainerd/types/types.go index 42d5f244760c1..de9a38589541e 100644 --- a/libcontainerd/types/types.go +++ b/libcontainerd/types/types.go @@ -6,7 +6,7 @@ import ( "github.com/containerd/containerd" "github.com/containerd/containerd/cio" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // EventType represents a possible event from libcontainerd diff --git a/libcontainerd/types/types_linux.go b/libcontainerd/types/types_linux.go index 0a2daf5777935..2e10743114755 100644 --- a/libcontainerd/types/types_linux.go +++ b/libcontainerd/types/types_linux.go @@ -4,7 +4,7 @@ import ( "time" "github.com/containerd/cgroups" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // Summary is not used on linux diff --git a/oci/defaults.go b/oci/defaults.go index 35fbcd1d8707b..c55d1aac022c3 100644 --- a/oci/defaults.go +++ b/oci/defaults.go @@ -4,7 +4,7 @@ import ( "os" "runtime" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) func iPtr(i int64) *int64 { return &i } diff --git a/oci/devices_linux.go b/oci/devices_linux.go index 46d4e1d32d43d..dc43faf7647eb 100644 --- a/oci/devices_linux.go +++ b/oci/devices_linux.go @@ -8,7 +8,7 @@ import ( "github.com/opencontainers/runc/libcontainer/configs" "github.com/opencontainers/runc/libcontainer/devices" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // Device transforms a libcontainer configs.Device to a specs.LinuxDevice object. @@ -61,7 +61,8 @@ func DevicesFromPath(pathOnHost, pathInContainer, cgroupPermissions string) (dev if src, e := os.Stat(resolvedPathOnHost); e == nil && src.IsDir() { // mount the internal devices recursively - filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, e error) error { + // TODO check if additional errors should be handled or logged + _ = filepath.Walk(resolvedPathOnHost, func(dpath string, f os.FileInfo, _ error) error { childDevice, e := devices.DeviceFromPath(dpath, cgroupPermissions) if e != nil { // ignore the device diff --git a/oci/namespaces.go b/oci/namespaces.go index 5a2d8f2087362..f32e489b4a27f 100644 --- a/oci/namespaces.go +++ b/oci/namespaces.go @@ -1,6 +1,6 @@ package oci // import "github.com/docker/docker/oci" -import "github.com/opencontainers/runtime-spec/specs-go" +import specs "github.com/opencontainers/runtime-spec/specs-go" // RemoveNamespace removes the `nsType` namespace from OCI spec `s` func RemoveNamespace(s *specs.Spec, nsType specs.LinuxNamespaceType) { diff --git a/opts/env_test.go b/opts/env_test.go index 1ecf1e2b945d6..d82495ec21000 100644 --- a/opts/env_test.go +++ b/opts/env_test.go @@ -96,9 +96,9 @@ func TestValidateEnv(t *testing.T) { }{ value: "PaTh", expected: fmt.Sprintf("PaTh=%v", os.Getenv("PATH")), + err: nil, } testcase = append(testcase, tmp) - } for _, r := range testcase { diff --git a/opts/opts.go b/opts/opts.go index de8aacb806d7a..c3bf5cd7c1638 100644 --- a/opts/opts.go +++ b/opts/opts.go @@ -7,7 +7,7 @@ import ( "regexp" "strings" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) var ( diff --git a/opts/ulimit.go b/opts/ulimit.go index 0e2a36236c1bf..61cc58d4d3293 100644 --- a/opts/ulimit.go +++ b/opts/ulimit.go @@ -3,7 +3,7 @@ package opts // import "github.com/docker/docker/opts" import ( "fmt" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) // UlimitOpt defines a map of Ulimits diff --git a/opts/ulimit_test.go b/opts/ulimit_test.go index 41e12627c8a3d..90b15d61e87b0 100644 --- a/opts/ulimit_test.go +++ b/opts/ulimit_test.go @@ -3,12 +3,12 @@ package opts // import "github.com/docker/docker/opts" import ( "testing" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) func TestUlimitOpt(t *testing.T) { ulimitMap := map[string]*units.Ulimit{ - "nofile": {"nofile", 1024, 512}, + "nofile": {Name: "nofile", Hard: 1024, Soft: 512}, } ulimitOpt := NewUlimitOpt(&ulimitMap) diff --git a/pkg/archive/archive_unix_test.go b/pkg/archive/archive_unix_test.go index 6119133f8eb40..c29cf344eca1d 100644 --- a/pkg/archive/archive_unix_test.go +++ b/pkg/archive/archive_unix_test.go @@ -166,6 +166,7 @@ func getNlink(path string) (uint64, error) { return 0, fmt.Errorf("expected type *syscall.Stat_t, got %t", stat.Sys()) } // We need this conversion on ARM64 + // nolint: unconvert return uint64(statT.Nlink), nil } diff --git a/pkg/containerfs/archiver.go b/pkg/containerfs/archiver.go index 22dce3308a72d..0a6ff68f64083 100644 --- a/pkg/containerfs/archiver.go +++ b/pkg/containerfs/archiver.go @@ -89,14 +89,14 @@ func (archiver *Archiver) CopyWithTar(src, dst string) error { // CopyFileWithTar emulates the behavior of the 'cp' command-line // for a single file. It copies a regular file from path `src` to // path `dst`, and preserves all its metadata. -func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { +func (archiver *Archiver) CopyFileWithTar(src, dst string) (retErr error) { logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) srcDriver := archiver.SrcDriver dstDriver := archiver.DstDriver - srcSt, err := srcDriver.Stat(src) - if err != nil { - return err + srcSt, retErr := srcDriver.Stat(src) + if retErr != nil { + return retErr } if srcSt.IsDir() { @@ -168,16 +168,16 @@ func (archiver *Archiver) CopyFileWithTar(src, dst string) (err error) { }() }() defer func() { - if er := <-errC; err == nil && er != nil { - err = er + if err := <-errC; retErr == nil && err != nil { + retErr = err } }() - err = archiver.Untar(r, dstDriver.Dir(dst), nil) - if err != nil { - r.CloseWithError(err) + retErr = archiver.Untar(r, dstDriver.Dir(dst), nil) + if retErr != nil { + r.CloseWithError(retErr) } - return err + return retErr } // IdentityMapping returns the IdentityMapping of the archiver. diff --git a/pkg/devicemapper/devmapper.go b/pkg/devicemapper/devmapper.go index 5cbab01f4c420..f9356f5ba6f78 100644 --- a/pkg/devicemapper/devmapper.go +++ b/pkg/devicemapper/devmapper.go @@ -14,7 +14,7 @@ import ( ) // Same as DM_DEVICE_* enum values from libdevmapper.h -// nolint: deadcode +// nolint: deadcode,unused,varcheck const ( deviceCreate TaskType = iota deviceReload diff --git a/pkg/devicemapper/devmapper_wrapper.go b/pkg/devicemapper/devmapper_wrapper.go index 616c1153fd973..56facd42c715f 100644 --- a/pkg/devicemapper/devmapper_wrapper.go +++ b/pkg/devicemapper/devmapper_wrapper.go @@ -206,6 +206,7 @@ func dmGetNextTargetFct(task *cdmTask, next unsafe.Pointer, start, length *uint6 *params = C.GoString(Cparams) }() + //lint:ignore SA4000 false positive on (identical expressions on the left and right side of the '==' operator) (staticcheck) nextp := C.dm_get_next_target((*C.struct_dm_task)(task), next, &Cstart, &Clength, &CtargetType, &Cparams) return nextp } diff --git a/pkg/directory/directory_test.go b/pkg/directory/directory_test.go index ea62bdf2363e5..04bb5d8d020ad 100644 --- a/pkg/directory/directory_test.go +++ b/pkg/directory/directory_test.go @@ -179,7 +179,7 @@ func TestMoveToSubdir(t *testing.T) { for _, info := range infos { results = append(results, info.Name()) } - sort.Sort(sort.StringSlice(results)) + sort.Strings(results) if !reflect.DeepEqual(filesList, results) { t.Fatalf("Results after migration do not equal list of files: expected: %v, got: %v", filesList, results) } diff --git a/pkg/filenotify/poller_test.go b/pkg/filenotify/poller_test.go index a46b60d94f8ce..ead2504372821 100644 --- a/pkg/filenotify/poller_test.go +++ b/pkg/filenotify/poller_test.go @@ -61,16 +61,18 @@ func TestPollerEvent(t *testing.T) { default: } - if err := ioutil.WriteFile(f.Name(), []byte("hello"), 0644); err != nil { + if err := ioutil.WriteFile(f.Name(), []byte("hello"), 0600); err != nil { t.Fatal(err) } + assertFileMode(t, f.Name(), 0600) if err := assertEvent(w, fsnotify.Write); err != nil { t.Fatal(err) } - if err := os.Chmod(f.Name(), 600); err != nil { + if err := os.Chmod(f.Name(), 0644); err != nil { t.Fatal(err) } + assertFileMode(t, f.Name(), 0644) if err := assertEvent(w, fsnotify.Chmod); err != nil { t.Fatal(err) } @@ -103,6 +105,17 @@ func TestPollerClose(t *testing.T) { } } +func assertFileMode(t *testing.T, fileName string, mode uint32) { + t.Helper() + f, err := os.Stat(fileName) + if err != nil { + t.Fatal(err) + } + if f.Mode() != os.FileMode(mode) { + t.Fatalf("expected file %s to have mode %#o, but got %#o", fileName, mode, f.Mode()) + } +} + func assertEvent(w FileWatcher, eType fsnotify.Op) error { var err error select { diff --git a/pkg/fileutils/fileutils_test.go b/pkg/fileutils/fileutils_test.go index 4b5f129a50afd..6918aa8818963 100644 --- a/pkg/fileutils/fileutils_test.go +++ b/pkg/fileutils/fileutils_test.go @@ -16,7 +16,7 @@ import ( // CopyFile with invalid src func TestCopyFileWithInvalidSrc(t *testing.T) { - tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") + tempFolder, err := ioutil.TempDir("", "docker-fileutils-test") // #nosec G303 defer os.RemoveAll(tempFolder) if err != nil { t.Fatal(err) @@ -182,6 +182,7 @@ func TestReadSymlinkedDirectoryToFile(t *testing.T) { var err error var file *os.File + // #nosec G303 if file, err = os.Create("/tmp/testReadSymlinkToFile"); err != nil { t.Fatalf("failed to create file: %s", err) } diff --git a/pkg/idtools/idtools_unix_test.go b/pkg/idtools/idtools_unix_test.go index be5d60262247f..11092c4699771 100644 --- a/pkg/idtools/idtools_unix_test.go +++ b/pkg/idtools/idtools_unix_test.go @@ -323,7 +323,7 @@ func TestNewIDMappings(t *testing.T) { gids, err := tempUser.GroupIds() assert.Check(t, err) - group, err := user.LookupGroupId(string(gids[0])) + group, err := user.LookupGroupId(gids[0]) assert.Check(t, err) idMapping, err := NewIdentityMapping(tempUser.Username, group.Name) diff --git a/pkg/ioutils/bytespipe_test.go b/pkg/ioutils/bytespipe_test.go index 9101f20a21aa9..5e361874821da 100644 --- a/pkg/ioutils/bytespipe_test.go +++ b/pkg/ioutils/bytespipe_test.go @@ -1,7 +1,7 @@ package ioutils // import "github.com/docker/docker/pkg/ioutils" import ( - "crypto/sha1" + "crypto/sha256" "encoding/hex" "math/rand" "testing" @@ -77,7 +77,7 @@ func TestBytesPipeWriteRandomChunks(t *testing.T) { for _, c := range cases { // first pass: write directly to hash - hash := sha1.New() + hash := sha256.New() for i := 0; i < c.iterations*c.writesPerLoop; i++ { if _, err := hash.Write(testMessage[:writeChunks[i%len(writeChunks)]]); err != nil { t.Fatal(err) diff --git a/pkg/ioutils/fswriters_test.go b/pkg/ioutils/fswriters_test.go index b283045de5b3d..bce68c2f71bde 100644 --- a/pkg/ioutils/fswriters_test.go +++ b/pkg/ioutils/fswriters_test.go @@ -45,7 +45,7 @@ func TestAtomicWriteToFile(t *testing.T) { if err != nil { t.Fatalf("Error statting file: %v", err) } - if expected := os.FileMode(testMode); st.Mode() != expected { + if expected := testMode; st.Mode() != expected { t.Fatalf("Mode mismatched, expected %o, got %o", expected, st.Mode()) } } @@ -93,7 +93,7 @@ func TestAtomicWriteSetCommit(t *testing.T) { if err != nil { t.Fatalf("Error statting file: %v", err) } - if expected := os.FileMode(testMode); st.Mode() != expected { + if expected := testMode; st.Mode() != expected { t.Fatalf("Mode mismatched, expected %o, got %o", expected, st.Mode()) } diff --git a/pkg/jsonmessage/jsonmessage.go b/pkg/jsonmessage/jsonmessage.go index a68b566cea2c8..6d66408984ffe 100644 --- a/pkg/jsonmessage/jsonmessage.go +++ b/pkg/jsonmessage/jsonmessage.go @@ -8,7 +8,7 @@ import ( "time" "github.com/docker/docker/pkg/term" - "github.com/docker/go-units" + units "github.com/docker/go-units" "github.com/morikuni/aec" ) diff --git a/pkg/jsonmessage/jsonmessage_test.go b/pkg/jsonmessage/jsonmessage_test.go index 3d9667a153f7a..a7100daa73f52 100644 --- a/pkg/jsonmessage/jsonmessage_test.go +++ b/pkg/jsonmessage/jsonmessage_test.go @@ -228,8 +228,9 @@ func TestDisplayJSONMessagesStreamInvalidJSON(t *testing.T) { reader := strings.NewReader("This is not a 'valid' JSON []") inFd, _ = term.GetFdInfo(reader) - if err := DisplayJSONMessagesStream(reader, data, inFd, false, nil); err == nil && err.Error()[:17] != "invalid character" { - t.Fatalf("Should have thrown an error (invalid character in ..), got %q", err) + exp := "invalid character " + if err := DisplayJSONMessagesStream(reader, data, inFd, false, nil); err == nil || !strings.HasPrefix(err.Error(), exp) { + t.Fatalf("Expected error (%s...), got %q", exp, err) } } diff --git a/pkg/mount/mount_unix_test.go b/pkg/mount/mount_unix_test.go index befff9d50c570..d05e189193e73 100644 --- a/pkg/mount/mount_unix_test.go +++ b/pkg/mount/mount_unix_test.go @@ -122,7 +122,7 @@ func TestMountReadonly(t *testing.T) { } }() - f, err = os.OpenFile(targetPath, os.O_RDWR, 0777) + _, err = os.OpenFile(targetPath, os.O_RDWR, 0777) if err == nil { t.Fatal("Should not be able to open a ro file as rw") } diff --git a/pkg/parsers/kernel/kernel_darwin.go b/pkg/parsers/kernel/kernel_darwin.go index 6e599eebcc21a..6a302dcee24ce 100644 --- a/pkg/parsers/kernel/kernel_darwin.go +++ b/pkg/parsers/kernel/kernel_darwin.go @@ -9,7 +9,7 @@ import ( "os/exec" "strings" - "github.com/mattn/go-shellwords" + shellwords "github.com/mattn/go-shellwords" ) // GetKernelVersion gets the current kernel version. diff --git a/pkg/parsers/kernel/kernel_unix_test.go b/pkg/parsers/kernel/kernel_unix_test.go index 9d2e496af5ba9..8706deca286f9 100644 --- a/pkg/parsers/kernel/kernel_unix_test.go +++ b/pkg/parsers/kernel/kernel_unix_test.go @@ -41,7 +41,10 @@ func TestParseRelease(t *testing.T) { for _, invalid := range invalids { expectedMessage := fmt.Sprintf("Can't parse kernel version %v", invalid) if _, err := ParseRelease(invalid); err == nil || err.Error() != expectedMessage { - + if err == nil { + t.Fatalf("Expected %q, got nil", expectedMessage) + } + t.Fatalf("Expected %q, got %q", expectedMessage, err.Error()) } } } diff --git a/pkg/parsers/operatingsystem/operatingsystem_linux.go b/pkg/parsers/operatingsystem/operatingsystem_linux.go index 8943c1ae313b0..18dc39472c5df 100644 --- a/pkg/parsers/operatingsystem/operatingsystem_linux.go +++ b/pkg/parsers/operatingsystem/operatingsystem_linux.go @@ -10,7 +10,7 @@ import ( "os" "strings" - "github.com/mattn/go-shellwords" + shellwords "github.com/mattn/go-shellwords" ) var ( diff --git a/pkg/pools/pools.go b/pkg/pools/pools.go index 46339c282f115..3b978fd3b5834 100644 --- a/pkg/pools/pools.go +++ b/pkg/pools/pools.go @@ -72,6 +72,7 @@ func (bp *bufferPool) Get() []byte { } func (bp *bufferPool) Put(b []byte) { + //nolint:staticcheck // TODO changing this to a pointer makes tests fail. Investigate if we should change or not (otherwise remove this TODO) bp.pool.Put(b) } diff --git a/pkg/signal/signal_test.go b/pkg/signal/signal_test.go index 0bfcf6ce448dd..9abe3883f6595 100644 --- a/pkg/signal/signal_test.go +++ b/pkg/signal/signal_test.go @@ -28,7 +28,7 @@ func TestValidSignalForPlatform(t *testing.T) { assert.Check(t, is.Equal(false, isValidSignal)) for _, sigN := range SignalMap { - isValidSignal = ValidSignalForPlatform(syscall.Signal(sigN)) + isValidSignal = ValidSignalForPlatform(sigN) assert.Check(t, is.Equal(true, isValidSignal)) } } diff --git a/pkg/system/chtimes_unix_test.go b/pkg/system/chtimes_unix_test.go index e25232c767556..779ed4b64cab6 100644 --- a/pkg/system/chtimes_unix_test.go +++ b/pkg/system/chtimes_unix_test.go @@ -28,7 +28,7 @@ func TestChtimesLinux(t *testing.T) { } stat := f.Sys().(*syscall.Stat_t) - aTime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) + aTime := time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } @@ -42,7 +42,7 @@ func TestChtimesLinux(t *testing.T) { } stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) + aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } @@ -56,7 +56,7 @@ func TestChtimesLinux(t *testing.T) { } stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) + aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert if aTime != unixEpochTime { t.Fatalf("Expected: %s, got: %s", unixEpochTime, aTime) } @@ -70,7 +70,7 @@ func TestChtimesLinux(t *testing.T) { } stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) + aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert if aTime != afterUnixEpochTime { t.Fatalf("Expected: %s, got: %s", afterUnixEpochTime, aTime) } @@ -84,7 +84,7 @@ func TestChtimesLinux(t *testing.T) { } stat = f.Sys().(*syscall.Stat_t) - aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) + aTime = time.Unix(int64(stat.Atim.Sec), int64(stat.Atim.Nsec)) // nolint: unconvert if aTime.Truncate(time.Second) != unixMaxTime.Truncate(time.Second) { t.Fatalf("Expected: %s, got: %s", unixMaxTime.Truncate(time.Second), aTime.Truncate(time.Second)) } diff --git a/pkg/system/meminfo_linux.go b/pkg/system/meminfo_linux.go index 09a9d79f1794a..cd060eff24de5 100644 --- a/pkg/system/meminfo_linux.go +++ b/pkg/system/meminfo_linux.go @@ -7,7 +7,7 @@ import ( "strconv" "strings" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) // ReadMemInfo retrieves memory statistics of the host system and returns a diff --git a/pkg/system/meminfo_unix_test.go b/pkg/system/meminfo_unix_test.go index 73f4e4d2cde42..e650cfa6271b2 100644 --- a/pkg/system/meminfo_unix_test.go +++ b/pkg/system/meminfo_unix_test.go @@ -6,7 +6,7 @@ import ( "strings" "testing" - "github.com/docker/go-units" + units "github.com/docker/go-units" ) // TestMemInfo tests parseMemInfo with a static meminfo string diff --git a/pkg/tailfile/tailfile.go b/pkg/tailfile/tailfile.go index c82fe603f663c..0d64ec58f2fad 100644 --- a/pkg/tailfile/tailfile.go +++ b/pkg/tailfile/tailfile.go @@ -127,7 +127,6 @@ type scanner struct { delim []byte err error idx int - done bool } func (s *scanner) Start(ctx context.Context) int64 { diff --git a/pkg/tarsum/tarsum_test.go b/pkg/tarsum/tarsum_test.go index 97ece8506cb24..6f6b3eb976f99 100644 --- a/pkg/tarsum/tarsum_test.go +++ b/pkg/tarsum/tarsum_test.go @@ -4,9 +4,9 @@ import ( "archive/tar" "bytes" "compress/gzip" - "crypto/md5" + "crypto/md5" // #nosec G501 "crypto/rand" - "crypto/sha1" + "crypto/sha1" // #nosec G505 "crypto/sha256" "crypto/sha512" "encoding/hex" diff --git a/pkg/term/term_linux_test.go b/pkg/term/term_linux_test.go index 272395a10ea46..28d28e3a67cda 100644 --- a/pkg/term/term_linux_test.go +++ b/pkg/term/term_linux_test.go @@ -31,8 +31,8 @@ func newTempFile() (*os.File, error) { func TestGetWinsize(t *testing.T) { tty, err := newTtyForTest(t) - defer tty.Close() assert.NilError(t, err) + defer tty.Close() winSize, err := GetWinsize(tty.Fd()) assert.NilError(t, err) assert.Assert(t, winSize != nil) @@ -49,8 +49,8 @@ var cmpWinsize = cmp.AllowUnexported(Winsize{}) func TestSetWinsize(t *testing.T) { tty, err := newTtyForTest(t) - defer tty.Close() assert.NilError(t, err) + defer tty.Close() winSize, err := GetWinsize(tty.Fd()) assert.NilError(t, err) assert.Assert(t, winSize != nil) @@ -64,8 +64,8 @@ func TestSetWinsize(t *testing.T) { func TestGetFdInfo(t *testing.T) { tty, err := newTtyForTest(t) - defer tty.Close() assert.NilError(t, err) + defer tty.Close() inFd, isTerminal := GetFdInfo(tty) assert.Equal(t, inFd, tty.Fd()) assert.Equal(t, isTerminal, true) @@ -79,8 +79,8 @@ func TestGetFdInfo(t *testing.T) { func TestIsTerminal(t *testing.T) { tty, err := newTtyForTest(t) - defer tty.Close() assert.NilError(t, err) + defer tty.Close() isTerminal := IsTerminal(tty.Fd()) assert.Equal(t, isTerminal, true) tmpFile, err := newTempFile() @@ -92,8 +92,8 @@ func TestIsTerminal(t *testing.T) { func TestSaveState(t *testing.T) { tty, err := newTtyForTest(t) - defer tty.Close() assert.NilError(t, err) + defer tty.Close() state, err := SaveState(tty.Fd()) assert.NilError(t, err) assert.Assert(t, state != nil) @@ -106,8 +106,8 @@ func TestSaveState(t *testing.T) { func TestDisableEcho(t *testing.T) { tty, err := newTtyForTest(t) - defer tty.Close() assert.NilError(t, err) + defer tty.Close() state, err := SetRawTerminal(tty.Fd()) defer RestoreTerminal(tty.Fd(), state) assert.NilError(t, err) diff --git a/pkg/term/term_windows.go b/pkg/term/term_windows.go index a3c3db1315740..6e83b59e90135 100644 --- a/pkg/term/term_windows.go +++ b/pkg/term/term_windows.go @@ -7,7 +7,7 @@ import ( "syscall" // used for STD_INPUT_HANDLE, STD_OUTPUT_HANDLE and STD_ERROR_HANDLE "github.com/Azure/go-ansiterm/winterm" - "github.com/docker/docker/pkg/term/windows" + windowsconsole "github.com/docker/docker/pkg/term/windows" ) // State holds the console mode for the terminal. diff --git a/pkg/term/windows/windows.go b/pkg/term/windows/windows.go index 3e5593ca6a683..7e8f265d47e96 100644 --- a/pkg/term/windows/windows.go +++ b/pkg/term/windows/windows.go @@ -1,3 +1,4 @@ +// +build windows // These files implement ANSI-aware input and output streams for use by the Docker Windows client. // When asked for the set of standard streams (e.g., stdin, stdout, stderr), the code will create // and return pseudo-streams that convert ANSI sequences to / from Windows Console API calls. @@ -9,7 +10,7 @@ import ( "os" "sync" - "github.com/Azure/go-ansiterm" + ansiterm "github.com/Azure/go-ansiterm" "github.com/sirupsen/logrus" ) diff --git a/plugin/backend_linux.go b/plugin/backend_linux.go index 044e14b0cbf81..3201527d44610 100644 --- a/plugin/backend_linux.go +++ b/plugin/backend_linux.go @@ -31,9 +31,9 @@ import ( "github.com/docker/docker/pkg/pools" "github.com/docker/docker/pkg/progress" "github.com/docker/docker/pkg/system" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" refstore "github.com/docker/docker/reference" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/plugin/blobstore.go b/plugin/blobstore.go index a24e7bdf4f8e4..0babefbbf5d85 100644 --- a/plugin/blobstore.go +++ b/plugin/blobstore.go @@ -15,7 +15,7 @@ import ( "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/chrootarchive" "github.com/docker/docker/pkg/progress" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" specs "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" "github.com/sirupsen/logrus" diff --git a/plugin/defs.go b/plugin/defs.go index d793f6f5aae57..9a3577a72b1f5 100644 --- a/plugin/defs.go +++ b/plugin/defs.go @@ -6,8 +6,8 @@ import ( "sync" "github.com/docker/docker/pkg/plugins" - "github.com/docker/docker/plugin/v2" - "github.com/opencontainers/runtime-spec/specs-go" + v2 "github.com/docker/docker/plugin/v2" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // Store manages the plugin inventory in memory and on-disk diff --git a/plugin/executor/containerd/containerd.go b/plugin/executor/containerd/containerd.go index 85a159f1ac20c..91bae6c6b9322 100644 --- a/plugin/executor/containerd/containerd.go +++ b/plugin/executor/containerd/containerd.go @@ -12,7 +12,7 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/libcontainerd" libcontainerdtypes "github.com/docker/docker/libcontainerd/types" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/plugin/manager.go b/plugin/manager.go index c6f896129b9b4..aac5a4666e598 100644 --- a/plugin/manager.go +++ b/plugin/manager.go @@ -21,10 +21,10 @@ import ( "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/pubsub" "github.com/docker/docker/pkg/system" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" "github.com/docker/docker/registry" - "github.com/opencontainers/go-digest" - "github.com/opencontainers/runtime-spec/specs-go" + digest "github.com/opencontainers/go-digest" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/plugin/manager_linux.go b/plugin/manager_linux.go index 23fa462865c13..bda272d71ca65 100644 --- a/plugin/manager_linux.go +++ b/plugin/manager_linux.go @@ -15,8 +15,8 @@ import ( "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/plugins" "github.com/docker/docker/pkg/stringid" - "github.com/docker/docker/plugin/v2" - "github.com/opencontainers/go-digest" + v2 "github.com/docker/docker/plugin/v2" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" "github.com/sirupsen/logrus" "golang.org/x/sys/unix" @@ -282,9 +282,6 @@ func (pm *Manager) setupNewPlugin(configDigest digest.Digest, blobsums []digest. } requiredPrivileges := computePrivileges(config) - if err != nil { - return types.PluginConfig{}, err - } if privileges != nil { if err := validatePrivileges(requiredPrivileges, *privileges); err != nil { return types.PluginConfig{}, err diff --git a/plugin/manager_linux_test.go b/plugin/manager_linux_test.go index 1b6a3bf7738d2..c75efb7b72988 100644 --- a/plugin/manager_linux_test.go +++ b/plugin/manager_linux_test.go @@ -12,8 +12,8 @@ import ( "github.com/docker/docker/pkg/mount" "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/system" - "github.com/docker/docker/plugin/v2" - "github.com/opencontainers/runtime-spec/specs-go" + v2 "github.com/docker/docker/plugin/v2" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "gotest.tools/skip" ) diff --git a/plugin/manager_windows.go b/plugin/manager_windows.go index 90cc52c99253c..89595dfd84936 100644 --- a/plugin/manager_windows.go +++ b/plugin/manager_windows.go @@ -3,7 +3,7 @@ package plugin // import "github.com/docker/docker/plugin" import ( "fmt" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" specs "github.com/opencontainers/runtime-spec/specs-go" ) diff --git a/plugin/store.go b/plugin/store.go index 8e96c11da4e45..e88861e5b3836 100644 --- a/plugin/store.go +++ b/plugin/store.go @@ -8,8 +8,8 @@ import ( "github.com/docker/docker/errdefs" "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/plugins" - "github.com/docker/docker/plugin/v2" - "github.com/opencontainers/runtime-spec/specs-go" + v2 "github.com/docker/docker/plugin/v2" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" "github.com/sirupsen/logrus" ) diff --git a/plugin/store_test.go b/plugin/store_test.go index 14b484f76c70b..47b4bd7d4ddd6 100644 --- a/plugin/store_test.go +++ b/plugin/store_test.go @@ -5,7 +5,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/plugingetter" - "github.com/docker/docker/plugin/v2" + v2 "github.com/docker/docker/plugin/v2" ) func TestFilterByCapNeg(t *testing.T) { diff --git a/plugin/v2/plugin.go b/plugin/v2/plugin.go index 6852511c5e664..b46ff60b31682 100644 --- a/plugin/v2/plugin.go +++ b/plugin/v2/plugin.go @@ -11,8 +11,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/plugingetter" "github.com/docker/docker/pkg/plugins" - "github.com/opencontainers/go-digest" - "github.com/opencontainers/runtime-spec/specs-go" + digest "github.com/opencontainers/go-digest" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // Plugin represents an individual plugin. diff --git a/plugin/v2/plugin_linux.go b/plugin/v2/plugin_linux.go index 58c432fcd6254..4ad582cd834d7 100644 --- a/plugin/v2/plugin_linux.go +++ b/plugin/v2/plugin_linux.go @@ -9,7 +9,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/oci" "github.com/docker/docker/pkg/system" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" "github.com/pkg/errors" ) diff --git a/plugin/v2/plugin_unsupported.go b/plugin/v2/plugin_unsupported.go index 5242fe124ca16..734b2ac664885 100644 --- a/plugin/v2/plugin_unsupported.go +++ b/plugin/v2/plugin_unsupported.go @@ -5,7 +5,7 @@ package v2 // import "github.com/docker/docker/plugin/v2" import ( "errors" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // InitSpec creates an OCI spec from the plugin's config. diff --git a/reference/store.go b/reference/store.go index b942c42ca2c7f..d6ef6697f535f 100644 --- a/reference/store.go +++ b/reference/store.go @@ -10,7 +10,7 @@ import ( "github.com/docker/distribution/reference" "github.com/docker/docker/pkg/ioutils" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "github.com/pkg/errors" ) diff --git a/reference/store_test.go b/reference/store_test.go index 921cd37ae54e8..4f2149590e30b 100644 --- a/reference/store_test.go +++ b/reference/store_test.go @@ -9,7 +9,7 @@ import ( "testing" "github.com/docker/distribution/reference" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) @@ -110,8 +110,9 @@ func TestAddDeleteGet(t *testing.T) { t.Fatalf("error creating temp file: %v", err) } _, err = jsonFile.Write([]byte(`{}`)) - jsonFile.Close() - defer os.RemoveAll(jsonFile.Name()) + assert.NilError(t, err) + _ = jsonFile.Close() + defer func() { _ = os.RemoveAll(jsonFile.Name()) }() store, err := NewReferenceStore(jsonFile.Name()) if err != nil { diff --git a/registry/endpoint_v1.go b/registry/endpoint_v1.go index 832fdb95a482b..2fc2ea0e741a4 100644 --- a/registry/endpoint_v1.go +++ b/registry/endpoint_v1.go @@ -124,9 +124,6 @@ func newV1EndpointFromStr(address string, tlsConfig *tls.Config, userAgent strin } endpoint := newV1Endpoint(*uri, tlsConfig, userAgent, metaHeaders) - if err != nil { - return nil, err - } return endpoint, nil } diff --git a/registry/session.go b/registry/session.go index ef142995942f7..59f5ad50ff9a7 100644 --- a/registry/session.go +++ b/registry/session.go @@ -3,6 +3,7 @@ package registry // import "github.com/docker/docker/registry" import ( "bytes" "crypto/sha256" + // this is required for some certificates _ "crypto/sha512" "encoding/hex" diff --git a/restartmanager/restartmanager_test.go b/restartmanager/restartmanager_test.go index 4b6f30247902a..82558946bc2f8 100644 --- a/restartmanager/restartmanager_test.go +++ b/restartmanager/restartmanager_test.go @@ -9,7 +9,7 @@ import ( func TestRestartManagerTimeout(t *testing.T) { rm := New(container.RestartPolicy{Name: "always"}, 0).(*restartManager) - var duration = time.Duration(1 * time.Second) + var duration = 1 * time.Second should, _, err := rm.ShouldRestart(0, false, duration) if err != nil { t.Fatal(err) @@ -25,7 +25,7 @@ func TestRestartManagerTimeout(t *testing.T) { func TestRestartManagerTimeoutReset(t *testing.T) { rm := New(container.RestartPolicy{Name: "always"}, 0).(*restartManager) rm.timeout = 5 * time.Second - var duration = time.Duration(10 * time.Second) + var duration = 10 * time.Second _, _, err := rm.ShouldRestart(0, false, duration) if err != nil { t.Fatal(err) diff --git a/rootless/specconv/specconv_linux.go b/rootless/specconv/specconv_linux.go index 77c9ce28b38c2..f02e94c293606 100644 --- a/rootless/specconv/specconv_linux.go +++ b/rootless/specconv/specconv_linux.go @@ -4,7 +4,7 @@ import ( "io/ioutil" "strconv" - "github.com/opencontainers/runtime-spec/specs-go" + specs "github.com/opencontainers/runtime-spec/specs-go" ) // ToRootless converts spec to be compatible with "rootless" runc. diff --git a/runconfig/config_test.go b/runconfig/config_test.go index 67d386969f4da..22506126a57d9 100644 --- a/runconfig/config_test.go +++ b/runconfig/config_test.go @@ -12,8 +12,6 @@ import ( "github.com/docker/docker/api/types/container" networktypes "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/strslice" - "gotest.tools/assert" - is "gotest.tools/assert/cmp" ) type f struct { @@ -134,57 +132,3 @@ func callDecodeContainerConfigIsolation(isolation string) (*container.Config, *c } return decodeContainerConfig(bytes.NewReader(b)) } - -type decodeConfigTestcase struct { - doc string - wrapper ContainerConfigWrapper - expectedErr string - expectedConfig *container.Config - expectedHostConfig *container.HostConfig - goos string -} - -func runDecodeContainerConfigTestCase(testcase decodeConfigTestcase) func(t *testing.T) { - return func(t *testing.T) { - raw := marshal(t, testcase.wrapper, testcase.doc) - config, hostConfig, _, err := decodeContainerConfig(bytes.NewReader(raw)) - if testcase.expectedErr != "" { - if !assert.Check(t, is.ErrorContains(err, "")) { - return - } - assert.Check(t, is.Contains(err.Error(), testcase.expectedErr)) - return - } - assert.Check(t, err) - assert.Check(t, is.DeepEqual(testcase.expectedConfig, config)) - assert.Check(t, is.DeepEqual(testcase.expectedHostConfig, hostConfig)) - } -} - -func marshal(t *testing.T, w ContainerConfigWrapper, doc string) []byte { - b, err := json.Marshal(w) - assert.NilError(t, err, "%s: failed to encode config wrapper", doc) - return b -} - -func containerWrapperWithVolume(volume string) ContainerConfigWrapper { - return ContainerConfigWrapper{ - Config: &container.Config{ - Volumes: map[string]struct{}{ - volume: {}, - }, - }, - HostConfig: &container.HostConfig{}, - } -} - -func containerWrapperWithBind(bind string) ContainerConfigWrapper { - return ContainerConfigWrapper{ - Config: &container.Config{ - Volumes: map[string]struct{}{}, - }, - HostConfig: &container.HostConfig{ - Binds: []string{bind}, - }, - } -} diff --git a/testutil/environment/environment.go b/testutil/environment/environment.go index 61f165e509989..195e698b0e159 100644 --- a/testutil/environment/environment.go +++ b/testutil/environment/environment.go @@ -34,7 +34,7 @@ type PlatformDefaults struct { } // New creates a new Execution struct -// This is configured useing the env client (see client.FromEnv) +// This is configured using the env client (see client.FromEnv) func New() (*Execution, error) { c, err := client.NewClientWithOpts(client.FromEnv) if err != nil { diff --git a/testutil/registry/registry.go b/testutil/registry/registry.go index 59af456a70b50..cc6c9eac37773 100644 --- a/testutil/registry/registry.go +++ b/testutil/registry/registry.go @@ -10,7 +10,7 @@ import ( "time" "github.com/docker/docker/testutil" - "github.com/opencontainers/go-digest" + digest "github.com/opencontainers/go-digest" "gotest.tools/assert" ) @@ -84,6 +84,7 @@ http: case "htpasswd": htpasswdPath := filepath.Join(tmp, "htpasswd") // generated with: htpasswd -Bbn testuser testpassword + // #nosec G101 userpasswd := "testuser:$2y$05$sBsSqk0OpSD1uTZkHXc4FeJ0Z70wLQdAX/82UiHuQOKbNbBrzs63m" username = "testuser" password = "testpassword" diff --git a/testutil/request/npipe_windows.go b/testutil/request/npipe_windows.go index a268aac922f0d..9741ae64c6534 100644 --- a/testutil/request/npipe_windows.go +++ b/testutil/request/npipe_windows.go @@ -4,7 +4,7 @@ import ( "net" "time" - "github.com/Microsoft/go-winio" + winio "github.com/Microsoft/go-winio" ) func npipeDial(path string, timeout time.Duration) (net.Conn, error) { diff --git a/volume/local/local.go b/volume/local/local.go index 6dc894873dd87..e587814d1990e 100644 --- a/volume/local/local.go +++ b/volume/local/local.go @@ -172,7 +172,7 @@ func (r *Root) Create(name string, opts map[string]string) (volume.Volume, error if err != nil { return nil, err } - if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 600); err != nil { + if err = ioutil.WriteFile(filepath.Join(filepath.Dir(path), "opts.json"), b, 0600); err != nil { return nil, errdefs.System(errors.Wrap(err, "error while persisting volume options")) } } diff --git a/volume/local/local_test.go b/volume/local/local_test.go index 51df1a7edfcec..9e0e6beb25de0 100644 --- a/volume/local/local_test.go +++ b/volume/local/local_test.go @@ -149,7 +149,7 @@ func TestCreate(t *testing.T) { } } - r, err = New(rootDir, idtools.Identity{UID: os.Geteuid(), GID: os.Getegid()}) + _, err = New(rootDir, idtools.Identity{UID: os.Geteuid(), GID: os.Getegid()}) if err != nil { t.Fatal(err) } @@ -295,7 +295,7 @@ func TestRelaodNoOpts(t *testing.T) { t.Fatal(err) } // make sure a file with `null` (.e.g. empty opts map from older daemon) is ok - if err := ioutil.WriteFile(filepath.Join(rootDir, "test2"), []byte("null"), 600); err != nil { + if err := ioutil.WriteFile(filepath.Join(rootDir, "test2"), []byte("null"), 0600); err != nil { t.Fatal(err) } @@ -303,7 +303,7 @@ func TestRelaodNoOpts(t *testing.T) { t.Fatal(err) } // make sure an empty opts file doesn't break us too - if err := ioutil.WriteFile(filepath.Join(rootDir, "test3"), nil, 600); err != nil { + if err := ioutil.WriteFile(filepath.Join(rootDir, "test3"), nil, 0600); err != nil { t.Fatal(err) } diff --git a/volume/service/service_test.go b/volume/service/service_test.go index 64a17ad9c78bb..dd83df31725c9 100644 --- a/volume/service/service_test.go +++ b/volume/service/service_test.go @@ -147,14 +147,14 @@ func TestServiceGet(t *testing.T) { assert.NilError(t, err) assert.Assert(t, is.Len(v.Status, 1), v.Status) - v, err = service.Get(ctx, "test", opts.WithGetDriver("notarealdriver")) + _, err = service.Get(ctx, "test", opts.WithGetDriver("notarealdriver")) assert.Assert(t, errdefs.IsConflict(err), err) v, err = service.Get(ctx, "test", opts.WithGetDriver("d1")) assert.Assert(t, err == nil) assert.Assert(t, is.DeepEqual(created, v)) assert.Assert(t, ds.Register(testutils.NewFakeDriver("d2"), "d2")) - v, err = service.Get(ctx, "test", opts.WithGetDriver("d2")) + _, err = service.Get(ctx, "test", opts.WithGetDriver("d2")) assert.Assert(t, errdefs.IsConflict(err), err) }