-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathfeatures.go
271 lines (255 loc) · 8.62 KB
/
features.go
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package features
import (
"archive/tar"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"github.com/GoogleContainerTools/kaniko/pkg/creds"
"github.com/go-git/go-billy/v5"
"github.com/google/go-containerregistry/pkg/name"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/otiai10/copy"
"github.com/tailscale/hujson"
)
func extractFromImage(fs billy.Filesystem, directory, reference string) error {
ref, err := name.ParseReference(reference)
if err != nil {
return fmt.Errorf("parse feature ref %s: %w", reference, err)
}
image, err := remote.Image(ref, remote.WithAuthFromKeychain(creds.GetKeychain()))
if err != nil {
return fmt.Errorf("fetch feature image %s: %w", reference, err)
}
manifest, err := image.Manifest()
if err != nil {
return fmt.Errorf("fetch feature manifest %s: %w", reference, err)
}
var tarLayer *tar.Reader
for _, manifestLayer := range manifest.Layers {
if manifestLayer.MediaType != TarLayerMediaType {
continue
}
layer, err := image.LayerByDigest(manifestLayer.Digest)
if err != nil {
return fmt.Errorf("fetch feature layer %s: %w", reference, err)
}
layerReader, err := layer.Uncompressed()
if err != nil {
return fmt.Errorf("uncompress feature layer %s: %w", reference, err)
}
tarLayer = tar.NewReader(layerReader)
break
}
if tarLayer == nil {
return fmt.Errorf("no tar layer found with media type %q: are you sure this is a devcontainer feature?", TarLayerMediaType)
}
for {
header, err := tarLayer.Next()
if err == io.EOF {
break
}
if err != nil {
return fmt.Errorf("read feature layer %s: %w", reference, err)
}
path := filepath.Join(directory, header.Name)
switch header.Typeflag {
case tar.TypeDir:
err = fs.MkdirAll(path, 0o755)
if err != nil {
return fmt.Errorf("mkdir %s: %w", path, err)
}
case tar.TypeReg:
outFile, err := fs.Create(path)
if err != nil {
return fmt.Errorf("create %s: %w", path, err)
}
_, err = io.Copy(outFile, tarLayer)
if err != nil {
return fmt.Errorf("copy %s: %w", path, err)
}
err = outFile.Close()
if err != nil {
return fmt.Errorf("close %s: %w", path, err)
}
default:
return fmt.Errorf("unknown type %d in %s", header.Typeflag, path)
}
}
return nil
}
// Extract unpacks the feature from the image and returns the
// parsed specification.
func Extract(fs billy.Filesystem, devcontainerDir, directory, reference string) (*Spec, error) {
if strings.HasPrefix(reference, "./") {
if err := copy.Copy(filepath.Join(devcontainerDir, reference), directory, copy.Options{
PreserveTimes: true,
PreserveOwner: true,
OnSymlink: func(src string) copy.SymlinkAction {
return copy.Shallow
},
OnError: func(src, dest string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("copy error: %q -> %q: %w", reference, directory, err)
},
}); err != nil {
return nil, err
}
} else if err := extractFromImage(fs, directory, reference); err != nil {
return nil, err
}
installScriptPath := filepath.Join(directory, "install.sh")
_, err := fs.Stat(installScriptPath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, errors.New("install.sh must be in the root of the feature")
}
return nil, fmt.Errorf("stat install.sh: %w", err)
}
chmodder, ok := fs.(interface {
Chmod(name string, mode os.FileMode) error
})
if ok {
// For some reason the filesystem abstraction doesn't support chmod.
// https://github.com/src-d/go-billy/issues/56
err = chmodder.Chmod(installScriptPath, 0o755)
}
if err != nil {
return nil, fmt.Errorf("chmod install.sh: %w", err)
}
featureFile, err := fs.Open(filepath.Join(directory, "devcontainer-feature.json"))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, errors.New("devcontainer-feature.json must be in the root of the feature")
}
return nil, fmt.Errorf("open devcontainer-feature.json: %w", err)
}
defer featureFile.Close()
featureFileBytes, err := io.ReadAll(featureFile)
if err != nil {
return nil, fmt.Errorf("read devcontainer-feature.json: %w", err)
}
standardizedFeatureFileBytes, err := hujson.Standardize(featureFileBytes)
if err != nil {
return nil, fmt.Errorf("standardize devcontainer-feature.json: %w", err)
}
var spec *Spec
if err := json.Unmarshal(standardizedFeatureFileBytes, &spec); err != nil {
return nil, fmt.Errorf("decode devcontainer-feature.json: %w", err)
}
// See https://containers.dev/implementors/features/#devcontainer-feature-json-properties
if spec.ID == "" {
return nil, errors.New(`devcontainer-feature.json: id is required`)
}
if spec.Version == "" {
return nil, errors.New(`devcontainer-feature.json: version is required`)
}
if spec.Name == "" {
return nil, errors.New(`devcontainer-feature.json: name is required`)
}
return spec, nil
}
const (
TarLayerMediaType = "application/vnd.devcontainers.layer.v1+tar"
)
type Option struct {
Type string `json:"type"` // "boolean" or "string"
Proposals []string `json:"proposals"`
Enum []string `json:"enum"`
Default any `json:"default"` // boolean or string
Description string `json:"description"`
}
type Spec struct {
ID string `json:"id"`
Version string `json:"version"`
Name string `json:"name"`
Description string `json:"description"`
DocumentationURL string `json:"documentationURL"`
LicenseURL string `json:"licenseURL"`
Keywords []string `json:"keywords"`
Options map[string]Option `json:"options"`
ContainerEnv map[string]string `json:"containerEnv"`
}
// Extract unpacks the feature from the image and returns a set of lines
// that should be appended to a Dockerfile to install the feature.
func (s *Spec) Compile(featureRef, featureName, featureDir, containerUser, remoteUser string, useBuildContexts bool, options map[string]any) (string, string, error) {
// TODO not sure how we figure out _(REMOTE|CONTAINER)_USER_HOME
// as per the feature spec.
// See https://containers.dev/implementors/features/#user-env-var
var fromDirective string
runDirective := []string{
"_CONTAINER_USER=" + strconv.Quote(containerUser),
"_REMOTE_USER=" + strconv.Quote(remoteUser),
}
for key, value := range s.Options {
strValue := fmt.Sprint(value.Default)
provided, ok := options[key]
if ok {
strValue = fmt.Sprint(provided)
// delete so we can check if there are any unknown options
delete(options, key)
}
runDirective = append(runDirective, fmt.Sprintf(`%s=%q`, convertOptionNameToEnv(key), strValue))
}
if len(options) > 0 {
return "", "", fmt.Errorf("unknown option: %v", options)
}
// It's critical that the Dockerfile produced is deterministic,
// regardless of map iteration order.
sort.Strings(runDirective)
// See https://containers.dev/implementors/features/#invoking-installsh
if useBuildContexts {
// Use a deterministic target directory to make the resulting Dockerfile cacheable
featureDir = "/.envbuilder/features/" + featureName
fromDirective = "FROM scratch AS envbuilder_feature_" + featureName + "\nCOPY --from=" + featureRef + " / /\n"
runDirective = append([]string{"RUN", "--mount=type=bind,from=envbuilder_feature_" + featureName + ",target=" + featureDir + ",rw"}, runDirective...)
} else {
runDirective = append([]string{"RUN"}, runDirective...)
}
runDirective = append(runDirective, "./install.sh")
comment := ""
if s.Name != "" {
comment += "# " + s.Name
}
if s.Version != "" {
comment += " " + s.Version
}
if s.Description != "" {
comment += " - " + s.Description
}
lines := []string{}
if comment != "" {
lines = append(lines, comment)
}
lines = append(lines, "WORKDIR "+featureDir)
envKeys := make([]string, 0, len(s.ContainerEnv))
for key := range s.ContainerEnv {
envKeys = append(envKeys, key)
}
// It's critical that the Dockerfile produced is deterministic,
// regardless of map iteration order.
sort.Strings(envKeys)
for _, key := range envKeys {
lines = append(lines, fmt.Sprintf("ENV %s=%s", key, s.ContainerEnv[key]))
}
lines = append(lines, strings.Join(runDirective, " "))
return fromDirective, strings.Join(lines, "\n"), nil
}
var (
matchNonWords = regexp.MustCompile(`/[^\w_]/g`)
matchPrefixDigitsAndUnderscores = regexp.MustCompile(`/^[\d_]+/g`)
)
// See https://containers.dev/implementors/features/#option-resolution
func convertOptionNameToEnv(optionName string) string {
optionName = matchNonWords.ReplaceAllString(optionName, "_")
optionName = matchPrefixDigitsAndUnderscores.ReplaceAllString(optionName, "")
return strings.ToUpper(optionName)
}