跳到主要内容

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

浏览文件

hostagent.go

1353 行 · 43.4 KB历史下载
1// SPDX-FileCopyrightText: Copyright The Lima Authors
2// SPDX-License-Identifier: Apache-2.0
3
4package hostagent
5
6import (
7 "bufio"
8 "bytes"
9 "context"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "io"
14 "net"
15 "os"
16 "os/exec"
17 "path/filepath"
18 "runtime"
19 "slices"
20 "strconv"
21 "strings"
22 "sync"
23 "time"
24
25 "github.com/lima-vm/sshocker/pkg/ssh"
26 "github.com/sethvargo/go-password/password"
27 "github.com/sirupsen/logrus"
28 "google.golang.org/grpc/codes"
29 "google.golang.org/grpc/status"
30
31 "github.com/lima-vm/lima/v2/pkg/autostart"
32 "github.com/lima-vm/lima/v2/pkg/cidata"
33 "github.com/lima-vm/lima/v2/pkg/driver"
34 "github.com/lima-vm/lima/v2/pkg/driver/external/server"
35 "github.com/lima-vm/lima/v2/pkg/driverutil"
36 "github.com/lima-vm/lima/v2/pkg/freeport"
37 guestagentapi "github.com/lima-vm/lima/v2/pkg/guestagent/api"
38 guestagentclient "github.com/lima-vm/lima/v2/pkg/guestagent/api/client"
39 hostagentapi "github.com/lima-vm/lima/v2/pkg/hostagent/api"
40 "github.com/lima-vm/lima/v2/pkg/hostagent/dns"
41 "github.com/lima-vm/lima/v2/pkg/hostagent/events"
42 "github.com/lima-vm/lima/v2/pkg/instance/hostname"
43 "github.com/lima-vm/lima/v2/pkg/limatype"
44 "github.com/lima-vm/lima/v2/pkg/limatype/filenames"
45 "github.com/lima-vm/lima/v2/pkg/limayaml"
46 "github.com/lima-vm/lima/v2/pkg/networks"
47 "github.com/lima-vm/lima/v2/pkg/networks/usernet"
48 "github.com/lima-vm/lima/v2/pkg/osutil"
49 "github.com/lima-vm/lima/v2/pkg/portfwd"
50 "github.com/lima-vm/lima/v2/pkg/sshutil"
51 "github.com/lima-vm/lima/v2/pkg/store"
52 "github.com/lima-vm/lima/v2/pkg/strutil"
53 "github.com/lima-vm/lima/v2/pkg/version/versionutil"
54)
55
56type HostAgent struct {
57 instConfig *limatype.LimaYAML
58 sshLocalPort int
59 udpDNSLocalPort int
60 tcpDNSLocalPort int
61 instDir string
62 instName string
63 instSSHAddress string
64 sshExe sshutil.SSHExe
65 sshConfig *ssh.SSHConfig
66 portForwarder *portForwarder // legacy SSH port forwarder
67 grpcPortForwarder *portfwd.Forwarder
68
69 onClose []func() error // LIFO
70 onCloseMu sync.Mutex
71
72 driver driver.Driver
73 signalCh chan os.Signal
74
75 eventEnc *json.Encoder
76 eventEncMu sync.Mutex
77
78 vSockPort int
79 virtioPort string
80 iid string // instance ID, changes on every boot
81
82 clientMu sync.RWMutex
83 client *guestagentclient.GuestAgentClient
84
85 // gaSockForwardMu serializes (re-)establishment of the SSH forward for
86 // the guest-agent unix socket. The reconnect loop in watchGuestAgentEvents
87 // and the inotify goroutine both touch the same local socket path; without
88 // this lock they can race on os.RemoveAll/bind and leave ga.sock missing.
89 gaSockForwardMu sync.Mutex
90
91 // reverse-sshfs mounts, set before the guest agent routines start.
92 mounts []*mount
93
94 guestAgentAliveCh chan struct{} // closed on establishing the connection
95 guestAgentAliveChOnce sync.Once
96
97 showProgress bool // whether to show cloud-init progress
98
99 statusMu sync.RWMutex
100 currentStatus events.Status
101}
102
103type options struct {
104 guestAgentBinary string
105 nerdctlArchive string // local path, not URL
106 showProgress bool
107}
108
109type Opt func(*options) error
110
111func WithGuestAgentBinary(s string) Opt {
112 return func(o *options) error {
113 o.guestAgentBinary = s
114 return nil
115 }
116}
117
118func WithNerdctlArchive(s string) Opt {
119 return func(o *options) error {
120 o.nerdctlArchive = s
121 return nil
122 }
123}
124
125func WithCloudInitProgress(enabled bool) Opt {
126 return func(o *options) error {
127 o.showProgress = enabled
128 return nil
129 }
130}
131
132// New creates the HostAgent.
133//
134// stdout is for emitting JSON lines of Events.
135func New(ctx context.Context, instName string, stdout io.Writer, signalCh chan os.Signal, opts ...Opt) (*HostAgent, error) {
136 var o options
137 for _, f := range opts {
138 if err := f(&o); err != nil {
139 return nil, err
140 }
141 }
142 inst, err := store.Inspect(ctx, instName)
143 if err != nil {
144 return nil, err
145 }
146
147 var limaVersion string
148 limaVersionFile := filepath.Join(inst.Dir, filenames.LimaVersion)
149 if b, err := os.ReadFile(limaVersionFile); err == nil {
150 limaVersion = strings.TrimSpace(string(b))
151 } else if !errors.Is(err, os.ErrNotExist) {
152 logrus.WithError(err).Warnf("Failed to read %#q", limaVersionFile)
153 }
154
155 // inst.Config is loaded with FillDefault() already, so no need to care about nil pointers.
156 sshLocalPort, err := determineSSHLocalPort(*inst.Config.SSH.LocalPort, instName, limaVersion)
157 if err != nil {
158 return nil, err
159 }
160
161 var udpDNSLocalPort, tcpDNSLocalPort int
162 if limayaml.HostResolverEnabled(inst.Config) {
163 udpDNSLocalPort, err = freeport.UDP()
164 if err != nil {
165 return nil, err
166 }
167 tcpDNSLocalPort, err = freeport.TCP()
168 if err != nil {
169 return nil, err
170 }
171 }
172
173 limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, sshLocalPort)
174 if err != nil {
175 return nil, fmt.Errorf("failed to create driver instance: %w", err)
176 }
177 if err := limayaml.Validate(inst.Config, true); err != nil {
178 return nil, fmt.Errorf("failed to validate the instance YAML after filling defaults: %w", err)
179 }
180 sshLocalPort = inst.SSHLocalPort
181
182 info := limaDriver.Info(ctx)
183 vSockPort := info.VsockPort
184 virtioPort := info.VirtioPort
185 noCloudInit := info.Features.NoCloudInit
186 rosettaEnabled := info.Features.RosettaEnabled
187 rosettaBinFmt := info.Features.RosettaBinFmt
188
189 // Disable Rosetta in Plain mode
190 if *inst.Config.Plain {
191 rosettaEnabled = false
192 rosettaBinFmt = false
193 }
194
195 var iid string
196 switch *inst.Config.OS {
197 case limatype.WINDOWS:
198 iid, err = cidata.GenerateWindowsISO(ctx, inst.Dir, instName, inst.Config, udpDNSLocalPort, tcpDNSLocalPort, vSockPort, virtioPort, noCloudInit, rosettaEnabled, rosettaBinFmt)
199 if err != nil {
200 return nil, err
201 }
202 default:
203 if err := cidata.GenerateCloudConfig(ctx, inst.Dir, instName, inst.Config); err != nil {
204 return nil, err
205 }
206 iid, err = cidata.GenerateISO9660(ctx, limaDriver, inst.Dir, instName, inst.Config, udpDNSLocalPort, tcpDNSLocalPort, o.guestAgentBinary, o.nerdctlArchive, vSockPort, virtioPort, noCloudInit, rosettaEnabled, rosettaBinFmt)
207 if err != nil {
208 return nil, err
209 }
210 }
211
212 sshExe, err := sshutil.NewSSHExe()
213 if err != nil {
214 return nil, err
215 }
216 sshOpts, err := sshutil.SSHOpts(
217 ctx,
218 sshExe,
219 inst.Dir,
220 *inst.Config.User.Name,
221 *inst.Config.SSH.LoadDotSSHPubKeys,
222 *inst.Config.SSH.ForwardAgent,
223 *inst.Config.SSH.ForwardX11,
224 *inst.Config.SSH.ForwardX11Trusted)
225 if err != nil {
226 return nil, err
227 }
228 if err = writeSSHConfigFile("ssh", inst.Name, inst.Dir, inst.SSHAddress, sshLocalPort, sshOpts); err != nil {
229 return nil, err
230 }
231 sshConfig := &ssh.SSHConfig{
232 AdditionalArgs: sshutil.SSHArgsFromOpts(sshOpts),
233 }
234
235 ignoreTCP := false
236 ignoreUDP := false
237 for _, rule := range inst.Config.PortForwards {
238 if rule.Ignore && rule.GuestPortRange[0] == 1 && rule.GuestPortRange[1] == 65535 {
239 switch rule.Proto {
240 case limatype.ProtoTCP:
241 ignoreTCP = true
242 logrus.Info("TCP port forwarding is disabled (except for SSH)")
243 case limatype.ProtoUDP:
244 ignoreUDP = true
245 logrus.Info("UDP port forwarding is disabled")
246 case limatype.ProtoAny:
247 ignoreTCP = true
248 ignoreUDP = true
249 logrus.Info("TCP (except for SSH) and UDP port forwarding is disabled")
250 }
251 } else {
252 break
253 }
254 }
255 rules := portForwardRules(inst.Dir, inst.Config.User, inst.Param, sshLocalPort, inst.Config.PortForwards)
256
257 a := &HostAgent{
258 instConfig: inst.Config,
259 sshLocalPort: sshLocalPort,
260 udpDNSLocalPort: udpDNSLocalPort,
261 tcpDNSLocalPort: tcpDNSLocalPort,
262 instDir: inst.Dir,
263 instName: instName,
264 instSSHAddress: inst.SSHAddress,
265 sshExe: sshExe,
266 sshConfig: sshConfig,
267 driver: limaDriver,
268 signalCh: signalCh,
269 eventEnc: json.NewEncoder(stdout),
270 vSockPort: vSockPort,
271 virtioPort: virtioPort,
272 iid: iid,
273 guestAgentAliveCh: make(chan struct{}),
274 showProgress: o.showProgress,
275 }
276 a.grpcPortForwarder = portfwd.NewPortForwarder(rules, ignoreTCP, ignoreUDP, func(ev *events.PortForwardEvent) {
277 a.emitPortForwardEvent(context.Background(), ev)
278 })
279 a.portForwarder = newPortForwarder(sshConfig, a.sshAddressPort, rules, ignoreTCP, inst.VMType, func(ev *events.PortForwardEvent) {
280 a.emitPortForwardEvent(context.Background(), ev)
281 })
282
283 // Set up vsock event callback if the driver supports it
284 if vsockEmitter, ok := limaDriver.Driver.(driver.VsockEventEmitter); ok {
285 vsockEmitter.SetVsockEventCallback(func(ev *events.VsockEvent) {
286 a.emitVsockEvent(context.Background(), ev)
287 })
288 }
289
290 return a, nil
291}
292
293func writeSSHConfigFile(sshPath, instName, instDir, instSSHAddress string, sshLocalPort int, sshOpts []string) error {
294 if instDir == "" {
295 return fmt.Errorf("directory is unknown for the instance %#q", instName)
296 }
297 b := bytes.NewBufferString(`# This SSH config file can be passed to 'ssh -F'.
298# This file is created by Lima, but not used by Lima itself currently.
299# Modifications to this file will be lost on restarting the Lima instance.
300`)
301 if runtime.GOOS == "windows" {
302 // Remove ControlMaster, ControlPath, and ControlPersist options,
303 // because Cygwin-based SSH clients do not support multiplexing when executing commands.
304 // References:
305 // https://inbox.sourceware.org/cygwin/[email protected]/T/
306 // https://stackoverflow.com/questions/20959792/is-ssh-controlmaster-with-cygwin-on-windows-actually-possible
307 // By removing these options:
308 // - Avoids execution failures when the control master is not yet available.
309 // - Prevents error messages such as:
310 // > mux_client_request_session: read from master failed: Connection reset by peer
311 // > ControlSocket ....sock already exists, disabling multiplexing
312 // Only remove these options when writing the SSH config file and executing `limactl shell`, since multiplexing seems to work with port forwarding.
313 sshOpts = sshutil.SSHOptsRemovingControlPath(sshOpts)
314 }
315 if err := sshutil.Format(b, sshPath, instName, sshutil.FormatConfig,
316 append(sshOpts,
317 fmt.Sprintf("Hostname=%s", instSSHAddress),
318 fmt.Sprintf("Port=%d", sshLocalPort),
319 )); err != nil {
320 return err
321 }
322 fileName := filepath.Join(instDir, filenames.SSHConfig)
323 return os.WriteFile(fileName, b.Bytes(), 0o600)
324}
325
326func determineSSHLocalPort(confLocalPort int, instName, limaVersion string) (int, error) {
327 if confLocalPort > 0 {
328 return confLocalPort, nil
329 }
330 if confLocalPort < 0 {
331 return 0, fmt.Errorf("invalid ssh local port %d", confLocalPort)
332 }
333 if versionutil.LessThan(limaVersion, "2.0.0") && instName == "default" {
334 // use hard-coded value for "default" instance, for backward compatibility
335 return 60022, nil
336 }
337 sshLocalPort, err := freeport.TCP()
338 if err != nil {
339 return 0, fmt.Errorf("failed to find a free port, try setting `ssh.localPort` manually: %w", err)
340 }
341 return sshLocalPort, nil
342}
343
344func (a *HostAgent) emitEvent(_ context.Context, ev events.Event) {
345 a.eventEncMu.Lock()
346 defer a.eventEncMu.Unlock()
347
348 a.statusMu.Lock()
349 a.currentStatus = ev.Status
350 a.statusMu.Unlock()
351
352 if ev.Time.IsZero() {
353 ev.Time = time.Now()
354 }
355 if err := a.eventEnc.Encode(ev); err != nil {
356 logrus.WithField("event", ev).WithError(err).Error("failed to emit an event")
357 }
358}
359
360func (a *HostAgent) emitCloudInitProgressEvent(ctx context.Context, progress *events.CloudInitProgress) {
361 // LogLine is read verbatim from the guest's cloud-init output over SSH, so an
362 // untrusted guest controls its bytes. limactl start/watch print it to the
363 // operator's terminal, so strip control characters here to keep the guest
364 // from injecting ANSI/OSC escape sequences.
365 progress.LogLine = strutil.RemoveControlChars(progress.LogLine)
366
367 a.statusMu.RLock()
368 currentStatus := a.currentStatus
369 a.statusMu.RUnlock()
370
371 currentStatus.CloudInitProgress = progress
372
373 ev := events.Event{Status: currentStatus}
374 a.emitEvent(ctx, ev)
375}
376
377func (a *HostAgent) emitPortForwardEvent(ctx context.Context, pfEvent *events.PortForwardEvent) {
378 a.statusMu.RLock()
379 currentStatus := a.currentStatus
380 a.statusMu.RUnlock()
381
382 currentStatus.PortForward = pfEvent
383
384 ev := events.Event{Status: currentStatus}
385 a.emitEvent(ctx, ev)
386}
387
388func (a *HostAgent) emitVsockEvent(ctx context.Context, vsockEvent *events.VsockEvent) {
389 a.statusMu.RLock()
390 currentStatus := a.currentStatus
391 a.statusMu.RUnlock()
392
393 currentStatus.Vsock = vsockEvent
394
395 ev := events.Event{Status: currentStatus}
396 a.emitEvent(ctx, ev)
397}
398
399func generatePassword(length int) (string, error) {
400 // avoid any special symbols, to make it easier to copy/paste
401 return password.Generate(length, length/4, 0, false, false)
402}
403
404func (a *HostAgent) Run(ctx context.Context) error {
405 defer func() {
406 exitingEv := events.Event{
407 Status: events.Status{
408 Exiting: true,
409 },
410 }
411 a.emitEvent(ctx, exitingEv)
412 }()
413 adjustNofileRlimit()
414
415 if limayaml.FirstUsernetIndex(a.instConfig) == -1 && limayaml.HostResolverEnabled(a.instConfig) {
416 hosts := a.instConfig.HostResolver.Hosts
417 if hosts == nil {
418 hosts = make(map[string]string)
419 }
420 hosts["host.lima.internal"] = networks.SlirpGateway
421 name := hostname.FromInstName(a.instName) // TODO: support customization
422 hosts[name] = networks.SlirpIPAddress
423 // The guest reaches this server on the host's loopback, past any
424 // usernet.Outbound policy.
425 usernet.AllowHostService("udp", a.udpDNSLocalPort)
426 usernet.AllowHostService("tcp", a.tcpDNSLocalPort)
427 srvOpts := dns.ServerOptions{
428 UDPPort: a.udpDNSLocalPort,
429 TCPPort: a.tcpDNSLocalPort,
430 Address: "127.0.0.1",
431 HandlerOptions: dns.HandlerOptions{
432 IPv6: *a.instConfig.HostResolver.IPv6,
433 StaticHosts: hosts,
434 },
435 }
436 dnsServer, err := dns.Start(srvOpts)
437 if err != nil {
438 return fmt.Errorf("cannot start DNS server: %w", err)
439 }
440 defer dnsServer.Shutdown()
441 }
442
443 errCh, err := a.driver.Start(ctx)
444 if err != nil {
445 return err
446 }
447
448 if err := a.driver.AdditionalSetupForSSH(ctx); err != nil {
449 return err
450 }
451 stopResources := a.startResourceManager(ctx)
452 defer stopResources()
453 a.cleanUp(func() error { stopResources(); return nil })
454
455 // WSL instance SSH address isn't known until after VM start
456 if a.driver.Info(ctx).Features.DynamicSSHAddress {
457 sshAddr, err := a.driver.SSHAddress(ctx)
458 if err != nil {
459 return err
460 }
461 a.instSSHAddress = sshAddr
462 }
463
464 if a.instConfig.Video.Display != nil && *a.instConfig.Video.Display == "vnc" {
465 vncdisplay, vncoptions, _ := strings.Cut(*a.instConfig.Video.VNC.Display, ",")
466 vnchost, vncnum, err := net.SplitHostPort(vncdisplay)
467 if err != nil {
468 return err
469 }
470 n, err := strconv.Atoi(vncnum)
471 if err != nil {
472 return err
473 }
474 vncport := strconv.Itoa(5900 + n)
475 vncpwdfile := filepath.Join(a.instDir, filenames.VNCPasswordFile)
476 vncpasswd, err := generatePassword(8)
477 if err != nil {
478 return err
479 }
480 if err := a.driver.ChangeDisplayPassword(ctx, vncpasswd); err != nil {
481 return err
482 }
483 if err := os.WriteFile(vncpwdfile, []byte(vncpasswd), 0o600); err != nil {
484 return err
485 }
486 if strings.Contains(vncoptions, "to=") {
487 vncport, err = a.driver.DisplayConnection(ctx)
488 if err != nil {
489 return err
490 }
491 p, err := strconv.Atoi(vncport)
492 if err != nil {
493 return err
494 }
495 vncnum = strconv.Itoa(p - 5900)
496 vncdisplay = net.JoinHostPort(vnchost, vncnum)
497 }
498 vncfile := filepath.Join(a.instDir, filenames.VNCDisplayFile)
499 if err := os.WriteFile(vncfile, []byte(vncdisplay), 0o600); err != nil {
500 return err
501 }
502 vncurl := "vnc://" + net.JoinHostPort(vnchost, vncport)
503 logrus.Infof("VNC server running at %s <%s>", vncdisplay, vncurl)
504 logrus.Infof("VNC Display: `%s`", vncfile)
505 logrus.Infof("VNC Password: `%s`", vncpwdfile)
506 }
507
508 if a.driver.Info(ctx).Features.CanRunGUI {
509 go func() {
510 err = a.startRoutinesAndWait(ctx, errCh)
511 if err != nil {
512 logrus.Error(err)
513 }
514 }()
515 return a.driver.RunGUI(ctx)
516 }
517 return a.startRoutinesAndWait(ctx, errCh)
518}
519
520func (a *HostAgent) startRoutinesAndWait(ctx context.Context, errCh <-chan error) error {
521 stBase := events.Status{
522 SSHLocalPort: a.sshLocalPort,
523 }
524 stBooting := stBase
525 a.emitEvent(ctx, events.Event{Status: stBooting})
526 ctxHA, cancelHA := context.WithCancel(ctx)
527 go func() {
528 stRunning := stBase
529 if haErr := a.startHostAgentRoutines(ctxHA); haErr != nil {
530 stRunning.Degraded = true
531 stRunning.Errors = append(stRunning.Errors, haErr.Error())
532 }
533 stRunning.Running = true
534 a.emitEvent(ctx, events.Event{Status: stRunning})
535 }()
536 // wait for either the driver to stop or a signal to shut down
537 select {
538 case driverErr := <-errCh:
539 logrus.Infof("Driver stopped due to error: %#q", driverErr)
540 case sig := <-a.signalCh:
541 logrus.Infof("Received %s, shutting down the host agent", osutil.SignalName(sig))
542 }
543 // close the host agent routines before cancelling the context
544 if closeErr := a.close(); closeErr != nil {
545 logrus.WithError(closeErr).Warn("an error during shutting down the host agent")
546 }
547 cancelHA()
548 stopErr := a.driver.Stop(ctx)
549 // Stop the external driver gRPC server now that the instance is shutting down.
550 server.Stop(a.instDir, false)
551 return stopErr
552}
553
554func (a *HostAgent) Screenshot(ctx context.Context, format string) ([]byte, error) {
555 // ConfiguredDriver wraps the concrete driver; unwrap to reach optional interfaces.
556 inner := a.driver
557 if cd, ok := a.driver.(*driver.ConfiguredDriver); ok {
558 inner = cd.Driver
559 }
560 s, ok := inner.(driver.Screenshotter)
561 if !ok {
562 return nil, fmt.Errorf("driver %q: %w", a.driver.Info(ctx).Name, driver.ErrDriverNotScreenshotter)
563 }
564 return s.CaptureScreenshot(format)
565}
566
567func (a *HostAgent) Info(_ context.Context) (*hostagentapi.Info, error) {
568 info := &hostagentapi.Info{
569 AutoStartedIdentifier: autostart.AutoStartedIdentifier(),
570 SSHLocalPort: a.sshLocalPort,
571 }
572 return info, nil
573}
574
575func (a *HostAgent) sshAddressPort() (sshAddress string, sshPort int) {
576 sshAddress = a.instSSHAddress
577 sshPort = a.sshLocalPort
578 return sshAddress, sshPort
579}
580
581func (a *HostAgent) startHostAgentRoutines(ctx context.Context) error {
582 if *a.instConfig.Plain {
583 msg := "Running in plain mode. Mounts, dynamic port forwarding, containerd, etc. will be ignored. Guest agent will not be running."
584 for _, port := range a.instConfig.PortForwards {
585 if port.Static {
586 msg += " Static port forwarding is allowed." //nolint:modernize // stringsbuilder is not needed
587 break
588 }
589 }
590 logrus.Info(msg)
591 }
592 a.cleanUp(func() error {
593 // Skip ExitMaster when the control socket does not exist.
594 // On Windows, the ControlMaster is used only for SSH port forwarding.
595 if !sshutil.IsControlMasterExisting(a.instDir) {
596 return nil
597 }
598 logrus.Debugf("shutting down the SSH master")
599 if exitMasterErr := ssh.ExitMaster(a.instSSHAddress, a.sshLocalPort, a.sshConfig); exitMasterErr != nil {
600 logrus.WithError(exitMasterErr).Warn("failed to exit SSH master")
601 }
602 return nil
603 })
604 var errs []error
605
606 essentialRequirements := a.essentialRequirements()
607 if *a.instConfig.OS == limatype.WINDOWS {
608 essentialRequirements = a.essentialWinRequirements()
609 }
610
611 if err := a.waitForRequirements("essential", essentialRequirements); err != nil {
612 errs = append(errs, err)
613 }
614
615 // Windows guest needs a marker file which shows all installation is done.
616 // In the next boot, Lima will not mount OS installer ISO file to prevent unexpected re-installation.
617 if *a.instConfig.OS == limatype.WINDOWS {
618 if _, err := os.Create(filepath.Join(a.instDir, filenames.WinDoneInstallation)); err != nil {
619 errs = append(errs, errors.New("failed to create a windows installation marker"))
620 }
621 }
622
623 if *a.instConfig.SSH.ForwardAgent {
624 if *a.instConfig.Plain {
625 logrus.Warn("Running in plain mode. Ignoring ssh.forwardAgent")
626 } else {
627 faScript := `#!/bin/bash
628set -eux -o pipefail
629ln -sf "${SSH_AUTH_SOCK}" /run/host-services/ssh-auth.sock`
630 faDesc := "linking ssh auth socket to static location /run/host-services/ssh-auth.sock"
631 stdout, stderr, err := ssh.ExecuteScript(a.instSSHAddress, a.sshLocalPort, a.sshConfig, faScript, faDesc)
632 logrus.Debugf("stdout=%#q, stderr=%#q, err=%v", stdout, stderr, err)
633 if err != nil {
634 errs = append(errs, fmt.Errorf("stdout=%#q, stderr=%#q: %w", stdout, stderr, err))
635 }
636 }
637 }
638 if *a.instConfig.MountType == limatype.REVSSHFS && !*a.instConfig.Plain {
639 mounts, err := a.setupMounts(ctx)
640 if err != nil {
641 errs = append(errs, err)
642 }
643 a.mounts = mounts
644 a.cleanUp(func() error {
645 var unmountErrs []error
646 for _, m := range mounts {
647 if unmountErr := m.close(); unmountErr != nil {
648 unmountErrs = append(unmountErrs, unmountErr)
649 }
650 }
651 return errors.Join(unmountErrs...)
652 })
653 }
654 if len(a.instConfig.AdditionalDisks) > 0 {
655 a.cleanUp(func() error {
656 var unlockErrs []error
657 for _, d := range a.instConfig.AdditionalDisks {
658 disk, inspectErr := store.InspectDisk(d.Name, d.FSType)
659 if inspectErr != nil {
660 unlockErrs = append(unlockErrs, inspectErr)
661 continue
662 }
663 logrus.Infof("Unmounting disk %#q", disk.Name)
664 if unlockErr := disk.Unlock(); unlockErr != nil {
665 unlockErrs = append(unlockErrs, unlockErr)
666 }
667 }
668 return errors.Join(unlockErrs...)
669 })
670 }
671
672 staticPortForwards := a.separateStaticPortForwards()
673 a.addStaticPortForwardsFromList(ctx, staticPortForwards)
674
675 hasGuestAgentDaemon := !*a.instConfig.Plain && *a.instConfig.OS == limatype.LINUX
676 if hasGuestAgentDaemon {
677 go a.watchGuestAgentEvents(ctx)
678 go a.startTimeSync(ctx)
679 if a.showProgress {
680 cloudInitDone := make(chan struct{})
681 go func() {
682 timeoutCtx, cancel := context.WithTimeout(ctx, 10*time.Minute)
683 defer cancel()
684
685 a.watchCloudInitProgress(timeoutCtx)
686 close(cloudInitDone)
687 }()
688
689 go func() {
690 <-cloudInitDone
691 logrus.Debug("Cloud-init monitoring completed, VM is fully ready")
692 }()
693 }
694 }
695
696 optionalRequirements := a.optionalRequirements()
697 if *a.instConfig.OS == limatype.WINDOWS {
698 optionalRequirements = a.optionalWinRequirements()
699 }
700
701 if err := a.waitForRequirements("optional", optionalRequirements); err != nil {
702 errs = append(errs, err)
703 }
704 if hasGuestAgentDaemon {
705 logrus.Info("Waiting for the guest agent to be running")
706 select {
707 case <-a.guestAgentAliveCh:
708 // NOP
709 case <-time.After(time.Minute):
710 errs = append(errs, errors.New("guest agent does not seem to be running; port forwards will not work"))
711 }
712 }
713
714 finalRequirements := a.finalRequirements()
715 if *a.instConfig.OS == limatype.WINDOWS {
716 finalRequirements = a.finalWinRequirements()
717 }
718
719 if err := a.waitForRequirements("final", finalRequirements); err != nil {
720 errs = append(errs, err)
721 }
722 // Copy all config files _after_ the requirements are done
723 for _, rule := range a.instConfig.CopyToHost {
724 sshAddress, sshPort := a.sshAddressPort()
725 if err := copyToHost(ctx, a.sshConfig, sshAddress, sshPort, rule.HostFile, rule.GuestFile, rule.SkipIfMissing); err != nil {
726 errs = append(errs, err)
727 }
728 }
729 a.cleanUp(func() error {
730 var rmErrs []error
731 for _, rule := range a.instConfig.CopyToHost {
732 if rule.DeleteOnStop {
733 logrus.Infof("Deleting %s", rule.HostFile)
734 if err := os.RemoveAll(rule.HostFile); err != nil {
735 rmErrs = append(rmErrs, err)
736 }
737 }
738 }
739 return errors.Join(rmErrs...)
740 })
741 return errors.Join(errs...)
742}
743
744// cleanUp registers a cleanup function to be called when the host agent is stopped.
745// The cleanup functions are called before the context is cancelled, in the reverse order of their registration.
746func (a *HostAgent) cleanUp(fn func() error) {
747 a.onCloseMu.Lock()
748 defer a.onCloseMu.Unlock()
749 a.onClose = append(a.onClose, fn)
750}
751
752func (a *HostAgent) close() error {
753 a.onCloseMu.Lock()
754 defer a.onCloseMu.Unlock()
755 logrus.Infof("Shutting down the host agent")
756 var errs []error
757 for _, f := range slices.Backward(a.onClose) {
758 if err := f(); err != nil {
759 errs = append(errs, err)
760 }
761 }
762 return errors.Join(errs...)
763}
764
765func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) {
766 // TODO: use vSock (when QEMU for macOS gets support for vSock)
767
768 // Setup all socket forwards and defer their teardown
769 if !a.driver.Info(ctx).Features.SkipSocketForwarding {
770 logrus.Debugf("Forwarding unix sockets")
771 sshAddress, sshPort := a.sshAddressPort()
772 for _, rule := range a.instConfig.PortForwards {
773 if rule.GuestSocket != "" {
774 local := hostAddress(rule, &guestagentapi.IPPort{})
775 _ = forwardSSH(ctx, a.sshConfig, sshAddress, sshPort, local, rule.GuestSocket, verbForward, rule.Reverse)
776 }
777 }
778 }
779
780 localUnix := filepath.Join(a.instDir, filenames.GuestAgentSock)
781 remoteUnix := "/run/lima-guestagent.sock"
782
783 a.cleanUp(func() error {
784 logrus.Debugf("Stop forwarding unix sockets")
785 var errs []error
786 sshAddress, sshPort := a.sshAddressPort()
787 for _, rule := range a.instConfig.PortForwards {
788 if rule.GuestSocket != "" {
789 local := hostAddress(rule, &guestagentapi.IPPort{})
790 if err := forwardSSH(ctx, a.sshConfig, sshAddress, sshPort, local, rule.GuestSocket, verbCancel, rule.Reverse); err != nil {
791 errs = append(errs, err)
792 }
793 }
794 }
795 if a.driver.ForwardGuestAgent(ctx) {
796 if err := a.cancelGuestAgentSockForward(ctx, localUnix, remoteUnix); err != nil {
797 errs = append(errs, err)
798 }
799 }
800 return errors.Join(errs...)
801 })
802
803 go func() {
804 if a.instConfig.MountInotify == nil || !*a.instConfig.MountInotify {
805 return
806 }
807 client := a.getClient()
808 if client == nil || !isGuestAgentSocketAccessible(ctx, client) {
809 if a.driver.ForwardGuestAgent(ctx) {
810 a.forwardGuestAgentSock(ctx, localUnix, remoteUnix)
811 }
812 }
813 // Re-spawn startInotify when its gRPC stream dies (typically because
814 // the guest agent restarted). Without this, host-side file changes
815 // silently stop propagating into the guest after the first reconnect.
816 for {
817 if err := a.startInotify(ctx); err != nil && !errors.Is(err, context.Canceled) {
818 logrus.WithError(err).Warn("inotify stream ended; will retry")
819 }
820 select {
821 case <-ctx.Done():
822 return
823 case <-time.After(10 * time.Second):
824 }
825 }
826 }()
827
828 // ensure close before ctx is cancelled
829 a.cleanUp(a.grpcPortForwarder.Close)
830 a.cleanUp(func() error {
831 a.clientMu.Lock()
832 defer a.clientMu.Unlock()
833 if a.client == nil {
834 return nil
835 }
836 err := a.client.Close()
837 a.client = nil
838 return err
839 })
840
841 for {
842 client := a.getClient()
843 if client == nil || !isGuestAgentSocketAccessible(ctx, client) {
844 if a.driver.ForwardGuestAgent(ctx) {
845 a.forwardGuestAgentSock(ctx, localUnix, remoteUnix)
846 }
847 }
848 client, err := a.getOrCreateClient(ctx)
849 if err == nil {
850 if err := a.processGuestAgentEvents(ctx, client); err != nil {
851 if !errors.Is(err, context.Canceled) {
852 logrus.WithError(err).Warn("guest agent events closed unexpectedly")
853 }
854 }
855 } else {
856 if !strings.Contains(err.Error(), context.Canceled.Error()) {
857 logrus.WithError(err).Warn("connection to the guest agent was closed unexpectedly")
858 }
859 }
860 select {
861 case <-ctx.Done():
862 return
863 case <-time.After(10 * time.Second):
864 }
865 }
866}
867
868func (a *HostAgent) addStaticPortForwardsFromList(ctx context.Context, staticPortForwards []limatype.PortForward) {
869 sshAddress, sshPort := a.sshAddressPort()
870 for _, rule := range staticPortForwards {
871 if rule.GuestSocket == "" {
872 guest := &guestagentapi.IPPort{
873 Ip: rule.GuestIP.String(),
874 Port: int32(rule.GuestPort),
875 Protocol: rule.Proto,
876 }
877 local, remote := a.portForwarder.forwardingAddresses(guest)
878 if local != "" {
879 logrus.Infof("Setting up static TCP forwarding from %s to %s", remote, local)
880 if err := forwardTCP(ctx, a.sshConfig, sshAddress, sshPort, local, remote, verbForward); err != nil {
881 logrus.WithError(err).Warnf("failed to set up static TCP forwarding %s -> %s", remote, local)
882 }
883 }
884 }
885 }
886}
887
888// separateStaticPortForwards separates static port forwards from a.instConfig.PortForwards,
889// updates a.instConfig.PortForwards to contain only non-static port forwards,
890// and returns the list of static port forwards.
891func (a *HostAgent) separateStaticPortForwards() []limatype.PortForward {
892 staticPortForwards := make([]limatype.PortForward, 0, len(a.instConfig.PortForwards))
893 nonStaticPortForwards := make([]limatype.PortForward, 0, len(a.instConfig.PortForwards))
894
895 for i := range len(a.instConfig.PortForwards) {
896 rule := a.instConfig.PortForwards[i]
897 if rule.Static {
898 logrus.Debugf("Found static port forward: guest=%d host=%d", rule.GuestPort, rule.HostPort)
899 staticPortForwards = append(staticPortForwards, rule)
900 } else {
901 logrus.Debugf("Found non-static port forward: guest=%d host=%d", rule.GuestPort, rule.HostPort)
902 nonStaticPortForwards = append(nonStaticPortForwards, rule)
903 }
904 }
905
906 logrus.Debugf("Static port forwards: %d, Non-static port forwards: %d", len(staticPortForwards), len(nonStaticPortForwards))
907
908 a.instConfig.PortForwards = nonStaticPortForwards
909 return staticPortForwards
910}
911
912func isGuestAgentSocketAccessible(ctx context.Context, client *guestagentclient.GuestAgentClient) bool {
913 // Reconnection holds clientMu while probing. Bound the RPC so a stale guest
914 // connection cannot prevent shutdown from acquiring the same lock.
915 ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
916 defer cancel()
917 _, err := client.Info(ctx)
918 return err == nil
919}
920
921// getClient returns the current guest agent client under the clientMu lock,
922// so callers observe a consistent (non-mid-transition) snapshot.
923func (a *HostAgent) getClient() *guestagentclient.GuestAgentClient {
924 a.clientMu.Lock()
925 defer a.clientMu.Unlock()
926 return a.client
927}
928
929func (a *HostAgent) getOrCreateClient(ctx context.Context) (*guestagentclient.GuestAgentClient, error) {
930 a.clientMu.Lock()
931 defer a.clientMu.Unlock()
932 if a.client != nil && isGuestAgentSocketAccessible(ctx, a.client) {
933 return a.client, nil
934 }
935 // The previous client (if any) is unreachable: close its underlying gRPC
936 // ClientConn before replacing it, otherwise the resolver/transport
937 // goroutines and the dialed net.Conn (e.g. forwarded ga.sock) leak across
938 // every guest agent restart or VM reboot.
939 if a.client != nil {
940 if err := a.client.Close(); err != nil {
941 logrus.WithError(err).Debug("failed to close stale guest agent client")
942 }
943 a.client = nil
944 }
945 var err error
946 a.client, err = guestagentclient.NewGuestAgentClient(a.createConnection)
947 return a.client, err
948}
949
950func (a *HostAgent) createConnection(ctx context.Context) (net.Conn, error) {
951 conn, _, err := a.driver.GuestAgentConn(ctx)
952 // default to forwarded sock
953 if conn == nil && err == nil {
954 var d net.Dialer
955 conn, err = d.DialContext(ctx, "unix", filepath.Join(a.instDir, filenames.GuestAgentSock))
956 }
957 return conn, err
958}
959
960func (a *HostAgent) processGuestAgentEvents(ctx context.Context, client *guestagentclient.GuestAgentClient) error {
961 info, err := client.Info(ctx)
962 if err != nil {
963 return err
964 }
965 logrus.Info("Guest agent is running")
966 a.guestAgentAliveChOnce.Do(func() {
967 close(a.guestAgentAliveCh)
968 })
969
970 logrus.Debugf("guest agent info: %+v", info)
971
972 onEvent := func(ev *guestagentapi.Event) error {
973 logrus.Debugf("guest agent event: %+v", ev)
974 for _, f := range ev.Errors {
975 logrus.Warnf("received error from the guest: %#q", f)
976 }
977 // IPPort.Ip is under the guest's control and ends up in PortForwardEvent.GuestAddr,
978 // which limactl start/watch print to the terminal, so reject anything that is not an IP.
979 for _, f := range slices.Concat(ev.AddedLocalPorts, ev.RemovedLocalPorts) {
980 if net.ParseIP(f.Ip) == nil {
981 return fmt.Errorf("guest agent reported invalid IP %#q", f.Ip)
982 }
983 }
984 // History of the default value of useSSHFwd:
985 // - v0.1.0: true (effectively)
986 // - v1.0.0: false
987 // - v1.0.1: true
988 // - v1.1.0-beta.0: false
989 useSSHFwd := false
990 if envVar := os.Getenv("LIMA_SSH_PORT_FORWARDER"); envVar != "" {
991 b, err := strconv.ParseBool(envVar)
992 if err != nil {
993 logrus.WithError(err).Warnf("invalid LIMA_SSH_PORT_FORWARDER value %#q", envVar)
994 } else {
995 useSSHFwd = b
996 }
997 }
998 if useSSHFwd {
999 a.portForwarder.OnEvent(ctx, ev)
1000 } else {
1001 dialContext := portfwd.DialContextToGRPCTunnel(client)
1002 a.grpcPortForwarder.OnEvent(ctx, dialContext, ev)
1003 }
1004 return nil
1005 }
1006
1007 if err := client.Events(ctx, onEvent); err != nil {
1008 if status.Code(err) == codes.Canceled {
1009 return context.Canceled
1010 }
1011 return err
1012 }
1013 return io.EOF
1014}
1015
1016const (
1017 verbForward = "forward"
1018 verbCancel = "cancel"
1019)
1020
1021func executeSSH(ctx context.Context, sshConfig *ssh.SSHConfig, sshAddress string, sshPort int, command ...string) error {
1022 args := sshConfig.Args()
1023 args = append(args,
1024 "-p", strconv.Itoa(sshPort),
1025 sshAddress,
1026 "--",
1027 )
1028 args = append(args, command...)
1029 cmd := exec.CommandContext(ctx, sshConfig.Binary(), args...)
1030 if out, err := cmd.Output(); err != nil {
1031 return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
1032 }
1033 return nil
1034}
1035
1036// forwardGuestAgentSock establishes (or re-establishes) the SSH local forward
1037// of the guest-agent unix socket. It is used both for the initial setup and
1038// to bring the forward back up after the guest agent has been restarted, the
1039// VM has been rebooted, or the gRPC stream has otherwise become unhealthy.
1040//
1041// The previous behavior was to call forwardSSH(verbForward) directly on every
1042// reconnect tick. forwardSSH unlinks the local socket file as its first step
1043// (so a fresh listener can bind), and the SSH ControlMaster still has the
1044// previous forward registered for the same listen path. The duplicate
1045// registration causes ssh -O forward to exit non-zero and forwardSSH to unlink
1046// the socket a second time on its failure branch — leaving ga.sock permanently
1047// missing on disk and breaking host↔guest gRPC, dynamic port forwarding, and
1048// inotify mount invalidation until limactl stop && limactl start. See #2227.
1049//
1050// The fix is twofold:
1051// 1. Best-effort verbCancel before verbForward, so the ControlMaster releases
1052// the prior registration and the new bind succeeds cleanly.
1053// 2. Serialize via gaSockForwardMu, so the reconnect loop in
1054// watchGuestAgentEvents, the inotify setup goroutine, and the cleanup
1055// path cannot race on os.RemoveAll/bind of the same path.
1056func (a *HostAgent) forwardGuestAgentSock(ctx context.Context, localUnix, remoteUnix string) {
1057 a.gaSockForwardMu.Lock()
1058 defer a.gaSockForwardMu.Unlock()
1059 sshAddress, sshPort := a.sshAddressPort()
1060 // Best-effort teardown of any prior forward registered with the
1061 // ControlMaster. Errors are expected (e.g. on the very first call when
1062 // no forward exists yet) and intentionally ignored. Use ctx so shutdown
1063 // can unblock this call if the ControlMaster is unresponsive.
1064 _ = forwardSSH(ctx, a.sshConfig, sshAddress, sshPort, localUnix, remoteUnix, verbCancel, false)
1065 if err := forwardSSH(ctx, a.sshConfig, sshAddress, sshPort, localUnix, remoteUnix, verbForward, false); err != nil {
1066 logrus.WithError(err).Warn("failed to (re-)establish forward for the guest agent socket; will retry")
1067 }
1068}
1069
1070// cancelGuestAgentSockForward tears down the SSH forward for the guest-agent
1071// unix socket. Serialized via gaSockForwardMu so it cannot race with the
1072// reconnect path in forwardGuestAgentSock.
1073func (a *HostAgent) cancelGuestAgentSockForward(ctx context.Context, localUnix, remoteUnix string) error {
1074 a.gaSockForwardMu.Lock()
1075 defer a.gaSockForwardMu.Unlock()
1076 sshAddress, sshPort := a.sshAddressPort()
1077 return forwardSSH(ctx, a.sshConfig, sshAddress, sshPort, localUnix, remoteUnix, verbCancel, false)
1078}
1079
1080// forwardSSH is a var (not a func) so tests can stub it without touching real ssh.
1081var forwardSSH = func(ctx context.Context, sshConfig *ssh.SSHConfig, sshAddress string, sshPort int, local, remote, verb string, reverse bool) error {
1082 args := sshConfig.Args()
1083 args = append(args,
1084 "-T",
1085 "-O", verb,
1086 )
1087 if reverse {
1088 args = append(args,
1089 "-R", remote+":"+local,
1090 )
1091 } else {
1092 args = append(args,
1093 "-L", local+":"+remote,
1094 )
1095 }
1096 args = append(args,
1097 "-N",
1098 "-f",
1099 "-p", strconv.Itoa(sshPort),
1100 sshAddress,
1101 "--",
1102 )
1103 if strings.HasPrefix(local, "/") {
1104 switch verb {
1105 case verbForward:
1106 if reverse {
1107 logrus.Infof("Forwarding %#q (host) to %#q (guest)", local, remote)
1108 if err := executeSSH(ctx, sshConfig, sshAddress, sshPort, "rm", "-f", remote); err != nil {
1109 logrus.WithError(err).Warnf("Failed to clean up %#q (guest) before setting up forwarding", remote)
1110 }
1111 } else {
1112 logrus.Infof("Forwarding %#q (guest) to %#q (host)", remote, local)
1113 if err := osutil.RemoveStaleSocket(local); err != nil {
1114 logrus.WithError(err).Warnf("Failed to clean up %#q (host) before setting up forwarding", local)
1115 }
1116 }
1117 if err := os.MkdirAll(filepath.Dir(local), 0o750); err != nil {
1118 return fmt.Errorf("can't create directory for local socket %#q: %w", local, err)
1119 }
1120 case verbCancel:
1121 if reverse {
1122 logrus.Infof("Stopping forwarding %#q (host) to %#q (guest)", local, remote)
1123 if err := executeSSH(ctx, sshConfig, sshAddress, sshPort, "rm", "-f", remote); err != nil {
1124 logrus.WithError(err).Warnf("Failed to clean up %#q (guest) after stopping forwarding", remote)
1125 }
1126 } else {
1127 logrus.Infof("Stopping forwarding %#q (guest) to %#q (host)", remote, local)
1128 defer func() {
1129 if err := osutil.RemoveStaleSocket(local); err != nil {
1130 logrus.WithError(err).Warnf("Failed to clean up %#q (host) after stopping forwarding", local)
1131 }
1132 }()
1133 }
1134 default:
1135 panic(fmt.Errorf("invalid verb %#q", verb))
1136 }
1137 }
1138 cmd := exec.CommandContext(ctx, sshConfig.Binary(), args...)
1139 logrus.Debugf("Running %#q", cmd)
1140 if out, err := cmd.Output(); err != nil {
1141 if verb == verbForward && strings.HasPrefix(local, "/") {
1142 if reverse {
1143 logrus.WithError(err).Warnf("Failed to set up forward from %#q (host) to %#q (guest)", local, remote)
1144 if err := executeSSH(ctx, sshConfig, sshAddress, sshPort, "rm", "-f", remote); err != nil {
1145 logrus.WithError(err).Warnf("Failed to clean up %#q (guest) after forwarding failed", remote)
1146 }
1147 } else {
1148 logrus.WithError(err).Warnf("Failed to set up forward from %#q (guest) to %#q (host)", remote, local)
1149 if removeErr := osutil.RemoveStaleSocket(local); removeErr != nil {
1150 logrus.WithError(removeErr).Warnf("Failed to clean up %#q (host) after forwarding failed", local)
1151 }
1152 }
1153 }
1154 return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
1155 }
1156 return nil
1157}
1158
1159func (a *HostAgent) watchCloudInitProgress(ctx context.Context) {
1160 exitReason := "Cloud-init monitoring completed successfully"
1161 var cmd *exec.Cmd
1162
1163 defer func() {
1164 a.emitCloudInitProgressEvent(context.Background(), &events.CloudInitProgress{
1165 Active: false,
1166 Completed: true,
1167 LogLine: exitReason,
1168 })
1169 logrus.Debug("Cloud-init progress monitoring completed")
1170 }()
1171
1172 logrus.Debug("Starting cloud-init progress monitoring")
1173
1174 a.emitCloudInitProgressEvent(ctx, &events.CloudInitProgress{
1175 Active: true,
1176 })
1177
1178 sshAddress, sshPort := a.sshAddressPort()
1179 args := a.sshConfig.Args()
1180 args = append(args,
1181 "-p", strconv.Itoa(sshPort),
1182 sshAddress,
1183 "sh", "-c",
1184 `"if command -v systemctl >/dev/null 2>&1 && systemctl is-enabled -q cloud-init-main.service; then
1185 journalctl -u cloud-init-main.service -b -S @0 -o cat -f
1186 else
1187 sudo tail -n +$(sudo awk '
1188 BEGIN{b=1; e=1}
1189 /^Cloud-init.* finished/{e=NR}
1190 /.*/{if(NR>e){b=e+1}}
1191 END{print b}
1192 ' /var/log/cloud-init-output.log) -f /var/log/cloud-init-output.log
1193 fi"`,
1194 )
1195
1196 cmd = exec.CommandContext(ctx, a.sshConfig.Binary(), args...)
1197 stdout, err := cmd.StdoutPipe()
1198 if err != nil {
1199 logrus.WithError(err).Warn("Failed to create stdout pipe for cloud-init monitoring")
1200 exitReason = "Failed to create stdout pipe for cloud-init monitoring"
1201 return
1202 }
1203
1204 if err := cmd.Start(); err != nil {
1205 logrus.WithError(err).Warn("Failed to start cloud-init monitoring command")
1206 exitReason = "Failed to start cloud-init monitoring command"
1207 return
1208 }
1209
1210 scanner := bufio.NewScanner(stdout)
1211 cloudInitMainServiceStarted := false
1212 cloudInitFinished := false
1213
1214 for scanner.Scan() {
1215 line := scanner.Text()
1216 if strings.TrimSpace(line) == "" {
1217 continue
1218 }
1219
1220 if !cloudInitMainServiceStarted {
1221 if isStartedCloudInitMainService(line) {
1222 logrus.Debug("cloud-init-main.service started detected via log pattern")
1223 cloudInitMainServiceStarted = true
1224 } else if !cloudInitFinished {
1225 if isCloudInitFinished(line) {
1226 logrus.Debug("Cloud-init completion detected via log pattern")
1227 cloudInitFinished = true
1228 }
1229 }
1230 } else if !cloudInitFinished && isDeactivatedCloudInitMainService(line) {
1231 logrus.Debug("cloud-init-main.service deactivated detected via log pattern")
1232 cloudInitFinished = true
1233 }
1234
1235 a.emitCloudInitProgressEvent(ctx, &events.CloudInitProgress{
1236 Active: !cloudInitFinished,
1237 LogLine: line,
1238 Completed: cloudInitFinished,
1239 })
1240
1241 if cloudInitFinished {
1242 logrus.Debug("Breaking from cloud-init monitoring loop - completion detected")
1243 if cmd.Process != nil {
1244 logrus.Debug("Killing cloud-init monitoring process after completion")
1245 if err := cmd.Process.Kill(); err != nil {
1246 logrus.WithError(err).Debug("Failed to kill cloud-init monitoring process")
1247 }
1248 }
1249 break
1250 }
1251 }
1252
1253 if err := cmd.Wait(); err != nil {
1254 if ctx.Err() == context.DeadlineExceeded {
1255 logrus.Warn("Cloud-init monitoring timed out after 10 minutes")
1256 exitReason = "Cloud-init monitoring timed out after 10 minutes"
1257 return
1258 }
1259 logrus.WithError(err).Debug("SSH command finished (expected when cloud-init completes)")
1260 }
1261
1262 if !cloudInitFinished {
1263 logrus.Debug("Connection dropped, checking for any remaining cloud-init logs")
1264
1265 finalArgs := a.sshConfig.Args()
1266 finalArgs = append(finalArgs,
1267 "-p", strconv.Itoa(sshPort),
1268 sshAddress,
1269 "sudo", "tail", "-n", "20", "/var/log/cloud-init-output.log",
1270 )
1271
1272 finalCmd := exec.CommandContext(ctx, a.sshConfig.Binary(), finalArgs...)
1273 if finalOutput, err := finalCmd.Output(); err == nil {
1274 for line := range strings.SplitSeq(string(finalOutput), "\n") {
1275 if strings.TrimSpace(line) != "" {
1276 if !cloudInitFinished {
1277 cloudInitFinished = isCloudInitFinished(line)
1278 }
1279
1280 a.emitCloudInitProgressEvent(ctx, &events.CloudInitProgress{
1281 Active: !cloudInitFinished,
1282 LogLine: line,
1283 Completed: cloudInitFinished,
1284 })
1285 }
1286 }
1287 }
1288 }
1289}
1290
1291func isCloudInitFinished(line string) bool {
1292 line = strings.ToLower(strings.TrimSpace(line))
1293 return strings.Contains(line, "cloud-init") && strings.Contains(line, "finished")
1294}
1295
1296func isStartedCloudInitMainService(line string) bool {
1297 line = strings.ToLower(strings.TrimSpace(line))
1298 return strings.HasPrefix(line, "started cloud-init-main.service")
1299}
1300
1301func isDeactivatedCloudInitMainService(line string) bool {
1302 line = strings.ToLower(strings.TrimSpace(line))
1303 // Deactivated event lines end with a line reporting consumed CPU time, etc.
1304 return strings.HasPrefix(line, "cloud-init-main.service: consumed")
1305}
1306
1307func copyToHost(ctx context.Context, sshConfig *ssh.SSHConfig, sshAddress string, sshPort int, local, remote string, skipIfMissing bool) error {
1308 args := sshConfig.Args()
1309 args = append(args,
1310 "-p", strconv.Itoa(sshPort),
1311 sshAddress,
1312 "--",
1313 "env", "LANG=C", "LC_ALL=C", "cat",
1314 remote,
1315 )
1316 logrus.Infof("Copying config from %s to %s", remote, local)
1317 if err := os.MkdirAll(filepath.Dir(local), 0o700); err != nil {
1318 return fmt.Errorf("can't create directory for local file %#q: %w", local, err)
1319 }
1320 cmd := exec.CommandContext(ctx, sshConfig.Binary(), args...)
1321 out, err := cmd.Output()
1322 if err != nil {
1323 var exitErr *exec.ExitError
1324 if errors.As(err, &exitErr) && strings.Contains(string(exitErr.Stderr), "Permission denied") {
1325 logrus.Infof("Retrying %s with sudo (permission denied)", remote)
1326 sudoArgs := sshConfig.Args()
1327 sudoArgs = append(sudoArgs,
1328 "-p", strconv.Itoa(sshPort),
1329 sshAddress,
1330 "--",
1331 "sudo", "cat",
1332 remote,
1333 )
1334 cmd = exec.CommandContext(ctx, sshConfig.Binary(), sudoArgs...)
1335 out, err = cmd.Output()
1336 }
1337 if errors.As(err, &exitErr) && strings.Contains(string(exitErr.Stderr), "No such file or directory") {
1338 if skipIfMissing {
1339 logrus.Infof("Skip missing %s (no such file or directory)", remote)
1340 return nil
1341 }
1342 }
1343 if err != nil {
1344 return fmt.Errorf("failed to run %v: %#q: %w", cmd.Args, string(out), err)
1345 }
1346 }
1347 // The destination may sit inside a writable mount, so don't follow a
1348 // symlink planted there by the guest.
1349 if err := osutil.WriteFileBeneathDir(local, out, 0o600); err != nil {
1350 return fmt.Errorf("can't write to local file %#q: %w", local, err)
1351 }
1352 return nil
1353}