summaryrefslogtreecommitdiff
path: root/cmd/podman/run.go
blob: 27247c5b5a4ed9cb4331b8619dc96b2494b59b4b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main

import (
	"os"

	"github.com/containers/libpod/cmd/podman/cliconfig"
	"github.com/containers/libpod/pkg/adapter"
	"github.com/opentracing/opentracing-go"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var (
	runCommand cliconfig.RunValues

	runDescription = "Runs a command in a new container from the given image"
	_runCommand    = &cobra.Command{
		Use:   "run [flags] IMAGE [COMMAND [ARG...]]",
		Short: "Run a command in a new container",
		Long:  runDescription,
		RunE: func(cmd *cobra.Command, args []string) error {
			runCommand.InputArgs = args
			runCommand.GlobalFlags = MainGlobalOpts
			runCommand.Remote = remoteclient
			return runCmd(&runCommand)
		},
		Example: `podman run imageID ls -alF /etc
  podman run --network=host imageID dnf -y install java
  podman run --volume /var/hostdir:/var/ctrdir -i -t fedora /bin/bash`,
	}
)

func init() {
	runCommand.Command = _runCommand
	runCommand.SetHelpTemplate(HelpTemplate())
	runCommand.SetUsageTemplate(UsageTemplate())
	flags := runCommand.Flags()
	flags.SetInterspersed(false)
	flags.SetNormalizeFunc(aliasFlags)
	flags.Bool("sig-proxy", true, "Proxy received signals to the process")
	flags.Bool("rmi", false, "Remove container image unless used by other containers")
	flags.AddFlagSet(getNetFlags())
	getCreateFlags(&runCommand.PodmanCommand)
	markFlagHiddenForRemoteClient("authfile", flags)
}

func runCmd(c *cliconfig.RunValues) error {
	if !remote && c.Bool("trace") {
		span, _ := opentracing.StartSpanFromContext(Ctx, "runCmd")
		defer span.Finish()
	}
	if c.String("authfile") != "" {
		if _, err := os.Stat(c.String("authfile")); err != nil {
			return errors.Wrapf(err, "error checking authfile path %s", c.String("authfile"))
		}
	}
	if err := createInit(&c.PodmanCommand); err != nil {
		return err
	}

	runtime, err := adapter.GetRuntime(getContext(), &c.PodmanCommand)
	if err != nil {
		return errors.Wrapf(err, "error creating libpod runtime")
	}
	defer runtime.DeferredShutdown(false)

	exitCode, err = runtime.Run(getContext(), c, exitCode)
	if c.Bool("rmi") {
		imageName := c.InputArgs[0]
		if newImage, newImageErr := runtime.NewImageFromLocal(imageName); newImageErr != nil {
			logrus.Errorf("%s", errors.Wrapf(newImageErr, "failed creating image object"))
		} else if _, errImage := runtime.RemoveImage(getContext(), newImage, false); errImage != nil {
			logrus.Errorf("%s", errors.Wrapf(errImage, "failed removing image"))
		}
	}
	return err
}