create-symlinks.go 3.62 KB
Newer Older
songlinfeng's avatar
songlinfeng committed
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
97
98
99
/**
# Copyright (c) 2024, HCUOpt CORPORATION.  All rights reserved.
**/

package symlinks

import (
	"dtk-container-toolkit/internal/logger"
	"dtk-container-toolkit/internal/oci"
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/urfave/cli/v2"
)

type command struct {
	logger logger.Interface
}

type config struct {
	hostRoot      string
	links         cli.StringSlice
	containerSpec string
}

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

// build
func (m command) build() *cli.Command {
	cfg := config{}

	// Create the '' command
	c := cli.Command{
		Name:  "create-symlinks",
		Usage: "A hook to create symlinks in the container. This can be used to process CSV mount specs",
		Action: func(c *cli.Context) error {
			return m.run(c, &cfg)
		},
	}

	c.Flags = []cli.Flag{
		&cli.StringFlag{
			Name:        "host-root",
			Usage:       "The root on the host filesystem to use to resolve symlinks",
			Destination: &cfg.hostRoot,
		},
		&cli.StringSliceFlag{
			Name:        "link",
			Usage:       "Specify a specific link to create. The link is specified as target::link",
			Destination: &cfg.links,
		},
		&cli.StringFlag{
			Name:        "container-spec",
			Usage:       "Specify the path to the OCI container spec. If empty or '-' the spec will be read from STDIN",
			Destination: &cfg.containerSpec,
		},
	}

	return &c
}

func (m command) run(c *cli.Context, cfg *config) error {
	s, err := oci.LoadContainerState(cfg.containerSpec)
	if err != nil {
		return fmt.Errorf("failed to load container state: %v", err)
	}

	containerRoot, err := s.GetContainerRoot()
	if err != nil {
		return fmt.Errorf("failed to determined container root: %v", err)
	}

	created := make(map[string]bool)

	links := cfg.links.Value()
	for _, l := range links {
		parts := strings.Split(l, "::")
		if len(parts) != 2 {
			m.logger.Warningf("Invalid link specification %v", l)
			continue
		}

		err := m.createLink(created, cfg.hostRoot, containerRoot, parts[0], parts[1])
		if err != nil {
			m.logger.Warningf("Failed to create link %v: %v", parts, err)
		}
	}

	return nil
}

songlinfeng's avatar
songlinfeng committed
100
101
102
103
104
105
106
107
func DirExists(path string) bool {
        _, err := os.Stat(path)
        if os.IsNotExist(err){
            return false
        }
        return err == nil
}

songlinfeng's avatar
songlinfeng committed
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
func (m command) createLink(created map[string]bool, hostRoot string, containerRoot string, target string, link string) error {
	linkPath, err := changeRoot(hostRoot, containerRoot, link)
	if err != nil {
		m.logger.Warningf("Failed to resolve path for link %v relative to %v: %v", link, containerRoot, err)
	}
	if created[linkPath] {
		m.logger.Debugf("Link %v already created", linkPath)
		return nil
	}

	targetPath, err := changeRoot(hostRoot, "/", target)
	if err != nil {
		m.logger.Warningf("Failed to resolve path for target %v relative to %v: %v", target, "/", err)
	}

	m.logger.Infof("Symlinking %v to %v", linkPath, targetPath)
songlinfeng's avatar
songlinfeng committed
124
125
126
127
        if DirExists(linkPath) {
           os.RemoveAll(linkPath)
           m.logger.Infof("remove dir %v", linkPath)
        }
songlinfeng's avatar
songlinfeng committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
	err = os.MkdirAll(filepath.Dir(linkPath), 0755)
	if err != nil {
		return fmt.Errorf("failed to create directory: %v", err)
	}
	err = os.Symlink(target, linkPath)
	if err != nil {
		return fmt.Errorf("failed to create symlink: %v", err)
	}

	return nil
}

func changeRoot(current string, new string, path string) (string, error) {
	if !filepath.IsAbs(path) {
		return path, nil
	}

	relative := path
	if current != "" {
		r, err := filepath.Rel(current, path)
		if err != nil {
			return "", err
		}
		relative = r
	}

	return filepath.Join(new, relative), nil
}