| 1 | |
| 2 | |
| 3 | |
| 4 | package limatmpl |
| 5 | |
| 6 | import ( |
| 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 | |
| 30 | const yBytesLimit = 4 * 1024 * 1024 |
| 31 | |
| 32 | func 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 | |
| 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 | |
| 132 | |
| 133 | return tmpl, nil |
| 134 | } |
| 135 | |
| 136 | |
| 137 | |
| 138 | var imageURLRegex = regexp.MustCompile(`\.(img|qcow2|raw|iso|ipsw)(\.(gz|xz|bz2|zstd))?$`) |
| 139 | |
| 140 | |
| 141 | var 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 | |
| 155 | var osKeywords = map[string]limatype.OS{ |
| 156 | "FreeBSD": limatype.FREEBSD, |
| 157 | "macOS": limatype.DARWIN, |
| 158 | ".ipsw": limatype.DARWIN, |
| 159 | } |
| 160 | |
| 161 | |
| 162 | var genericTags = []string{ |
| 163 | "base", |
| 164 | "basic", |
| 165 | "cloud", |
| 166 | "cloudimg", |
| 167 | "cloudinit", |
| 168 | "current", |
| 169 | "daily", |
| 170 | "default", |
| 171 | "generic", |
| 172 | "genericcloud", |
| 173 | "kvm", |
| 174 | "latest", |
| 175 | "linux", |
| 176 | "minimal", |
| 177 | "openstack", |
| 178 | "release", |
| 179 | "restore", |
| 180 | "server", |
| 181 | "std", |
| 182 | "stream", |
| 183 | "uefi", |
| 184 | "vm", |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | |
| 190 | func 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 | |
| 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 |
| 227 | arch: %q |
| 228 | images: |
| 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 | |
| 239 | func InstNameFromImageURL(locator, imageArch string) string { |
| 240 | |
| 241 | name := strings.ToLower(filepath.Base(path.Base(locator))) |
| 242 | |
| 243 | name = imageURLRegex.ReplaceAllString(name, "") |
| 244 | |
| 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 | |
| 251 | |
| 252 | name = strings.Replace(name, "universalmac_", "macos-", 1) |
| 253 | |
| 254 | |
| 255 | name = strings.Replace(name, "arm64-aarch64", "arm64", 1) |
| 256 | |
| 257 | if limatype.IsNativeArch(imageArch) { |
| 258 | re := regexp.MustCompile(fmt.Sprintf(`[-_.]%s\b`, imageArch)) |
| 259 | name = re.ReplaceAllString(name, "") |
| 260 | } |
| 261 | |
| 262 | |
| 263 | name = regexp.MustCompile(`[-_.]20\d{6}([-_.]\d+)?\b`).ReplaceAllString(name, "") |
| 264 | |
| 265 | name = regexp.MustCompile(`^arch\b`).ReplaceAllString(name, "archlinux") |
| 266 | |
| 267 | |
| 268 | |
| 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 | |
| 274 | return "-" + submatch[1] + "." |
| 275 | } |
| 276 | return match |
| 277 | }) |
| 278 | |
| 279 | name = regexp.MustCompile(`^(macos-[\d.]+)[-_].*$`).ReplaceAllString(name, "$1") |
| 280 | return name |
| 281 | } |
| 282 | |
| 283 | |
| 284 | |
| 285 | func 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 | |
| 300 | func 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 | |
| 312 | func 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 | |
| 320 | func 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 | |
| 328 | func InstNameFromYAMLPath(yamlPath string) (string, error) { |
| 329 | s := strings.ToLower(filepath.Base(yamlPath)) |
| 330 | s = strings.TrimSuffix(strings.TrimSuffix(s, ".yml"), ".yaml") |
| 331 | |
| 332 | |
| 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 | |
| 339 | func 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 | |
| 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 | |
| 390 | func 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 | } |