Skip to content

Commit d321bbf

Browse files
committed
refactor: reduce context.Background()
Signed-off-by: ashwat287 <ashwatpas@gmail.com>
1 parent 1daec3a commit d321bbf

31 files changed

+162
-134
lines changed

cmd/limactl/clone.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ func cloneAction(cmd *cobra.Command, args []string) error {
7171
if err != nil {
7272
return err
7373
}
74-
yBytes, err := yqutil.EvaluateExpression(yq, yContent)
74+
yBytes, err := yqutil.EvaluateExpression(cmd.Context(), yq, yContent)
7575
if err != nil {
7676
return err
7777
}

cmd/limactl/edit.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func editAction(cmd *cobra.Command, args []string) error {
8787
var yBytes []byte
8888
if len(yqExprs) > 0 {
8989
yq := yqutil.Join(yqExprs)
90-
yBytes, err = yqutil.EvaluateExpression(yq, yContent)
90+
yBytes, err = yqutil.EvaluateExpression(cmd.Context(), yq, yContent)
9191
if err != nil {
9292
return err
9393
}

cmd/limactl/network.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
package main
55

66
import (
7+
"context"
78
"encoding/json"
89
"errors"
910
"fmt"
@@ -183,7 +184,7 @@ func networkCreateAction(cmd *cobra.Command, args []string) error {
183184
return fmt.Errorf("network mode %q requires specifying interface", mode)
184185
}
185186
yq := fmt.Sprintf(`.networks.%q = {"mode":%q,"interface":%q}`, name, mode, intf)
186-
return networkApplyYQ(yq)
187+
return networkApplyYQ(cmd.Context(), yq)
187188
default:
188189
if gateway == "" {
189190
return fmt.Errorf("network mode %q requires specifying gateway", mode)
@@ -208,11 +209,11 @@ func networkCreateAction(cmd *cobra.Command, args []string) error {
208209
// TODO: check IP range collision
209210

210211
yq := fmt.Sprintf(`.networks.%q = {"mode":%q,"gateway":%q,"netmask":%q,"interface":%q}`, name, mode, gwIP.String(), gwMaskStr, intf)
211-
return networkApplyYQ(yq)
212+
return networkApplyYQ(cmd.Context(), yq)
212213
}
213214
}
214215

215-
func networkApplyYQ(yq string) error {
216+
func networkApplyYQ(ctx context.Context, yq string) error {
216217
filePath, err := networks.ConfigFile()
217218
if err != nil {
218219
return err
@@ -221,7 +222,7 @@ func networkApplyYQ(yq string) error {
221222
if err != nil {
222223
return err
223224
}
224-
yBytes, err := yqutil.EvaluateExpression(yq, yContent)
225+
yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent)
225226
if err != nil {
226227
return err
227228
}
@@ -263,7 +264,7 @@ func networkDeleteAction(cmd *cobra.Command, args []string) error {
263264
yq += " | "
264265
}
265266
}
266-
return networkApplyYQ(yq)
267+
return networkApplyYQ(cmd.Context(), yq)
267268
}
268269

269270
func networkBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {

cmd/limactl/start.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ func loadOrCreateInstance(cmd *cobra.Command, args []string, createOnly bool) (*
234234
}
235235
} else {
236236
logrus.Info("Terminal is not available, proceeding without opening an editor")
237-
if err := modifyInPlace(tmpl, yq); err != nil {
237+
if err := modifyInPlace(cmd.Context(), tmpl, yq); err != nil {
238238
return nil, err
239239
}
240240
}
@@ -252,7 +252,7 @@ func applyYQExpressionToExistingInstance(ctx context.Context, inst *store.Instan
252252
return nil, err
253253
}
254254
logrus.Debugf("Applying yq expression %q to an existing instance %q", yq, inst.Name)
255-
yBytes, err := yqutil.EvaluateExpression(yq, yContent)
255+
yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent)
256256
if err != nil {
257257
return nil, err
258258
}
@@ -275,8 +275,8 @@ func applyYQExpressionToExistingInstance(ctx context.Context, inst *store.Instan
275275
return store.Inspect(ctx, inst.Name)
276276
}
277277

278-
func modifyInPlace(st *limatmpl.Template, yq string) error {
279-
out, err := yqutil.EvaluateExpression(yq, st.Bytes)
278+
func modifyInPlace(ctx context.Context, st *limatmpl.Template, yq string) error {
279+
out, err := yqutil.EvaluateExpression(ctx, yq, st.Bytes)
280280
if err != nil {
281281
return err
282282
}
@@ -301,7 +301,7 @@ func (exitSuccessError) ExitCode() int {
301301

302302
func chooseNextCreatorState(ctx context.Context, tmpl *limatmpl.Template, yq string) (*limatmpl.Template, error) {
303303
for {
304-
if err := modifyInPlace(tmpl, yq); err != nil {
304+
if err := modifyInPlace(ctx, tmpl, yq); err != nil {
305305
logrus.WithError(err).Warn("Failed to evaluate yq expression")
306306
return tmpl, err
307307
}

cmd/limactl/template.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ func templateCopyAction(cmd *cobra.Command, args []string) error {
119119
if embed && verbatim {
120120
return errors.New("--verbatim cannot be used with any of --embed, --embed-all, or --fill")
121121
}
122-
tmpl, err := limatmpl.Read(cmd.Context(), "", source)
122+
tmpl, err := limatmpl.Read(ctx, "", source)
123123
if err != nil {
124124
return err
125125
}
@@ -129,11 +129,11 @@ func templateCopyAction(cmd *cobra.Command, args []string) error {
129129
if !verbatim {
130130
if embed {
131131
// Embed default base.yaml only when fill is true.
132-
if err := tmpl.Embed(cmd.Context(), embedAll, fill); err != nil {
132+
if err := tmpl.Embed(ctx, embedAll, fill); err != nil {
133133
return err
134134
}
135135
} else {
136-
if err := tmpl.UseAbsLocators(); err != nil {
136+
if err := tmpl.UseAbsLocators(ctx); err != nil {
137137
return err
138138
}
139139
}

pkg/driver/driver.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ type Lifecycle interface {
4040
type GUI interface {
4141
// RunGUI is for starting GUI synchronously by hostagent. This method should be wait and return only after vm terminates
4242
// It returns error if there are any failures
43-
RunGUI() error
43+
RunGUI(ctx context.Context) error
4444

4545
ChangeDisplayPassword(ctx context.Context, password string) error
4646
DisplayConnection(ctx context.Context) (string, error)
@@ -63,7 +63,7 @@ type Registration interface {
6363
// GuestAgent defines operations for the guest agent.
6464
type GuestAgent interface {
6565
// ForwardGuestAgent returns if the guest agent sock needs forwarding by host agent.
66-
ForwardGuestAgent() bool
66+
ForwardGuestAgent(_ context.Context) bool
6767

6868
// GuestAgentConn returns the guest agent connection, or nil (if forwarded by ssh).
6969
GuestAgentConn(_ context.Context) (net.Conn, string, error)
@@ -77,10 +77,10 @@ type Driver interface {
7777
Registration
7878
GuestAgent
7979

80-
Info() Info
80+
Info(_ context.Context) Info
8181

8282
// SetConfig sets the configuration for the instance.
83-
Configure(inst *store.Instance) *ConfiguredDriver
83+
Configure(_ context.Context, inst *store.Instance) *ConfiguredDriver
8484
}
8585

8686
type ConfiguredDriver struct {

pkg/driver/external/client/methods.go

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,10 @@ func (d *DriverClient) Stop(ctx context.Context) error {
102102
return nil
103103
}
104104

105-
func (d *DriverClient) RunGUI() error {
105+
func (d *DriverClient) RunGUI(ctx context.Context) error {
106106
d.logger.Debug("Running GUI for the driver instance")
107107

108-
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
108+
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
109109
defer cancel()
110110

111111
_, err := d.DriverSvc.RunGUI(ctx, &emptypb.Empty{})
@@ -230,10 +230,10 @@ func (d *DriverClient) Unregister(ctx context.Context) error {
230230
return nil
231231
}
232232

233-
func (d *DriverClient) ForwardGuestAgent() bool {
233+
func (d *DriverClient) ForwardGuestAgent(ctx context.Context) bool {
234234
d.logger.Debug("Checking if guest agent needs to be forwarded")
235235

236-
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
236+
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
237237
defer cancel()
238238

239239
resp, err := d.DriverSvc.ForwardGuestAgent(ctx, &emptypb.Empty{})
@@ -256,10 +256,10 @@ func (d *DriverClient) GuestAgentConn(ctx context.Context) (net.Conn, string, er
256256
return nil, "", nil
257257
}
258258

259-
func (d *DriverClient) Info() driver.Info {
259+
func (d *DriverClient) Info(ctx context.Context) driver.Info {
260260
d.logger.Debug("Getting driver info")
261261

262-
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
262+
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
263263
defer cancel()
264264

265265
resp, err := d.DriverSvc.GetInfo(ctx, &emptypb.Empty{})
@@ -278,7 +278,7 @@ func (d *DriverClient) Info() driver.Info {
278278
return info
279279
}
280280

281-
func (d *DriverClient) Configure(inst *store.Instance) *driver.ConfiguredDriver {
281+
func (d *DriverClient) Configure(ctx context.Context, inst *store.Instance) *driver.ConfiguredDriver {
282282
d.logger.Debugf("Setting config for instance %s with SSH local port %d", inst.Name, inst.SSHLocalPort)
283283

284284
instJSON, err := inst.MarshalJSON()
@@ -287,7 +287,7 @@ func (d *DriverClient) Configure(inst *store.Instance) *driver.ConfiguredDriver
287287
return nil
288288
}
289289

290-
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
290+
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
291291
defer cancel()
292292

293293
_, err = d.DriverSvc.SetConfig(ctx, &pb.SetConfigRequest{

pkg/driver/external/server/methods.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ func (s *DriverServer) Start(_ *emptypb.Empty, stream pb.Driver_StartServer) err
5353
}
5454
}
5555

56-
func (s *DriverServer) SetConfig(_ context.Context, req *pb.SetConfigRequest) (*emptypb.Empty, error) {
56+
func (s *DriverServer) SetConfig(ctx context.Context, req *pb.SetConfigRequest) (*emptypb.Empty, error) {
5757
s.logger.Debugf("Received SetConfig request")
5858
var inst store.Instance
5959

@@ -62,7 +62,7 @@ func (s *DriverServer) SetConfig(_ context.Context, req *pb.SetConfigRequest) (*
6262
return &emptypb.Empty{}, err
6363
}
6464

65-
_ = s.driver.Configure(&inst)
65+
_ = s.driver.Configure(ctx, &inst)
6666

6767
return &emptypb.Empty{}, nil
6868
}
@@ -76,7 +76,7 @@ func (s *DriverServer) GuestAgentConn(ctx context.Context, _ *emptypb.Empty) (*e
7676
}
7777

7878
if connType != "unix" {
79-
proxySocketPath := filepath.Join(s.driver.Info().InstanceDir, filenames.GuestAgentSock)
79+
proxySocketPath := filepath.Join(s.driver.Info(ctx).InstanceDir, filenames.GuestAgentSock)
8080

8181
var lc net.ListenConfig
8282
listener, err := lc.Listen(ctx, "unix", proxySocketPath)
@@ -102,9 +102,9 @@ func (s *DriverServer) GuestAgentConn(ctx context.Context, _ *emptypb.Empty) (*e
102102
return &emptypb.Empty{}, nil
103103
}
104104

105-
func (s *DriverServer) GetInfo(_ context.Context, _ *emptypb.Empty) (*pb.InfoResponse, error) {
105+
func (s *DriverServer) GetInfo(ctx context.Context, _ *emptypb.Empty) (*pb.InfoResponse, error) {
106106
s.logger.Debug("Received GetInfo request")
107-
info := s.driver.Info()
107+
info := s.driver.Info(ctx)
108108

109109
infoJSON, err := json.Marshal(info)
110110
if err != nil {
@@ -161,9 +161,9 @@ func (s *DriverServer) Stop(ctx context.Context, empty *emptypb.Empty) (*emptypb
161161
return empty, nil
162162
}
163163

164-
func (s *DriverServer) RunGUI(_ context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
164+
func (s *DriverServer) RunGUI(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
165165
s.logger.Debug("Received RunGUI request")
166-
err := s.driver.RunGUI()
166+
err := s.driver.RunGUI(ctx)
167167
if err != nil {
168168
s.logger.Errorf("RunGUI failed: %v", err)
169169
return empty, err
@@ -260,7 +260,7 @@ func (s *DriverServer) Unregister(ctx context.Context, empty *emptypb.Empty) (*e
260260
return empty, nil
261261
}
262262

263-
func (s *DriverServer) ForwardGuestAgent(_ context.Context, _ *emptypb.Empty) (*pb.ForwardGuestAgentResponse, error) {
263+
func (s *DriverServer) ForwardGuestAgent(ctx context.Context, _ *emptypb.Empty) (*pb.ForwardGuestAgentResponse, error) {
264264
s.logger.Debug("Received ForwardGuestAgent request")
265-
return &pb.ForwardGuestAgentResponse{ShouldForward: s.driver.ForwardGuestAgent()}, nil
265+
return &pb.ForwardGuestAgentResponse{ShouldForward: s.driver.ForwardGuestAgent(ctx)}, nil
266266
}

pkg/driver/external/server/server.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ func Serve(ctx context.Context, driver driver.Driver) {
5454
logger := logrus.New()
5555
logger.SetLevel(logrus.DebugLevel)
5656

57-
socketPath := filepath.Join(os.TempDir(), fmt.Sprintf("lima-driver-%s-%d.sock", driver.Info().DriverName, os.Getpid()))
57+
socketPath := filepath.Join(os.TempDir(), fmt.Sprintf("lima-driver-%s-%d.sock", driver.Info(ctx).DriverName, os.Getpid()))
5858

5959
defer func() {
6060
if err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {
@@ -132,8 +132,8 @@ func Serve(ctx context.Context, driver driver.Driver) {
132132
}
133133
}()
134134

135-
go func() {
136-
logger.Infof("Starting external driver server for %s", driver.Info().DriverName)
135+
go func(ctx context.Context) {
136+
logger.Infof("Starting external driver server for %s", driver.Info(ctx).DriverName)
137137
logger.Infof("Server starting on Unix socket: %s", socketPath)
138138
if err := server.Serve(tListener); err != nil {
139139
if errors.Is(err, grpc.ErrServerStopped) {
@@ -142,7 +142,7 @@ func Serve(ctx context.Context, driver driver.Driver) {
142142
logger.Errorf("Failed to serve: %v", err)
143143
}
144144
}
145-
}()
145+
}(ctx)
146146

147147
<-shutdownCh
148148
server.GracefulStop()
@@ -155,7 +155,7 @@ func Start(extDriver *registry.ExternalDriver, instName string) error {
155155
}
156156
extDriver.InstanceName = instName
157157

158-
ctx, cancel := context.WithCancel(context.Background())
158+
ctx, cancel := context.WithCancel(extDriver.Ctx)
159159
cmd := exec.CommandContext(ctx, extDriver.Path)
160160

161161
stdout, err := cmd.StdoutPipe()

pkg/driver/qemu/qemu_driver.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func New() *LimaQemuDriver {
6464
}
6565
}
6666

67-
func (l *LimaQemuDriver) Configure(inst *store.Instance) *driver.ConfiguredDriver {
67+
func (l *LimaQemuDriver) Configure(_ context.Context, inst *store.Instance) *driver.ConfiguredDriver {
6868
l.Instance = inst
6969
l.SSHLocalPort = inst.SSHLocalPort
7070

@@ -96,8 +96,8 @@ func (l *LimaQemuDriver) CreateDisk(ctx context.Context) error {
9696
return EnsureDisk(ctx, qCfg)
9797
}
9898

99-
func (l *LimaQemuDriver) Start(_ context.Context) (chan error, error) {
100-
ctx, cancel := context.WithCancel(context.Background())
99+
func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) {
100+
ctx, cancel := context.WithCancel(ctx)
101101
defer func() {
102102
if l.qCmd == nil {
103103
cancel()
@@ -381,7 +381,7 @@ func (l *LimaQemuDriver) shutdownQEMU(ctx context.Context, timeout time.Duration
381381
logrus.WithError(err).Warnf("failed to send system_powerdown command via the QMP socket %q, forcibly killing QEMU", qmpSockPath)
382382
return l.killQEMU(ctx, timeout, qCmd, qWaitCh)
383383
}
384-
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), timeout)
384+
timeoutCtx, timeoutCancel := context.WithTimeout(ctx, timeout)
385385
defer timeoutCancel()
386386

387387
select {
@@ -528,7 +528,7 @@ func (a *qArgTemplateApplier) applyTemplate(qArg string) (string, error) {
528528
return b.String(), nil
529529
}
530530

531-
func (l *LimaQemuDriver) Info() driver.Info {
531+
func (l *LimaQemuDriver) Info(_ context.Context) driver.Info {
532532
var info driver.Info
533533
if l.Instance != nil && l.Instance.Dir != "" {
534534
info.InstanceDir = l.Instance.Dir
@@ -544,7 +544,7 @@ func (l *LimaQemuDriver) Initialize(_ context.Context) error {
544544
return nil
545545
}
546546

547-
func (l *LimaQemuDriver) RunGUI() error {
547+
func (l *LimaQemuDriver) RunGUI(_ context.Context) error {
548548
return nil
549549
}
550550

@@ -556,7 +556,7 @@ func (l *LimaQemuDriver) Unregister(_ context.Context) error {
556556
return nil
557557
}
558558

559-
func (l *LimaQemuDriver) ForwardGuestAgent() bool {
559+
func (l *LimaQemuDriver) ForwardGuestAgent(_ context.Context) bool {
560560
// if driver is not providing, use host agent
561561
return l.vSockPort == 0 && l.virtioPort == ""
562562
}

0 commit comments

Comments
 (0)