| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "os" |
| 13 | "os/signal" |
| 14 | "runtime" |
| 15 | "sync" |
| 16 | "syscall" |
| 17 | "time" |
| 18 | |
| 19 | "github.com/sirupsen/logrus" |
| 20 | "github.com/spf13/cobra" |
| 21 | |
| 22 | "github.com/lima-vm/lima/v2/pkg/hostagent" |
| 23 | "github.com/lima-vm/lima/v2/pkg/hostagent/api/server" |
| 24 | "github.com/lima-vm/lima/v2/pkg/store" |
| 25 | ) |
| 26 | |
| 27 | func newHostagentCommand() *cobra.Command { |
| 28 | hostagentCommand := &cobra.Command{ |
| 29 | Use: "hostagent INSTANCE", |
| 30 | Short: "Run hostagent", |
| 31 | Args: WrapArgsError(cobra.ExactArgs(1)), |
| 32 | RunE: hostagentAction, |
| 33 | Hidden: true, |
| 34 | } |
| 35 | hostagentCommand.Flags().StringP("pidfile", "p", "", "Write PID to file") |
| 36 | hostagentCommand.Flags().String("socket", "", "Path of hostagent socket") |
| 37 | hostagentCommand.Flags().Bool("run-gui", false, "Run GUI synchronously within hostagent") |
| 38 | hostagentCommand.Flags().String("guestagent", "", "Local file path (not URL) of lima-guestagent.OS-ARCH[.gz]") |
| 39 | hostagentCommand.Flags().String("nerdctl-archive", "", "Local file path (not URL) of nerdctl-full-VERSION-GOOS-GOARCH.tar.gz") |
| 40 | hostagentCommand.Flags().Bool("progress", false, "Show provision script progress by monitoring cloud-init logs") |
| 41 | return hostagentCommand |
| 42 | } |
| 43 | |
| 44 | func hostagentAction(cmd *cobra.Command, args []string) error { |
| 45 | ctx := cmd.Context() |
| 46 | pidfile, err := cmd.Flags().GetString("pidfile") |
| 47 | if err != nil { |
| 48 | return err |
| 49 | } |
| 50 | if pidfile != "" { |
| 51 | if existingPID, err := store.ReadPIDFile(pidfile); existingPID != 0 { |
| 52 | return fmt.Errorf("another hostagent may already be running with pid %d (pidfile %#q)", existingPID, pidfile) |
| 53 | } else if err != nil { |
| 54 | return fmt.Errorf("failed to determine if another hostagent is running: %w", err) |
| 55 | } |
| 56 | if err := store.WritePIDFile(pidfile, os.Getpid()); err != nil { |
| 57 | return err |
| 58 | } |
| 59 | defer os.RemoveAll(pidfile) |
| 60 | } |
| 61 | socket, err := cmd.Flags().GetString("socket") |
| 62 | if err != nil { |
| 63 | return err |
| 64 | } |
| 65 | if socket == "" { |
| 66 | return errors.New("socket must be specified (limactl version mismatch?)") |
| 67 | } |
| 68 | |
| 69 | instName := args[0] |
| 70 | |
| 71 | runGUI, err := cmd.Flags().GetBool("run-gui") |
| 72 | if err != nil { |
| 73 | return err |
| 74 | } |
| 75 | if runGUI { |
| 76 | |
| 77 | runtime.LockOSThread() |
| 78 | defer runtime.UnlockOSThread() |
| 79 | } |
| 80 | |
| 81 | signalCh := make(chan os.Signal, 1) |
| 82 | signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM) |
| 83 | |
| 84 | stdout := &syncWriter{w: cmd.OutOrStdout()} |
| 85 | stderr := &syncWriter{w: cmd.ErrOrStderr()} |
| 86 | defer stdout.flush() |
| 87 | defer stderr.flush() |
| 88 | |
| 89 | initLogrus(stderr) |
| 90 | var opts []hostagent.Opt |
| 91 | guestagentBinary, err := cmd.Flags().GetString("guestagent") |
| 92 | if err != nil { |
| 93 | return err |
| 94 | } |
| 95 | if guestagentBinary != "" { |
| 96 | opts = append(opts, hostagent.WithGuestAgentBinary(guestagentBinary)) |
| 97 | } |
| 98 | nerdctlArchive, err := cmd.Flags().GetString("nerdctl-archive") |
| 99 | if err != nil { |
| 100 | return err |
| 101 | } |
| 102 | if nerdctlArchive != "" { |
| 103 | opts = append(opts, hostagent.WithNerdctlArchive(nerdctlArchive)) |
| 104 | } |
| 105 | showProgress, err := cmd.Flags().GetBool("progress") |
| 106 | if err != nil { |
| 107 | return err |
| 108 | } |
| 109 | if showProgress { |
| 110 | opts = append(opts, hostagent.WithCloudInitProgress(showProgress)) |
| 111 | } |
| 112 | ha, err := hostagent.New(ctx, instName, stdout, signalCh, opts...) |
| 113 | if err != nil { |
| 114 | return err |
| 115 | } |
| 116 | |
| 117 | backend := &server.Backend{ |
| 118 | Agent: ha, |
| 119 | } |
| 120 | r := http.NewServeMux() |
| 121 | server.AddRoutes(r, backend) |
| 122 | srv := &http.Server{Handler: r} |
| 123 | err = os.RemoveAll(socket) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | var lc net.ListenConfig |
| 128 | l, err := lc.Listen(ctx, "unix", socket) |
| 129 | logrus.Infof("hostagent socket created at %s", socket) |
| 130 | if err != nil { |
| 131 | return err |
| 132 | } |
| 133 | go func() { |
| 134 | if serveErr := srv.Serve(l); serveErr != http.ErrServerClosed { |
| 135 | logrus.WithError(serveErr).Warn("hostagent API server exited with an error") |
| 136 | } |
| 137 | }() |
| 138 | defer srv.Close() |
| 139 | return ha.Run(ctx) |
| 140 | } |
| 141 | |
| 142 | |
| 143 | type syncer interface { |
| 144 | Sync() error |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | const syncInterval = 100 * time.Millisecond |
| 157 | |
| 158 | type syncWriter struct { |
| 159 | w io.Writer |
| 160 | |
| 161 | mu sync.Mutex |
| 162 | dirty bool |
| 163 | timer *time.Timer |
| 164 | } |
| 165 | |
| 166 | func (w *syncWriter) Write(p []byte) (int, error) { |
| 167 | w.mu.Lock() |
| 168 | defer w.mu.Unlock() |
| 169 | |
| 170 | written, err := w.w.Write(p) |
| 171 | if err == nil { |
| 172 | w.dirty = true |
| 173 | if w.timer == nil { |
| 174 | w.timer = time.AfterFunc(syncInterval, w.flush) |
| 175 | } |
| 176 | } |
| 177 | return written, err |
| 178 | } |
| 179 | |
| 180 | |
| 181 | func (w *syncWriter) flush() { |
| 182 | w.mu.Lock() |
| 183 | defer w.mu.Unlock() |
| 184 | |
| 185 | if w.timer != nil { |
| 186 | w.timer.Stop() |
| 187 | w.timer = nil |
| 188 | } |
| 189 | if !w.dirty { |
| 190 | return |
| 191 | } |
| 192 | if s, ok := w.w.(syncer); ok { |
| 193 | _ = s.Sync() |
| 194 | } |
| 195 | w.dirty = false |
| 196 | } |
| 197 | |
| 198 | func initLogrus(stderr io.Writer) { |
| 199 | logrus.SetOutput(stderr) |
| 200 | |
| 201 | logrus.SetFormatter(new(logrus.JSONFormatter)) |
| 202 | |
| 203 | if logrus.GetLevel() == logrus.DebugLevel { |
| 204 | logrus.SetLevel(logrus.TraceLevel) |
| 205 | } else { |
| 206 | logrus.SetLevel(logrus.DebugLevel) |
| 207 | } |
| 208 | } |