diff --git a/apis/filters/parse.go b/apis/filters/parse.go index 49108587d..00988861d 100644 --- a/apis/filters/parse.go +++ b/apis/filters/parse.go @@ -152,10 +152,7 @@ func FromParam(p string) (Args, error) { raw := []byte(p) err := json.Unmarshal(raw, &args) - if err != nil { - return args, err - } - return args, nil + return args, err } // FromFilterOpts parse key=value to Args string from cli opts diff --git a/apis/opts/config/blkio.go b/apis/opts/config/blkio.go index c355c08ce..7f25dac4c 100644 --- a/apis/opts/config/blkio.go +++ b/apis/opts/config/blkio.go @@ -66,9 +66,7 @@ func (w *WeightDevice) Type() string { // Value returns all values as type WeightDevice func (w *WeightDevice) Value() []*types.WeightDevice { var weightDevice []*types.WeightDevice - for _, v := range w.values { - weightDevice = append(weightDevice, v) - } + weightDevice = append(weightDevice, w.values...) return weightDevice } @@ -124,9 +122,7 @@ func (t *ThrottleBpsDevice) Type() string { // Value returns all values as type ThrottleDevice func (t *ThrottleBpsDevice) Value() []*types.ThrottleDevice { var throttleDevice []*types.ThrottleDevice - for _, v := range t.values { - throttleDevice = append(throttleDevice, v) - } + throttleDevice = append(throttleDevice, t.values...) return throttleDevice } @@ -182,9 +178,7 @@ func (t *ThrottleIOpsDevice) Type() string { // Value returns all values func (t *ThrottleIOpsDevice) Value() []*types.ThrottleDevice { var throttleDevice []*types.ThrottleDevice - for _, v := range t.values { - throttleDevice = append(throttleDevice, v) - } + throttleDevice = append(throttleDevice, t.values...) return throttleDevice } diff --git a/apis/opts/config/runtime.go b/apis/opts/config/runtime.go index 72dbd8bae..cdfaf4197 100644 --- a/apis/opts/config/runtime.go +++ b/apis/opts/config/runtime.go @@ -47,7 +47,7 @@ func (r *Runtime) Set(val string) error { func (r *Runtime) String() string { var str []string for k := range *r.values { - str = append(str, fmt.Sprintf("%s", k)) + str = append(str, k) } return fmt.Sprintf("%v", str) diff --git a/apis/server/image_bridge.go b/apis/server/image_bridge.go index c7bf01d6d..c198657f3 100644 --- a/apis/server/image_bridge.go +++ b/apis/server/image_bridge.go @@ -192,11 +192,8 @@ func (s *Server) saveImage(ctx context.Context, rw http.ResponseWriter, req *htt defer r.Close() output := newWriteFlusher(rw) - if _, err := io.Copy(output, r); err != nil { - return err - } - - return nil + _, err = io.Copy(output, r) + return err } // getImageHistory gets image history. diff --git a/cli/container.go b/cli/container.go index 3b5c8bef7..b5f9cba0b 100644 --- a/cli/container.go +++ b/cli/container.go @@ -65,7 +65,7 @@ type container struct { networks []string ports []string expose []string - publicAll bool + publishAll bool securityOpt []string capAdd []string capDrop []string diff --git a/cli/image_list.go b/cli/image_list.go index f82d1a0c9..296152b1a 100644 --- a/cli/image_list.go +++ b/cli/image_list.go @@ -108,9 +108,9 @@ func (i *ImagesCommand) runImages(args []string) error { for _, dimg := range dimgs { if i.flagDigest { - display.AddRow([]string{dimg.id, dimg.name, dimg.digest, fmt.Sprintf("%s", dimg.size)}) + display.AddRow([]string{dimg.id, dimg.name, dimg.digest, string(dimg.size)}) } else { - display.AddRow([]string{dimg.id, dimg.name, fmt.Sprintf("%s", dimg.size)}) + display.AddRow([]string{dimg.id, dimg.name, string(dimg.size)}) } } diff --git a/cli/tag.go b/cli/tag.go index cf4d7a47b..1bab23c80 100644 --- a/cli/tag.go +++ b/cli/tag.go @@ -12,7 +12,6 @@ var tagDescription = "tag command is to add tag reference for the existing image // TagCommand use to implement 'tag' command. type TagCommand struct { baseCommand - args []string } // Init initialize tag command. diff --git a/cli/top.go b/cli/top.go index de72eabe5..048cb25fe 100644 --- a/cli/top.go +++ b/cli/top.go @@ -17,7 +17,6 @@ var topDescription = "top command is to display the running processes of a conta // TopCommand use to implement 'top' command, it displays all processes in a container. type TopCommand struct { baseCommand - args []string } // Init initialize top command. diff --git a/cli/update.go b/cli/update.go index 8baf29188..6799a86d6 100644 --- a/cli/update.go +++ b/cli/update.go @@ -17,7 +17,6 @@ var updateDescription = "Update a container's configurations, including memory, type UpdateCommand struct { baseCommand container - image string } // Init initialize update command. diff --git a/client/request.go b/client/request.go index 984497346..c016432e9 100644 --- a/client/request.go +++ b/client/request.go @@ -102,10 +102,8 @@ func (client *APIClient) newRequest(method, path string, query url.Values, body return nil, err } - if header != nil { - for k, v := range header { - req.Header[k] = v - } + for k, v := range header { + req.Header[k] = v } return req, err diff --git a/cri/criservice.go b/cri/criservice.go index 3a9146431..6a9148b3e 100644 --- a/cri/criservice.go +++ b/cri/criservice.go @@ -39,7 +39,6 @@ func RunCriService(daemonconfig *config.Config, containerMgr mgr.ContainerMgr, i readyCh <- false err = fmt.Errorf("failed to start CRI service: invalid CRI version %s, expected to be v1alpha1 or v1alpha2", daemonconfig.CriConfig.CriVersion) } - return } // Start CRI service with CRI version: v1alpha1 diff --git a/cri/stream/portforward/httpstream.go b/cri/stream/portforward/httpstream.go index e6142df52..50be52df6 100644 --- a/cri/stream/portforward/httpstream.go +++ b/cri/stream/portforward/httpstream.go @@ -111,13 +111,6 @@ func (h *httpStreamHandler) getStreamPair(requestID string) (*httpStreamPair, bo return pair, true } -// hasStreamPair returns a bool indicating if a stream pair for requestID exists. -func (h *httpStreamHandler) hasStreamPair(requestID string) bool { - _, ok := h.streamPairs.Get(requestID).Result() - - return ok -} - // removeStreamPair removes the stream pair identified by requestID from streamPairs. func (h *httpStreamHandler) removeStreamPair(requestID string) { h.streamPairs.Remove(requestID) diff --git a/cri/stream/portforward/portforward.go b/cri/stream/portforward/portforward.go index eae91821f..e99d6f093 100644 --- a/cri/stream/portforward/portforward.go +++ b/cri/stream/portforward/portforward.go @@ -28,6 +28,4 @@ func ServePortForward(ctx context.Context, w http.ResponseWriter, req *http.Requ logrus.Errorf("failed to serve port forward: %v", err) return } - - return } diff --git a/ctrd/client.go b/ctrd/client.go index d83fec8f9..19b3b518f 100644 --- a/ctrd/client.go +++ b/ctrd/client.go @@ -32,8 +32,6 @@ type Client struct { watch *watch lock *containerLock - rpcAddr string - // containerd grpc pool pool []scheduler.Factory scheduler scheduler.Scheduler diff --git a/ctrd/container.go b/ctrd/container.go index 53efb66e0..834cfdfc2 100644 --- a/ctrd/container.go +++ b/ctrd/container.go @@ -701,9 +701,8 @@ func (c *Client) waitContainer(ctx context.Context, id string) (types.ContainerW return c.ProbeContainer(ctx, id, -1*time.Second) } - var msg *Message // wait for the task to exit. - msg = waitExit() + msg := waitExit() errMsg := "" err = msg.RawError() diff --git a/ctrd/snapshot.go b/ctrd/snapshot.go index 53f0fcc34..234840f88 100644 --- a/ctrd/snapshot.go +++ b/ctrd/snapshot.go @@ -32,10 +32,8 @@ func (c *Client) CreateSnapshot(ctx context.Context, id, ref string) error { } parent := identity.ChainID(diffIDs).String() - if _, err := wrapperCli.client.SnapshotService(defaultSnapshotterName).Prepare(ctx, id, parent); err != nil { - return err - } - return nil + _, err = wrapperCli.client.SnapshotService(defaultSnapshotterName).Prepare(ctx, id, parent) + return err } // GetSnapshot returns the snapshot's info by id. diff --git a/daemon/config/config.go b/daemon/config/config.go index b1012ff1f..7b456b107 100644 --- a/daemon/config/config.go +++ b/daemon/config/config.go @@ -179,7 +179,7 @@ func (cfg *Config) MergeConfigurations(flagSet *pflag.FlagSet) error { return nil } - fileFlags := make(map[string]interface{}, 0) + fileFlags := make(map[string]interface{}) flattenConfig(origin, fileFlags) // check conflict in command line flags and config file diff --git a/daemon/logger/jsonfile/jsonfile_read_test.go b/daemon/logger/jsonfile/jsonfile_read_test.go index d8c9e5038..b41f97c4b 100644 --- a/daemon/logger/jsonfile/jsonfile_read_test.go +++ b/daemon/logger/jsonfile/jsonfile_read_test.go @@ -31,7 +31,7 @@ func TestReadLogMessagesWithRemoveFileInFollowMode(t *testing.T) { os.RemoveAll(f.Name()) select { - case _, _ = <-watcher.Msgs: + case <-watcher.Msgs: case <-time.After(250 * time.Millisecond): // NOTE: watchTimeout is 200ms t.Fatal("expected watcher.Msgs has been closed after removed file, but it's still alive") @@ -64,7 +64,7 @@ func TestReadLogMessagesForEmptyFileWithoutFollow(t *testing.T) { <-time.After(100 * time.Millisecond) select { - case _, _ = <-watcher.Msgs: + case <-watcher.Msgs: case <-time.After(100 * time.Millisecond): t.Fatalf("expected watcher.Msgs has been closed after removed file, but it's still alive") } diff --git a/daemon/logger/jsonfile/utils_test.go b/daemon/logger/jsonfile/utils_test.go index 8547530b3..32fdb3341 100644 --- a/daemon/logger/jsonfile/utils_test.go +++ b/daemon/logger/jsonfile/utils_test.go @@ -8,11 +8,14 @@ import ( "os" "reflect" "strings" + "sync" "testing" "time" "github.com/alibaba/pouch/daemon/logger" "github.com/alibaba/pouch/pkg/utils" + + "github.com/pkg/errors" ) var _ logger.LogDriver = &JSONLogFile{} @@ -133,21 +136,25 @@ func TestFollowFile(t *testing.T) { // create goroutine to read the file watcher := logger.NewLogWatcher() waitCh := make(chan struct{}) + errchan := make(chan error) + var wg sync.WaitGroup defer func() { watcher.Close() <-waitCh }() go func() { - // NOTE: make sure all the goutine exits + wg.Add(1) + // NOTE: make sure all the goroutine exits defer func() { waitCh <- struct{}{} }() newF, err := os.Open(f.Name()) if err != nil { - t.Fatalf("unexpected error during open file for followFile: %v", err) + errchan <- errors.Errorf("unexpected error during open file for followFile: %v", err) } + wg.Done() cfg := &logger.ReadConfig{ Since: generateTime(t, "2018-05-09T10:00:01.1Z"), @@ -156,6 +163,15 @@ func TestFollowFile(t *testing.T) { followFile(newF, cfg, newUnmarshal, watcher) }() + go func() { + wg.Wait() + close(errchan) + }() + + if err := <-errchan; err != nil { + t.Fatal(err) + } + // should read three log message for _, el := range expectedMsgs[:2] { checkExpectedLogMessage(t, watcher, el) diff --git a/daemon/mgr/container.go b/daemon/mgr/container.go index a952be283..6a03bb651 100644 --- a/daemon/mgr/container.go +++ b/daemon/mgr/container.go @@ -36,7 +36,6 @@ import ( containerdtypes "github.com/containerd/containerd/api/types" "github.com/containerd/containerd/mount" "github.com/docker/go-units" - "github.com/docker/libnetwork" "github.com/go-openapi/strfmt" ocispec "github.com/opencontainers/image-spec/specs-go/v1" "github.com/pkg/errors" @@ -1525,41 +1524,6 @@ func (mgr *ContainerManager) connectToNetwork(ctx context.Context, container *Co return mgr.updateNetworkConfig(container, networkIDOrName, endpoint.EndpointConfig) } -// FIXME: remove this useless functions -func (mgr *ContainerManager) updateNetworkSettings(container *Container, n libnetwork.Network) error { - if container.NetworkSettings == nil { - container.NetworkSettings = &types.NetworkSettings{Networks: make(map[string]*types.EndpointSettings)} - } - - if !IsHost(container.HostConfig.NetworkMode) && IsHost(n.Type()) { - return fmt.Errorf("container cannot be connected to host network") - } - - for s := range container.NetworkSettings.Networks { - sn, err := mgr.NetworkMgr.Get(context.Background(), s) - if err != nil { - continue - } - - if sn.Name == n.Name() { - // Avoid duplicate config - return nil - } - if !IsPrivate(sn.Type) || !IsPrivate(n.Type()) { - return fmt.Errorf("container sharing network namespace with another container or host cannot be connected to any other network") - } - if IsNone(sn.Name) || IsNone(n.Name()) { - return fmt.Errorf("container cannot be connected to multiple networks with one of the networks in none mode") - } - } - - if _, ok := container.NetworkSettings.Networks[n.Name()]; !ok { - container.NetworkSettings.Networks[n.Name()] = new(types.EndpointSettings) - } - - return nil -} - func (mgr *ContainerManager) initContainerIO(c *Container) (*containerio.IO, error) { if io := mgr.IOs.Get(c.ID); io != nil { return nil, errors.Wrap(errtypes.ErrConflict, "failed to create containerIO") @@ -1814,7 +1778,6 @@ func (mgr *ContainerManager) resetContainerIOs(containerID string) { } io.Reset() - return } // buildContainerEndpoint builds Endpoints according to container diff --git a/daemon/mgr/container_logger.go b/daemon/mgr/container_logger.go index 22c3debc8..60da8941f 100644 --- a/daemon/mgr/container_logger.go +++ b/daemon/mgr/container_logger.go @@ -62,5 +62,4 @@ func (mgr *ContainerManager) SetContainerLogPath(c *Container) { if c.HostConfig.LogConfig.LogDriver == "json-file" { c.LogPath = filepath.Join(mgr.Config.HomeDir, "containers", c.ID, "json.log") } - return } diff --git a/daemon/mgr/container_storage.go b/daemon/mgr/container_storage.go index 74ed67f8d..f85042331 100644 --- a/daemon/mgr/container_storage.go +++ b/daemon/mgr/container_storage.go @@ -736,7 +736,7 @@ func copyImageContent(source, destination string) error { // destination directory is not exist, so mkdir for it. logrus.Warnf("(%s) is not exist", destination) - if err := os.MkdirAll(destination, 755); err != nil && !os.IsExist(err) { + if err := os.MkdirAll(destination, 0755); err != nil && !os.IsExist(err) { return err } } else if !fi.IsDir() { diff --git a/daemon/mgr/container_types.go b/daemon/mgr/container_types.go index b5472a11a..409a31654 100644 --- a/daemon/mgr/container_types.go +++ b/daemon/mgr/container_types.go @@ -452,7 +452,7 @@ func (c *Container) UnsetMergedDir() { // SetSnapshotterMeta sets snapshotter for container func (c *Container) SetSnapshotterMeta(mounts []mount.Mount) { // TODO(ziren): now we only support overlayfs - data := make(map[string]string, 0) + data := make(map[string]string) for _, opt := range mounts[0].Options { if strings.HasPrefix(opt, "upperdir=") { data["UpperDir"] = strings.TrimPrefix(opt, "upperdir=") diff --git a/daemon/mgr/image_store.go b/daemon/mgr/image_store.go index 0111dd1e6..045e99e2f 100644 --- a/daemon/mgr/image_store.go +++ b/daemon/mgr/image_store.go @@ -171,9 +171,8 @@ func (store *imageStore) Search(ref reference.Named) (digest.Digest, reference.N func (store *imageStore) searchIDs(refID string) (digest.Digest, error) { var ids []digest.Digest - var id string - id = refID + id := refID if !strings.HasPrefix(refID, digest.Canonical.String()) { id = fmt.Sprintf("%s:%s", digest.Canonical.String(), refID) } diff --git a/lxcfs/lxcfs.go b/lxcfs/lxcfs.go index d310e8cd8..92dcfb508 100644 --- a/lxcfs/lxcfs.go +++ b/lxcfs/lxcfs.go @@ -44,7 +44,7 @@ func CheckLxcfsMount() error { break } } - if isMount == false { + if !isMount { return fmt.Errorf("%s is not a mount point, please run \" lxcfs %s \" before Pouchd", LxcfsHomeDir, LxcfsHomeDir) } return nil diff --git a/pkg/archive/archive.go b/pkg/archive/archive.go index d7f493ab4..fceee88a4 100644 --- a/pkg/archive/archive.go +++ b/pkg/archive/archive.go @@ -50,11 +50,8 @@ func tarFromDir(src string, writer io.Writer) error { defer f.Close() // copy file data into tar writer - if _, err := io.Copy(tw, f); err != nil { - return err - } - - return nil + _, err = io.Copy(tw, f) + return err }) } diff --git a/pkg/kmutex/kmutex_test.go b/pkg/kmutex/kmutex_test.go index 0c61e1203..dfd71aab3 100644 --- a/pkg/kmutex/kmutex_test.go +++ b/pkg/kmutex/kmutex_test.go @@ -5,12 +5,15 @@ import ( "sync" "testing" "time" + + "github.com/pkg/errors" ) func TestKMutex(t *testing.T) { m := New() var wg sync.WaitGroup + errchan := make(chan error) for i := 0; i < 10; i++ { wg.Add(1) @@ -20,48 +23,58 @@ func TestKMutex(t *testing.T) { k := strconv.Itoa(i) - if m.Trylock(k) == false { - t.Fatalf("failed to trylock: %d", i) + if !m.Trylock(k) { + errchan <- errors.Errorf("failed to trylock: %d", i) } - if m.Trylock(k) == true { - t.Fatalf("trylock is error: %d", i) + if m.Trylock(k) { + errchan <- errors.Errorf("trylock is error: %d", i) } m.Unlock(k) - if m.Trylock(k) == false { - t.Fatalf("failed to trylock: %d", i) + if !m.Trylock(k) { + errchan <- errors.Errorf("failed to trylock: %d", i) } }(i) } - wg.Wait() + go func() { + wg.Wait() + close(errchan) + }() + + if err := <-errchan; err != nil { + t.Fatal(err) + } } func TestKMutexTimeout(t *testing.T) { m := New() running := make(chan struct{}) - wait := make(chan struct{}) + errchan := make(chan error) + go func() { - if m.Trylock("key") == false { - t.Fatalf("failed to trylock") + if !m.Trylock("key") { + errchan <- errors.New("failed to trylock") + return } close(running) time.Sleep(time.Second * 10) - close(wait) }() - <-running - go func() { - <-wait - t.Fatalf("failed to trylock with timeout") + <-running + close(errchan) }() - if m.LockWithTimeout("key", time.Second*5) == true { + if err := <-errchan; err != nil { + t.Fatal(err) + } + + if m.LockWithTimeout("key", time.Second*5) { t.Fatalf("trylock with timeout is error") } } diff --git a/pkg/meta/local.go b/pkg/meta/local.go index 727d6c3e5..89a17a94b 100644 --- a/pkg/meta/local.go +++ b/pkg/meta/local.go @@ -39,12 +39,9 @@ func NewLocalStore(cfg Config) (Backend, error) { // initialize cache handle := func(f os.FileInfo) error { - if _, err := s.Get(MetaJSONFile, f.Name()); err != nil { - return err - } + _, err := s.Get(MetaJSONFile, f.Name()) + return err // TODO maybe get other file. - - return nil } if err := walkDir(s.base, handle); err != nil { diff --git a/pkg/meta/store.go b/pkg/meta/store.go index 13a034306..1d06a0019 100644 --- a/pkg/meta/store.go +++ b/pkg/meta/store.go @@ -260,10 +260,8 @@ func (s *Store) KeysWithPrefix(prefix string) ([]string, error) { s.trieLock.Lock() defer s.trieLock.Unlock() - if err := s.trie.VisitSubtree(patricia.Prefix(prefix), fn); err != nil { - return keys, err - } - return keys, nil + err := s.trie.VisitSubtree(patricia.Prefix(prefix), fn) + return keys, err } // Path returns the path with specified key. diff --git a/pkg/netutils/interface_test.go b/pkg/netutils/interface_test.go index 589781e53..ddc863bb1 100644 --- a/pkg/netutils/interface_test.go +++ b/pkg/netutils/interface_test.go @@ -299,10 +299,8 @@ func (validNetworkInterface) InterfaceByName(intfName string) (*net.Interface, e return &upIntf, nil } func (validNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil + return []net.Addr{ + addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}}, nil } func (validNetworkInterface) Interfaces() ([]net.Interface, error) { return []net.Interface{upIntf}, nil @@ -316,11 +314,10 @@ func (v4v6NetworkInterface) InterfaceByName(intfName string) (*net.Interface, er return &upIntf, nil } func (v4v6NetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "2001::10/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil + return []net.Addr{ + addrStruct{val: "2001::10/64"}, addrStruct{val: "10.254.71.145/17"}}, nil } + func (v4v6NetworkInterface) Interfaces() ([]net.Interface, error) { return []net.Interface{upIntf}, nil } @@ -333,9 +330,7 @@ func (ipv6NetworkInterface) InterfaceByName(intfName string) (*net.Interface, er return &upIntf, nil } func (ipv6NetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "2001::200/64"}} - return ifat, nil + return []net.Addr{addrStruct{val: "2001::200/64"}}, nil } func (ipv6NetworkInterface) Interfaces() ([]net.Interface, error) { @@ -350,10 +345,9 @@ func (networkInterfaceWithOnlyLinkLocals) InterfaceByName(intfName string) (*net return &upIntf, nil } func (networkInterfaceWithOnlyLinkLocals) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "169.254.162.166/16"}, addrStruct{val: "fe80::200/10"}} - return ifat, nil + return []net.Addr{addrStruct{val: "169.254.162.166/16"}, addrStruct{val: "fe80::200/10"}}, nil } + func (networkInterfaceWithOnlyLinkLocals) Interfaces() ([]net.Interface, error) { return []net.Interface{upIntf}, nil } @@ -394,10 +388,8 @@ func (downNetworkInterface) InterfaceByName(intfName string) (*net.Interface, er return &downIntf, nil } func (downNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}} - return ifat, nil + return []net.Addr{ + addrStruct{val: "fe80::2f7:6fff:fe6e:2956/64"}, addrStruct{val: "10.254.71.145/17"}}, nil } func (downNetworkInterface) Interfaces() ([]net.Interface, error) { return []net.Interface{downIntf}, nil @@ -411,10 +403,8 @@ func (loopbackNetworkInterface) InterfaceByName(intfName string) (*net.Interface return &loopbackIntf, nil } func (loopbackNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "::1/128"}, addrStruct{val: "127.0.0.1/8"}} - return ifat, nil + return []net.Addr{ + addrStruct{val: "::1/128"}, addrStruct{val: "127.0.0.1/8"}}, nil } func (loopbackNetworkInterface) Interfaces() ([]net.Interface, error) { return []net.Interface{loopbackIntf}, nil @@ -428,10 +418,8 @@ func (p2pNetworkInterface) InterfaceByName(intfName string) (*net.Interface, err return &p2pIntf, nil } func (p2pNetworkInterface) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{ - addrStruct{val: "::1/128"}, addrStruct{val: "127.0.0.1/8"}} - return ifat, nil + return []net.Addr{ + addrStruct{val: "::1/128"}, addrStruct{val: "127.0.0.1/8"}}, nil } func (p2pNetworkInterface) Interfaces() ([]net.Interface, error) { return []net.Interface{p2pIntf}, nil @@ -459,8 +447,7 @@ func (networkInterfaceWithNoAddrs) InterfaceByName(intfName string) (*net.Interf return &upIntf, nil } func (networkInterfaceWithNoAddrs) Addrs(intf *net.Interface) ([]net.Addr, error) { - ifat := []net.Addr{} - return ifat, nil + return []net.Addr{}, nil } func (networkInterfaceWithNoAddrs) Interfaces() ([]net.Interface, error) { return []net.Interface{upIntf}, nil @@ -474,9 +461,7 @@ func (networkInterfaceWithInvalidAddr) InterfaceByName(intfName string) (*net.In return &upIntf, nil } func (networkInterfaceWithInvalidAddr) Addrs(intf *net.Interface) ([]net.Addr, error) { - var ifat []net.Addr - ifat = []net.Addr{addrStruct{val: "10.20.30.40.50/24"}} - return ifat, nil + return []net.Addr{addrStruct{val: "10.20.30.40.50/24"}}, nil } func (networkInterfaceWithInvalidAddr) Interfaces() ([]net.Interface, error) { return []net.Interface{upIntf}, nil diff --git a/pkg/user/user.go b/pkg/user/user.go index 0f9ae9bc4..686a2532c 100644 --- a/pkg/user/user.go +++ b/pkg/user/user.go @@ -33,9 +33,6 @@ type uidParser struct { placeholder string uid int gid int - finger []string - userdir string - shell string } // gidParser defines lines in /etc/group, eg: root:x:0:. @@ -43,7 +40,6 @@ type gidParser struct { group string placeholder string gid int - otherGroup []string } // Get accepts user and group slice, return valid uid, gid and additional gids. diff --git a/pkg/utils/timeutils.go b/pkg/utils/timeutils.go index 0e01036de..d37c0abc6 100644 --- a/pkg/utils/timeutils.go +++ b/pkg/utils/timeutils.go @@ -33,7 +33,7 @@ var errInvalid = errors.New("invalid time") // FormatTimeInterval is used to show the time interval from input time to now. func FormatTimeInterval(input int64) (formattedTime string, err error) { start := time.Unix(0, input) - diff := time.Now().Sub(start) + diff := time.Since(start) // That should not happen. if diff < 0 { diff --git a/pkg/utils/utils.go b/pkg/utils/utils.go index bfd6fd7d3..bdd23a586 100644 --- a/pkg/utils/utils.go +++ b/pkg/utils/utils.go @@ -368,7 +368,7 @@ func ToStringMap(in map[string]interface{}) map[string]string { if in == nil { return nil } - out := make(map[string]string, 0) + out := make(map[string]string) for k, v := range in { if s, ok := v.(string); ok { out[k] = s diff --git a/registry/auth.go b/registry/auth.go index 26bd9b95c..590a85f15 100644 --- a/registry/auth.go +++ b/registry/auth.go @@ -1,7 +1,6 @@ package registry import ( - "crypto/tls" "encoding/json" "fmt" "net/http" @@ -22,9 +21,9 @@ type challengeClient struct { } type registryEndpoint struct { - version string - url *url.URL - tlsConfig *tls.Config + version string + url *url.URL + // TODO: support tls for registry. } // token defines a token that registry may return after login successfully. diff --git a/registry/auth_challenge.go b/registry/auth_challenge.go index eea33d20d..b7aa53898 100644 --- a/registry/auth_challenge.go +++ b/registry/auth_challenge.go @@ -49,8 +49,8 @@ func init() { var t octetType isCtl := c <= 31 || c == 127 isChar := 0 <= c && c <= 127 - isSeparator := strings.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 - if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { + isSeparator := strings.ContainsRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) + if strings.ContainsRune(" \t\r\n", rune(c)) { t |= isSpace } if isChar && !isCtl && !isSeparator { diff --git a/storage/plugins/client.go b/storage/plugins/client.go index 75828b51a..86055a435 100644 --- a/storage/plugins/client.go +++ b/storage/plugins/client.go @@ -51,7 +51,7 @@ func NewPluginClient(addr string, tlsconfig *TLSConfig) (*PluginClient, error) { // Scheme is https, generate the tls config if url.Scheme == "https" { - if tlsconfig != nil && tlsconfig.InsecureSkipVerify == false { + if tlsconfig != nil && !tlsconfig.InsecureSkipVerify { config, err = httputils.GenTLSConfig(tlsconfig.KeyFile, tlsconfig.CertFile, tlsconfig.CAFile) if err != nil { return nil, fmt.Errorf("failed to parse plugin tls config: %v", err) diff --git a/storage/quota/grpquota.go b/storage/quota/grpquota.go index a11a05480..c2a8582a7 100644 --- a/storage/quota/grpquota.go +++ b/storage/quota/grpquota.go @@ -90,7 +90,7 @@ func (quota *GrpQuotaDriver) EnforceQuota(dir string) (string, error) { header[4] = 0x01 } - if writeErr := ioutil.WriteFile(filename, header, 644); writeErr != nil { + if writeErr := ioutil.WriteFile(filename, header, 0644); writeErr != nil { return mountPoint, errors.Wrapf(writeErr, "failed to write file, filename: (%s), vfs version: (%s)", filename, vfsVersion) } diff --git a/storage/quota/quota.go b/storage/quota/quota.go index 5c316e4d3..25b100e7c 100644 --- a/storage/quota/quota.go +++ b/storage/quota/quota.go @@ -29,8 +29,6 @@ const ( ) var ( - hasQuota bool - // GQuotaDriver represents global quota driver. GQuotaDriver = NewQuotaDriver("") @@ -344,7 +342,7 @@ func getOverlayMountInfo(basefs string) (*OverlayMount, error) { // #500 -- 47504 0 0 101 0 0 // #16777221 -- 3048576 0 3048576 8 0 0 func loadQuotaIDs(repquotaOpt string) (map[uint32]struct{}, uint32, error) { - quotaIDs := make(map[uint32]struct{}, 0) + quotaIDs := make(map[uint32]struct{}) minID := QuotaMinID exit, output, stderr, err := exec.Run(0, "repquota", repquotaOpt) diff --git a/storage/volume/core_test.go b/storage/volume/core_test.go index faff2de60..73a2224cc 100644 --- a/storage/volume/core_test.go +++ b/storage/volume/core_test.go @@ -170,7 +170,7 @@ func TestListVolumes(t *testing.T) { for k := 0; k < len(volarray); k++ { vol := volarray[k] _, found := volmap[vol.Name] - if found == false { + if !found { t.Fatalf("list volumes %v not found", vol) } } @@ -253,7 +253,7 @@ func TestListVolumeName(t *testing.T) { for k := 0; k < len(volarray); k++ { vol := volarray[k] _, found := volmap[vol.Name] - if found == false { + if !found { t.Fatalf("list volumes %v not found", vol) } } @@ -265,7 +265,7 @@ func TestListVolumeName(t *testing.T) { } for j := 0; j < len(volNames); j++ { _, found := volmap[volNames[j]] - if found == false { + if !found { t.Fatalf("list volumes name %s not found", volNames[j]) } } diff --git a/storage/volume/driver/driver.go b/storage/volume/driver/driver.go index 5ff18fe7c..1ca193d0a 100644 --- a/storage/volume/driver/driver.go +++ b/storage/volume/driver/driver.go @@ -49,18 +49,12 @@ func (m VolumeStoreMode) Valid() bool { // local store if m.IsLocal() { - if m.CentralCreateDelete() { - return false - } - return true + return !m.CentralCreateDelete() } // remote store if m.IsRemote() { - if m.UseLocalMeta() { - return false - } - return true + return !m.UseLocalMeta() } return false @@ -225,11 +219,7 @@ func GetAll() ([]Driver, error) { // Exist return true if the backend driver is registered. func Exist(name string) bool { _, err := Get(name) - if err != nil { - return false - } - - return true + return err == nil } // AllDriversName return all registered backend driver's name. diff --git a/storage/volume/driver/driver_test.go b/storage/volume/driver/driver_test.go index 5e46be701..f5dee1ca7 100644 --- a/storage/volume/driver/driver_test.go +++ b/storage/volume/driver/driver_test.go @@ -26,7 +26,7 @@ func TestRegister(t *testing.T) { } success := Unregister(testDriverName) - if success == false { + if !success { t.Fatal("failed to unregister testdriver") } @@ -49,7 +49,7 @@ func TestGetAll(t *testing.T) { defer func() { for _, name := range driverNames { success := Unregister(name) - if success == false { + if !success { t.Fatalf("failed to unregister driver: %s", name) } } @@ -80,7 +80,7 @@ func TestAlias(t *testing.T) { defer func() { for _, name := range driverNames { success := Unregister(name) - if success == false { + if !success { t.Fatalf("failed to unregister driver: %s", name) } } diff --git a/storage/volume/driver/remote.go b/storage/volume/driver/remote.go index dd119d946..4c7af6a76 100644 --- a/storage/volume/driver/remote.go +++ b/storage/volume/driver/remote.go @@ -115,11 +115,7 @@ func (r *remoteDriverWrapper) Attach(ctx Context, v *types.Volume) error { ctx.Log.Debugf("driver wrapper [%s] attach volume: %s", r.Name(ctx), v.Name) _, err := r.proxy.Mount(v.Name, v.UID) - if err != nil { - return err - } - - return nil + return err } // Detach a remote volume. diff --git a/test/cli_exec_test.go b/test/cli_exec_test.go index a9331b0c7..84499b85f 100644 --- a/test/cli_exec_test.go +++ b/test/cli_exec_test.go @@ -59,10 +59,10 @@ func (suite *PouchExecSuite) TestExecCommand(c *check.C) { func (suite *PouchExecSuite) TestExecNoCommand(c *check.C) { cname := "TestExecNoCommand" - res := command.PouchRun("run", "-d", "--name", cname, busyboxImage, "sleep", "100000").Assert(c, icmd.Success) + command.PouchRun("run", "-d", "--name", cname, busyboxImage, "sleep", "100000").Assert(c, icmd.Success) defer DelContainerForceMultyTime(c, cname) - res = command.PouchRun("exec", cname) + res := command.PouchRun("exec", cname) expectedError := "requires at least 2 arg(s), only received 1" if out := res.Combined(); !strings.Contains(out, expectedError) { c.Fatalf("unexpected output %s, expected %s", out, expectedError) diff --git a/test/cli_run_blkio_test.go b/test/cli_run_blkio_test.go index c7e6992bb..add9fc827 100644 --- a/test/cli_run_blkio_test.go +++ b/test/cli_run_blkio_test.go @@ -79,7 +79,7 @@ func (suite *PouchRunBlkioSuite) TestRunBlockIOWeightDevice(c *check.C) { SkipIfFalse(c, func() bool { file := fmt.Sprintf("/sys/block/%s/queue/scheduler", - strings.Trim(testDisk, "/dev/")) + strings.TrimPrefix(testDisk, "/dev/")) if data, err := ioutil.ReadFile(file); err == nil { return strings.Contains(string(data), "[cfq]") } diff --git a/test/cli_run_cgroup_test.go b/test/cli_run_cgroup_test.go index 520d65256..ccd563db3 100644 --- a/test/cli_run_cgroup_test.go +++ b/test/cli_run_cgroup_test.go @@ -55,9 +55,7 @@ func testRunWithCgroupParent(c *check.C, cgroupParent, name string) { c.Assert(err, check.IsNil) // this code slice may not robust, but for this test case is enough. - if strings.HasPrefix(cgroupParent, "/") { - cgroupParent = cgroupParent[1:] - } + cgroupParent = strings.TrimPrefix(cgroupParent, "/") if cgroupParent == "" { cgroupParent = "default" diff --git a/test/daemon/daemon.go b/test/daemon/daemon.go index 34ca7c7bb..030595d3c 100644 --- a/test/daemon/daemon.go +++ b/test/daemon/daemon.go @@ -168,8 +168,8 @@ func (d *Config) StartDaemon() error { close(wait) }() - if util.WaitTimeout(time.Duration(d.timeout)*time.Second, d.IsDaemonUp) == false { - if d.Debug == true { + if !util.WaitTimeout(time.Duration(d.timeout)*time.Second, d.IsDaemonUp) { + if d.Debug { d.DumpLog() fmt.Printf("\nFailed to launch pouchd:%v\n", d.Args) @@ -201,7 +201,7 @@ func (d *Config) DumpLog() { // KillDaemon kill pouchd. func (d *Config) KillDaemon() { - if d.IsDaemonUp() == false { + if !d.IsDaemonUp() { return } @@ -215,5 +215,4 @@ func (d *Config) KillDaemon() { d.LogFile.Close() } - return } diff --git a/test/environment/env.go b/test/environment/env.go index 9ccece111..8a6cef9bd 100644 --- a/test/environment/env.go +++ b/test/environment/env.go @@ -116,10 +116,7 @@ func IsLinux() bool { // IsAliKernel checks if the kernel of test environment is AliKernel. func IsAliKernel() bool { cmd := "uname -r | grep -i alios" - if icmd.RunCommand("bash", "-c", cmd).ExitCode == 0 { - return true - } - return false + return icmd.RunCommand("bash", "-c", cmd).ExitCode == 0 } // IsDumbInitExist checks if the dumb-init binary exists on host. @@ -133,10 +130,7 @@ func IsDumbInitExist() bool { // IsRuncVersionSupportRichContianer checks if the version of runc supports rich container. func IsRuncVersionSupportRichContianer() bool { cmd := "runc -v|grep 1.0.0-rc4-1" - if icmd.RunCommand("bash", "-c", cmd).ExitCode == 0 { - return true - } - return false + return icmd.RunCommand("bash", "-c", cmd).ExitCode == 0 } // IsHubConnected checks if hub address can be connected. @@ -147,10 +141,7 @@ func IsHubConnected() bool { // IsDiskQuota checks if it can use disk quota for container. func IsDiskQuota() bool { - if icmd.RunCommand("which", "quotaon").ExitCode == 0 { - return true - } - return false + return icmd.RunCommand("which", "quotaon").ExitCode == 0 } // IsPrjquota checks if there is prjquota set on test machine @@ -174,17 +165,11 @@ func IsLxcfsEnabled() bool { return false } cmd := "ps -ef |grep pouchd |grep \"enable\\-lxcfs\"" - if icmd.RunCommand("sh", "-c", cmd).ExitCode != 0 { - return false - } - return true + return icmd.RunCommand("sh", "-c", cmd).ExitCode == 0 } // IsCRIUExist checks if criu exist on machine. func IsCRIUExist() bool { _, err := exec.LookPath("criu") - if err != nil { - return false - } - return true + return err == nil } diff --git a/test/util/util.go b/test/util/util.go index 5346e0ba7..f610c5777 100644 --- a/test/util/util.go +++ b/test/util/util.go @@ -30,7 +30,7 @@ func WaitTimeout(timeout time.Duration, condition func() bool) bool { fmt.Printf("condition failed to return true within %f seconds.\n", timeout.Seconds()) return false case <-ticker.C: - if condition() == true { + if condition() { ch <- true } } diff --git a/test/utils.go b/test/utils.go index 6840a8e72..421549ed9 100644 --- a/test/utils.go +++ b/test/utils.go @@ -69,7 +69,7 @@ type VerifyCondition func() bool // SkipIfFalse skips the suite, if any of the conditions is not satisfied. func SkipIfFalse(c *check.C, conditions ...VerifyCondition) { for _, con := range conditions { - if con() == false { + if !con() { c.Skip("Skip test as condition is not matched") } }