make lint: enable gocritic

`gocritic` is a powerful linter that helps in preventing certain kinds
of errors as well as enforcing a coding style.

Signed-off-by: Valentin Rothberg <rothberg@redhat.com>
This commit is contained in:
Valentin Rothberg
2020-01-13 13:01:45 +01:00
parent 270d892c3d
commit 67165b7675
45 changed files with 206 additions and 215 deletions

View File

@ -24,7 +24,6 @@ linters:
- gochecknoglobals - gochecknoglobals
- gochecknoinits - gochecknoinits
- goconst - goconst
- gocritic
- gocyclo - gocyclo
- golint - golint
- goimports - goimports

View File

@ -116,21 +116,22 @@ func getContainerfiles(files []string) []string {
func getNsValues(c *cliconfig.BuildValues) ([]buildah.NamespaceOption, error) { func getNsValues(c *cliconfig.BuildValues) ([]buildah.NamespaceOption, error) {
var ret []buildah.NamespaceOption var ret []buildah.NamespaceOption
if c.Network != "" { if c.Network != "" {
if c.Network == "host" { switch {
case c.Network == "host":
ret = append(ret, buildah.NamespaceOption{ ret = append(ret, buildah.NamespaceOption{
Name: string(specs.NetworkNamespace), Name: string(specs.NetworkNamespace),
Host: true, Host: true,
}) })
} else if c.Network == "container" { case c.Network == "container":
ret = append(ret, buildah.NamespaceOption{ ret = append(ret, buildah.NamespaceOption{
Name: string(specs.NetworkNamespace), Name: string(specs.NetworkNamespace),
}) })
} else if c.Network[0] == '/' { case c.Network[0] == '/':
ret = append(ret, buildah.NamespaceOption{ ret = append(ret, buildah.NamespaceOption{
Name: string(specs.NetworkNamespace), Name: string(specs.NetworkNamespace),
Path: c.Network, Path: c.Network,
}) })
} else { default:
return nil, fmt.Errorf("unsupported configuration network=%s", c.Network) return nil, fmt.Errorf("unsupported configuration network=%s", c.Network)
} }
} }

View File

@ -24,7 +24,8 @@ func getAllOrLatestContainers(c *cliconfig.PodmanCommand, runtime *libpod.Runtim
var containers []*libpod.Container var containers []*libpod.Container
var lastError error var lastError error
var err error var err error
if c.Bool("all") { switch {
case c.Bool("all"):
if filterState != -1 { if filterState != -1 {
var filterFuncs []libpod.ContainerFilter var filterFuncs []libpod.ContainerFilter
filterFuncs = append(filterFuncs, func(c *libpod.Container) bool { filterFuncs = append(filterFuncs, func(c *libpod.Container) bool {
@ -38,13 +39,13 @@ func getAllOrLatestContainers(c *cliconfig.PodmanCommand, runtime *libpod.Runtim
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to get %s containers", verb) return nil, errors.Wrapf(err, "unable to get %s containers", verb)
} }
} else if c.Bool("latest") { case c.Bool("latest"):
lastCtr, err := runtime.GetLatestContainer() lastCtr, err := runtime.GetLatestContainer()
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "unable to get latest container") return nil, errors.Wrapf(err, "unable to get latest container")
} }
containers = append(containers, lastCtr) containers = append(containers, lastCtr)
} else { default:
args := c.InputArgs args := c.InputArgs
for _, i := range args { for _, i := range args {
container, err := runtime.LookupContainer(i) container, err := runtime.LookupContainer(i)

View File

@ -138,25 +138,25 @@ func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest strin
hostOwner := idtools.IDPair{UID: int(hostUID), GID: int(hostGID)} hostOwner := idtools.IDPair{UID: int(hostUID), GID: int(hostGID)}
if isFromHostToCtr { if isFromHostToCtr {
if isVol, volDestName, volName := isVolumeDestName(destPath, ctr); isVol { if isVol, volDestName, volName := isVolumeDestName(destPath, ctr); isVol { //nolint(gocritic)
path, err := pathWithVolumeMount(ctr, runtime, volDestName, volName, destPath) path, err := pathWithVolumeMount(ctr, runtime, volDestName, volName, destPath)
if err != nil { if err != nil {
return errors.Wrapf(err, "error getting destination path from volume %s", volDestName) return errors.Wrapf(err, "error getting destination path from volume %s", volDestName)
} }
destPath = path destPath = path
} else if isBindMount, mount := isBindMountDestName(destPath, ctr); isBindMount { } else if isBindMount, mount := isBindMountDestName(destPath, ctr); isBindMount { //nolint(gocritic)
path, err := pathWithBindMountSource(mount, destPath) path, err := pathWithBindMountSource(mount, destPath)
if err != nil { if err != nil {
return errors.Wrapf(err, "error getting destination path from bind mount %s", mount.Destination) return errors.Wrapf(err, "error getting destination path from bind mount %s", mount.Destination)
} }
destPath = path destPath = path
} else if filepath.IsAbs(destPath) { } else if filepath.IsAbs(destPath) { //nolint(gocritic)
cleanedPath, err := securejoin.SecureJoin(mountPoint, destPath) cleanedPath, err := securejoin.SecureJoin(mountPoint, destPath)
if err != nil { if err != nil {
return err return err
} }
destPath = cleanedPath destPath = cleanedPath
} else { } else { //nolint(gocritic)
ctrWorkDir, err := securejoin.SecureJoin(mountPoint, ctr.WorkingDir()) ctrWorkDir, err := securejoin.SecureJoin(mountPoint, ctr.WorkingDir())
if err != nil { if err != nil {
return err return err
@ -172,25 +172,25 @@ func copyBetweenHostAndContainer(runtime *libpod.Runtime, src string, dest strin
} }
} else { } else {
destOwner = idtools.IDPair{UID: os.Getuid(), GID: os.Getgid()} destOwner = idtools.IDPair{UID: os.Getuid(), GID: os.Getgid()}
if isVol, volDestName, volName := isVolumeDestName(srcPath, ctr); isVol { if isVol, volDestName, volName := isVolumeDestName(srcPath, ctr); isVol { //nolint(gocritic)
path, err := pathWithVolumeMount(ctr, runtime, volDestName, volName, srcPath) path, err := pathWithVolumeMount(ctr, runtime, volDestName, volName, srcPath)
if err != nil { if err != nil {
return errors.Wrapf(err, "error getting source path from volume %s", volDestName) return errors.Wrapf(err, "error getting source path from volume %s", volDestName)
} }
srcPath = path srcPath = path
} else if isBindMount, mount := isBindMountDestName(srcPath, ctr); isBindMount { } else if isBindMount, mount := isBindMountDestName(srcPath, ctr); isBindMount { //nolint(gocritic)
path, err := pathWithBindMountSource(mount, srcPath) path, err := pathWithBindMountSource(mount, srcPath)
if err != nil { if err != nil {
return errors.Wrapf(err, "error getting source path from bind mount %s", mount.Destination) return errors.Wrapf(err, "error getting source path from bind mount %s", mount.Destination)
} }
srcPath = path srcPath = path
} else if filepath.IsAbs(srcPath) { } else if filepath.IsAbs(srcPath) { //nolint(gocritic)
cleanedPath, err := securejoin.SecureJoin(mountPoint, srcPath) cleanedPath, err := securejoin.SecureJoin(mountPoint, srcPath)
if err != nil { if err != nil {
return err return err
} }
srcPath = cleanedPath srcPath = cleanedPath
} else { } else { //nolint(gocritic)
cleanedPath, err := securejoin.SecureJoin(mountPoint, filepath.Join(ctr.WorkingDir(), srcPath)) cleanedPath, err := securejoin.SecureJoin(mountPoint, filepath.Join(ctr.WorkingDir(), srcPath))
if err != nil { if err != nil {
return err return err

View File

@ -115,14 +115,14 @@ func genHistoryFormat(format string, quiet bool) string {
} }
// historyToGeneric makes an empty array of interfaces for output // historyToGeneric makes an empty array of interfaces for output
func historyToGeneric(templParams []historyTemplateParams, JSONParams []*image.History) (genericParams []interface{}) { func historyToGeneric(templParams []historyTemplateParams, jsonParams []*image.History) (genericParams []interface{}) {
if len(templParams) > 0 { if len(templParams) > 0 {
for _, v := range templParams { for _, v := range templParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return
} }
for _, v := range JSONParams { for _, v := range jsonParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return

View File

@ -209,7 +209,7 @@ func (i imagesOptions) setOutputFormat() string {
} }
// imagesToGeneric creates an empty array of interfaces for output // imagesToGeneric creates an empty array of interfaces for output
func imagesToGeneric(templParams []imagesTemplateParams, JSONParams []imagesJSONParams) []interface{} { func imagesToGeneric(templParams []imagesTemplateParams, jsonParams []imagesJSONParams) []interface{} {
genericParams := []interface{}{} genericParams := []interface{}{}
if len(templParams) > 0 { if len(templParams) > 0 {
for _, v := range templParams { for _, v := range templParams {
@ -217,7 +217,7 @@ func imagesToGeneric(templParams []imagesTemplateParams, JSONParams []imagesJSON
} }
return genericParams return genericParams
} }
for _, v := range JSONParams { for _, v := range jsonParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return genericParams return genericParams
@ -282,10 +282,8 @@ func getImagesTemplateOutput(ctx context.Context, images []*adapter.ContainerIma
if len(tag) == 71 && strings.HasPrefix(tag, "sha256:") { if len(tag) == 71 && strings.HasPrefix(tag, "sha256:") {
imageDigest = digest.Digest(tag) imageDigest = digest.Digest(tag)
tag = "" tag = ""
} else { } else if img.Digest() != "" {
if img.Digest() != "" { imageDigest = img.Digest()
imageDigest = img.Digest()
}
} }
params := imagesTemplateParams{ params := imagesTemplateParams{
Repository: repo, Repository: repo,

View File

@ -72,17 +72,13 @@ var mainCommands = []*cobra.Command{
} }
var rootCmd = &cobra.Command{ var rootCmd = &cobra.Command{
Use: path.Base(os.Args[0]), Use: path.Base(os.Args[0]),
Long: "manage pods and images", Long: "manage pods and images",
RunE: commandRunE(), RunE: commandRunE(),
PersistentPreRunE: func(cmd *cobra.Command, args []string) error { PersistentPreRunE: before,
return before(cmd, args) PersistentPostRunE: after,
}, SilenceUsage: true,
PersistentPostRunE: func(cmd *cobra.Command, args []string) error { SilenceErrors: true,
return after(cmd, args)
},
SilenceUsage: true,
SilenceErrors: true,
} }
var MainGlobalOpts cliconfig.MainFlags var MainGlobalOpts cliconfig.MainFlags
@ -160,16 +156,13 @@ func main() {
} }
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
outputError(err) outputError(err)
} else { } else if exitCode == define.ExecErrorCodeGeneric {
// The exitCode modified from define.ExecErrorCodeGeneric, // The exitCode modified from define.ExecErrorCodeGeneric,
// indicates an application // indicates an application
// running inside of a container failed, as opposed to the // running inside of a container failed, as opposed to the
// podman command failed. Must exit with that exit code // podman command failed. Must exit with that exit code
// otherwise command exited correctly. // otherwise command exited correctly.
if exitCode == define.ExecErrorCodeGeneric { exitCode = 0
exitCode = 0
}
} }
// Check if /etc/containers/registries.conf exists when running in // Check if /etc/containers/registries.conf exists when running in

View File

@ -320,13 +320,14 @@ func generatePodFilterFuncs(filter, filterValue string) (func(pod *adapter.Pod)
// generate the template based on conditions given // generate the template based on conditions given
func genPodPsFormat(c *cliconfig.PodPsValues) string { func genPodPsFormat(c *cliconfig.PodPsValues) string {
format := "" format := ""
if c.Format != "" { switch {
case c.Format != "":
// "\t" from the command line is not being recognized as a tab // "\t" from the command line is not being recognized as a tab
// replacing the string "\t" to a tab character if the user passes in "\t" // replacing the string "\t" to a tab character if the user passes in "\t"
format = strings.Replace(c.Format, `\t`, "\t", -1) format = strings.Replace(c.Format, `\t`, "\t", -1)
} else if c.Quiet { case c.Quiet:
format = formats.IDString format = formats.IDString
} else { default:
format = "table {{.ID}}\t{{.Name}}\t{{.Status}}\t{{.Created}}" format = "table {{.ID}}\t{{.Name}}\t{{.Status}}\t{{.Created}}"
if c.Bool("namespace") { if c.Bool("namespace") {
format += "\t{{.Cgroup}}\t{{.Namespaces}}" format += "\t{{.Cgroup}}\t{{.Namespaces}}"
@ -341,14 +342,14 @@ func genPodPsFormat(c *cliconfig.PodPsValues) string {
return format return format
} }
func podPsToGeneric(templParams []podPsTemplateParams, JSONParams []podPsJSONParams) (genericParams []interface{}) { func podPsToGeneric(templParams []podPsTemplateParams, jsonParams []podPsJSONParams) (genericParams []interface{}) {
if len(templParams) > 0 { if len(templParams) > 0 {
for _, v := range templParams { for _, v := range templParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return
} }
for _, v := range JSONParams { for _, v := range jsonParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return

View File

@ -124,10 +124,8 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error {
for i := 0; i < t.NumField(); i++ { for i := 0; i < t.NumField(); i++ {
value := strings.ToUpper(splitCamelCase(t.Field(i).Name)) value := strings.ToUpper(splitCamelCase(t.Field(i).Name))
switch value { switch value {
case "CPU": case "CPU", "MEM":
value = value + " %" value += " %"
case "MEM":
value = value + " %"
case "MEM USAGE": case "MEM USAGE":
value = "MEM USAGE / LIMIT" value = "MEM USAGE / LIMIT"
} }
@ -167,10 +165,8 @@ func podStatsCmd(c *cliconfig.PodStatsValues) error {
results := podContainerStatsToPodStatOut(newStats) results := podContainerStatsToPodStatOut(newStats)
if len(format) == 0 { if len(format) == 0 {
outputToStdOut(results) outputToStdOut(results)
} else { } else if err := printPSFormat(c.Format, results, headerNames); err != nil {
if err := printPSFormat(c.Format, results, headerNames); err != nil { return err
return err
}
} }
} }
time.Sleep(time.Second) time.Sleep(time.Second)

View File

@ -65,7 +65,7 @@ func rmiCmd(c *cliconfig.RmiValues) error {
return errors.Errorf("when using the --all switch, you may not pass any images names or IDs") return errors.Errorf("when using the --all switch, you may not pass any images names or IDs")
} }
images := args[:] images := args
removeImage := func(img *adapter.ContainerImage) { removeImage := func(img *adapter.ContainerImage) {
response, err := runtime.RemoveImage(ctx, img, c.Force) response, err := runtime.RemoveImage(ctx, img, c.Force)

View File

@ -650,10 +650,7 @@ func getNamespaceInfo(path string) (string, error) {
// getStrFromSquareBrackets gets the string inside [] from a string. // getStrFromSquareBrackets gets the string inside [] from a string.
func getStrFromSquareBrackets(cmd string) string { func getStrFromSquareBrackets(cmd string) string {
reg, err := regexp.Compile(`.*\[|\].*`) reg := regexp.MustCompile(`.*\[|\].*`)
if err != nil {
return ""
}
arr := strings.Split(reg.ReplaceAllLiteralString(cmd, ""), ",") arr := strings.Split(reg.ReplaceAllLiteralString(cmd, ""), ",")
return strings.Join(arr, ",") return strings.Join(arr, ",")
} }

View File

@ -444,11 +444,12 @@ func ParseCreateOpts(ctx context.Context, c *GenericCLIResults, runtime *libpod.
// USER // USER
user := c.String("user") user := c.String("user")
if user == "" { if user == "" {
if usernsMode.IsKeepID() { switch {
case usernsMode.IsKeepID():
user = fmt.Sprintf("%d:%d", rootless.GetRootlessUID(), rootless.GetRootlessGID()) user = fmt.Sprintf("%d:%d", rootless.GetRootlessUID(), rootless.GetRootlessGID())
} else if data == nil { case data == nil:
user = "0" user = "0"
} else { default:
user = data.Config.User user = data.Config.User
} }
} }

View File

@ -59,18 +59,20 @@ func CreatePodStatusResults(ctrStatuses map[string]define.ContainerStatus) (stri
} }
} }
if statuses[PodStateRunning] > 0 { switch {
case statuses[PodStateRunning] > 0:
return PodStateRunning, nil return PodStateRunning, nil
} else if statuses[PodStatePaused] == ctrNum { case statuses[PodStatePaused] == ctrNum:
return PodStatePaused, nil return PodStatePaused, nil
} else if statuses[PodStateStopped] == ctrNum { case statuses[PodStateStopped] == ctrNum:
return PodStateExited, nil return PodStateExited, nil
} else if statuses[PodStateStopped] > 0 { case statuses[PodStateStopped] > 0:
return PodStateStopped, nil return PodStateStopped, nil
} else if statuses[PodStateErrored] > 0 { case statuses[PodStateErrored] > 0:
return PodStateErrored, nil return PodStateErrored, nil
default:
return PodStateCreated, nil
} }
return PodStateCreated, nil
} }
// GetNamespaceOptions transforms a slice of kernel namespaces // GetNamespaceOptions transforms a slice of kernel namespaces

View File

@ -105,9 +105,10 @@ func statsCmd(c *cliconfig.StatsValues) error {
var ctrs []*libpod.Container var ctrs []*libpod.Container
containerFunc := runtime.GetRunningContainers containerFunc := runtime.GetRunningContainers
if len(c.InputArgs) > 0 { switch {
case len(c.InputArgs) > 0:
containerFunc = func() ([]*libpod.Container, error) { return runtime.GetContainersByList(c.InputArgs) } containerFunc = func() ([]*libpod.Container, error) { return runtime.GetContainersByList(c.InputArgs) }
} else if latest { case latest:
containerFunc = func() ([]*libpod.Container, error) { containerFunc = func() ([]*libpod.Container, error) {
lastCtr, err := runtime.GetLatestContainer() lastCtr, err := runtime.GetLatestContainer()
if err != nil { if err != nil {
@ -115,7 +116,7 @@ func statsCmd(c *cliconfig.StatsValues) error {
} }
return []*libpod.Container{lastCtr}, nil return []*libpod.Container{lastCtr}, nil
} }
} else if all { case all:
containerFunc = runtime.GetAllContainers containerFunc = runtime.GetAllContainers
} }
@ -219,14 +220,14 @@ func genStatsFormat(format string) string {
} }
// imagesToGeneric creates an empty array of interfaces for output // imagesToGeneric creates an empty array of interfaces for output
func statsToGeneric(templParams []statsOutputParams, JSONParams []statsOutputParams) (genericParams []interface{}) { func statsToGeneric(templParams []statsOutputParams, jsonParams []statsOutputParams) (genericParams []interface{}) {
if len(templParams) > 0 { if len(templParams) > 0 {
for _, v := range templParams { for _, v := range templParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return
} }
for _, v := range JSONParams { for _, v := range jsonParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return

View File

@ -113,12 +113,12 @@ func printImageChildren(layerMap map[string]*image.LayerInfo, layerID string, pr
intend := middleItem intend := middleItem
if !last { if !last {
// add continueItem i.e. '|' for next iteration prefix // add continueItem i.e. '|' for next iteration prefix
prefix = prefix + continueItem prefix += continueItem
} else if len(ll.ChildID) > 1 || len(ll.ChildID) == 0 { } else if len(ll.ChildID) > 1 || len(ll.ChildID) == 0 {
// The above condition ensure, alignment happens for node, which has more then 1 children. // The above condition ensure, alignment happens for node, which has more then 1 children.
// If node is last in printing hierarchy, it should not be printed as middleItem i.e. ├── // If node is last in printing hierarchy, it should not be printed as middleItem i.e. ├──
intend = lastItem intend = lastItem
prefix = prefix + " " prefix += " "
} }
var tags string var tags string

View File

@ -134,14 +134,14 @@ func genVolLsFormat(c *cliconfig.VolumeLsValues) string {
} }
// Convert output to genericParams for printing // Convert output to genericParams for printing
func volLsToGeneric(templParams []volumeLsTemplateParams, JSONParams []volumeLsJSONParams) (genericParams []interface{}) { func volLsToGeneric(templParams []volumeLsTemplateParams, jsonParams []volumeLsJSONParams) (genericParams []interface{}) {
if len(templParams) > 0 { if len(templParams) > 0 {
for _, v := range templParams { for _, v := range templParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return
} }
for _, v := range JSONParams { for _, v := range jsonParams {
genericParams = append(genericParams, interface{}(v)) genericParams = append(genericParams, interface{}(v))
} }
return return

View File

@ -652,11 +652,9 @@ func (s *BoltState) addContainer(ctr *Container, pod *Pod) error {
if string(depCtrPod) != pod.ID() { if string(depCtrPod) != pod.ID() {
return errors.Wrapf(define.ErrInvalidArg, "container %s depends on container %s which is in a different pod (%s)", ctr.ID(), dependsCtr, string(depCtrPod)) return errors.Wrapf(define.ErrInvalidArg, "container %s depends on container %s which is in a different pod (%s)", ctr.ID(), dependsCtr, string(depCtrPod))
} }
} else { } else if depCtrPod != nil {
// If we're not part of a pod, we cannot depend on containers in a pod // If we're not part of a pod, we cannot depend on containers in a pod
if depCtrPod != nil { return errors.Wrapf(define.ErrInvalidArg, "container %s depends on container %s which is in a pod - containers not in pods cannot depend on containers in pods", ctr.ID(), dependsCtr)
return errors.Wrapf(define.ErrInvalidArg, "container %s depends on container %s which is in a pod - containers not in pods cannot depend on containers in pods", ctr.ID(), dependsCtr)
}
} }
depNamespace := depCtrBkt.Get(namespaceKey) depNamespace := depCtrBkt.Get(namespaceKey)

View File

@ -472,11 +472,9 @@ func (c *Container) specFromState() (*spec.Spec, error) {
if err := json.Unmarshal(content, &returnSpec); err != nil { if err := json.Unmarshal(content, &returnSpec); err != nil {
return nil, errors.Wrapf(err, "error unmarshalling container config") return nil, errors.Wrapf(err, "error unmarshalling container config")
} }
} else { } else if !os.IsNotExist(err) {
// ignore when the file does not exist // ignore when the file does not exist
if !os.IsNotExist(err) { return nil, errors.Wrapf(err, "error opening container config")
return nil, errors.Wrapf(err, "error opening container config")
}
} }
return returnSpec, nil return returnSpec, nil

View File

@ -56,7 +56,7 @@ func (c *Container) readFromLogFile(options *logs.LogOptions, logChannel chan *l
continue continue
} }
if nll.Partial() { if nll.Partial() {
partial = partial + nll.Msg partial += nll.Msg
continue continue
} else if !nll.Partial() && len(partial) > 1 { } else if !nll.Partial() && len(partial) > 1 {
nll.Msg = partial nll.Msg = partial

View File

@ -113,7 +113,7 @@ func detectCycles(graph *ContainerGraph) (bool, error) {
info := new(nodeInfo) info := new(nodeInfo)
info.index = index info.index = index
info.lowLink = index info.lowLink = index
index = index + 1 index++
nodes[node.id] = info nodes[node.id] = info

View File

@ -1214,11 +1214,12 @@ func (c *Container) generateInspectContainerHostConfig(ctrSpec *spec.Spec, named
// Network mode parsing. // Network mode parsing.
networkMode := "" networkMode := ""
if c.config.CreateNetNS { switch {
case c.config.CreateNetNS:
networkMode = "default" networkMode = "default"
} else if c.config.NetNsCtr != "" { case c.config.NetNsCtr != "":
networkMode = fmt.Sprintf("container:%s", c.config.NetNsCtr) networkMode = fmt.Sprintf("container:%s", c.config.NetNsCtr)
} else { default:
// Find the spec's network namespace. // Find the spec's network namespace.
// If there is none, it's host networking. // If there is none, it's host networking.
// If there is one and it has a path, it's "ns:". // If there is one and it has a path, it's "ns:".

View File

@ -22,7 +22,7 @@ import (
"github.com/containers/storage" "github.com/containers/storage"
"github.com/containers/storage/pkg/archive" "github.com/containers/storage/pkg/archive"
"github.com/containers/storage/pkg/mount" "github.com/containers/storage/pkg/mount"
"github.com/cyphar/filepath-securejoin" securejoin "github.com/cyphar/filepath-securejoin"
spec "github.com/opencontainers/runtime-spec/specs-go" spec "github.com/opencontainers/runtime-spec/specs-go"
"github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/runtime-tools/generate"
"github.com/opencontainers/selinux/go-selinux/label" "github.com/opencontainers/selinux/go-selinux/label"
@ -339,7 +339,7 @@ func (c *Container) handleRestartPolicy(ctx context.Context) (restarted bool, er
c.newContainerEvent(events.Restart) c.newContainerEvent(events.Restart)
// Increment restart count // Increment restart count
c.state.RestartCount = c.state.RestartCount + 1 c.state.RestartCount += 1
logrus.Debugf("Container %s now on retry %d", c.ID(), c.state.RestartCount) logrus.Debugf("Container %s now on retry %d", c.ID(), c.state.RestartCount)
if err := c.save(); err != nil { if err := c.save(); err != nil {
return false, err return false, err
@ -1286,7 +1286,7 @@ func (c *Container) restartWithTimeout(ctx context.Context, timeout uint) (err e
// TODO: Add ability to override mount label so we can use this for Mount() too // TODO: Add ability to override mount label so we can use this for Mount() too
// TODO: Can we use this for export? Copying SHM into the export might not be // TODO: Can we use this for export? Copying SHM into the export might not be
// good // good
func (c *Container) mountStorage() (_ string, Err error) { func (c *Container) mountStorage() (_ string, deferredErr error) {
var err error var err error
// Container already mounted, nothing to do // Container already mounted, nothing to do
if c.state.Mounted { if c.state.Mounted {
@ -1307,7 +1307,7 @@ func (c *Container) mountStorage() (_ string, Err error) {
return "", errors.Wrapf(err, "failed to chown %s", c.config.ShmDir) return "", errors.Wrapf(err, "failed to chown %s", c.config.ShmDir)
} }
defer func() { defer func() {
if Err != nil { if deferredErr != nil {
if err := c.unmountSHM(c.config.ShmDir); err != nil { if err := c.unmountSHM(c.config.ShmDir); err != nil {
logrus.Errorf("Error unmounting SHM for container %s after mount error: %v", c.ID(), err) logrus.Errorf("Error unmounting SHM for container %s after mount error: %v", c.ID(), err)
} }
@ -1324,7 +1324,7 @@ func (c *Container) mountStorage() (_ string, Err error) {
return "", err return "", err
} }
defer func() { defer func() {
if Err != nil { if deferredErr != nil {
if err := c.unmount(false); err != nil { if err := c.unmount(false); err != nil {
logrus.Errorf("Error unmounting container %s after mount error: %v", c.ID(), err) logrus.Errorf("Error unmounting container %s after mount error: %v", c.ID(), err)
} }
@ -1339,7 +1339,7 @@ func (c *Container) mountStorage() (_ string, Err error) {
return "", err return "", err
} }
defer func() { defer func() {
if Err == nil { if deferredErr == nil {
return return
} }
vol.lock.Lock() vol.lock.Lock()

View File

@ -62,7 +62,7 @@ func (c *Container) unmountSHM(mount string) error {
// prepare mounts the container and sets up other required resources like net // prepare mounts the container and sets up other required resources like net
// namespaces // namespaces
func (c *Container) prepare() (Err error) { func (c *Container) prepare() error {
var ( var (
wg sync.WaitGroup wg sync.WaitGroup
netNS ns.NetNS netNS ns.NetNS
@ -1277,21 +1277,21 @@ func (c *Container) generateResolvConf() (string, error) {
} }
// If the user provided dns, it trumps all; then dns masq; then resolv.conf // If the user provided dns, it trumps all; then dns masq; then resolv.conf
if len(c.config.DNSServer) > 0 { switch {
case len(c.config.DNSServer) > 0:
// We store DNS servers as net.IP, so need to convert to string // We store DNS servers as net.IP, so need to convert to string
for _, server := range c.config.DNSServer { for _, server := range c.config.DNSServer {
nameservers = append(nameservers, server.String()) nameservers = append(nameservers, server.String())
} }
} else if len(cniNameServers) > 0 { case len(cniNameServers) > 0:
nameservers = append(nameservers, cniNameServers...) nameservers = append(nameservers, cniNameServers...)
} else { default:
// Make a new resolv.conf // Make a new resolv.conf
nameservers = resolvconf.GetNameservers(resolv.Content) nameservers = resolvconf.GetNameservers(resolv.Content)
// slirp4netns has a built in DNS server. // slirp4netns has a built in DNS server.
if c.config.NetMode.IsSlirp4netns() { if c.config.NetMode.IsSlirp4netns() {
nameservers = append([]string{"10.0.2.3"}, nameservers...) nameservers = append([]string{"10.0.2.3"}, nameservers...)
} }
} }
search := resolvconf.GetSearchDomains(resolv.Content) search := resolvconf.GetSearchDomains(resolv.Content)
@ -1451,23 +1451,24 @@ func (c *Container) getOCICgroupPath() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
if (rootless.IsRootless() && !unified) || c.config.NoCgroups { switch {
case (rootless.IsRootless() && !unified) || c.config.NoCgroups:
return "", nil return "", nil
} else if c.runtime.config.CgroupManager == define.SystemdCgroupsManager { case c.runtime.config.CgroupManager == define.SystemdCgroupsManager:
// When runc is set to use Systemd as a cgroup manager, it // When runc is set to use Systemd as a cgroup manager, it
// expects cgroups to be passed as follows: // expects cgroups to be passed as follows:
// slice:prefix:name // slice:prefix:name
systemdCgroups := fmt.Sprintf("%s:libpod:%s", path.Base(c.config.CgroupParent), c.ID()) systemdCgroups := fmt.Sprintf("%s:libpod:%s", path.Base(c.config.CgroupParent), c.ID())
logrus.Debugf("Setting CGroups for container %s to %s", c.ID(), systemdCgroups) logrus.Debugf("Setting CGroups for container %s to %s", c.ID(), systemdCgroups)
return systemdCgroups, nil return systemdCgroups, nil
} else if c.runtime.config.CgroupManager == define.CgroupfsCgroupsManager { case c.runtime.config.CgroupManager == define.CgroupfsCgroupsManager:
cgroupPath, err := c.CGroupPath() cgroupPath, err := c.CGroupPath()
if err != nil { if err != nil {
return "", err return "", err
} }
logrus.Debugf("Setting CGroup path for container %s to %s", c.ID(), cgroupPath) logrus.Debugf("Setting CGroup path for container %s to %s", c.ID(), cgroupPath)
return cgroupPath, nil return cgroupPath, nil
} else { default:
return "", errors.Wrapf(define.ErrInvalidArg, "invalid cgroup manager %s requested", c.runtime.config.CgroupManager) return "", errors.Wrapf(define.ErrInvalidArg, "invalid cgroup manager %s requested", c.runtime.config.CgroupManager)
} }
} }

View File

@ -129,8 +129,6 @@ func StringToStatus(name string) (Status, error) {
return Attach, nil return Attach, nil
case Checkpoint.String(): case Checkpoint.String():
return Checkpoint, nil return Checkpoint, nil
case Restore.String():
return Restore, nil
case Cleanup.String(): case Cleanup.String():
return Cleanup, nil return Cleanup, nil
case Commit.String(): case Commit.String():

View File

@ -238,7 +238,7 @@ func (c *Container) updateHealthCheckLog(hcl HealthCheckLog, inStartPeriod bool)
} }
if !inStartPeriod { if !inStartPeriod {
// increment failing streak // increment failing streak
healthCheck.FailingStreak = healthCheck.FailingStreak + 1 healthCheck.FailingStreak += 1
// if failing streak > retries, then status to unhealthy // if failing streak > retries, then status to unhealthy
if healthCheck.FailingStreak >= c.HealthCheckConfig().Retries { if healthCheck.FailingStreak >= c.HealthCheckConfig().Retries {
healthCheck.Status = HealthCheckUnhealthy healthCheck.Status = HealthCheckUnhealthy

View File

@ -902,8 +902,7 @@ func (i *Image) Annotations(ctx context.Context) (map[string]string, error) {
} }
} }
annotations := make(map[string]string) annotations := make(map[string]string)
switch manifestType { if manifestType == ociv1.MediaTypeImageManifest {
case ociv1.MediaTypeImageManifest:
var m ociv1.Manifest var m ociv1.Manifest
if err := json.Unmarshal(imageManifest, &m); err == nil { if err := json.Unmarshal(imageManifest, &m); err == nil {
for k, v := range m.Annotations { for k, v := range m.Annotations {

View File

@ -15,7 +15,7 @@ import (
"github.com/opencontainers/runtime-tools/generate" "github.com/opencontainers/runtime-tools/generate"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"k8s.io/api/core/v1" v1 "k8s.io/api/core/v1"
v12 "k8s.io/apimachinery/pkg/apis/meta/v1" v12 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
@ -365,11 +365,12 @@ func generateKubeVolumeMount(m specs.Mount) (v1.VolumeMount, v1.Volume, error) {
// neither a directory or a file lives here, default to creating a directory // neither a directory or a file lives here, default to creating a directory
// TODO should this be an error instead? // TODO should this be an error instead?
var hostPathType v1.HostPathType var hostPathType v1.HostPathType
if err != nil { switch {
case err != nil:
hostPathType = v1.HostPathDirectoryOrCreate hostPathType = v1.HostPathDirectoryOrCreate
} else if isDir { case isDir:
hostPathType = v1.HostPathDirectory hostPathType = v1.HostPathDirectory
} else { default:
hostPathType = v1.HostPathFile hostPathType = v1.HostPathFile
} }
vo.HostPath.Type = &hostPathType vo.HostPath.Type = &hostPathType

View File

@ -96,7 +96,7 @@ func getTailLog(path string, tail int) ([]*LogLine, error) {
} }
nlls = append(nlls, nll) nlls = append(nlls, nll)
if !nll.Partial() { if !nll.Partial() {
tailCounter = tailCounter + 1 tailCounter++
} }
if tailCounter == tail { if tailCounter == tail {
break break
@ -105,9 +105,9 @@ func getTailLog(path string, tail int) ([]*LogLine, error) {
// Now we iterate the results and assemble partial messages to become full messages // Now we iterate the results and assemble partial messages to become full messages
for _, nll := range nlls { for _, nll := range nlls {
if nll.Partial() { if nll.Partial() {
partial = partial + nll.Msg partial += nll.Msg
} else { } else {
nll.Msg = nll.Msg + partial nll.Msg += partial
tailLog = append(tailLog, nll) tailLog = append(tailLog, nll)
partial = "" partial = ""
} }
@ -127,7 +127,7 @@ func (l *LogLine) String(options *LogOptions) string {
out = fmt.Sprintf("%s ", cid) out = fmt.Sprintf("%s ", cid)
} }
if options.Timestamps { if options.Timestamps {
out = out + fmt.Sprintf("%s ", l.Time.Format(LogTimeFormat)) out += fmt.Sprintf("%s ", l.Time.Format(LogTimeFormat))
} }
return out + l.Msg return out + l.Msg
} }

View File

@ -586,7 +586,8 @@ func (r *ConmonOCIRuntime) ExecContainer(c *Container, sessionID string, options
// we don't want to step on users fds they asked to preserve // we don't want to step on users fds they asked to preserve
// Since 0-2 are used for stdio, start the fds we pass in at preserveFDs+3 // Since 0-2 are used for stdio, start the fds we pass in at preserveFDs+3
execCmd.Env = append(r.conmonEnv, fmt.Sprintf("_OCI_SYNCPIPE=%d", options.PreserveFDs+3), fmt.Sprintf("_OCI_STARTPIPE=%d", options.PreserveFDs+4), fmt.Sprintf("_OCI_ATTACHPIPE=%d", options.PreserveFDs+5)) execCmd.Env = r.conmonEnv
execCmd.Env = append(execCmd.Env, fmt.Sprintf("_OCI_SYNCPIPE=%d", options.PreserveFDs+3), fmt.Sprintf("_OCI_STARTPIPE=%d", options.PreserveFDs+4), fmt.Sprintf("_OCI_ATTACHPIPE=%d", options.PreserveFDs+5))
execCmd.Env = append(execCmd.Env, conmonEnv...) execCmd.Env = append(execCmd.Env, conmonEnv...)
execCmd.ExtraFiles = append(execCmd.ExtraFiles, childSyncPipe, childStartPipe, childAttachPipe) execCmd.ExtraFiles = append(execCmd.ExtraFiles, childSyncPipe, childStartPipe, childAttachPipe)
@ -998,7 +999,8 @@ func (r *ConmonOCIRuntime) createOCIContainer(ctr *Container, restoreOptions *Co
return err return err
} }
cmd.Env = append(r.conmonEnv, fmt.Sprintf("_OCI_SYNCPIPE=%d", 3), fmt.Sprintf("_OCI_STARTPIPE=%d", 4)) cmd.Env = r.conmonEnv
cmd.Env = append(cmd.Env, fmt.Sprintf("_OCI_SYNCPIPE=%d", 3), fmt.Sprintf("_OCI_STARTPIPE=%d", 4))
cmd.Env = append(cmd.Env, conmonEnv...) cmd.Env = append(cmd.Env, conmonEnv...)
cmd.ExtraFiles = append(cmd.ExtraFiles, childSyncPipe, childStartPipe) cmd.ExtraFiles = append(cmd.ExtraFiles, childSyncPipe, childStartPipe)
cmd.ExtraFiles = append(cmd.ExtraFiles, envFiles...) cmd.ExtraFiles = append(cmd.ExtraFiles, envFiles...)
@ -1306,12 +1308,10 @@ func (r *ConmonOCIRuntime) moveConmonToCgroupAndSignal(ctr *Container, cmd *exec
control, err := cgroups.New(cgroupPath, &spec.LinuxResources{}) control, err := cgroups.New(cgroupPath, &spec.LinuxResources{})
if err != nil { if err != nil {
logrus.Warnf("Failed to add conmon to cgroupfs sandbox cgroup: %v", err) logrus.Warnf("Failed to add conmon to cgroupfs sandbox cgroup: %v", err)
} else { } else if err := control.AddPid(cmd.Process.Pid); err != nil {
// we need to remove this defer and delete the cgroup once conmon exits // we need to remove this defer and delete the cgroup once conmon exits
// maybe need a conmon monitor? // maybe need a conmon monitor?
if err := control.AddPid(cmd.Process.Pid); err != nil { logrus.Warnf("Failed to add conmon to cgroupfs sandbox cgroup: %v", err)
logrus.Warnf("Failed to add conmon to cgroupfs sandbox cgroup: %v", err)
}
} }
} }
} }

View File

@ -733,7 +733,9 @@ func WithExitCommand(exitCommand []string) CtrCreateOption {
return define.ErrCtrFinalized return define.ErrCtrFinalized
} }
ctr.config.ExitCommand = append(exitCommand, ctr.ID()) ctr.config.ExitCommand = exitCommand
ctr.config.ExitCommand = append(ctr.config.ExitCommand, ctr.ID())
return nil return nil
} }
} }

View File

@ -180,12 +180,13 @@ func getLockManager(runtime *Runtime) (lock.Manager, error) {
// Set up the lock manager // Set up the lock manager
manager, err = lock.OpenSHMLockManager(lockPath, runtime.config.NumLocks) manager, err = lock.OpenSHMLockManager(lockPath, runtime.config.NumLocks)
if err != nil { if err != nil {
if os.IsNotExist(errors.Cause(err)) { switch {
case os.IsNotExist(errors.Cause(err)):
manager, err = lock.NewSHMLockManager(lockPath, runtime.config.NumLocks) manager, err = lock.NewSHMLockManager(lockPath, runtime.config.NumLocks)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "failed to get new shm lock manager") return nil, errors.Wrapf(err, "failed to get new shm lock manager")
} }
} else if errors.Cause(err) == syscall.ERANGE && runtime.doRenumber { case errors.Cause(err) == syscall.ERANGE && runtime.doRenumber:
logrus.Debugf("Number of locks does not match - removing old locks") logrus.Debugf("Number of locks does not match - removing old locks")
// ERANGE indicates a lock numbering mismatch. // ERANGE indicates a lock numbering mismatch.
@ -199,7 +200,7 @@ func getLockManager(runtime *Runtime) (lock.Manager, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
} else { default:
return nil, err return nil, err
} }
} }
@ -289,10 +290,8 @@ func makeRuntime(ctx context.Context, runtime *Runtime) (err error) {
logrus.Debug("Not configuring container store") logrus.Debug("Not configuring container store")
} else if runtime.noStore { } else if runtime.noStore {
logrus.Debug("No store required. Not opening container store.") logrus.Debug("No store required. Not opening container store.")
} else { } else if err := runtime.configureStore(); err != nil {
if err := runtime.configureStore(); err != nil { return err
return err
}
} }
defer func() { defer func() {
if err != nil && store != nil { if err != nil && store != nil {
@ -718,18 +717,14 @@ func (r *Runtime) generateName() (string, error) {
// Make sure container with this name does not exist // Make sure container with this name does not exist
if _, err := r.state.LookupContainer(name); err == nil { if _, err := r.state.LookupContainer(name); err == nil {
continue continue
} else { } else if errors.Cause(err) != define.ErrNoSuchCtr {
if errors.Cause(err) != define.ErrNoSuchCtr { return "", err
return "", err
}
} }
// Make sure pod with this name does not exist // Make sure pod with this name does not exist
if _, err := r.state.LookupPod(name); err == nil { if _, err := r.state.LookupPod(name); err == nil {
continue continue
} else { } else if errors.Cause(err) != define.ErrNoSuchPod {
if errors.Cause(err) != define.ErrNoSuchPod { return "", err
return "", err
}
} }
return name, nil return name, nil
} }

View File

@ -107,15 +107,13 @@ func (r *Runtime) removeStorageContainer(idOrName string, force bool) error {
if timesMounted > 0 { if timesMounted > 0 {
return errors.Wrapf(define.ErrCtrStateInvalid, "container %q is mounted and cannot be removed without using force", idOrName) return errors.Wrapf(define.ErrCtrStateInvalid, "container %q is mounted and cannot be removed without using force", idOrName)
} }
} else { } else if _, err := r.store.Unmount(ctr.ID, true); err != nil {
if _, err := r.store.Unmount(ctr.ID, true); err != nil { if errors.Cause(err) == storage.ErrContainerUnknown {
if errors.Cause(err) == storage.ErrContainerUnknown { // Container again gone, no error
// Container again gone, no error logrus.Warnf("Storage for container %s already removed", ctr.ID)
logrus.Warnf("Storage for container %s already removed", ctr.ID) return nil
return nil
}
return errors.Wrapf(err, "error unmounting container %q", idOrName)
} }
return errors.Wrapf(err, "error unmounting container %q", idOrName)
} }
if err := r.store.DeleteContainer(ctr.ID); err != nil { if err := r.store.DeleteContainer(ctr.ID); err != nil {

View File

@ -234,15 +234,16 @@ func (r *Runtime) setupContainer(ctx context.Context, ctr *Container) (c *Contai
} }
case define.SystemdCgroupsManager: case define.SystemdCgroupsManager:
if ctr.config.CgroupParent == "" { if ctr.config.CgroupParent == "" {
if pod != nil && pod.config.UsePodCgroup { switch {
case pod != nil && pod.config.UsePodCgroup:
podCgroup, err := pod.CgroupPath() podCgroup, err := pod.CgroupPath()
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "error retrieving pod %s cgroup", pod.ID()) return nil, errors.Wrapf(err, "error retrieving pod %s cgroup", pod.ID())
} }
ctr.config.CgroupParent = podCgroup ctr.config.CgroupParent = podCgroup
} else if rootless.IsRootless() { case rootless.IsRootless():
ctr.config.CgroupParent = SystemdDefaultRootlessCgroupParent ctr.config.CgroupParent = SystemdDefaultRootlessCgroupParent
} else { default:
ctr.config.CgroupParent = SystemdDefaultCgroupParent ctr.config.CgroupParent = SystemdDefaultCgroupParent
} }
} else if len(ctr.config.CgroupParent) < 6 || !strings.HasSuffix(path.Base(ctr.config.CgroupParent), ".slice") { } else if len(ctr.config.CgroupParent) < 6 || !strings.HasSuffix(path.Base(ctr.config.CgroupParent), ".slice") {
@ -361,10 +362,8 @@ func (r *Runtime) setupContainer(ctx context.Context, ctr *Container) (c *Contai
if err := r.state.AddContainerToPod(pod, ctr); err != nil { if err := r.state.AddContainerToPod(pod, ctr); err != nil {
return nil, err return nil, err
} }
} else { } else if err := r.state.AddContainer(ctr); err != nil {
if err := r.state.AddContainer(ctr); err != nil { return nil, err
return nil, err
}
} }
ctr.newContainerEvent(events.Create) ctr.newContainerEvent(events.Create)
return ctr, nil return ctr, nil

View File

@ -19,7 +19,7 @@ import (
) )
// NewPod makes a new, empty pod // NewPod makes a new, empty pod
func (r *Runtime) NewPod(ctx context.Context, options ...PodCreateOption) (_ *Pod, Err error) { func (r *Runtime) NewPod(ctx context.Context, options ...PodCreateOption) (_ *Pod, deferredErr error) {
r.lock.Lock() r.lock.Lock()
defer r.lock.Unlock() defer r.lock.Unlock()
@ -65,7 +65,7 @@ func (r *Runtime) NewPod(ctx context.Context, options ...PodCreateOption) (_ *Po
pod.config.LockID = pod.lock.ID() pod.config.LockID = pod.lock.ID()
defer func() { defer func() {
if Err != nil { if deferredErr != nil {
if err := pod.lock.Free(); err != nil { if err := pod.lock.Free(); err != nil {
logrus.Errorf("Error freeing pod lock after failed creation: %v", err) logrus.Errorf("Error freeing pod lock after failed creation: %v", err)
} }
@ -126,7 +126,7 @@ func (r *Runtime) NewPod(ctx context.Context, options ...PodCreateOption) (_ *Po
return nil, errors.Wrapf(err, "error adding pod to state") return nil, errors.Wrapf(err, "error adding pod to state")
} }
defer func() { defer func() {
if Err != nil { if deferredErr != nil {
if err := r.removePod(ctx, pod, true, true); err != nil { if err := r.removePod(ctx, pod, true, true); err != nil {
logrus.Errorf("Error removing pod after pause container creation failure: %v", err) logrus.Errorf("Error removing pod after pause container creation failure: %v", err)
} }

View File

@ -28,7 +28,7 @@ func (r *Runtime) NewVolume(ctx context.Context, options ...VolumeCreateOption)
} }
// newVolume creates a new empty volume // newVolume creates a new empty volume
func (r *Runtime) newVolume(ctx context.Context, options ...VolumeCreateOption) (_ *Volume, Err error) { func (r *Runtime) newVolume(ctx context.Context, options ...VolumeCreateOption) (_ *Volume, deferredErr error) {
volume, err := newVolume(r) volume, err := newVolume(r)
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "error creating volume") return nil, errors.Wrapf(err, "error creating volume")
@ -98,7 +98,7 @@ func (r *Runtime) newVolume(ctx context.Context, options ...VolumeCreateOption)
volume.config.LockID = volume.lock.ID() volume.config.LockID = volume.lock.ID()
defer func() { defer func() {
if Err != nil { if deferredErr != nil {
if err := volume.lock.Free(); err != nil { if err := volume.lock.Free(); err != nil {
logrus.Errorf("Error freeing volume lock after failed creation: %v", err) logrus.Errorf("Error freeing volume lock after failed creation: %v", err)
} }

View File

@ -39,7 +39,7 @@ func (v *Volume) mount() error {
// If the count is non-zero, the volume is already mounted. // If the count is non-zero, the volume is already mounted.
// Nothing to do. // Nothing to do.
if v.state.MountCount > 0 { if v.state.MountCount > 0 {
v.state.MountCount = v.state.MountCount + 1 v.state.MountCount += 1
logrus.Debugf("Volume %s mount count now at %d", v.Name(), v.state.MountCount) logrus.Debugf("Volume %s mount count now at %d", v.Name(), v.state.MountCount)
return v.save() return v.save()
} }
@ -81,7 +81,7 @@ func (v *Volume) mount() error {
logrus.Debugf("Mounted volume %s", v.Name()) logrus.Debugf("Mounted volume %s", v.Name())
// Increment the mount counter // Increment the mount counter
v.state.MountCount = v.state.MountCount + 1 v.state.MountCount += 1
logrus.Debugf("Volume %s mount count now at %d", v.Name(), v.state.MountCount) logrus.Debugf("Volume %s mount count now at %d", v.Name(), v.state.MountCount)
return v.save() return v.save()
} }
@ -124,7 +124,7 @@ func (v *Volume) unmount(force bool) error {
} }
if !force { if !force {
v.state.MountCount = v.state.MountCount - 1 v.state.MountCount -= 1
} else { } else {
v.state.MountCount = 0 v.state.MountCount = 0
} }

View File

@ -609,11 +609,12 @@ func (r *LocalRuntime) Restore(ctx context.Context, c *cliconfig.RestoreValues)
return state == define.ContainerStateExited return state == define.ContainerStateExited
}) })
if c.Import != "" { switch {
case c.Import != "":
containers, err = crImportCheckpoint(ctx, r.Runtime, c.Import, c.Name) containers, err = crImportCheckpoint(ctx, r.Runtime, c.Import, c.Name)
} else if c.All { case c.All:
containers, err = r.GetContainers(filterFuncs...) containers, err = r.GetContainers(filterFuncs...)
} else { default:
containers, err = shortcuts.GetContainersByContext(false, c.Latest, c.InputArgs, r.Runtime) containers, err = shortcuts.GetContainersByContext(false, c.Latest, c.InputArgs, r.Runtime)
} }
if err != nil { if err != nil {
@ -835,25 +836,26 @@ func (r *LocalRuntime) Restart(ctx context.Context, c *cliconfig.RestartValues)
inputTimeout := c.Timeout inputTimeout := c.Timeout
// Handle --latest // Handle --latest
if c.Latest { switch {
case c.Latest:
lastCtr, err := r.Runtime.GetLatestContainer() lastCtr, err := r.Runtime.GetLatestContainer()
if err != nil { if err != nil {
return nil, nil, errors.Wrapf(err, "unable to get latest container") return nil, nil, errors.Wrapf(err, "unable to get latest container")
} }
restartContainers = append(restartContainers, lastCtr) restartContainers = append(restartContainers, lastCtr)
} else if c.Running { case c.Running:
containers, err = r.GetRunningContainers() containers, err = r.GetRunningContainers()
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
restartContainers = append(restartContainers, containers...) restartContainers = append(restartContainers, containers...)
} else if c.All { case c.All:
containers, err = r.Runtime.GetAllContainers() containers, err = r.Runtime.GetAllContainers()
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
} }
restartContainers = append(restartContainers, containers...) restartContainers = append(restartContainers, containers...)
} else { default:
for _, id := range c.InputArgs { for _, id := range c.InputArgs {
ctr, err := r.Runtime.LookupContainer(id) ctr, err := r.Runtime.LookupContainer(id)
if err != nil { if err != nil {

View File

@ -407,7 +407,8 @@ func (r *LocalRuntime) Events(c *cliconfig.EventValues) error {
} }
w := bufio.NewWriter(os.Stdout) w := bufio.NewWriter(os.Stdout)
for event := range eventChannel { for event := range eventChannel {
if c.Format == formats.JSONString { switch {
case c.Format == formats.JSONString:
jsonStr, err := event.ToJSONString() jsonStr, err := event.ToJSONString()
if err != nil { if err != nil {
return errors.Wrapf(err, "unable to format json") return errors.Wrapf(err, "unable to format json")
@ -415,11 +416,11 @@ func (r *LocalRuntime) Events(c *cliconfig.EventValues) error {
if _, err := w.Write([]byte(jsonStr)); err != nil { if _, err := w.Write([]byte(jsonStr)); err != nil {
return err return err
} }
} else if len(c.Format) > 0 { case len(c.Format) > 0:
if err := tmpl.Execute(w, event); err != nil { if err := tmpl.Execute(w, event); err != nil {
return err return err
} }
} else { default:
if _, err := w.Write([]byte(event.ToHumanReadable())); err != nil { if _, err := w.Write([]byte(event.ToHumanReadable())); err != nil {
return err return err
} }

View File

@ -42,12 +42,13 @@ func GetContainersByContext(all, latest bool, names []string, runtime *libpod.Ru
var ctr *libpod.Container var ctr *libpod.Container
ctrs = []*libpod.Container{} ctrs = []*libpod.Container{}
if all { switch {
case all:
ctrs, err = runtime.GetAllContainers() ctrs, err = runtime.GetAllContainers()
} else if latest { case latest:
ctr, err = runtime.GetLatestContainer() ctr, err = runtime.GetLatestContainer()
ctrs = append(ctrs, ctr) ctrs = append(ctrs, ctr)
} else { default:
for _, n := range names { for _, n := range names {
ctr, e := runtime.LookupContainer(n) ctr, e := runtime.LookupContainer(n)
if e != nil { if e != nil {

View File

@ -12,19 +12,19 @@ import (
// WriteResponse encodes the given value as JSON or string and renders it for http client // WriteResponse encodes the given value as JSON or string and renders it for http client
func WriteResponse(w http.ResponseWriter, code int, value interface{}) { func WriteResponse(w http.ResponseWriter, code int, value interface{}) {
switch value.(type) { switch v := value.(type) {
case string: case string:
w.Header().Set("Content-Type", "text/plain; charset=us-ascii") w.Header().Set("Content-Type", "text/plain; charset=us-ascii")
w.WriteHeader(code) w.WriteHeader(code)
if _, err := fmt.Fprintln(w, value); err != nil { if _, err := fmt.Fprintln(w, v); err != nil {
log.Errorf("unable to send string response: %q", err) log.Errorf("unable to send string response: %q", err)
} }
case *os.File: case *os.File:
w.Header().Set("Content-Type", "application/octet; charset=us-ascii") w.Header().Set("Content-Type", "application/octet; charset=us-ascii")
w.WriteHeader(code) w.WriteHeader(code)
if _, err := io.Copy(w, value.(*os.File)); err != nil { if _, err := io.Copy(w, v); err != nil {
log.Errorf("unable to copy to response: %q", err) log.Errorf("unable to copy to response: %q", err)
} }
default: default:

View File

@ -155,7 +155,7 @@ func (c *CgroupControl) getCgroupv1Path(name string) string {
} }
// createCgroupv2Path creates the cgroupv2 path and enables all the available controllers // createCgroupv2Path creates the cgroupv2 path and enables all the available controllers
func createCgroupv2Path(path string) (Err error) { func createCgroupv2Path(path string) (deferredError error) {
content, err := ioutil.ReadFile("/sys/fs/cgroup/cgroup.controllers") content, err := ioutil.ReadFile("/sys/fs/cgroup/cgroup.controllers")
if err != nil { if err != nil {
return errors.Wrapf(err, "read /sys/fs/cgroup/cgroup.controllers") return errors.Wrapf(err, "read /sys/fs/cgroup/cgroup.controllers")
@ -169,7 +169,7 @@ func createCgroupv2Path(path string) (Err error) {
if i == 0 { if i == 0 {
res = fmt.Sprintf("+%s", c) res = fmt.Sprintf("+%s", c)
} else { } else {
res = res + fmt.Sprintf(" +%s", c) res += fmt.Sprintf(" +%s", c)
} }
} }
resByte := []byte(res) resByte := []byte(res)
@ -186,7 +186,7 @@ func createCgroupv2Path(path string) (Err error) {
} else { } else {
// If the directory was created, be sure it is not left around on errors. // If the directory was created, be sure it is not left around on errors.
defer func() { defer func() {
if Err != nil { if deferredError != nil {
os.Remove(current) os.Remove(current)
} }
}() }()

View File

@ -44,7 +44,8 @@ func (c *NetworkConfig) ToCreateOptions(runtime *libpod.Runtime, userns *UserCon
} }
} }
if c.NetMode.IsNS() { switch {
case c.NetMode.IsNS():
ns := c.NetMode.NS() ns := c.NetMode.NS()
if ns == "" { if ns == "" {
return nil, errors.Errorf("invalid empty user-defined network namespace") return nil, errors.Errorf("invalid empty user-defined network namespace")
@ -53,13 +54,13 @@ func (c *NetworkConfig) ToCreateOptions(runtime *libpod.Runtime, userns *UserCon
if err != nil { if err != nil {
return nil, err return nil, err
} }
} else if c.NetMode.IsContainer() { case c.NetMode.IsContainer():
connectedCtr, err := runtime.LookupContainer(c.NetMode.Container()) connectedCtr, err := runtime.LookupContainer(c.NetMode.Container())
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "container %q not found", c.NetMode.Container()) return nil, errors.Wrapf(err, "container %q not found", c.NetMode.Container())
} }
options = append(options, libpod.WithNetNSFrom(connectedCtr)) options = append(options, libpod.WithNetNSFrom(connectedCtr))
} else if !c.NetMode.IsHost() && !c.NetMode.IsNone() { case !c.NetMode.IsHost() && !c.NetMode.IsNone():
postConfigureNetNS := userns.getPostConfigureNetNS() postConfigureNetNS := userns.getPostConfigureNetNS()
options = append(options, libpod.WithNetNS(portBindings, postConfigureNetNS, string(c.NetMode), networks)) options = append(options, libpod.WithNetNS(portBindings, postConfigureNetNS, string(c.NetMode), networks))
} }
@ -102,29 +103,31 @@ func (c *NetworkConfig) ToCreateOptions(runtime *libpod.Runtime, userns *UserCon
// state of the NetworkConfig. // state of the NetworkConfig.
func (c *NetworkConfig) ConfigureGenerator(g *generate.Generator) error { func (c *NetworkConfig) ConfigureGenerator(g *generate.Generator) error {
netMode := c.NetMode netMode := c.NetMode
if netMode.IsHost() { netCtr := netMode.Container()
switch {
case netMode.IsHost():
logrus.Debug("Using host netmode") logrus.Debug("Using host netmode")
if err := g.RemoveLinuxNamespace(string(spec.NetworkNamespace)); err != nil { if err := g.RemoveLinuxNamespace(string(spec.NetworkNamespace)); err != nil {
return err return err
} }
} else if netMode.IsNone() { case netMode.IsNone():
logrus.Debug("Using none netmode") logrus.Debug("Using none netmode")
} else if netMode.IsBridge() { case netMode.IsBridge():
logrus.Debug("Using bridge netmode") logrus.Debug("Using bridge netmode")
} else if netCtr := netMode.Container(); netCtr != "" { case netCtr != "":
logrus.Debugf("using container %s netmode", netCtr) logrus.Debugf("using container %s netmode", netCtr)
} else if IsNS(string(netMode)) { case IsNS(string(netMode)):
logrus.Debug("Using ns netmode") logrus.Debug("Using ns netmode")
if err := g.AddOrReplaceLinuxNamespace(string(spec.NetworkNamespace), NS(string(netMode))); err != nil { if err := g.AddOrReplaceLinuxNamespace(string(spec.NetworkNamespace), NS(string(netMode))); err != nil {
return err return err
} }
} else if IsPod(string(netMode)) { case IsPod(string(netMode)):
logrus.Debug("Using pod netmode, unless pod is not sharing") logrus.Debug("Using pod netmode, unless pod is not sharing")
} else if netMode.IsSlirp4netns() { case netMode.IsSlirp4netns():
logrus.Debug("Using slirp4netns netmode") logrus.Debug("Using slirp4netns netmode")
} else if netMode.IsUserDefined() { case netMode.IsUserDefined():
logrus.Debug("Using user defined netmode") logrus.Debug("Using user defined netmode")
} else { default:
return errors.Errorf("unknown network mode") return errors.Errorf("unknown network mode")
} }
@ -220,7 +223,8 @@ func (c *CgroupConfig) ToCreateOptions(runtime *libpod.Runtime) ([]libpod.CtrCre
// ToCreateOptions converts the input to container create options. // ToCreateOptions converts the input to container create options.
func (c *UserConfig) ToCreateOptions(runtime *libpod.Runtime) ([]libpod.CtrCreateOption, error) { func (c *UserConfig) ToCreateOptions(runtime *libpod.Runtime) ([]libpod.CtrCreateOption, error) {
options := make([]libpod.CtrCreateOption, 0) options := make([]libpod.CtrCreateOption, 0)
if c.UsernsMode.IsNS() { switch {
case c.UsernsMode.IsNS():
ns := c.UsernsMode.NS() ns := c.UsernsMode.NS()
if ns == "" { if ns == "" {
return nil, errors.Errorf("invalid empty user-defined user namespace") return nil, errors.Errorf("invalid empty user-defined user namespace")
@ -230,13 +234,13 @@ func (c *UserConfig) ToCreateOptions(runtime *libpod.Runtime) ([]libpod.CtrCreat
return nil, err return nil, err
} }
options = append(options, libpod.WithIDMappings(*c.IDMappings)) options = append(options, libpod.WithIDMappings(*c.IDMappings))
} else if c.UsernsMode.IsContainer() { case c.UsernsMode.IsContainer():
connectedCtr, err := runtime.LookupContainer(c.UsernsMode.Container()) connectedCtr, err := runtime.LookupContainer(c.UsernsMode.Container())
if err != nil { if err != nil {
return nil, errors.Wrapf(err, "container %q not found", c.UsernsMode.Container()) return nil, errors.Wrapf(err, "container %q not found", c.UsernsMode.Container())
} }
options = append(options, libpod.WithUserNSFrom(connectedCtr)) options = append(options, libpod.WithUserNSFrom(connectedCtr))
} else { default:
options = append(options, libpod.WithIDMappings(*c.IDMappings)) options = append(options, libpod.WithIDMappings(*c.IDMappings))
} }
@ -413,20 +417,22 @@ func (c *UtsConfig) ToCreateOptions(runtime *libpod.Runtime, pod *libpod.Pod) ([
// of the UtsConfig. // of the UtsConfig.
func (c *UtsConfig) ConfigureGenerator(g *generate.Generator, net *NetworkConfig, runtime *libpod.Runtime) error { func (c *UtsConfig) ConfigureGenerator(g *generate.Generator, net *NetworkConfig, runtime *libpod.Runtime) error {
hostname := c.Hostname hostname := c.Hostname
utsCtrID := c.UtsMode.Container()
var err error var err error
if hostname == "" { if hostname == "" {
if utsCtrID := c.UtsMode.Container(); utsCtrID != "" { switch {
case utsCtrID != "":
utsCtr, err := runtime.GetContainer(utsCtrID) utsCtr, err := runtime.GetContainer(utsCtrID)
if err != nil { if err != nil {
return errors.Wrapf(err, "unable to retrieve hostname from dependency container %s", utsCtrID) return errors.Wrapf(err, "unable to retrieve hostname from dependency container %s", utsCtrID)
} }
hostname = utsCtr.Hostname() hostname = utsCtr.Hostname()
} else if net.NetMode.IsHost() || c.UtsMode.IsHost() { case net.NetMode.IsHost() || c.UtsMode.IsHost():
hostname, err = os.Hostname() hostname, err = os.Hostname()
if err != nil { if err != nil {
return errors.Wrap(err, "unable to retrieve hostname of the host") return errors.Wrap(err, "unable to retrieve hostname of the host")
} }
} else { default:
logrus.Debug("No hostname set; container's hostname will default to runtime default") logrus.Debug("No hostname set; container's hostname will default to runtime default")
} }
} }

View File

@ -409,9 +409,10 @@ func getBindMount(args []string) (spec.Mount, error) {
// ro=[true|false] // ro=[true|false]
// rw // rw
// rw=[true|false] // rw=[true|false]
if len(kv) == 1 { switch len(kv) {
case 1:
newMount.Options = append(newMount.Options, kv[0]) newMount.Options = append(newMount.Options, kv[0])
} else if len(kv) == 2 { case 2:
switch strings.ToLower(kv[1]) { switch strings.ToLower(kv[1]) {
case "true": case "true":
newMount.Options = append(newMount.Options, kv[0]) newMount.Options = append(newMount.Options, kv[0])
@ -424,7 +425,7 @@ func getBindMount(args []string) (spec.Mount, error) {
default: default:
return newMount, errors.Wrapf(optionArgError, "%s must be set to true or false, instead received %q", kv[0], kv[1]) return newMount, errors.Wrapf(optionArgError, "%s must be set to true or false, instead received %q", kv[0], kv[1])
} }
} else { default:
return newMount, errors.Wrapf(optionArgError, "badly formatted option %q", val) return newMount, errors.Wrapf(optionArgError, "badly formatted option %q", val)
} }
case "nosuid", "suid": case "nosuid", "suid":

View File

@ -34,7 +34,7 @@ func GetTimestamp(value string, reference time.Time) (string, error) {
// if the string has a Z or a + or three dashes use parse otherwise use parseinlocation // if the string has a Z or a + or three dashes use parse otherwise use parseinlocation
parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3) parseInLocation := !(strings.ContainsAny(value, "zZ+") || strings.Count(value, "-") == 3)
if strings.Contains(value, ".") { if strings.Contains(value, ".") { // nolint(gocritic)
if parseInLocation { if parseInLocation {
format = rFC3339NanoLocal format = rFC3339NanoLocal
} else { } else {

View File

@ -321,14 +321,14 @@ func ParseSignal(rawSignal string) (syscall.Signal, error) {
} }
// ParseIDMapping takes idmappings and subuid and subgid maps and returns a storage mapping // ParseIDMapping takes idmappings and subuid and subgid maps and returns a storage mapping
func ParseIDMapping(mode namespaces.UsernsMode, UIDMapSlice, GIDMapSlice []string, subUIDMap, subGIDMap string) (*storage.IDMappingOptions, error) { func ParseIDMapping(mode namespaces.UsernsMode, uidMapSlice, gidMapSlice []string, subUIDMap, subGIDMap string) (*storage.IDMappingOptions, error) {
options := storage.IDMappingOptions{ options := storage.IDMappingOptions{
HostUIDMapping: true, HostUIDMapping: true,
HostGIDMapping: true, HostGIDMapping: true,
} }
if mode.IsKeepID() { if mode.IsKeepID() {
if len(UIDMapSlice) > 0 || len(GIDMapSlice) > 0 { if len(uidMapSlice) > 0 || len(gidMapSlice) > 0 {
return nil, errors.New("cannot specify custom mappings with --userns=keep-id") return nil, errors.New("cannot specify custom mappings with --userns=keep-id")
} }
if len(subUIDMap) > 0 || len(subGIDMap) > 0 { if len(subUIDMap) > 0 || len(subGIDMap) > 0 {
@ -384,17 +384,17 @@ func ParseIDMapping(mode namespaces.UsernsMode, UIDMapSlice, GIDMapSlice []strin
if subUIDMap == "" && subGIDMap != "" { if subUIDMap == "" && subGIDMap != "" {
subUIDMap = subGIDMap subUIDMap = subGIDMap
} }
if len(GIDMapSlice) == 0 && len(UIDMapSlice) != 0 { if len(gidMapSlice) == 0 && len(uidMapSlice) != 0 {
GIDMapSlice = UIDMapSlice gidMapSlice = uidMapSlice
} }
if len(UIDMapSlice) == 0 && len(GIDMapSlice) != 0 { if len(uidMapSlice) == 0 && len(gidMapSlice) != 0 {
UIDMapSlice = GIDMapSlice uidMapSlice = gidMapSlice
} }
if len(UIDMapSlice) == 0 && subUIDMap == "" && os.Getuid() != 0 { if len(uidMapSlice) == 0 && subUIDMap == "" && os.Getuid() != 0 {
UIDMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getuid())} uidMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getuid())}
} }
if len(GIDMapSlice) == 0 && subGIDMap == "" && os.Getuid() != 0 { if len(gidMapSlice) == 0 && subGIDMap == "" && os.Getuid() != 0 {
GIDMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getgid())} gidMapSlice = []string{fmt.Sprintf("0:%d:1", os.Getgid())}
} }
if subUIDMap != "" && subGIDMap != "" { if subUIDMap != "" && subGIDMap != "" {
@ -405,11 +405,11 @@ func ParseIDMapping(mode namespaces.UsernsMode, UIDMapSlice, GIDMapSlice []strin
options.UIDMap = mappings.UIDs() options.UIDMap = mappings.UIDs()
options.GIDMap = mappings.GIDs() options.GIDMap = mappings.GIDs()
} }
parsedUIDMap, err := idtools.ParseIDMap(UIDMapSlice, "UID") parsedUIDMap, err := idtools.ParseIDMap(uidMapSlice, "UID")
if err != nil { if err != nil {
return nil, err return nil, err
} }
parsedGIDMap, err := idtools.ParseIDMap(GIDMapSlice, "GID") parsedGIDMap, err := idtools.ParseIDMap(gidMapSlice, "GID")
if err != nil { if err != nil {
return nil, err return nil, err
} }