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

import (
	"dtk-container-toolkit/internal/logger"
	"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
79
80
81
82
83
84
85
86
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)  
        }

	cmd := exec.Command("cp", "/usr/bin/dtk-docker", "/usr/bin/"+runtime)
	err = cmd.Run()
	if err != nil {
		return fmt.Errorf("failed to copy dtk-docker to /usr/bin/%s: %w", runtime, err)
	}
	return nil
}