跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

locator.go

414 行 · 11.9 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limatmpl
5
6import (
7 "context"
8 "errors"
9 "fmt"
10 "io"
11 "net/http"
12 "net/url"
13 "os"
14 "os/exec"
15 "path"
16 "path/filepath"
17 "regexp"
18 "runtime"
19 "strings"
20
21 "github.com/sirupsen/logrus"
22
23 "github.com/lima-vm/lima/v2/pkg/identifiers"
24 "github.com/lima-vm/lima/v2/pkg/ioutilx"
25 "github.com/lima-vm/lima/v2/pkg/limatype"
26 "github.com/lima-vm/lima/v2/pkg/plugins"
27 "github.com/lima-vm/lima/v2/pkg/templatestore"
28)
29
30const yBytesLimit = 4 * 1024 * 1024 // 4MiB
31
32func Read(ctx context.Context, name, locator string) (*Template, error) {
33 tmpl := &Template{
34 Name: name,
35 Locator: locator,
36 }
37
38 locator, err := TransformCustomURL(ctx, locator)
39 if err != nil {
40 return nil, err
41 }
42
43 if imageTemplate(tmpl, locator) {
44 return tmpl, nil
45 }
46
47 isTemplateURL, templateName := SeemsTemplateURL(locator)
48 switch {
49 case isTemplateURL:
50 logrus.Debugf("interpreting argument %#q as a template name %#q", locator, templateName)
51 if tmpl.Name == "" {
52 // e.g., templateName = "deprecated/centos-7.yaml" , tmpl.Name = "centos-7"
53 tmpl.Name, err = InstNameFromYAMLPath(templateName)
54 if err != nil {
55 return nil, err
56 }
57 }
58 tmpl.Bytes, err = templatestore.Read(templateName)
59 if err != nil {
60 return nil, err
61 }
62 case SeemsHTTPURL(locator):
63 if tmpl.Name == "" {
64 tmpl.Name, err = InstNameFromURL(locator)
65 if err != nil {
66 return nil, err
67 }
68 }
69 logrus.Debugf("interpreting argument %#q as a http url for instance %#q", locator, tmpl.Name)
70 req, err := http.NewRequestWithContext(ctx, http.MethodGet, locator, http.NoBody)
71 if err != nil {
72 return nil, err
73 }
74 resp, err := http.DefaultClient.Do(req)
75 if err != nil {
76 return nil, err
77 }
78 defer resp.Body.Close()
79 tmpl.Bytes, err = ioutilx.ReadAtMaximum(resp.Body, yBytesLimit)
80 if err != nil {
81 return nil, err
82 }
83 case SeemsFileURL(locator):
84 if tmpl.Name == "" {
85 tmpl.Name, err = InstNameFromURL(locator)
86 if err != nil {
87 return nil, err
88 }
89 }
90 logrus.Debugf("interpreting argument %#q as a file URL for instance %#q", locator, tmpl.Name)
91 filePath := strings.TrimPrefix(locator, "file://")
92 if !filepath.IsAbs(filePath) {
93 return nil, fmt.Errorf("file URL %#q is not an absolute path", locator)
94 }
95 r, err := os.Open(filePath)
96 if err != nil {
97 return nil, err
98 }
99 defer r.Close()
100 tmpl.Bytes, err = ioutilx.ReadAtMaximum(r, yBytesLimit)
101 if err != nil {
102 return nil, err
103 }
104 case locator == "-":
105 tmpl.Bytes, err = io.ReadAll(os.Stdin)
106 if err != nil {
107 return nil, fmt.Errorf("unexpected error reading stdin: %w", err)
108 }
109 default:
110 if tmpl.Name == "" {
111 tmpl.Name, err = InstNameFromYAMLPath(locator)
112 if err != nil {
113 return nil, err
114 }
115 }
116 logrus.Debugf("interpreting argument %#q as a file path for instance %#q", locator, tmpl.Name)
117 if locator, err = filepath.Abs(locator); err != nil {
118 return nil, err
119 }
120 tmpl.Locator = locator
121 r, err := os.Open(locator)
122 if err != nil {
123 return nil, err
124 }
125 defer r.Close()
126 tmpl.Bytes, err = ioutilx.ReadAtMaximum(r, yBytesLimit)
127 if err != nil {
128 return nil, err
129 }
130 }
131 // The only reason not to call tmpl.UseAbsLocators() here is that `limactl tmpl copy --verbatim …`
132 // should create an unmodified copy of the template.
133 return tmpl, nil
134}
135
136// Locators with an image file format extension, optionally followed by a compression method.
137// This regex is also used to remove the file format suffix from the instance name.
138var imageURLRegex = regexp.MustCompile(`\.(img|qcow2|raw|iso|ipsw)(\.(gz|xz|bz2|zstd))?$`)
139
140// Image architecture will be guessed based on the presence of arch keywords.
141var archKeywords = map[string]limatype.Arch{
142 "aarch64": limatype.AARCH64,
143 "amd64": limatype.X8664,
144 "arm64": limatype.AARCH64,
145 "armhf": limatype.ARMV7L,
146 "armv7l": limatype.ARMV7L,
147 "ppc64el": limatype.PPC64LE,
148 "ppc64le": limatype.PPC64LE,
149 "riscv64": limatype.RISCV64,
150 "s390x": limatype.S390X,
151 "x86_64": limatype.X8664,
152}
153
154// OS will be guessed based on the presence of OS keywords.
155var osKeywords = map[string]limatype.OS{
156 "FreeBSD": limatype.FREEBSD,
157 "macOS": limatype.DARWIN,
158 ".ipsw": limatype.DARWIN,
159}
160
161// These generic tags will be stripped from an image name before turning it into an instance name.
162var genericTags = []string{
163 "base", // Fedora, Rocky
164 "basic", // FreeBSD
165 "cloud", // Fedora, openSUSE
166 "cloudimg", // Ubuntu, Arch
167 "cloudinit", // Alpine
168 "current", // FreeBSD
169 "daily", // Debian
170 "default", // Gentoo
171 "generic", // Fedora
172 "genericcloud", // CentOS, Debian, Rocky, Alma
173 "kvm", // Oracle
174 "latest", // Gentoo, CentOS, Rocky, Alma
175 "linux", // Arch
176 "minimal", // openSUSE
177 "openstack", // Gentoo
178 "release", // FreeBSD
179 "restore", // macOS
180 "server", // Ubuntu
181 "std", // Alpine-Lima
182 "stream", // CentOS
183 "uefi", // Alpine
184 "vm", // openSUSE
185}
186
187// imageTemplate checks if the locator specifies an image URL.
188// It will create a minimal template with the image URL and arch derived from the image name
189// and also set the default instance name to the image name, but stripped of generic tags.
190func imageTemplate(tmpl *Template, locator string) bool {
191 if !imageURLRegex.MatchString(locator) {
192 return false
193 }
194
195 var imageOS limatype.OS
196 for keyword, os := range osKeywords {
197 pattern := fmt.Sprintf(`(?i)\b%s\b`, keyword)
198 if regexp.MustCompile(pattern).MatchString(locator) {
199 imageOS = os
200 break
201 }
202 }
203 if imageOS == "" {
204 imageOS = limatype.LINUX
205 logrus.Debugf("cannot determine image OS from URL %#q; assuming %#q", locator, imageOS)
206 }
207
208 var imageArch limatype.Arch
209 for keyword, arch := range archKeywords {
210 pattern := fmt.Sprintf(`\b%s\b`, keyword)
211 if regexp.MustCompile(pattern).MatchString(locator) {
212 imageArch = arch
213 break
214 }
215 }
216 if imageArch == "" {
217 if imageOS == limatype.DARWIN {
218 imageArch = limatype.AARCH64
219 // Other architectures were never supported for macOS guests
220 } else {
221 imageArch = limatype.NewArch(runtime.GOARCH)
222 logrus.Warnf("cannot determine image arch from URL %#q; assuming %#q", locator, imageArch)
223 }
224 }
225
226 template := `os: %q
227arch: %q
228images:
229- location: %q
230 arch: %q
231`
232 tmpl.Bytes = fmt.Appendf(nil, template, imageOS, imageArch, locator, imageArch)
233 if tmpl.Name == "" {
234 tmpl.Name = InstNameFromImageURL(locator, imageArch)
235 }
236 return true
237}
238
239func InstNameFromImageURL(locator, imageArch string) string {
240 // We intentionally call both path.Base and filepath.Base in case we are running on Windows.
241 name := strings.ToLower(filepath.Base(path.Base(locator)))
242 // Remove file format and compression file types.
243 name = imageURLRegex.ReplaceAllString(name, "")
244 // The Alpine "nocloud_" prefix does not fit the genericTags pattern.
245 name = strings.TrimPrefix(name, "nocloud_")
246 for _, tag := range genericTags {
247 re := regexp.MustCompile(fmt.Sprintf(`[-_.]%s\b`, tag))
248 name = re.ReplaceAllString(name, "")
249 }
250 // The "UniversalMac" prefix does not fit the genericTags pattern and also should be normalized to "macos".
251 // "UniversalMac_15.6.1_24G90_Restore.ipsw"
252 name = strings.Replace(name, "universalmac_", "macos-", 1)
253 // ARM64 FreeBSD images have both "arm64" and "aarch64" in their names.
254 // "FreeBSD-16.0-CURRENT-arm64-aarch64-BASIC-CLOUDINIT-ufs.qcow2.xz"
255 name = strings.Replace(name, "arm64-aarch64", "arm64", 1)
256 // Remove imageArch as well if it is the native arch.
257 if limatype.IsNativeArch(imageArch) {
258 re := regexp.MustCompile(fmt.Sprintf(`[-_.]%s\b`, imageArch))
259 name = re.ReplaceAllString(name, "")
260 }
261 // Remove timestamps from name: 8 digit date, optionally followed by
262 // a delimiter and one or more digits before a word boundary.
263 name = regexp.MustCompile(`[-_.]20\d{6}([-_.]\d+)?\b`).ReplaceAllString(name, "")
264 // Normalize archlinux name
265 name = regexp.MustCompile(`^arch\b`).ReplaceAllString(name, "archlinux")
266 // Remove redundant major version, e.g. "rocky-8-8.10" becomes "rocky-8.10".
267 // Unfortunately regexp doesn't support back references, so we have to
268 // check manually if both numbers are the same.
269 re := regexp.MustCompile(`-(\d+)-(\d+)\.`)
270 name = re.ReplaceAllStringFunc(name, func(match string) string {
271 submatch := re.FindStringSubmatch(match)
272 if submatch[1] == submatch[2] {
273 // Replace -X-X. with -X.
274 return "-" + submatch[1] + "."
275 }
276 return match
277 })
278 // Normalize "macos-15.6.1_24g90" to "macos-15.6.1"
279 name = regexp.MustCompile(`^(macos-[\d.]+)[-_].*$`).ReplaceAllString(name, "$1")
280 return name
281}
282
283// SeemsTemplateURL returns true if the arg is a URL using the template scheme.
284// When it returns true, it also returns the template name.
285func SeemsTemplateURL(arg string) (isTemplate bool, templateName string) {
286 u, err := url.Parse(arg)
287 if err != nil {
288 return false, ""
289 }
290 if u.Scheme == "template" {
291 if u.Opaque == "" {
292 return true, path.Join(u.Host, u.Path)
293 }
294 return true, u.Opaque
295 }
296 return false, ""
297}
298
299// SeemsHTTPURL returns true if the arg is a URL using the http or https scheme.
300func SeemsHTTPURL(arg string) bool {
301 u, err := url.Parse(arg)
302 if err != nil {
303 return false
304 }
305 if u.Scheme != "http" && u.Scheme != "https" {
306 return false
307 }
308 return true
309}
310
311// SeemsFileURL returns true if the arg is a URL using the file scheme.
312func SeemsFileURL(arg string) bool {
313 u, err := url.Parse(arg)
314 if err != nil {
315 return false
316 }
317 return u.Scheme == "file"
318}
319
320func InstNameFromURL(urlStr string) (string, error) {
321 u, err := url.Parse(urlStr)
322 if err != nil {
323 return "", err
324 }
325 return InstNameFromYAMLPath(path.Base(u.Path))
326}
327
328func InstNameFromYAMLPath(yamlPath string) (string, error) {
329 s := strings.ToLower(filepath.Base(yamlPath))
330 s = strings.TrimSuffix(strings.TrimSuffix(s, ".yml"), ".yaml")
331 // "." is allowed in instance names, but replaced to "-" for hostnames.
332 // e.g., yaml: "ubuntu-24.04.yaml" , instance name: "ubuntu-24.04", hostname: "lima-ubuntu-24-04"
333 if err := identifiers.Validate(s); err != nil {
334 return "", fmt.Errorf("filename %#q is invalid: %w", yamlPath, err)
335 }
336 return s, nil
337}
338
339func transformCustomURL(ctx context.Context, locator string) (string, error) {
340 u, err := url.Parse(locator)
341 if err != nil || len(u.Scheme) <= 1 {
342 return locator, nil
343 }
344
345 if u.Scheme == "template" {
346 if u.Opaque != "" {
347 return locator, nil
348 }
349 // Fix malformed "template:" URLs.
350 newLocator := "template:" + path.Join(u.Host, u.Path)
351 logrus.Warnf("Template locator %#q should be written %#q since Lima v2.0", locator, newLocator)
352 return newLocator, nil
353 }
354
355 if u.Scheme == "github" {
356 return transformGitHubURL(ctx, u.Opaque)
357 }
358
359 plugin, err := plugins.Find("url-" + u.Scheme)
360 if err != nil {
361 return "", err
362 }
363 if plugin == nil {
364 return locator, nil
365 }
366
367 currentPath := os.Getenv("PATH")
368 defer os.Setenv("PATH", currentPath)
369 err = plugins.UpdatePath()
370 if err != nil {
371 return "", err
372 }
373
374 cmd := exec.CommandContext(ctx, plugin.Path, strings.TrimPrefix(u.String(), u.Scheme+":"))
375 cmd.Env = os.Environ()
376
377 stdout, err := cmd.Output()
378 if err != nil {
379 if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
380 stderrMsg := string(exitErr.Stderr)
381 if stderrMsg != "" {
382 return "", fmt.Errorf("command %#q failed: %s", cmd.String(), strings.TrimSpace(stderrMsg))
383 }
384 }
385 return "", fmt.Errorf("command %#q failed: %w", cmd.String(), err)
386 }
387 return strings.TrimSpace(string(stdout)), nil
388}
389
390func TransformCustomURL(ctx context.Context, locator string) (string, error) {
391 seen := make(map[string]bool)
392 origLocator := locator
393 githubSchemeDetected := false
394
395 for !seen[locator] {
396 seen[locator] = true
397 if strings.HasPrefix(locator, "github:") {
398 githubSchemeDetected = true
399 }
400 newLocator, err := transformCustomURL(ctx, locator)
401 if err != nil {
402 return "", err
403 }
404 if newLocator == locator {
405 if githubSchemeDetected {
406 logrus.Warn("The github: scheme is still EXPERIMENTAL")
407 }
408 return newLocator, nil
409 }
410 logrus.Debugf("Locator %#q replaced with %#q", locator, newLocator)
411 locator = newLocator
412 }
413 return "", fmt.Errorf("custom locator %#q has a redirect loop", origLocator)
414}