aboutsummaryrefslogtreecommitdiff
path: root/cmd/podman/restart.go
blob: 08e8b615bc82c316437f772915b76cba29c1812a (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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main

import (
	"context"
	"fmt"
	"os"

	"github.com/pkg/errors"
	"github.com/projectatomic/libpod/cmd/podman/libpodruntime"
	"github.com/projectatomic/libpod/libpod"
	"github.com/urfave/cli"
)

var (
	restartFlags = []cli.Flag{
		cli.UintFlag{
			Name:  "timeout, time, t",
			Usage: "Seconds to wait for stop before killing the container",
			Value: libpod.CtrRemoveTimeout,
		},
		LatestFlag,
	}
	restartDescription = `Restarts one or more running containers. The container ID or name can be used. A timeout before forcibly stopping can be set, but defaults to 10 seconds`

	restartCommand = cli.Command{
		Name:                   "restart",
		Usage:                  "Restart one or more containers",
		Description:            restartDescription,
		Flags:                  restartFlags,
		Action:                 restartCmd,
		ArgsUsage:              "CONTAINER [CONTAINER ...]",
		UseShortOptionHandling: true,
	}
)

func restartCmd(c *cli.Context) error {
	args := c.Args()
	if len(args) < 1 && !c.Bool("latest") {
		return errors.Wrapf(libpod.ErrInvalidArg, "you must provide at least one container name or ID")
	}

	if err := validateFlags(c, restartFlags); err != nil {
		return err
	}

	runtime, err := libpodruntime.GetRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "error creating libpod runtime")
	}
	defer runtime.Shutdown(false)

	var lastError error

	timeout := c.Uint("timeout")
	useTimeout := c.IsSet("timeout")

	// Handle --latest
	if c.Bool("latest") {
		lastCtr, err := runtime.GetLatestContainer()
		if err != nil {
			lastError = errors.Wrapf(err, "unable to get latest container")
		} else {
			ctrTimeout := lastCtr.StopTimeout()
			if useTimeout {
				ctrTimeout = timeout
			}

			lastError = lastCtr.RestartWithTimeout(context.TODO(), ctrTimeout)
		}
	}

	for _, id := range args {
		ctr, err := runtime.LookupContainer(id)
		if err != nil {
			if lastError != nil {
				fmt.Fprintln(os.Stderr, lastError)
			}
			lastError = errors.Wrapf(err, "unable to find container %s", id)
			continue
		}

		ctrTimeout := ctr.StopTimeout()
		if useTimeout {
			ctrTimeout = timeout
		}

		if err := ctr.RestartWithTimeout(context.TODO(), ctrTimeout); err != nil {
			if lastError != nil {
				fmt.Fprintln(os.Stderr, lastError)
			}
			lastError = errors.Wrapf(err, "error restarting container %s", ctr.ID())
		}
	}

	return lastError
}