跳到主要内容

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

浏览文件

defaults.go

1117 行 · 31.6 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package limayaml
5
6import (
7 "bytes"
8 "context"
9 "crypto/sha256"
10 _ "embed"
11 "errors"
12 "fmt"
13 "maps"
14 "net"
15 "os"
16 "os/user"
17 "path/filepath"
18 "runtime"
19 "slices"
20 "strconv"
21 "strings"
22 "text/template"
23
24 "github.com/docker/go-units"
25 "github.com/goccy/go-yaml"
26 "github.com/pbnjay/memory"
27 "github.com/sirupsen/logrus"
28
29 "github.com/lima-vm/lima/v2/pkg/fsutil"
30 "github.com/lima-vm/lima/v2/pkg/instance/hostname"
31 "github.com/lima-vm/lima/v2/pkg/limatype"
32 "github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
33 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
34 "github.com/lima-vm/lima/v2/pkg/localpathutil"
35 . "github.com/lima-vm/lima/v2/pkg/must"
36 "github.com/lima-vm/lima/v2/pkg/networks"
37 "github.com/lima-vm/lima/v2/pkg/osutil"
38 "github.com/lima-vm/lima/v2/pkg/version"
39)
40
41const (
42 // Default9pSecurityModel is "none" for supporting symlinks
43 // https://gitlab.com/qemu-project/qemu/-/issues/173
44 Default9pSecurityModel string = "none"
45 Default9pProtocolVersion string = "9p2000.L"
46 Default9pMsize string = "128KiB"
47 Default9pCacheForRO string = "fscache"
48 Default9pCacheForRW string = "mmap"
49
50 DefaultVirtiofsQueueSize int = 1024
51)
52
53var (
54 IPv4loopback1 = net.IPv4(127, 0, 0, 1)
55
56 userHomeDir = Must(os.UserHomeDir())
57 currentUser = Must(user.Current())
58)
59
60//go:embed containerd.yaml
61var defaultContainerdYAML []byte
62
63type ContainerdYAML struct {
64 Archives []limatype.File
65}
66
67func defaultContainerdArchives() []limatype.File {
68 var containerd ContainerdYAML
69 err := yaml.UnmarshalWithOptions(defaultContainerdYAML, &containerd, yaml.Strict())
70 if err != nil {
71 panic(fmt.Errorf("failed to unmarshal as YAML: %w", err))
72 }
73 return containerd.Archives
74}
75
76// FirstUsernetIndex gets the index of first usernet network under l.Network[]. Returns -1 if no usernet network found.
77func FirstUsernetIndex(l *limatype.LimaYAML) int {
78 return slices.IndexFunc(l.Networks, func(network limatype.Network) bool { return networks.IsUsernet(network.Lima) })
79}
80
81// HostResolverEnabled returns whether the host resolver is enabled.
82// The default value depends on the driver and is filled in the driver-specific FillDefault().
83// A nil value is treated as true to keep HostResolver.Enabled true for drivers which do not fill the field.
84
85func HostResolverEnabled(l *limatype.LimaYAML) bool {
86 return l.HostResolver.Enabled == nil || *l.HostResolver.Enabled
87}
88
89func MACAddress(uniqueID string) string {
90 sha := sha256.Sum256([]byte(osutil.MachineID() + uniqueID))
91 // "5" is the magic number in the Lima ecosystem.
92 // (Visit https://en.wiktionary.org/wiki/lima and Command-F "five")
93 //
94 // But the second hex number is changed to 2 to satisfy the convention for
95 // local MAC addresses (https://en.wikipedia.org/wiki/MAC_address#Ranges_of_group_and_locally_administered_addresses)
96 //
97 // See also https://gitlab.com/wireshark/wireshark/-/blob/release-4.0/manuf to confirm the uniqueness of this prefix.
98 hw := append(net.HardwareAddr{0x52, 0x55, 0x55}, sha[0:3]...)
99 return hw.String()
100}
101
102// MountTag generates a stable mount tag from location and mountPoint.
103// Both paths are hashed to handle the same location mounted to multiple mount points.
104func MountTag(location, mountPoint string) string {
105 sha := sha256.Sum256([]byte(location + ":" + mountPoint))
106 return fmt.Sprintf("lima-%x", sha[0:8])
107}
108
109func defaultCPUs() int {
110 const x = 4
111 if hostCPUs := runtime.NumCPU(); hostCPUs < x {
112 return hostCPUs
113 }
114 return x
115}
116
117func defaultMemory() uint64 {
118 const x uint64 = 4 * 1024 * 1024 * 1024
119 if halfOfHostMemory := memory.TotalMemory() / 2; halfOfHostMemory < x {
120 return halfOfHostMemory
121 }
122 return x
123}
124
125func defaultMemoryAsString() string {
126 return units.BytesSize(float64(defaultMemory()))
127}
128
129func defaultDiskSizeAsString() string {
130 // currently just hardcoded
131 return "100GiB"
132}
133
134func defaultGuestInstallPrefix() string {
135 return "/usr/local"
136}
137
138// FillDefault updates undefined fields in y with defaults from d (or built-in default), and overwrites with values from o.
139// Both d and o may be empty.
140//
141// Maps (`Env`) are being merged: first populated from d, overwritten by y, and again overwritten by o.
142// Slices (e.g. `Mounts`, `Provision`) are appended, starting with o, followed by y, and finally d. This
143// makes sure o takes priority over y over d, in cases it matters (e.g. `PortForwards`, where the first
144// matching rule terminates the search).
145//
146// Exceptions:
147// - Mounts are appended in d, y, o order, but "merged" when the Location matches a previous entry;
148// the highest priority Writable setting wins.
149// - Networks are appended in d, y, o order
150// - DNS are picked from the highest priority where DNS is not empty.
151// - CACertificates Files and Certs are uniquely appended in d, y, o order
152func FillDefault(ctx context.Context, y, d, o *limatype.LimaYAML, filePath string, warn bool) {
153 instDir := filepath.Dir(filePath)
154
155 existingLimaVersion := ExistingLimaVersion(instDir)
156
157 // OS has to be resolved before User
158 if y.OS == nil {
159 y.OS = d.OS
160 }
161 if o.OS != nil {
162 y.OS = o.OS
163 }
164 y.OS = new(ResolveOS(y.OS))
165
166 if y.User.Name == nil {
167 y.User.Name = d.User.Name
168 }
169 if y.User.Comment == nil {
170 y.User.Comment = d.User.Comment
171 }
172 if y.User.Home == nil {
173 y.User.Home = d.User.Home
174 }
175 if y.User.Shell == nil {
176 y.User.Shell = d.User.Shell
177 }
178 if y.User.UID == nil {
179 y.User.UID = d.User.UID
180 }
181 if y.User.PasswordlessSudo == nil {
182 y.User.PasswordlessSudo = d.User.PasswordlessSudo
183 }
184 if o.User.Name != nil {
185 y.User.Name = o.User.Name
186 }
187 if o.User.Comment != nil {
188 y.User.Comment = o.User.Comment
189 }
190 if o.User.Home != nil {
191 y.User.Home = o.User.Home
192 }
193 if o.User.Shell != nil {
194 y.User.Shell = o.User.Shell
195 }
196 if o.User.UID != nil {
197 y.User.UID = o.User.UID
198 }
199 if o.User.PasswordlessSudo != nil {
200 y.User.PasswordlessSudo = o.User.PasswordlessSudo
201 }
202 if y.User.Name == nil {
203 y.User.Name = new(osutil.LimaUser(ctx, existingLimaVersion, warn, y.OS).Username)
204 warn = false
205 }
206 if y.User.Comment == nil {
207 y.User.Comment = new(osutil.LimaUser(ctx, existingLimaVersion, warn, y.OS).Name)
208 warn = false
209 }
210 if y.User.Home == nil {
211 y.User.Home = new(osutil.LimaUser(ctx, existingLimaVersion, warn, y.OS).HomeDir)
212 warn = false
213 }
214 if y.User.Shell == nil {
215 switch *y.OS {
216 case limatype.FREEBSD:
217 y.User.Shell = new("/bin/sh")
218 case limatype.DARWIN:
219 y.User.Shell = new("/bin/zsh")
220 case limatype.WINDOWS:
221 y.User.Shell = new("cmd.exe")
222 default:
223 y.User.Shell = new("/bin/bash")
224 }
225 }
226 if y.User.UID == nil {
227 uidString := osutil.LimaUser(ctx, existingLimaVersion, warn, y.OS).Uid
228 if uid, err := strconv.ParseUint(uidString, 10, 32); err == nil {
229 y.User.UID = new(uint32(uid))
230 } else {
231 // This should never happen; LimaUser() makes sure that .Uid is numeric
232 logrus.WithError(err).Warnf("Can't parse `user.uid` %#q", uidString)
233 y.User.UID = new(uint32(1000))
234 }
235 // warn = false
236 }
237
238 // fallback to nopasswd
239 if y.User.PasswordlessSudo == nil {
240 if y.OS != nil && *y.OS == limatype.DARWIN {
241 y.User.PasswordlessSudo = new(false)
242 } else {
243 y.User.PasswordlessSudo = new(true)
244 }
245 }
246 if out, err := executeGuestTemplate(*y.User.Home, instDir, y.User, y.Param); err == nil {
247 y.User.Home = new(out.String())
248 } else {
249 logrus.WithError(err).Warnf("Couldn't process `user.home` value %#q as a template", *y.User.Home)
250 }
251
252 if y.VMType == nil {
253 y.VMType = d.VMType
254 }
255 if o.VMType != nil {
256 y.VMType = o.VMType
257 }
258
259 if y.Arch == nil {
260 y.Arch = d.Arch
261 }
262 if o.Arch != nil {
263 y.Arch = o.Arch
264 }
265 y.Arch = new(ResolveArch(y.Arch))
266
267 y.Images = slices.Concat(o.Images, y.Images, d.Images)
268 for i := range y.Images {
269 img := &y.Images[i]
270 if img.Arch == "" {
271 img.Arch = *y.Arch
272 }
273 if img.Kernel != nil && img.Kernel.Arch == "" {
274 img.Kernel.Arch = img.Arch
275 }
276 if img.Initrd != nil && img.Initrd.Arch == "" {
277 img.Initrd.Arch = img.Arch
278 }
279 }
280
281 if y.CPUs == nil {
282 y.CPUs = d.CPUs
283 }
284 if o.CPUs != nil {
285 y.CPUs = o.CPUs
286 }
287 if y.CPUs == nil || *y.CPUs == 0 {
288 y.CPUs = new(defaultCPUs())
289 }
290
291 if y.Memory == nil {
292 y.Memory = d.Memory
293 }
294 if o.Memory != nil {
295 y.Memory = o.Memory
296 }
297 if y.Memory == nil || *y.Memory == "" {
298 y.Memory = new(defaultMemoryAsString())
299 }
300
301 if y.Disk == nil {
302 y.Disk = d.Disk
303 }
304 if o.Disk != nil {
305 y.Disk = o.Disk
306 }
307 if y.Disk == nil || *y.Disk == "" {
308 y.Disk = new(defaultDiskSizeAsString())
309 }
310
311 y.AdditionalDisks = slices.Concat(o.AdditionalDisks, y.AdditionalDisks, d.AdditionalDisks)
312
313 if y.Audio.Device == nil {
314 y.Audio.Device = d.Audio.Device
315 }
316 if o.Audio.Device != nil {
317 y.Audio.Device = o.Audio.Device
318 }
319 if y.Audio.Device == nil {
320 y.Audio.Device = new("")
321 }
322
323 if y.Audio.Interface == nil {
324 y.Audio.Interface = d.Audio.Interface
325 }
326 if o.Audio.Interface != nil {
327 y.Audio.Interface = o.Audio.Interface
328 }
329 if y.Audio.Interface == nil {
330 y.Audio.Interface = new("")
331 }
332
333 if y.Audio.Microphone == nil {
334 y.Audio.Microphone = d.Audio.Microphone
335 }
336 if o.Audio.Microphone != nil {
337 y.Audio.Microphone = o.Audio.Microphone
338 }
339 if y.Audio.Microphone == nil {
340 y.Audio.Microphone = new(false)
341 }
342
343 if y.Video.Display == nil {
344 y.Video.Display = d.Video.Display
345 }
346 if o.Video.Display != nil {
347 y.Video.Display = o.Video.Display
348 }
349 if y.Video.Display == nil || *y.Video.Display == "" {
350 y.Video.Display = new("none")
351 }
352
353 if y.Video.VNC.Display == nil {
354 y.Video.VNC.Display = d.Video.VNC.Display
355 }
356 if o.Video.VNC.Display != nil {
357 y.Video.VNC.Display = o.Video.VNC.Display
358 }
359
360 if y.Firmware.LegacyBIOS == nil {
361 y.Firmware.LegacyBIOS = d.Firmware.LegacyBIOS
362 }
363 if o.Firmware.LegacyBIOS != nil {
364 y.Firmware.LegacyBIOS = o.Firmware.LegacyBIOS
365 }
366 if y.Firmware.LegacyBIOS == nil {
367 y.Firmware.LegacyBIOS = new(false)
368 }
369
370 y.Firmware.Images = slices.Concat(o.Firmware.Images, y.Firmware.Images, d.Firmware.Images)
371 for i := range y.Firmware.Images {
372 f := &y.Firmware.Images[i]
373 if f.Arch == "" {
374 f.Arch = *y.Arch
375 }
376 }
377
378 if y.TimeZone == nil {
379 y.TimeZone = d.TimeZone
380 }
381 if o.TimeZone != nil {
382 y.TimeZone = o.TimeZone
383 }
384 if y.TimeZone == nil {
385 y.TimeZone = new(hostTimeZone())
386 }
387
388 if y.SSH.LocalPort == nil {
389 y.SSH.LocalPort = d.SSH.LocalPort
390 }
391 if o.SSH.LocalPort != nil {
392 y.SSH.LocalPort = o.SSH.LocalPort
393 }
394 if y.SSH.LocalPort == nil {
395 // y.SSH.LocalPort value is not filled here (filled by the hostagent)
396 y.SSH.LocalPort = new(0)
397 }
398 if y.SSH.LoadDotSSHPubKeys == nil {
399 y.SSH.LoadDotSSHPubKeys = d.SSH.LoadDotSSHPubKeys
400 }
401 if o.SSH.LoadDotSSHPubKeys != nil {
402 y.SSH.LoadDotSSHPubKeys = o.SSH.LoadDotSSHPubKeys
403 }
404 if y.SSH.LoadDotSSHPubKeys == nil {
405 y.SSH.LoadDotSSHPubKeys = new(false) // was true before Lima v1.0
406 }
407
408 if y.SSH.ForwardAgent == nil {
409 y.SSH.ForwardAgent = d.SSH.ForwardAgent
410 }
411 if o.SSH.ForwardAgent != nil {
412 y.SSH.ForwardAgent = o.SSH.ForwardAgent
413 }
414 if y.SSH.ForwardAgent == nil {
415 y.SSH.ForwardAgent = new(false)
416 }
417
418 if y.SSH.ForwardX11 == nil {
419 y.SSH.ForwardX11 = d.SSH.ForwardX11
420 }
421 if o.SSH.ForwardX11 != nil {
422 y.SSH.ForwardX11 = o.SSH.ForwardX11
423 }
424 if y.SSH.ForwardX11 == nil {
425 y.SSH.ForwardX11 = new(false)
426 }
427
428 if y.SSH.ForwardX11Trusted == nil {
429 y.SSH.ForwardX11Trusted = d.SSH.ForwardX11Trusted
430 }
431 if o.SSH.ForwardX11Trusted != nil {
432 y.SSH.ForwardX11Trusted = o.SSH.ForwardX11Trusted
433 }
434 if y.SSH.ForwardX11Trusted == nil {
435 y.SSH.ForwardX11Trusted = new(false)
436 }
437
438 if y.SSH.OverVsock == nil {
439 y.SSH.OverVsock = d.SSH.OverVsock
440 }
441 if o.SSH.OverVsock != nil {
442 y.SSH.OverVsock = o.SSH.OverVsock
443 }
444 // y.SSH.OverVsock default value depends on the driver; filled in driver-specific FillDefault()
445
446 // The deprecated environment variable LIMA_SSH_OVER_VSOCK takes precedence over .ssh.overVsock
447 if envVar := os.Getenv("LIMA_SSH_OVER_VSOCK"); envVar != "" {
448 logrus.Warn("The environment variable LIMA_SSH_OVER_VSOCK is deprecated in favor of the YAML field .ssh.overVsock")
449 b, err := strconv.ParseBool(envVar)
450 if err != nil {
451 logrus.WithError(err).Warnf("invalid LIMA_SSH_OVER_VSOCK value %#q", envVar)
452 } else {
453 logrus.Debugf("Overriding ssh.overVsock from %v to %v via LIMA_SSH_OVER_VSOCK", y.SSH.OverVsock, &b)
454 y.SSH.OverVsock = new(b)
455 }
456 }
457
458 hosts := make(map[string]string)
459 // Values can be either names or IP addresses. Name values are canonicalized in the hostResolver.
460 maps.Copy(hosts, d.HostResolver.Hosts)
461 maps.Copy(hosts, y.HostResolver.Hosts)
462 maps.Copy(hosts, o.HostResolver.Hosts)
463 y.HostResolver.Hosts = hosts
464
465 y.Provision = slices.Concat(o.Provision, y.Provision, d.Provision)
466 for i := range y.Provision {
467 provision := &y.Provision[i]
468 if provision.Mode == "" {
469 provision.Mode = limatype.ProvisionModeSystem
470 }
471 if provision.Mode == limatype.ProvisionModeDependency && provision.SkipDefaultDependencyResolution == nil {
472 provision.SkipDefaultDependencyResolution = new(false)
473 }
474 if provision.Mode == limatype.ProvisionModeData {
475 if provision.Content == nil {
476 provision.Content = new("")
477 } else {
478 if out, err := executeGuestTemplate(*provision.Content, instDir, y.User, y.Param); err == nil {
479 provision.Content = new(out.String())
480 } else {
481 logrus.WithError(err).Warnf("Couldn't process data content %#q as a template", *provision.Content)
482 }
483 }
484 if provision.Overwrite == nil {
485 provision.Overwrite = new(true)
486 }
487 }
488 if provision.Mode == limatype.ProvisionModeYQ {
489 if provision.Expression != nil {
490 if out, err := executeGuestTemplate(*provision.Expression, instDir, y.User, y.Param); err == nil {
491 provision.Expression = new(out.String())
492 } else {
493 logrus.WithError(err).Warnf("Couldn't process expression %#q as a template", *provision.Expression)
494 }
495 }
496 if provision.Format == nil {
497 provision.Format = new("auto")
498 }
499 }
500 if provision.Mode == limatype.ProvisionModeData || provision.Mode == limatype.ProvisionModeYQ {
501 if provision.Owner == nil {
502 switch *y.OS {
503 case limatype.DARWIN, limatype.FREEBSD:
504 provision.Owner = new("root:wheel")
505 default:
506 provision.Owner = new("root:root")
507 }
508 } else {
509 if out, err := executeGuestTemplate(*provision.Owner, instDir, y.User, y.Param); err == nil {
510 provision.Owner = new(out.String())
511 } else {
512 logrus.WithError(err).Warnf("Couldn't process owner %#q as a template", *provision.Owner)
513 }
514 }
515 // Path is required; validation will throw an error when it is nil
516 if provision.Path != nil {
517 if out, err := executeGuestTemplate(*provision.Path, instDir, y.User, y.Param); err == nil {
518 provision.Path = new(out.String())
519 } else {
520 logrus.WithError(err).Warnf("Couldn't process path %#q as a template", *provision.Path)
521 }
522 }
523 if provision.Permissions == nil {
524 provision.Permissions = new("644")
525 }
526 }
527 if provision.Script == nil {
528 provision.Script = new("")
529 }
530 if *provision.Script != "" {
531 if out, err := executeGuestTemplate(*provision.Script, instDir, y.User, y.Param); err == nil {
532 *provision.Script = out.String()
533 } else {
534 logrus.WithError(err).Warnf("Couldn't process provisioning script %#q as a template", *provision.Script)
535 }
536 }
537 }
538
539 if y.GuestInstallPrefix == nil {
540 y.GuestInstallPrefix = d.GuestInstallPrefix
541 }
542 if o.GuestInstallPrefix != nil {
543 y.GuestInstallPrefix = o.GuestInstallPrefix
544 }
545 if y.GuestInstallPrefix == nil {
546 y.GuestInstallPrefix = new(defaultGuestInstallPrefix())
547 }
548
549 if y.UpgradePackages == nil {
550 y.UpgradePackages = d.UpgradePackages
551 }
552 if o.UpgradePackages != nil {
553 y.UpgradePackages = o.UpgradePackages
554 }
555 if y.UpgradePackages == nil {
556 y.UpgradePackages = new(false)
557 }
558
559 if y.Containerd.System == nil {
560 y.Containerd.System = d.Containerd.System
561 }
562 if o.Containerd.System != nil {
563 y.Containerd.System = o.Containerd.System
564 }
565 if y.Containerd.System == nil {
566 y.Containerd.System = new(false)
567 }
568 if y.Containerd.User == nil {
569 y.Containerd.User = d.Containerd.User
570 }
571 if o.Containerd.User != nil {
572 y.Containerd.User = o.Containerd.User
573 }
574 if y.Containerd.User == nil {
575 // nerdctl is a Linux-only container runtime; only default
576 // containerd.user=true when the guest OS is Linux. Otherwise
577 // downloading the nerdctl archive (~250 MiB) is wasted I/O.
578 if *y.OS == limatype.LINUX {
579 switch *y.Arch {
580 case limatype.X8664, limatype.AARCH64:
581 y.Containerd.User = new(true)
582 default:
583 y.Containerd.User = new(false)
584 }
585 } else {
586 y.Containerd.User = new(false)
587 }
588 }
589
590 y.Containerd.Archives = slices.Concat(o.Containerd.Archives, y.Containerd.Archives, d.Containerd.Archives)
591 if len(y.Containerd.Archives) == 0 {
592 y.Containerd.Archives = defaultContainerdArchives()
593 }
594 for i := range y.Containerd.Archives {
595 f := &y.Containerd.Archives[i]
596 if f.Arch == "" {
597 f.Arch = *y.Arch
598 }
599 }
600
601 y.Probes = slices.Concat(o.Probes, y.Probes, d.Probes)
602 for i := range y.Probes {
603 probe := &y.Probes[i]
604 if probe.Mode == "" {
605 probe.Mode = limatype.ProbeModeReadiness
606 }
607 if probe.Description == "" {
608 probe.Description = fmt.Sprintf("user probe %d/%d", i+1, len(y.Probes))
609 }
610 if probe.Script == nil {
611 probe.Script = new("")
612 }
613 if out, err := executeGuestTemplate(*probe.Script, instDir, y.User, y.Param); err == nil {
614 probe.Script = new(out.String())
615 } else {
616 logrus.WithError(err).Warnf("Couldn't process probing script %#q as a template", *probe.Script)
617 }
618 }
619
620 y.PortForwards = slices.Concat(o.PortForwards, y.PortForwards, d.PortForwards)
621 for i := range y.PortForwards {
622 FillPortForwardDefaults(&y.PortForwards[i], instDir, y.User, y.Param)
623 // After defaults processing the singular HostPort and GuestPort values should not be used again.
624 }
625
626 y.CopyToHost = slices.Concat(o.CopyToHost, y.CopyToHost, d.CopyToHost)
627 for i := range y.CopyToHost {
628 FillCopyToHostDefaults(&y.CopyToHost[i], instDir, y.User, y.Param)
629 }
630
631 if y.HostResolver.Enabled == nil {
632 y.HostResolver.Enabled = d.HostResolver.Enabled
633 }
634 if o.HostResolver.Enabled != nil {
635 y.HostResolver.Enabled = o.HostResolver.Enabled
636 }
637 // y.HostResolver.Enabled default value depends on the driver; filled in driver-specific FillDefault()
638
639 if y.HostResolver.IPv6 == nil {
640 y.HostResolver.IPv6 = d.HostResolver.IPv6
641 }
642 if o.HostResolver.IPv6 != nil {
643 y.HostResolver.IPv6 = o.HostResolver.IPv6
644 }
645 if y.HostResolver.IPv6 == nil {
646 y.HostResolver.IPv6 = new(false)
647 }
648
649 if y.PropagateProxyEnv == nil {
650 y.PropagateProxyEnv = d.PropagateProxyEnv
651 }
652 if o.PropagateProxyEnv != nil {
653 y.PropagateProxyEnv = o.PropagateProxyEnv
654 }
655 if y.PropagateProxyEnv == nil {
656 y.PropagateProxyEnv = new(true)
657 }
658
659 networks := make([]limatype.Network, 0, len(d.Networks)+len(y.Networks)+len(o.Networks))
660 iface := make(map[string]int)
661 for _, nw := range slices.Concat(d.Networks, y.Networks, o.Networks) {
662 if i, ok := iface[nw.Interface]; ok {
663 if nw.Socket != "" {
664 networks[i].Socket = nw.Socket
665 networks[i].Lima = ""
666 }
667 if nw.Lima != "" {
668 if nw.Socket != "" {
669 // We can't return an error, so just log it, and prefer `lima` over `socket`
670 logrus.Errorf("Network %#q has both socket=%#q and lima=%#q fields; ignoring socket",
671 nw.Interface, nw.Socket, nw.Lima)
672 }
673 networks[i].Lima = nw.Lima
674 networks[i].Socket = ""
675 }
676 if nw.MACAddress != "" {
677 networks[i].MACAddress = nw.MACAddress
678 }
679 if nw.Metric != nil {
680 networks[i].Metric = nw.Metric
681 }
682 } else {
683 // unnamed network definitions are not combined/overwritten
684 if nw.Interface != "" {
685 iface[nw.Interface] = len(networks)
686 }
687 networks = append(networks, nw)
688 }
689 }
690 y.Networks = networks
691 for i := range y.Networks {
692 nw := &y.Networks[i]
693 if nw.MACAddress == "" {
694 // every interface in every limayaml file must get its own unique MAC address
695 nw.MACAddress = MACAddress(fmt.Sprintf("%s#%d", filePath, i))
696 }
697 if nw.Interface == "" {
698 nw.Interface = "lima" + strconv.Itoa(i)
699 }
700 if nw.Metric == nil {
701 nw.Metric = new(uint32(100))
702 }
703 }
704
705 y.MountTypesUnsupported = slices.Concat(o.MountTypesUnsupported, y.MountTypesUnsupported, d.MountTypesUnsupported)
706
707 // MountType has to be resolved before resolving Mounts
708 if y.MountType == nil {
709 y.MountType = d.MountType
710 }
711 if o.MountType != nil {
712 y.MountType = o.MountType
713 }
714
715 if y.MountInotify == nil {
716 y.MountInotify = d.MountInotify
717 }
718 if o.MountInotify != nil {
719 y.MountInotify = o.MountInotify
720 }
721 if y.MountInotify == nil {
722 y.MountInotify = new(false)
723 }
724
725 // Combine all mounts; highest priority entry determines writable status.
726 // Only works for exact matches; does not normalize case or resolve symlinks.
727 mounts := make([]limatype.Mount, 0, len(d.Mounts)+len(y.Mounts)+len(o.Mounts))
728 mountPoint := make(map[string]int)
729 for _, mount := range slices.Concat(d.Mounts, y.Mounts, o.Mounts) {
730 if out, err := executeHostTemplate(mount.Location, instDir, y.Param); err == nil {
731 mount.Location = filepath.Clean(out.String())
732 } else {
733 logrus.WithError(err).Warnf("Couldn't process mount location %#q as a template", mount.Location)
734 }
735 // Expand a path that begins with `~`. Relative paths are not modified, and rejected by Validate() later.
736 if localpathutil.IsTildePath(mount.Location) {
737 if location, err := localpathutil.Expand(mount.Location); err == nil {
738 mount.Location = location
739 } else {
740 logrus.WithError(err).Warnf("Couldn't expand location %#q", mount.Location)
741 }
742 }
743 if mount.MountPoint == nil {
744 mountLocation := mount.Location
745 if runtime.GOOS == "windows" {
746 var err error
747 mountLocation, err = fsutil.WindowsSubsystemPath(ctx, mountLocation)
748 if err != nil {
749 logrus.WithError(err).Warnf("Couldn't convert location %#q into mount target", mount.Location)
750 }
751 }
752 mount.MountPoint = new(mountLocation)
753 } else {
754 if out, err := executeGuestTemplate(*mount.MountPoint, instDir, y.User, y.Param); err == nil {
755 mount.MountPoint = new(out.String())
756 } else {
757 logrus.WithError(err).Warnf("Couldn't process mount point %#q as a template", *mount.MountPoint)
758 }
759 }
760 if i, ok := mountPoint[*mount.MountPoint]; ok {
761 if mount.SSHFS.Cache != nil {
762 mounts[i].SSHFS.Cache = mount.SSHFS.Cache
763 }
764 if mount.SSHFS.FollowSymlinks != nil {
765 mounts[i].SSHFS.FollowSymlinks = mount.SSHFS.FollowSymlinks
766 }
767 if mount.SSHFS.SFTPDriver != nil {
768 mounts[i].SSHFS.SFTPDriver = mount.SSHFS.SFTPDriver
769 }
770 if mount.SSHFS.ReadonlyNames != nil {
771 mounts[i].SSHFS.ReadonlyNames = mount.SSHFS.ReadonlyNames
772 }
773 if mount.NineP.SecurityModel != nil {
774 mounts[i].NineP.SecurityModel = mount.NineP.SecurityModel
775 }
776 if mount.NineP.ProtocolVersion != nil {
777 mounts[i].NineP.ProtocolVersion = mount.NineP.ProtocolVersion
778 }
779 if mount.NineP.Msize != nil {
780 mounts[i].NineP.Msize = mount.NineP.Msize
781 }
782 if mount.NineP.Cache != nil {
783 mounts[i].NineP.Cache = mount.NineP.Cache
784 }
785 if mount.Virtiofs.QueueSize != nil {
786 mounts[i].Virtiofs.QueueSize = mount.Virtiofs.QueueSize
787 }
788 if mount.Writable != nil {
789 mounts[i].Writable = mount.Writable
790 }
791 if mount.MountPoint != nil {
792 mounts[i].MountPoint = mount.MountPoint
793 }
794 } else {
795 mountPoint[*mount.MountPoint] = len(mounts)
796 mounts = append(mounts, mount)
797 }
798 }
799 y.Mounts = mounts
800
801 for i := range y.Mounts {
802 mount := &y.Mounts[i]
803 if mount.SSHFS.Cache == nil {
804 mount.SSHFS.Cache = new(true)
805 }
806 if mount.SSHFS.FollowSymlinks == nil {
807 mount.SSHFS.FollowSymlinks = new(false)
808 }
809 if mount.SSHFS.SFTPDriver == nil {
810 mount.SSHFS.SFTPDriver = new("")
811 }
812 if mount.NineP.SecurityModel == nil {
813 mounts[i].NineP.SecurityModel = new(Default9pSecurityModel)
814 }
815 if mount.NineP.ProtocolVersion == nil {
816 mounts[i].NineP.ProtocolVersion = new(Default9pProtocolVersion)
817 }
818 if mount.NineP.Msize == nil {
819 mounts[i].NineP.Msize = new(Default9pMsize)
820 }
821 if mount.Writable == nil {
822 mount.Writable = new(false)
823 }
824 if mount.NineP.Cache == nil {
825 if *mount.Writable {
826 mounts[i].NineP.Cache = new(Default9pCacheForRW)
827 } else {
828 mounts[i].NineP.Cache = new(Default9pCacheForRO)
829 }
830 }
831 }
832
833 // Note: DNS lists are not combined; highest priority setting is picked
834 if len(y.DNS) == 0 {
835 y.DNS = d.DNS
836 }
837 if len(o.DNS) > 0 {
838 y.DNS = o.DNS
839 }
840
841 env := make(map[string]string)
842 maps.Copy(env, d.Env)
843 maps.Copy(env, y.Env)
844 maps.Copy(env, o.Env)
845 y.Env = env
846
847 param := make(map[string]string)
848 maps.Copy(param, d.Param)
849 maps.Copy(param, y.Param)
850 maps.Copy(param, o.Param)
851 y.Param = param
852
853 vmOpts := make(limatype.VMOpts)
854 maps.Copy(vmOpts, d.VMOpts)
855 maps.Copy(vmOpts, y.VMOpts)
856 maps.Copy(vmOpts, o.VMOpts)
857 y.VMOpts = vmOpts
858
859 if y.CACertificates.RemoveDefaults == nil {
860 y.CACertificates.RemoveDefaults = d.CACertificates.RemoveDefaults
861 }
862 if o.CACertificates.RemoveDefaults != nil {
863 y.CACertificates.RemoveDefaults = o.CACertificates.RemoveDefaults
864 }
865 if y.CACertificates.RemoveDefaults == nil {
866 y.CACertificates.RemoveDefaults = new(false)
867 }
868
869 y.CACertificates.Files = unique(slices.Concat(d.CACertificates.Files, y.CACertificates.Files, o.CACertificates.Files))
870 y.CACertificates.Certs = unique(slices.Concat(d.CACertificates.Certs, y.CACertificates.Certs, o.CACertificates.Certs))
871
872 if y.NestedVirtualization == nil {
873 y.NestedVirtualization = d.NestedVirtualization
874 }
875 if o.NestedVirtualization != nil {
876 y.NestedVirtualization = o.NestedVirtualization
877 }
878 if y.NestedVirtualization == nil {
879 y.NestedVirtualization = new(false)
880 }
881
882 if y.Plain == nil {
883 y.Plain = d.Plain
884 }
885 if o.Plain != nil {
886 y.Plain = o.Plain
887 }
888 if y.Plain == nil {
889 y.Plain = new(false)
890 }
891
892 if y.TPM == nil {
893 y.TPM = d.TPM
894 }
895 if o.TPM != nil {
896 y.TPM = o.TPM
897 }
898 if y.TPM == nil {
899 y.TPM = new(false)
900 }
901 osOpts := make(limatype.OsOpts)
902 maps.Copy(osOpts, d.OsOpts)
903 maps.Copy(osOpts, y.OsOpts)
904 maps.Copy(osOpts, o.OsOpts)
905 y.OsOpts = osOpts
906
907 fixUpForPlainMode(y)
908}
909
910// ExistingLimaVersion returns the version that created the instance, the empty string
911// for instances created before Lima v0.20 (which have no recorded version), or the
912// current version when the instance doesn't exist yet.
913func ExistingLimaVersion(instDir string) string {
914 if !IsExistingInstanceDir(instDir) {
915 return version.Version
916 }
917
918 limaVersionFile := filepath.Join(instDir, filenames.LimaVersion)
919 b, err := os.ReadFile(limaVersionFile)
920 switch {
921 case err == nil:
922 return strings.TrimSpace(string(b))
923 case errors.Is(err, os.ErrNotExist):
924 // Instances created before Lima v0.20 have no version file. versionutil treats
925 // the empty string as older than any release.
926 return ""
927 default:
928 logrus.WithError(err).Warnf("Failed to read %#q", limaVersionFile)
929 return version.Version
930 }
931}
932
933func fixUpForPlainMode(y *limatype.LimaYAML) {
934 if !*y.Plain {
935 return
936 }
937 deleteNonStaticPortForwards(&y.PortForwards)
938 y.Mounts = nil
939 y.Containerd.System = new(false)
940 y.Containerd.User = new(false)
941 y.TimeZone = new("")
942}
943
944// deleteNonStaticPortForwards removes all non-static port forwarding rules in case of Plain mode.
945func deleteNonStaticPortForwards(portForwards *[]limatype.PortForward) {
946 staticPortForwards := make([]limatype.PortForward, 0, len(*portForwards))
947 for _, rule := range *portForwards {
948 if rule.Static {
949 staticPortForwards = append(staticPortForwards, rule)
950 }
951 }
952 *portForwards = staticPortForwards
953}
954
955func executeGuestTemplate(format, instDir string, user limatype.User, param map[string]string) (bytes.Buffer, error) {
956 tmpl, err := template.New("").Parse(format)
957 if err == nil {
958 name := filepath.Base(instDir)
959 data := map[string]any{
960 "Name": name,
961 "Hostname": hostname.FromInstName(name), // TODO: support customization
962 "UID": *user.UID,
963 "User": *user.Name,
964 "Home": *user.Home,
965 "Param": param,
966 }
967 var out bytes.Buffer
968 err = tmpl.Execute(&out, data)
969 if err == nil {
970 return out, nil
971 }
972 }
973 return bytes.Buffer{}, err
974}
975
976func executeHostTemplate(format, instDir string, param map[string]string) (bytes.Buffer, error) {
977 tmpl, err := template.New("").Parse(format)
978 if err == nil {
979 limaHome, _ := dirnames.LimaDir()
980 globalTempDir := "/tmp"
981 if runtime.GOOS == "windows" {
982 // On Windows the global temp directory "%SystemRoot%\Temp" (normally "C:\Windows\Temp")
983 // is not writable by regular users.
984 globalTempDir = os.TempDir()
985 }
986 data := map[string]any{
987 "Dir": instDir,
988 "Name": filepath.Base(instDir),
989 // TODO: add hostname fields for the host and the guest
990 "UID": currentUser.Uid,
991 "User": currentUser.Username,
992 "Home": userHomeDir,
993 "Param": param,
994 "GlobalTempDir": globalTempDir,
995 "TempDir": os.TempDir(),
996
997 "Instance": filepath.Base(instDir), // DEPRECATED, use `{{.Name}}`
998 "LimaHome": limaHome, // DEPRECATED, use `{{.Dir}}` instead of `{{.LimaHome}}/{{.Instance}}`
999 }
1000 var out bytes.Buffer
1001 err = tmpl.Execute(&out, data)
1002 if err == nil {
1003 return out, nil
1004 }
1005 }
1006 return bytes.Buffer{}, err
1007}
1008
1009func FillPortForwardDefaults(rule *limatype.PortForward, instDir string, user limatype.User, param map[string]string) {
1010 if rule.Proto == "" {
1011 rule.Proto = limatype.ProtoAny
1012 }
1013 if rule.GuestIP == nil {
1014 if rule.GuestIPMustBeZero != nil && *rule.GuestIPMustBeZero {
1015 rule.GuestIP = net.IPv4zero
1016 } else {
1017 rule.GuestIP = IPv4loopback1
1018 }
1019 }
1020 if rule.GuestIPMustBeZero == nil {
1021 rule.GuestIPMustBeZero = new(rule.GuestIP.Equal(net.IPv4zero))
1022 }
1023 if rule.HostIP == nil {
1024 rule.HostIP = IPv4loopback1
1025 }
1026 if rule.GuestPortRange[0] == 0 && rule.GuestPortRange[1] == 0 {
1027 if rule.GuestPort == 0 {
1028 rule.GuestPortRange[0] = 1
1029 rule.GuestPortRange[1] = 65535
1030 } else {
1031 rule.GuestPortRange[0] = rule.GuestPort
1032 rule.GuestPortRange[1] = rule.GuestPort
1033 }
1034 }
1035 if rule.GuestSocket != "" {
1036 if out, err := executeGuestTemplate(rule.GuestSocket, instDir, user, param); err == nil {
1037 rule.GuestSocket = out.String()
1038 } else {
1039 logrus.WithError(err).Warnf("Couldn't process guestSocket %#q as a template", rule.GuestSocket)
1040 }
1041 }
1042 if rule.HostSocket != "" {
1043 if out, err := executeHostTemplate(rule.HostSocket, instDir, param); err == nil {
1044 rule.HostSocket = out.String()
1045 } else {
1046 logrus.WithError(err).Warnf("Couldn't process hostSocket %#q as a template", rule.HostSocket)
1047 }
1048 if !filepath.IsAbs(rule.HostSocket) {
1049 rule.HostSocket = filepath.Join(instDir, filenames.SocketDir, rule.HostSocket)
1050 }
1051 } else if rule.HostPortRange[0] == 0 && rule.HostPortRange[1] == 0 {
1052 if rule.HostPort == 0 {
1053 rule.HostPortRange = rule.GuestPortRange
1054 } else {
1055 rule.HostPortRange[0] = rule.HostPort
1056 rule.HostPortRange[1] = rule.HostPort
1057 }
1058 }
1059}
1060
1061func FillCopyToHostDefaults(rule *limatype.CopyToHost, instDir string, user limatype.User, param map[string]string) {
1062 if rule.GuestFile != "" {
1063 if out, err := executeGuestTemplate(rule.GuestFile, instDir, user, param); err == nil {
1064 rule.GuestFile = out.String()
1065 } else {
1066 logrus.WithError(err).Warnf("Couldn't process guest %#q as a template", rule.GuestFile)
1067 }
1068 }
1069 if rule.HostFile != "" {
1070 if out, err := executeHostTemplate(rule.HostFile, instDir, param); err == nil {
1071 rule.HostFile = out.String()
1072 } else {
1073 logrus.WithError(err).Warnf("Couldn't process host %#q as a template", rule.HostFile)
1074 }
1075 }
1076}
1077
1078func IsExistingInstanceDir(dir string) bool {
1079 // existence of "lima.yaml" does not signify existence of the instance,
1080 // because the file is created during the initialization of the instance.
1081 for _, f := range []string{
1082 filenames.HostAgentStdoutLog, filenames.HostAgentStderrLog,
1083 filenames.VzIdentifier, filenames.Image, filenames.Disk, filenames.BaseDiskLegacy, filenames.DiffDiskLegacy, filenames.CIDataISO,
1084 } {
1085 file := filepath.Join(dir, f)
1086 if _, err := os.Lstat(file); !errors.Is(err, os.ErrNotExist) {
1087 return true
1088 }
1089 }
1090 return false
1091}
1092
1093func ResolveOS(s *string) limatype.OS {
1094 if s == nil || *s == "" || *s == "default" {
1095 return limatype.NewOS("linux")
1096 }
1097 return *s
1098}
1099
1100func ResolveArch(s *string) limatype.Arch {
1101 if s == nil || *s == "" || *s == "default" {
1102 return limatype.NewArch(runtime.GOARCH)
1103 }
1104 return *s
1105}
1106
1107func unique(s []string) []string {
1108 keys := make(map[string]bool)
1109 list := []string{}
1110 for _, entry := range s {
1111 if _, found := keys[entry]; !found {
1112 keys[entry] = true
1113 list = append(list, entry)
1114 }
1115 }
1116 return list
1117}