-
Notifications
You must be signed in to change notification settings - Fork 311
/
features.go
280 lines (236 loc) · 8.12 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
272
273
274
275
276
277
278
279
280
package feature
import (
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"strings"
"github.com/google/go-containerregistry/pkg/authn"
"github.com/google/go-containerregistry/pkg/name"
v1 "github.com/google/go-containerregistry/pkg/v1"
"github.com/google/go-containerregistry/pkg/v1/remote"
"github.com/loft-sh/devpod/pkg/devcontainer/config"
"github.com/loft-sh/devpod/pkg/extract"
devpodhttp "github.com/loft-sh/devpod/pkg/http"
"github.com/loft-sh/log"
"github.com/loft-sh/log/hash"
"github.com/pkg/errors"
)
const DEVCONTAINER_MANIFEST_MEDIATYPE = "application/vnd.devcontainers"
var directTarballRegEx = regexp.MustCompile("devcontainer-feature-([a-zA-Z0-9_-]+).tgz")
func getFeatureInstallWrapperScript(idWithoutVersion string, feature *config.FeatureConfig, options []string) string {
id := escapeQuotesForShell(idWithoutVersion)
name := escapeQuotesForShell(feature.Name)
description := escapeQuotesForShell(feature.Description)
version := escapeQuotesForShell(feature.Version)
documentation := escapeQuotesForShell(feature.DocumentationURL)
optionsIndented := escapeQuotesForShell(" " + strings.Join(options, "\n "))
warningHeader := ""
if feature.Deprecated {
warningHeader += `(!) WARNING: Using the deprecated Feature "${escapeQuotesForShell(feature.id)}". This Feature will no longer receive any further updates/support.\n`
}
echoWarning := ""
if warningHeader != "" {
echoWarning = `echo '` + warningHeader + `'`
}
errorMessage := `ERROR: Feature "` + name + `" (` + id + `) failed to install!`
troubleshootingMessage := ""
if documentation != "" {
troubleshootingMessage = ` Look at the documentation at ${documentation} for help troubleshooting this error.`
}
return `#!/bin/sh
set -e
on_exit () {
[ $? -eq 0 ] && exit
echo '` + errorMessage + troubleshootingMessage + `'
}
trap on_exit EXIT
set -a
. ../devcontainer-features.builtin.env
. ./devcontainer-features.env
set +a
echo ===========================================================================
` + echoWarning + `
echo 'Feature : ` + name + `'
echo 'Description : ` + description + `'
echo 'Id : ` + id + `'
echo 'Version : ` + version + `'
echo 'Documentation : ` + documentation + `'
echo 'Options :'
echo '` + optionsIndented + `'
echo 'Environment :'
printenv
echo ===========================================================================
chmod +x ./install.sh
./install.sh
`
}
func escapeQuotesForShell(str string) string {
// The `input` is expected to be a string which will be printed inside single quotes
// by the caller. This means we need to escape any nested single quotes within the string.
// We can do this by ending the first string with a single quote ('), printing an escaped
// single quote (\'), and then opening a new string (').
return strings.ReplaceAll(str, "'", `'\''`)
}
func ProcessFeatureID(id string, devContainerConfig *config.DevContainerConfig, log log.Logger, forceBuild bool) (string, error) {
if strings.HasPrefix(id, "https://") || strings.HasPrefix(id, "http://") {
log.Debugf("Process url feature")
return processDirectTarFeature(id, config.GetDevPodCustomizations(devContainerConfig).FeatureDownloadHTTPHeaders, log, forceBuild)
} else if strings.HasPrefix(id, "./") || strings.HasPrefix(id, "../") {
log.Debugf("Process local feature")
return filepath.Abs(path.Join(filepath.ToSlash(filepath.Dir(devContainerConfig.Origin)), id))
}
// get oci feature
log.Debugf("Process OCI feature")
return processOCIFeature(id, log)
}
func processOCIFeature(id string, log log.Logger) (string, error) {
// feature already exists?
featureFolder := getFeaturesTempFolder(id)
featureExtractedFolder := filepath.Join(featureFolder, "extracted")
_, err := os.Stat(featureExtractedFolder)
if err == nil {
// make sure feature.json is there as well
_, err = os.Stat(filepath.Join(featureExtractedFolder, config.DEVCONTAINER_FEATURE_FILE_NAME))
if err == nil {
return featureExtractedFolder, nil
} else {
log.Debugf("Feature folder already exists but seems to be empty")
_ = os.RemoveAll(featureFolder)
}
}
ref, err := name.ParseReference(id)
if err != nil {
return "", err
}
img, err := remote.Image(ref, remote.WithAuthFromKeychain(authn.DefaultKeychain))
if err != nil {
return "", err
}
destFile := filepath.Join(featureFolder, "feature.tgz")
err = downloadLayer(img, id, destFile, log)
if err != nil {
return "", err
}
file, err := os.Open(destFile)
if err != nil {
return "", err
}
defer file.Close()
log.Debugf("Extract feature into %s", featureExtractedFolder)
err = extract.Extract(file, featureExtractedFolder)
if err != nil {
_ = os.RemoveAll(featureExtractedFolder)
return "", err
}
return featureExtractedFolder, nil
}
func downloadLayer(img v1.Image, id, destFile string, log log.Logger) error {
manifest, err := img.Manifest()
if err != nil {
return err
} else if manifest.Config.MediaType != DEVCONTAINER_MANIFEST_MEDIATYPE {
return fmt.Errorf("incorrect manifest type %s, expected %s", manifest.Config.MediaType, DEVCONTAINER_MANIFEST_MEDIATYPE)
} else if len(manifest.Layers) == 0 {
return fmt.Errorf("unexpected amount of layers, expected at least 1")
}
// download layer
log.Debugf("Download feature %s layer %s into %s...", id, manifest.Layers[0].Digest, destFile)
layer, err := img.LayerByDigest(manifest.Layers[0].Digest)
if err != nil {
return errors.Wrap(err, "retrieve layer")
}
data, err := layer.Uncompressed()
if err != nil {
return errors.Wrap(err, "download")
}
defer data.Close()
err = os.MkdirAll(filepath.Dir(destFile), 0755)
if err != nil {
return errors.Wrap(err, "create target folder")
}
file, err := os.Create(destFile)
if err != nil {
return errors.Wrap(err, "create file")
}
defer file.Close()
_, err = io.Copy(file, data)
if err != nil {
return errors.Wrap(err, "download layer")
}
return nil
}
func processDirectTarFeature(id string, httpHeaders map[string]string, log log.Logger, forceDownload bool) (string, error) {
downloadBase := id[strings.LastIndex(id, "/"):]
if !directTarballRegEx.MatchString(downloadBase) {
return "", fmt.Errorf("expected tarball name to follow 'devcontainer-feature-<feature-id>.tgz' format. Received '%s' ", downloadBase)
}
// feature already exists?
featureFolder := getFeaturesTempFolder(id)
featureExtractedFolder := filepath.Join(featureFolder, "extracted")
_, err := os.Stat(featureExtractedFolder)
if err == nil && !forceDownload {
return featureExtractedFolder, nil
}
// download feature tarball
downloadFile := filepath.Join(featureFolder, "feature.tgz")
err = downloadFeatureFromURL(id, downloadFile, httpHeaders, log)
if err != nil {
return "", err
}
// extract file
file, err := os.Open(downloadFile)
if err != nil {
return "", err
}
defer file.Close()
// extract tar.gz
err = extract.Extract(file, featureExtractedFolder)
if err != nil {
_ = os.RemoveAll(featureExtractedFolder)
return "", errors.Wrap(err, "extract folder")
}
return featureExtractedFolder, nil
}
func downloadFeatureFromURL(url string, destFile string, httpHeaders map[string]string, log log.Logger) error {
// create the features temp folder
err := os.MkdirAll(filepath.Dir(destFile), 0755)
if err != nil {
return errors.Wrap(err, "create feature folder")
}
// initiate download
log.Debugf("Download feature from %s", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return errors.Wrap(err, "make request")
}
for key, value := range httpHeaders {
req.Header.Set(key, value)
}
resp, err := devpodhttp.GetHTTPClient().Do(req)
if err != nil {
return errors.Wrap(err, "make request")
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return fmt.Errorf("GET request failed, status code is '%d'", resp.StatusCode)
}
// download the tar.gz file
file, err := os.Create(destFile)
if err != nil {
return errors.Wrap(err, "create download file")
}
defer file.Close()
_, err = io.Copy(file, resp.Body)
if err != nil {
return errors.Wrap(err, "download feature")
}
return nil
}
func getFeaturesTempFolder(id string) string {
hashedID := hash.String(id)[:10]
return filepath.Join(os.TempDir(), "devpod", "features", hashedID)
}