main.go 1.84 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
1
2
3
package rootless

import (
4
	"dcu-container-toolkit/internal/logger"
songlinfeng's avatar
songlinfeng committed
5
6
7
	"fmt"
	"os"
	"os/exec"
songlinfeng's avatar
songlinfeng committed
8
        "os/user"
songlinfeng's avatar
songlinfeng committed
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
	"github.com/urfave/cli/v2"
)

type rootlessCommand struct {
	logger logger.Interface
}
type options struct {
	runtime string
}

// NewCommand constructs a rootless command with the specified logger
func NewCommand(logger logger.Interface) *cli.Command {
	c := rootlessCommand{
		logger: logger,
	}
	return c.build()
}

// build
func (m rootlessCommand) build() *cli.Command {
	// Create the 'rootless' command
	opts := options{}

	c := cli.Command{
		Name:   "rootless",
		Usage:  "Provide tools for configuring rootless container runtimes",
songlinfeng's avatar
songlinfeng committed
35
		Before: func(ctx *cli.Context) error { return validateGenOptions(ctx) },
songlinfeng's avatar
songlinfeng committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
		Action: func(ctx *cli.Context) error { return run(ctx, &opts) },
	}

	c.Flags = []cli.Flag{
		&cli.StringFlag{
			Name:        "runtime",
			Aliases:     []string{"r"},
			Usage:       "docker or podman",
			Value:       "docker",
			Destination: &opts.runtime,
		},
	}

	return &c
}

songlinfeng's avatar
songlinfeng committed
52
53
54
55
56
57
58
59
60
func validateGenOptions(c *cli.Context) error {
	curUser, err := user.Current()
	if err != nil || curUser.Uid != "0" {
		return fmt.Errorf("Permission denied: Not running as root")
	}

	return nil
}

songlinfeng's avatar
songlinfeng committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
func run(c *cli.Context, opts *options) error {
	runtime := opts.runtime
	if runtime != "docker" && runtime != "podman" {
		return fmt.Errorf("invalid runtime %s", runtime)
	}

	_, err := os.Stat("/usr/bin/s" + runtime)

	if os.IsNotExist(err) {
		cmd := exec.Command("cp", "/usr/bin/"+runtime, "/usr/bin/s"+runtime)
		cmd.Run()
	}
        _, err = os.Stat("/usr/bin/" + runtime)

        if err == nil {
                os.Remove("/usr/bin/" + runtime)  
        }

79
	cmd := exec.Command("cp", "/usr/bin/dcu-docker", "/usr/bin/"+runtime)
songlinfeng's avatar
songlinfeng committed
80
81
	err = cmd.Run()
	if err != nil {
82
		return fmt.Errorf("failed to copy dcu-docker to /usr/bin/%s: %w", runtime, err)
songlinfeng's avatar
songlinfeng committed
83
84
85
86
	}
	return nil
}