From 79954fd7a98554192740e06cbc02e036706a1ccf Mon Sep 17 00:00:00 2001 From: nerdylucifer Date: Thu, 21 Aug 2025 15:40:34 +0000 Subject: [PATCH] refactor: reduce context.Background() Signed-off-by: nerdylucifer --- cmd/limactl/clone.go | 2 +- cmd/limactl/delete.go | 4 ++-- cmd/limactl/edit.go | 2 +- cmd/limactl/hostagent.go | 2 +- cmd/limactl/list.go | 2 +- cmd/limactl/network.go | 13 ++++++++----- cmd/limactl/start.go | 18 ++++++++--------- cmd/limactl/template.go | 14 +++++++------- pkg/driver/driver.go | 8 ++++---- pkg/driver/external/client/methods.go | 16 +++++++-------- pkg/driver/external/server/methods.go | 18 ++++++++--------- pkg/driver/external/server/server.go | 10 +++++----- pkg/driver/qemu/qemu_driver.go | 14 +++++++------- pkg/driver/qemu/register.go | 8 ++++++-- pkg/driver/vz/register.go | 8 ++++++-- pkg/driver/vz/vz_driver_darwin.go | 8 ++++---- pkg/driver/wsl2/register.go | 8 ++++++-- pkg/driver/wsl2/wsl_driver_windows.go | 8 ++++---- pkg/driverutil/instance.go | 9 +++++---- pkg/hostagent/hostagent.go | 20 +++++++++---------- pkg/instance/create.go | 2 +- pkg/instance/delete.go | 2 +- pkg/instance/start.go | 4 ++-- pkg/limatmpl/abs.go | 9 +++++---- pkg/limatmpl/abs_test.go | 2 +- pkg/limatmpl/embed.go | 28 +++++++++++++-------------- pkg/registry/registry.go | 4 ++-- pkg/registry/registry_test.go | 23 +++++++++++----------- pkg/snapshot/snapshot.go | 8 ++++---- pkg/yqutil/fuzz_test.go | 4 ++-- pkg/yqutil/yqutil.go | 4 ++-- pkg/yqutil/yqutil_test.go | 10 +++++----- 32 files changed, 155 insertions(+), 137 deletions(-) diff --git a/cmd/limactl/clone.go b/cmd/limactl/clone.go index 18e1c5a6fbd..394cb3ae989 100644 --- a/cmd/limactl/clone.go +++ b/cmd/limactl/clone.go @@ -72,7 +72,7 @@ func cloneAction(cmd *cobra.Command, args []string) error { if err != nil { return err } - yBytes, err := yqutil.EvaluateExpression(yq, yContent) + yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent) if err != nil { return err } diff --git a/cmd/limactl/delete.go b/cmd/limactl/delete.go index 168f41d47ef..5fa53edbfed 100644 --- a/cmd/limactl/delete.go +++ b/cmd/limactl/delete.go @@ -47,7 +47,7 @@ func deleteAction(cmd *cobra.Command, args []string) error { } return err } - if err := instance.Delete(cmd.Context(), inst, force); err != nil { + if err := instance.Delete(ctx, inst, force); err != nil { return fmt.Errorf("failed to delete instance %q: %w", instName, err) } if runtime.GOOS == "darwin" || runtime.GOOS == "linux" { @@ -60,7 +60,7 @@ func deleteAction(cmd *cobra.Command, args []string) error { } logrus.Infof("Deleted %q (%q)", instName, inst.Dir) } - return networks.Reconcile(cmd.Context(), "") + return networks.Reconcile(ctx, "") } func deleteBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { diff --git a/cmd/limactl/edit.go b/cmd/limactl/edit.go index c503e54abd0..5ae9cf58f46 100644 --- a/cmd/limactl/edit.go +++ b/cmd/limactl/edit.go @@ -90,7 +90,7 @@ func editAction(cmd *cobra.Command, args []string) error { var yBytes []byte if len(yqExprs) > 0 { yq := yqutil.Join(yqExprs) - yBytes, err = yqutil.EvaluateExpression(yq, yContent) + yBytes, err = yqutil.EvaluateExpression(ctx, yq, yContent) if err != nil { return err } diff --git a/cmd/limactl/hostagent.go b/cmd/limactl/hostagent.go index d0a363f79ed..37a2de0edb1 100644 --- a/cmd/limactl/hostagent.go +++ b/cmd/limactl/hostagent.go @@ -130,7 +130,7 @@ func hostagentAction(cmd *cobra.Command, args []string) error { } }() defer srv.Close() - return ha.Run(cmd.Context()) + return ha.Run(ctx) } // syncer is implemented by *os.File. diff --git a/cmd/limactl/list.go b/cmd/limactl/list.go index 3ae81851560..eada1130620 100644 --- a/cmd/limactl/list.go +++ b/cmd/limactl/list.go @@ -287,7 +287,7 @@ func listAction(cmd *cobra.Command, args []string) error { } } else { var res []byte - if res, err = yqutil.EvaluateExpression(yqExpr, buf.Bytes()); err != nil { + if res, err = yqutil.EvaluateExpression(ctx, yqExpr, buf.Bytes()); err != nil { return err } str = string(res) diff --git a/cmd/limactl/network.go b/cmd/limactl/network.go index 492237c4d92..c97ae5783f8 100644 --- a/cmd/limactl/network.go +++ b/cmd/limactl/network.go @@ -4,6 +4,7 @@ package main import ( + "context" "encoding/json" "errors" "fmt" @@ -174,6 +175,8 @@ func networkCreateAction(cmd *cobra.Command, args []string) error { return err } + ctx := cmd.Context() + switch mode { case networks.ModeBridged: if gateway != "" { @@ -183,7 +186,7 @@ func networkCreateAction(cmd *cobra.Command, args []string) error { return fmt.Errorf("network mode %q requires specifying interface", mode) } yq := fmt.Sprintf(`.networks.%q = {"mode":%q,"interface":%q}`, name, mode, intf) - return networkApplyYQ(yq) + return networkApplyYQ(ctx, yq) default: if gateway == "" { return fmt.Errorf("network mode %q requires specifying gateway", mode) @@ -208,11 +211,11 @@ func networkCreateAction(cmd *cobra.Command, args []string) error { // TODO: check IP range collision yq := fmt.Sprintf(`.networks.%q = {"mode":%q,"gateway":%q,"netmask":%q,"interface":%q}`, name, mode, gwIP.String(), gwMaskStr, intf) - return networkApplyYQ(yq) + return networkApplyYQ(ctx, yq) } } -func networkApplyYQ(yq string) error { +func networkApplyYQ(ctx context.Context, yq string) error { filePath, err := networks.ConfigFile() if err != nil { return err @@ -221,7 +224,7 @@ func networkApplyYQ(yq string) error { if err != nil { return err } - yBytes, err := yqutil.EvaluateExpression(yq, yContent) + yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent) if err != nil { return err } @@ -263,7 +266,7 @@ func networkDeleteAction(cmd *cobra.Command, args []string) error { yq += " | " } } - return networkApplyYQ(yq) + return networkApplyYQ(cmd.Context(), yq) } func networkBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { diff --git a/cmd/limactl/start.go b/cmd/limactl/start.go index 4b6c2dc016f..c592d6faeb5 100644 --- a/cmd/limactl/start.go +++ b/cmd/limactl/start.go @@ -307,7 +307,7 @@ func loadOrCreateInstance(cmd *cobra.Command, args []string, createOnly bool) (* return nil, err } } else { - tmpl, err = limatmpl.Read(cmd.Context(), name, arg) + tmpl, err = limatmpl.Read(ctx, name, arg) if err != nil { return nil, err } @@ -321,7 +321,7 @@ func loadOrCreateInstance(cmd *cobra.Command, args []string, createOnly bool) (* } } - if err := tmpl.Embed(cmd.Context(), true, true); err != nil { + if err := tmpl.Embed(ctx, true, true); err != nil { return nil, err } yqExprs, err := editflags.YQExpressions(flags, true) @@ -331,18 +331,18 @@ func loadOrCreateInstance(cmd *cobra.Command, args []string, createOnly bool) (* yq := yqutil.Join(yqExprs) if tty { var err error - tmpl, err = chooseNextCreatorState(cmd.Context(), tmpl, yq) + tmpl, err = chooseNextCreatorState(ctx, tmpl, yq) if err != nil { return nil, err } } else { logrus.Info("Terminal is not available, proceeding without opening an editor") - if err := modifyInPlace(tmpl, yq); err != nil { + if err := modifyInPlace(ctx, tmpl, yq); err != nil { return nil, err } } saveBrokenYAML := tty - return instance.Create(cmd.Context(), tmpl.Name, tmpl.Bytes, saveBrokenYAML) + return instance.Create(ctx, tmpl.Name, tmpl.Bytes, saveBrokenYAML) } func applyYQExpressionToExistingInstance(ctx context.Context, inst *limatype.Instance, yq string) (*limatype.Instance, error) { @@ -355,7 +355,7 @@ func applyYQExpressionToExistingInstance(ctx context.Context, inst *limatype.Ins return nil, err } logrus.Debugf("Applying yq expression %q to an existing instance %q", yq, inst.Name) - yBytes, err := yqutil.EvaluateExpression(yq, yContent) + yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent) if err != nil { return nil, err } @@ -381,8 +381,8 @@ func applyYQExpressionToExistingInstance(ctx context.Context, inst *limatype.Ins return store.Inspect(ctx, inst.Name) } -func modifyInPlace(st *limatmpl.Template, yq string) error { - out, err := yqutil.EvaluateExpression(yq, st.Bytes) +func modifyInPlace(ctx context.Context, st *limatmpl.Template, yq string) error { + out, err := yqutil.EvaluateExpression(ctx, yq, st.Bytes) if err != nil { return err } @@ -407,7 +407,7 @@ func (exitSuccessError) ExitCode() int { func chooseNextCreatorState(ctx context.Context, tmpl *limatmpl.Template, yq string) (*limatmpl.Template, error) { for { - if err := modifyInPlace(tmpl, yq); err != nil { + if err := modifyInPlace(ctx, tmpl, yq); err != nil { logrus.WithError(err).Warn("Failed to evaluate yq expression") return tmpl, err } diff --git a/cmd/limactl/template.go b/cmd/limactl/template.go index 005829cfb83..4008691f998 100644 --- a/cmd/limactl/template.go +++ b/cmd/limactl/template.go @@ -125,7 +125,7 @@ func templateCopyAction(cmd *cobra.Command, args []string) error { if embed && verbatim { return errors.New("--verbatim cannot be used with any of --embed, --embed-all, or --fill") } - tmpl, err := limatmpl.Read(cmd.Context(), "", source) + tmpl, err := limatmpl.Read(ctx, "", source) if err != nil { return err } @@ -135,11 +135,11 @@ func templateCopyAction(cmd *cobra.Command, args []string) error { if !verbatim { if embed { // Embed default base.yaml only when fill is true. - if err := tmpl.Embed(cmd.Context(), embedAll, fill); err != nil { + if err := tmpl.Embed(ctx, embedAll, fill); err != nil { return err } } else { - if err := tmpl.UseAbsLocators(); err != nil { + if err := tmpl.UseAbsLocators(ctx); err != nil { return err } } @@ -197,14 +197,14 @@ func templateYQAction(cmd *cobra.Command, args []string) error { ctx := cmd.Context() locator := args[0] expr := args[1] - tmpl, err := limatmpl.Read(cmd.Context(), "", locator) + tmpl, err := limatmpl.Read(ctx, "", locator) if err != nil { return err } if len(tmpl.Bytes) == 0 { return fmt.Errorf("don't know how to interpret %q as a template locator", locator) } - if err := tmpl.Embed(cmd.Context(), true, true); err != nil { + if err := tmpl.Embed(ctx, true, true); err != nil { return err } if err := fillDefaults(ctx, tmpl); err != nil { @@ -241,7 +241,7 @@ func templateValidateAction(cmd *cobra.Command, args []string) error { } for _, arg := range args { - tmpl, err := limatmpl.Read(cmd.Context(), "", arg) + tmpl, err := limatmpl.Read(ctx, "", arg) if err != nil { return err } @@ -252,7 +252,7 @@ func templateValidateAction(cmd *cobra.Command, args []string) error { return fmt.Errorf("can't determine instance name from template locator %q", arg) } // Embed default base.yaml only when fill is true. - if err := tmpl.Embed(cmd.Context(), true, fill); err != nil { + if err := tmpl.Embed(ctx, true, fill); err != nil { return err } // Load() will merge the template with override.yaml and default.yaml via FillDefaults(). diff --git a/pkg/driver/driver.go b/pkg/driver/driver.go index 94c192f0cd4..743c25a51c8 100644 --- a/pkg/driver/driver.go +++ b/pkg/driver/driver.go @@ -46,7 +46,7 @@ type Lifecycle interface { type GUI interface { // RunGUI is for starting GUI synchronously by hostagent. This method should be wait and return only after vm terminates // It returns error if there are any failures - RunGUI() error + RunGUI(context.Context) error ChangeDisplayPassword(ctx context.Context, password string) error DisplayConnection(ctx context.Context) (string, error) @@ -63,7 +63,7 @@ type SnapshotManager interface { // GuestAgent defines operations for the guest agent. type GuestAgent interface { // ForwardGuestAgent returns if the guest agent sock needs forwarding by host agent. - ForwardGuestAgent() bool + ForwardGuestAgent(context.Context) bool // GuestAgentConn returns the guest agent connection, or nil (if forwarded by ssh). GuestAgentConn(_ context.Context) (net.Conn, string, error) @@ -76,12 +76,12 @@ type Driver interface { SnapshotManager GuestAgent - Info() Info + Info(context.Context) Info // Configure sets the configuration for the instance. // TODO: merge Configure and FillConfig? // Or come up with a better name to clarify the difference. - Configure(inst *limatype.Instance) *ConfiguredDriver + Configure(_ context.Context, inst *limatype.Instance) *ConfiguredDriver // FillConfig fills and validates the configuration for the instance. // The config is not set to the instance. diff --git a/pkg/driver/external/client/methods.go b/pkg/driver/external/client/methods.go index b26114bed14..adb230501ff 100644 --- a/pkg/driver/external/client/methods.go +++ b/pkg/driver/external/client/methods.go @@ -119,10 +119,10 @@ func (d *DriverClient) FillConfig(_ context.Context, _ *limatype.LimaYAML, _ str return errors.New("pre-configured driver action not implemented in client driver") } -func (d *DriverClient) RunGUI() error { +func (d *DriverClient) RunGUI(ctx context.Context) error { d.logger.Debug("Running GUI for the driver instance") - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() _, err := d.DriverSvc.RunGUI(ctx, &emptypb.Empty{}) @@ -221,10 +221,10 @@ func (d *DriverClient) ListSnapshots(ctx context.Context) (string, error) { return resp.Snapshots, nil } -func (d *DriverClient) ForwardGuestAgent() bool { +func (d *DriverClient) ForwardGuestAgent(ctx context.Context) bool { d.logger.Debug("Checking if guest agent needs to be forwarded") - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() resp, err := d.DriverSvc.ForwardGuestAgent(ctx, &emptypb.Empty{}) @@ -247,10 +247,10 @@ func (d *DriverClient) GuestAgentConn(ctx context.Context) (net.Conn, string, er return nil, "", nil } -func (d *DriverClient) Info() driver.Info { +func (d *DriverClient) Info(ctx context.Context) driver.Info { d.logger.Debug("Getting driver info") - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() resp, err := d.DriverSvc.Info(ctx, &emptypb.Empty{}) @@ -269,7 +269,7 @@ func (d *DriverClient) Info() driver.Info { return info } -func (d *DriverClient) Configure(inst *limatype.Instance) *driver.ConfiguredDriver { +func (d *DriverClient) Configure(ctx context.Context, inst *limatype.Instance) *driver.ConfiguredDriver { d.logger.Debugf("Setting config for instance %s with SSH local port %d", inst.Name, inst.SSHLocalPort) instJSON, err := inst.MarshalJSON() @@ -278,7 +278,7 @@ func (d *DriverClient) Configure(inst *limatype.Instance) *driver.ConfiguredDriv return nil } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() _, err = d.DriverSvc.Configure(ctx, &pb.SetConfigRequest{ diff --git a/pkg/driver/external/server/methods.go b/pkg/driver/external/server/methods.go index 44fdcc54fd4..54bc21a2f1b 100644 --- a/pkg/driver/external/server/methods.go +++ b/pkg/driver/external/server/methods.go @@ -54,7 +54,7 @@ func (s *DriverServer) Start(_ *emptypb.Empty, stream pb.Driver_StartServer) err } } -func (s *DriverServer) Configure(_ context.Context, req *pb.SetConfigRequest) (*emptypb.Empty, error) { +func (s *DriverServer) Configure(ctx context.Context, req *pb.SetConfigRequest) (*emptypb.Empty, error) { s.logger.Debugf("Received SetConfig request") var inst limatype.Instance @@ -63,7 +63,7 @@ func (s *DriverServer) Configure(_ context.Context, req *pb.SetConfigRequest) (* return &emptypb.Empty{}, err } - _ = s.driver.Configure(&inst) + _ = s.driver.Configure(ctx, &inst) return &emptypb.Empty{}, nil } @@ -77,7 +77,7 @@ func (s *DriverServer) GuestAgentConn(ctx context.Context, _ *emptypb.Empty) (*e } if connType != "unix" { - proxySocketPath := filepath.Join(s.driver.Info().InstanceDir, filenames.GuestAgentSock) + proxySocketPath := filepath.Join(s.driver.Info(ctx).InstanceDir, filenames.GuestAgentSock) var lc net.ListenConfig listener, err := lc.Listen(ctx, "unix", proxySocketPath) @@ -103,9 +103,9 @@ func (s *DriverServer) GuestAgentConn(ctx context.Context, _ *emptypb.Empty) (*e return &emptypb.Empty{}, nil } -func (s *DriverServer) Info(_ context.Context, _ *emptypb.Empty) (*pb.InfoResponse, error) { +func (s *DriverServer) Info(ctx context.Context, _ *emptypb.Empty) (*pb.InfoResponse, error) { s.logger.Debug("Received GetInfo request") - info := s.driver.Info() + info := s.driver.Info(ctx) infoJSON, err := json.Marshal(info) if err != nil { @@ -162,9 +162,9 @@ func (s *DriverServer) Stop(ctx context.Context, empty *emptypb.Empty) (*emptypb return empty, nil } -func (s *DriverServer) RunGUI(_ context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) { +func (s *DriverServer) RunGUI(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) { s.logger.Debug("Received RunGUI request") - err := s.driver.RunGUI() + err := s.driver.RunGUI(ctx) if err != nil { s.logger.Errorf("RunGUI failed: %v", err) return empty, err @@ -280,7 +280,7 @@ func (s *DriverServer) ListSnapshots(ctx context.Context, _ *emptypb.Empty) (*pb return &pb.ListSnapshotsResponse{Snapshots: snapshots}, nil } -func (s *DriverServer) ForwardGuestAgent(_ context.Context, _ *emptypb.Empty) (*pb.ForwardGuestAgentResponse, error) { +func (s *DriverServer) ForwardGuestAgent(ctx context.Context, _ *emptypb.Empty) (*pb.ForwardGuestAgentResponse, error) { s.logger.Debug("Received ForwardGuestAgent request") - return &pb.ForwardGuestAgentResponse{ShouldForward: s.driver.ForwardGuestAgent()}, nil + return &pb.ForwardGuestAgentResponse{ShouldForward: s.driver.ForwardGuestAgent(ctx)}, nil } diff --git a/pkg/driver/external/server/server.go b/pkg/driver/external/server/server.go index bc69ffe8c78..a6730dd94e3 100644 --- a/pkg/driver/external/server/server.go +++ b/pkg/driver/external/server/server.go @@ -68,7 +68,7 @@ func Serve(ctx context.Context, driver driver.Driver) { logger := logrus.New() logger.SetLevel(logrus.DebugLevel) - socketPath := filepath.Join(os.TempDir(), fmt.Sprintf("lima-driver-%s-%d.sock", driver.Info().Name, os.Getpid())) + socketPath := filepath.Join(os.TempDir(), fmt.Sprintf("lima-driver-%s-%d.sock", driver.Info(ctx).Name, os.Getpid())) defer func() { if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) { @@ -145,8 +145,8 @@ func Serve(ctx context.Context, driver driver.Driver) { } }() - go func() { - logger.Infof("Starting external driver server for %s", driver.Info().Name) + go func(ctx context.Context) { + logger.Infof("Starting external driver server for %s", driver.Info(ctx).Name) logger.Infof("Server starting on Unix socket: %s", socketPath) if err := server.Serve(tListener); err != nil { if errors.Is(err, grpc.ErrServerStopped) { @@ -155,7 +155,7 @@ func Serve(ctx context.Context, driver driver.Driver) { logger.Errorf("Failed to serve: %v", err) } } - }() + }(ctx) <-shutdownCh server.GracefulStop() @@ -214,7 +214,7 @@ func Start(extDriver *registry.ExternalDriver, instName string) error { } extDriver.InstanceName = instName - ctx, cancel := context.WithCancel(context.Background()) + ctx, cancel := context.WithCancel(extDriver.Ctx) cmd := exec.CommandContext(ctx, extDriver.Path) stdout, err := cmd.StdoutPipe() diff --git a/pkg/driver/qemu/qemu_driver.go b/pkg/driver/qemu/qemu_driver.go index e468e55b384..ac952bdfc38 100644 --- a/pkg/driver/qemu/qemu_driver.go +++ b/pkg/driver/qemu/qemu_driver.go @@ -68,7 +68,7 @@ func New() *LimaQemuDriver { } } -func (l *LimaQemuDriver) Configure(inst *limatype.Instance) *driver.ConfiguredDriver { +func (l *LimaQemuDriver) Configure(_ context.Context, inst *limatype.Instance) *driver.ConfiguredDriver { l.Instance = inst l.SSHLocalPort = inst.SSHLocalPort @@ -214,8 +214,8 @@ func (l *LimaQemuDriver) CreateDisk(ctx context.Context) error { return EnsureDisk(ctx, qCfg) } -func (l *LimaQemuDriver) Start(_ context.Context) (chan error, error) { - ctx, cancel := context.WithCancel(context.Background()) +func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { + ctx, cancel := context.WithCancel(ctx) defer func() { if l.qCmd == nil { cancel() @@ -499,7 +499,7 @@ func (l *LimaQemuDriver) shutdownQEMU(ctx context.Context, timeout time.Duration logrus.WithError(err).Warnf("failed to send system_powerdown command via the QMP socket %q, forcibly killing QEMU", qmpSockPath) return l.killQEMU(ctx, timeout, qCmd, qWaitCh) } - timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), timeout) + timeoutCtx, timeoutCancel := context.WithTimeout(ctx, timeout) defer timeoutCancel() select { @@ -646,7 +646,7 @@ func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) { return b.String(), nil } -func (l *LimaQemuDriver) Info() driver.Info { +func (l *LimaQemuDriver) Info(_ context.Context) driver.Info { var info driver.Info info.Name = "qemu" if l.Instance != nil && l.Instance.Dir != "" { @@ -679,7 +679,7 @@ func (l *LimaQemuDriver) Delete(_ context.Context) error { return nil } -func (l *LimaQemuDriver) RunGUI() error { +func (l *LimaQemuDriver) RunGUI(_ context.Context) error { return nil } @@ -691,7 +691,7 @@ func (l *LimaQemuDriver) Unregister(_ context.Context) error { return nil } -func (l *LimaQemuDriver) ForwardGuestAgent() bool { +func (l *LimaQemuDriver) ForwardGuestAgent(_ context.Context) bool { // if driver is not providing, use host agent return l.vSockPort == 0 && l.virtioPort == "" } diff --git a/pkg/driver/qemu/register.go b/pkg/driver/qemu/register.go index 8efca9d2c98..ccd64fe040e 100644 --- a/pkg/driver/qemu/register.go +++ b/pkg/driver/qemu/register.go @@ -5,8 +5,12 @@ package qemu -import "github.com/lima-vm/lima/v2/pkg/registry" +import ( + "context" + + "github.com/lima-vm/lima/v2/pkg/registry" +) func init() { - registry.Register(New()) + registry.Register(context.Background(), New()) } diff --git a/pkg/driver/vz/register.go b/pkg/driver/vz/register.go index 41ac32a5dd2..582ba69a057 100644 --- a/pkg/driver/vz/register.go +++ b/pkg/driver/vz/register.go @@ -5,8 +5,12 @@ package vz -import "github.com/lima-vm/lima/v2/pkg/registry" +import ( + "context" + + "github.com/lima-vm/lima/v2/pkg/registry" +) func init() { - registry.Register(New()) + registry.Register(context.Background(), New()) } diff --git a/pkg/driver/vz/vz_driver_darwin.go b/pkg/driver/vz/vz_driver_darwin.go index 235557e552f..52be061ea4e 100644 --- a/pkg/driver/vz/vz_driver_darwin.go +++ b/pkg/driver/vz/vz_driver_darwin.go @@ -90,7 +90,7 @@ func New() *LimaVzDriver { } } -func (l *LimaVzDriver) Configure(inst *limatype.Instance) *driver.ConfiguredDriver { +func (l *LimaVzDriver) Configure(_ context.Context, inst *limatype.Instance) *driver.ConfiguredDriver { l.Instance = inst l.SSHLocalPort = inst.SSHLocalPort @@ -287,7 +287,7 @@ func (l *LimaVzDriver) canRunGUI() bool { } } -func (l *LimaVzDriver) RunGUI() error { +func (l *LimaVzDriver) RunGUI(_ context.Context) error { if l.canRunGUI() { return l.machine.StartGraphicApplication(1920, 1200) } @@ -333,7 +333,7 @@ func (l *LimaVzDriver) GuestAgentConn(_ context.Context) (net.Conn, string, erro return nil, "", errors.New("unable to connect to guest agent via vsock port 2222") } -func (l *LimaVzDriver) Info() driver.Info { +func (l *LimaVzDriver) Info(_ context.Context) driver.Info { var info driver.Info info.Name = "vz" @@ -399,7 +399,7 @@ func (l *LimaVzDriver) ListSnapshots(_ context.Context) (string, error) { return "", errUnimplemented } -func (l *LimaVzDriver) ForwardGuestAgent() bool { +func (l *LimaVzDriver) ForwardGuestAgent(_ context.Context) bool { // If driver is not providing, use host agent return l.vSockPort == 0 && l.virtioPort == "" } diff --git a/pkg/driver/wsl2/register.go b/pkg/driver/wsl2/register.go index e824d064580..c75d6c289ad 100644 --- a/pkg/driver/wsl2/register.go +++ b/pkg/driver/wsl2/register.go @@ -5,8 +5,12 @@ package wsl2 -import "github.com/lima-vm/lima/v2/pkg/registry" +import ( + "context" + + "github.com/lima-vm/lima/v2/pkg/registry" +) func init() { - registry.Register(New()) + registry.Register(context.Background(), New()) } diff --git a/pkg/driver/wsl2/wsl_driver_windows.go b/pkg/driver/wsl2/wsl_driver_windows.go index 17886de8863..c1acff1cf30 100644 --- a/pkg/driver/wsl2/wsl_driver_windows.go +++ b/pkg/driver/wsl2/wsl_driver_windows.go @@ -71,7 +71,7 @@ func New() *LimaWslDriver { } } -func (l *LimaWslDriver) Configure(inst *limatype.Instance) *driver.ConfiguredDriver { +func (l *LimaWslDriver) Configure(_ context.Context, inst *limatype.Instance) *driver.ConfiguredDriver { l.Instance = inst l.SSHLocalPort = inst.SSHLocalPort @@ -264,7 +264,7 @@ func (l *LimaWslDriver) canRunGUI() bool { return false } -func (l *LimaWslDriver) RunGUI() error { +func (l *LimaWslDriver) RunGUI(_ context.Context) error { return fmt.Errorf("RunGUI is not supported for the given driver '%s' and display '%s'", "wsl", *l.Instance.Config.Video.Display) } @@ -298,7 +298,7 @@ func (l *LimaWslDriver) GuestAgentConn(ctx context.Context) (net.Conn, string, e return conn, "vsock", nil } -func (l *LimaWslDriver) Info() driver.Info { +func (l *LimaWslDriver) Info(_ context.Context) driver.Info { var info driver.Info info.Name = "wsl2" if l.Instance != nil { @@ -351,7 +351,7 @@ func (l *LimaWslDriver) ListSnapshots(_ context.Context) (string, error) { return "", errUnimplemented } -func (l *LimaWslDriver) ForwardGuestAgent() bool { +func (l *LimaWslDriver) ForwardGuestAgent(_ context.Context) bool { // If driver is not providing, use host agent return l.vSockPort == 0 && l.virtioPort == "" } diff --git a/pkg/driverutil/instance.go b/pkg/driverutil/instance.go index dfb1422c20b..065f2f55cef 100644 --- a/pkg/driverutil/instance.go +++ b/pkg/driverutil/instance.go @@ -4,6 +4,7 @@ package driverutil import ( + "context" "fmt" "github.com/sirupsen/logrus" @@ -15,7 +16,7 @@ import ( ) // CreateConfiguredDriver creates a driver.ConfiguredDriver for the given instance. -func CreateConfiguredDriver(inst *limatype.Instance, sshLocalPort int) (*driver.ConfiguredDriver, error) { +func CreateConfiguredDriver(ctx context.Context, inst *limatype.Instance, sshLocalPort int) (*driver.ConfiguredDriver, error) { limaDriver := inst.Config.VMType extDriver, intDriver, exists := registry.Get(*limaDriver) if !exists { @@ -36,9 +37,9 @@ func CreateConfiguredDriver(inst *limatype.Instance, sshLocalPort int) (*driver. extDriver.InstanceName = inst.Name } - return extDriver.Client.Configure(inst), nil + return extDriver.Client.Configure(ctx, inst), nil } - logrus.Debugf("Using internal driver %q", intDriver.Info().Name) - return intDriver.Configure(inst), nil + logrus.Debugf("Using internal driver %q", intDriver.Info(ctx).Name) + return intDriver.Configure(ctx, inst), nil } diff --git a/pkg/hostagent/hostagent.go b/pkg/hostagent/hostagent.go index 3affdf6b0c1..1e287f0cf5e 100644 --- a/pkg/hostagent/hostagent.go +++ b/pkg/hostagent/hostagent.go @@ -155,13 +155,13 @@ func New(ctx context.Context, instName string, stdout io.Writer, signalCh chan o } } - limaDriver, err := driverutil.CreateConfiguredDriver(inst, sshLocalPort) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, sshLocalPort) if err != nil { return nil, fmt.Errorf("failed to create driver instance: %w", err) } - vSockPort := limaDriver.Info().VsockPort - virtioPort := limaDriver.Info().VirtioPort + vSockPort := limaDriver.Info(ctx).VsockPort + virtioPort := limaDriver.Info(ctx).VirtioPort if err := cidata.GenerateCloudConfig(ctx, inst.Dir, instName, inst.Config); err != nil { return nil, err @@ -358,7 +358,7 @@ func (a *HostAgent) Run(ctx context.Context) error { } // WSL instance SSH address isn't known until after VM start - if a.driver.Info().Features.DynamicSSHAddress { + if a.driver.Info(ctx).Features.DynamicSSHAddress { sshAddr, err := a.driver.SSHAddress(ctx) if err != nil { return err @@ -410,14 +410,14 @@ func (a *HostAgent) Run(ctx context.Context) error { logrus.Infof("VNC Password: `%s`", vncpwdfile) } - if a.driver.Info().Features.CanRunGUI { + if a.driver.Info(ctx).Features.CanRunGUI { go func() { err = a.startRoutinesAndWait(ctx, errCh) if err != nil { logrus.Error(err) } }() - return a.driver.RunGUI() + return a.driver.RunGUI(ctx) } return a.startRoutinesAndWait(ctx, errCh) } @@ -611,7 +611,7 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) { // TODO: use vSock (when QEMU for macOS gets support for vSock) // Setup all socket forwards and defer their teardown - if !(a.driver.Info().Features.DynamicSSHAddress) { + if !(a.driver.Info(ctx).Features.DynamicSSHAddress) { logrus.Debugf("Forwarding unix sockets") for _, rule := range a.instConfig.PortForwards { if rule.GuestSocket != "" { @@ -636,7 +636,7 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) { } } } - if a.driver.ForwardGuestAgent() { + if a.driver.ForwardGuestAgent(ctx) { if err := forwardSSH(context.Background(), a.sshConfig, a.sshLocalPort, localUnix, remoteUnix, verbCancel, false); err != nil { errs = append(errs, err) } @@ -647,7 +647,7 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) { go func() { if a.instConfig.MountInotify != nil && *a.instConfig.MountInotify { if a.client == nil || !isGuestAgentSocketAccessible(ctx, a.client) { - if a.driver.ForwardGuestAgent() { + if a.driver.ForwardGuestAgent(ctx) { _ = forwardSSH(ctx, a.sshConfig, a.sshLocalPort, localUnix, remoteUnix, verbForward, false) } } @@ -660,7 +660,7 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) { for { if a.client == nil || !isGuestAgentSocketAccessible(ctx, a.client) { - if a.driver.ForwardGuestAgent() { + if a.driver.ForwardGuestAgent(ctx) { _ = forwardSSH(ctx, a.sshConfig, a.sshLocalPort, localUnix, remoteUnix, verbForward, false) } } diff --git a/pkg/instance/create.go b/pkg/instance/create.go index 08c5bd42212..405286c1ace 100644 --- a/pkg/instance/create.go +++ b/pkg/instance/create.go @@ -80,7 +80,7 @@ func Create(ctx context.Context, instName string, instConfig []byte, saveBrokenY return nil, err } - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return nil, fmt.Errorf("failed to create driver instance: %w", err) } diff --git a/pkg/instance/delete.go b/pkg/instance/delete.go index df0954db5e6..61e5956acff 100644 --- a/pkg/instance/delete.go +++ b/pkg/instance/delete.go @@ -36,7 +36,7 @@ func Delete(ctx context.Context, inst *limatype.Instance, force bool) error { } func unregister(ctx context.Context, inst *limatype.Instance) error { - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return fmt.Errorf("failed to create driver instance: %w", err) } diff --git a/pkg/instance/start.go b/pkg/instance/start.go index 3114ec1b361..4ea22095050 100644 --- a/pkg/instance/start.go +++ b/pkg/instance/start.go @@ -53,7 +53,7 @@ func Prepare(ctx context.Context, inst *limatype.Instance) (*Prepared, error) { return nil, err } } - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return nil, fmt.Errorf("failed to create driver instance: %w", err) } @@ -191,7 +191,7 @@ func Start(ctx context.Context, inst *limatype.Instance, limactl string, launchH "hostagent", "--pidfile", haPIDPath, "--socket", haSockPath) - if prepared.Driver.Info().Features.CanRunGUI { + if prepared.Driver.Info(ctx).Features.CanRunGUI { args = append(args, "--run-gui") } if prepared.GuestAgent != "" { diff --git a/pkg/limatmpl/abs.go b/pkg/limatmpl/abs.go index bfc7060e9e5..0104ab94339 100644 --- a/pkg/limatmpl/abs.go +++ b/pkg/limatmpl/abs.go @@ -4,6 +4,7 @@ package limatmpl import ( + "context" "errors" "fmt" "net/url" @@ -17,12 +18,12 @@ import ( // UseAbsLocators will replace all relative template locators with absolute ones, so this template // can be stored anywhere and still reference the same base templates and files. -func (tmpl *Template) UseAbsLocators() error { - err := tmpl.useAbsLocators() +func (tmpl *Template) UseAbsLocators(ctx context.Context) error { + err := tmpl.useAbsLocators(ctx) return tmpl.ClearOnError(err) } -func (tmpl *Template) useAbsLocators() error { +func (tmpl *Template) useAbsLocators(ctx context.Context) error { if err := tmpl.Unmarshal(); err != nil { return err } @@ -66,7 +67,7 @@ func (tmpl *Template) useAbsLocators() error { tmpl.expr.WriteString(fmt.Sprintf("| ($a.provision[%d].file | select(type == \"!!map\") | .url) = %q\n", i, absLocator)) } } - return tmpl.evalExpr() + return tmpl.evalExpr(ctx) } // withVolume adds the volume name of the current working directory to a path without volume name. diff --git a/pkg/limatmpl/abs_test.go b/pkg/limatmpl/abs_test.go index 5b78e9c155b..160bdb2fd8c 100644 --- a/pkg/limatmpl/abs_test.go +++ b/pkg/limatmpl/abs_test.go @@ -126,7 +126,7 @@ func RunUseAbsLocatorTest(t *testing.T, tc useAbsLocatorsTestCase) { Bytes: []byte(strings.TrimSpace(tc.template)), Locator: tc.locator, } - err := tmpl.UseAbsLocators() + err := tmpl.UseAbsLocators(t.Context()) assert.NilError(t, err, tc.description) actual := strings.TrimSpace(string(tmpl.Bytes)) diff --git a/pkg/limatmpl/embed.go b/pkg/limatmpl/embed.go index a58712247bf..2c601da58ec 100644 --- a/pkg/limatmpl/embed.go +++ b/pkg/limatmpl/embed.go @@ -29,7 +29,7 @@ import ( // template with the merged result. It also inlines all external provisioning // and probe scripts. func (tmpl *Template) Embed(ctx context.Context, embedAll, defaultBase bool) error { - if err := tmpl.UseAbsLocators(); err != nil { + if err := tmpl.UseAbsLocators(ctx); err != nil { return err } seen := make(map[string]bool) @@ -38,7 +38,7 @@ func (tmpl *Template) Embed(ctx context.Context, embedAll, defaultBase bool) err // This must be done after **all** base templates have been merged, so that wildcard keys can match // against all earlier list entries, and not just against the direct parent template. if err == nil { - err = tmpl.combineListEntries() + err = tmpl.combineListEntries(ctx) } return tmpl.ClearOnError(err) } @@ -58,7 +58,7 @@ func (tmpl *Template) embedAllBases(ctx context.Context, embedAll, defaultBase b tmpl.expr.WriteString("| ($a.base | select(type == \"!!map\")) |= [[] + .]\n") // prepend base template at the beginning of the list tmpl.expr.WriteString(fmt.Sprintf("| $a.base = [%q, $a.base[]]\n", defaultBaseFilename)) - if err := tmpl.evalExpr(); err != nil { + if err := tmpl.evalExpr(ctx); err != nil { return err } } @@ -115,13 +115,13 @@ func (tmpl *Template) embedBase(ctx context.Context, baseLocator limatype.Locato if err != nil { return err } - if err := base.UseAbsLocators(); err != nil { + if err := base.UseAbsLocators(ctx); err != nil { return err } if err := base.embedAllBases(ctx, embedAll, false, seen); err != nil { return err } - if err := tmpl.merge(base); err != nil { + if err := tmpl.merge(ctx, base); err != nil { return err } if len(tmpl.Bytes) > yBytesLimit { @@ -132,10 +132,10 @@ func (tmpl *Template) embedBase(ctx context.Context, baseLocator limatype.Locato // evalExprImpl evaluates tmpl.expr against one or more documents. // Called by evalExpr() and embedAllScripts() for single documents and merge() for 2 documents. -func (tmpl *Template) evalExprImpl(prefix string, b []byte) error { +func (tmpl *Template) evalExprImpl(ctx context.Context, prefix string, b []byte) error { var err error expr := prefix + tmpl.expr.String() + "| $a" - tmpl.Bytes, err = yqutil.EvaluateExpression(expr, b) + tmpl.Bytes, err = yqutil.EvaluateExpression(ctx, expr, b) // Make sure the YAML ends with just a single newline tmpl.Bytes = append(bytes.TrimRight(tmpl.Bytes, "\n"), '\n') tmpl.Config = nil @@ -144,23 +144,23 @@ func (tmpl *Template) evalExprImpl(prefix string, b []byte) error { } // evalExpr evaluates tmpl.expr against the tmpl.Bytes document. -func (tmpl *Template) evalExpr() error { +func (tmpl *Template) evalExpr(ctx context.Context) error { var err error if tmpl.expr.Len() > 0 { // There is just a single document; $a and $b are the same singleDocument := "select(document_index == 0) as $a | $a as $b\n" - err = tmpl.evalExprImpl(singleDocument, tmpl.Bytes) + err = tmpl.evalExprImpl(ctx, singleDocument, tmpl.Bytes) } return err } // merge merges the base template into tmpl. -func (tmpl *Template) merge(base *Template) error { +func (tmpl *Template) merge(ctx context.Context, base *Template) error { if err := tmpl.mergeBase(base); err != nil { return tmpl.ClearOnError(err) } documents := fmt.Sprintf("%s\n---\n%s", string(tmpl.Bytes), string(base.Bytes)) - return tmpl.evalExprImpl(mergeDocuments, []byte(documents)) + return tmpl.evalExprImpl(ctx, mergeDocuments, []byte(documents)) } // mergeBase generates a yq script to merge the template with a base. @@ -328,7 +328,7 @@ func (tmpl *Template) upgradeListEntryStringToMapField(list string, idx int, fie // * The field order is not maintained when entries with a matching key are merged. // * The unique keys (and mount locations) are assumed to not be subject to Go templating. // * A wildcard key '*' matches all prior list entries. -func (tmpl *Template) combineListEntries() error { +func (tmpl *Template) combineListEntries(ctx context.Context) error { if err := tmpl.Unmarshal(); err != nil { return err } @@ -337,7 +337,7 @@ func (tmpl *Template) combineListEntries() error { tmpl.combineMounts() tmpl.combineNetworks() - return tmpl.evalExpr() + return tmpl.evalExpr(ctx) } // TODO: Maybe instead of hard-coding all the yaml names of LimaYAML struct fields we should @@ -667,5 +667,5 @@ func (tmpl *Template) embedAllScripts(ctx context.Context, embedAll bool) error tmpl.updateScript("provision", i, newName, string(scriptTmpl.Bytes), p.File.URL) } } - return tmpl.evalExpr() + return tmpl.evalExpr(ctx) } diff --git a/pkg/registry/registry.go b/pkg/registry/registry.go index e9369203602..b562741e13b 100644 --- a/pkg/registry/registry.go +++ b/pkg/registry/registry.go @@ -194,8 +194,8 @@ func isExecutable(mode os.FileMode) bool { return mode&0o111 != 0 } -func Register(driver driver.Driver) { - name := driver.Info().Name +func Register(ctx context.Context, driver driver.Driver) { + name := driver.Info(ctx).Name if _, exists := internalDrivers[name]; exists { return } diff --git a/pkg/registry/registry_test.go b/pkg/registry/registry_test.go index 8e783f44994..c9219a083ee 100644 --- a/pkg/registry/registry_test.go +++ b/pkg/registry/registry_test.go @@ -33,7 +33,7 @@ func (m *mockDriver) Delete(_ context.Context) error func (m *mockDriver) CreateDisk(_ context.Context) error { return nil } func (m *mockDriver) Start(_ context.Context) (chan error, error) { return nil, nil } func (m *mockDriver) Stop(_ context.Context) error { return nil } -func (m *mockDriver) RunGUI() error { return nil } +func (m *mockDriver) RunGUI(_ context.Context) error { return nil } func (m *mockDriver) ChangeDisplayPassword(_ context.Context, _ string) error { return nil } func (m *mockDriver) DisplayConnection(_ context.Context) (string, error) { return "", nil } func (m *mockDriver) CreateSnapshot(_ context.Context, _ string) error { return nil } @@ -42,12 +42,12 @@ func (m *mockDriver) DeleteSnapshot(_ context.Context, _ string) error func (m *mockDriver) ListSnapshots(_ context.Context) (string, error) { return "", nil } func (m *mockDriver) Register(_ context.Context) error { return nil } func (m *mockDriver) Unregister(_ context.Context) error { return nil } -func (m *mockDriver) ForwardGuestAgent() bool { return false } +func (m *mockDriver) ForwardGuestAgent(_ context.Context) bool { return false } func (m *mockDriver) GuestAgentConn(_ context.Context) (net.Conn, string, error) { return nil, "", nil } -func (m *mockDriver) Info() driver.Info { - return driver.Info{Name: m.Name} +func (m *mockDriver) Info(_ context.Context) driver.Info { return driver.Info{Name: m.Name} } +func (m *mockDriver) Configure(_ context.Context, _ *limatype.Instance) *driver.ConfiguredDriver { + return nil } -func (m *mockDriver) Configure(_ *limatype.Instance) *driver.ConfiguredDriver { return nil } func (m *mockDriver) FillConfig(_ context.Context, _ *limatype.LimaYAML, _ string) error { return nil } func (m *mockDriver) InspectStatus(_ context.Context, _ *limatype.Instance) string { return "" } func (m *mockDriver) SSHAddress(_ context.Context) (string, error) { return "", nil } @@ -56,10 +56,11 @@ func (m *mockDriver) BootScripts() (map[string][]byte, error) func TestRegister(t *testing.T) { BackupRegistry(t) + ctx := t.Context() mockDrv := newMockDriver("test-driver") mockDrv2 := newMockDriver("test-driver-2") - Register(mockDrv) - Register(mockDrv2) + Register(ctx, mockDrv) + Register(ctx, mockDrv2) assert.Equal(t, len(internalDrivers), 2) assert.Equal(t, internalDrivers["test-driver"], mockDrv) @@ -67,7 +68,7 @@ func TestRegister(t *testing.T) { // Test registering duplicate driver (should not overwrite) mockDrv3 := newMockDriver("test-driver") - Register(mockDrv3) + Register(ctx, mockDrv3) assert.Equal(t, len(internalDrivers), 2) assert.Equal(t, internalDrivers["test-driver"], mockDrv) @@ -79,7 +80,7 @@ func TestRegister(t *testing.T) { assert.Equal(t, exists, true) assert.Assert(t, extDriver == nil) assert.Assert(t, intDriver != nil) - assert.Equal(t, intDriver.Info().Name, "test-driver") + assert.Equal(t, intDriver.Info(ctx).Name, "test-driver") vmTypes := List() assert.Equal(t, vmTypes["test-driver-2"], Internal) @@ -183,7 +184,7 @@ func TestGet(t *testing.T) { BackupRegistry(t) mockDrv := newMockDriver("internal-test") - Register(mockDrv) + Register(t.Context(), mockDrv) extDriver, intDriver, exists := Get("internal-test") assert.Equal(t, exists, true) @@ -211,7 +212,7 @@ func TestList(t *testing.T) { assert.Equal(t, len(vmTypes), 0) mockDrv := newMockDriver("internal-test") - Register(mockDrv) + Register(t.Context(), mockDrv) vmTypes = List() assert.Equal(t, len(vmTypes), 1) diff --git a/pkg/snapshot/snapshot.go b/pkg/snapshot/snapshot.go index e76caa6efdf..ec0ee3ba02b 100644 --- a/pkg/snapshot/snapshot.go +++ b/pkg/snapshot/snapshot.go @@ -12,7 +12,7 @@ import ( ) func Del(ctx context.Context, inst *limatype.Instance, tag string) error { - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return fmt.Errorf("failed to create driver instance: %w", err) } @@ -21,7 +21,7 @@ func Del(ctx context.Context, inst *limatype.Instance, tag string) error { } func Save(ctx context.Context, inst *limatype.Instance, tag string) error { - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return fmt.Errorf("failed to create driver instance: %w", err) } @@ -29,7 +29,7 @@ func Save(ctx context.Context, inst *limatype.Instance, tag string) error { } func Load(ctx context.Context, inst *limatype.Instance, tag string) error { - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return fmt.Errorf("failed to create driver instance: %w", err) } @@ -37,7 +37,7 @@ func Load(ctx context.Context, inst *limatype.Instance, tag string) error { } func List(ctx context.Context, inst *limatype.Instance) (string, error) { - limaDriver, err := driverutil.CreateConfiguredDriver(inst, 0) + limaDriver, err := driverutil.CreateConfiguredDriver(ctx, inst, 0) if err != nil { return "", fmt.Errorf("failed to create driver instance: %w", err) } diff --git a/pkg/yqutil/fuzz_test.go b/pkg/yqutil/fuzz_test.go index 368f85ba264..28973838309 100644 --- a/pkg/yqutil/fuzz_test.go +++ b/pkg/yqutil/fuzz_test.go @@ -8,7 +8,7 @@ import ( ) func FuzzEvaluateExpression(f *testing.F) { - f.Fuzz(func(_ *testing.T, expression string, content []byte) { - _, _ = EvaluateExpression(expression, content) + f.Fuzz(func(t *testing.T, expression string, content []byte) { + _, _ = EvaluateExpression(t.Context(), expression, content) }) } diff --git a/pkg/yqutil/yqutil.go b/pkg/yqutil/yqutil.go index bfd4a6c7238..af0c6ff4276 100644 --- a/pkg/yqutil/yqutil.go +++ b/pkg/yqutil/yqutil.go @@ -88,7 +88,7 @@ func EvaluateExpressionPlain(expression, content string, colorsEnabled bool) (st } // EvaluateExpression evaluates the yq expression and returns the output formatted with yamlfmt. -func EvaluateExpression(expression string, content []byte) ([]byte, error) { +func EvaluateExpression(ctx context.Context, expression string, content []byte) ([]byte, error) { if expression == "" { return content, nil } @@ -101,7 +101,7 @@ func EvaluateExpression(expression string, content []byte) ([]byte, error) { // once here and once inside `formatter.Format`. // Currently, calling `ApplyFeatures()` with `FeatureApplyBefore` twice is not an issue, // but future changes to `yamlfmt` might cause problems if it is called twice. - _, contentModified, err := formatter.Features.ApplyFeatures(context.Background(), content, yamlfmt.FeatureApplyBefore) + _, contentModified, err := formatter.Features.ApplyFeatures(ctx, content, yamlfmt.FeatureApplyBefore) if err != nil { return nil, err } diff --git a/pkg/yqutil/yqutil_test.go b/pkg/yqutil/yqutil_test.go index 7fdc5da94cf..a299063c317 100644 --- a/pkg/yqutil/yqutil_test.go +++ b/pkg/yqutil/yqutil_test.go @@ -35,7 +35,7 @@ func TestEvaluateExpressionEmpty(t *testing.T) { foo: bar ` expected := content - out, err := EvaluateExpression(expression, []byte(content)) + out, err := EvaluateExpression(t.Context(), expression, []byte(content)) assert.NilError(t, err) assert.Equal(t, expected, string(out)) } @@ -57,7 +57,7 @@ cpus: 2 # Memory size memory: 2GiB ` - out, err := EvaluateExpression(expression, []byte(content)) + out, err := EvaluateExpression(t.Context(), expression, []byte(content)) assert.NilError(t, err) assert.Equal(t, expected, string(out)) } @@ -89,14 +89,14 @@ mounts: - location: foo mountPoint: bar ` - out, err := EvaluateExpression(expression, []byte(content)) + out, err := EvaluateExpression(t.Context(), expression, []byte(content)) assert.NilError(t, err) assert.Equal(t, expected, string(out)) } func TestEvaluateExpressionError(t *testing.T) { expression := `arch: aarch64` - _, err := EvaluateExpression(expression, []byte("")) + _, err := EvaluateExpression(t.Context(), expression, []byte("")) assert.ErrorContains(t, err, "invalid input text") } @@ -119,7 +119,7 @@ foo: baz: 2 fomo: false ` - out, err := EvaluateExpression(expression, []byte(strings.TrimSpace(content))) + out, err := EvaluateExpression(t.Context(), expression, []byte(strings.TrimSpace(content))) assert.NilError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(out))) }