@@ -448,26 +448,19 @@ func (a *HostAgent) startRoutinesAndWait(ctx context.Context, errCh <-chan error
448
448
stRunning .Running = true
449
449
a .emitEvent (ctx , events.Event {Status : stRunning })
450
450
}()
451
- for {
452
- select {
453
- case driverErr := <- errCh :
454
- logrus .Infof ("Driver stopped due to error: %q" , driverErr )
455
- cancelHA ()
456
- if closeErr := a .close (); closeErr != nil {
457
- logrus .WithError (closeErr ).Warn ("an error during shutting down the host agent" )
458
- }
459
- err := a .driver .Stop (ctx )
460
- return err
461
- case sig := <- a .signalCh :
462
- logrus .Infof ("Received %s, shutting down the host agent" , osutil .SignalName (sig ))
463
- cancelHA ()
464
- if closeErr := a .close (); closeErr != nil {
465
- logrus .WithError (closeErr ).Warn ("an error during shutting down the host agent" )
466
- }
467
- err := a .driver .Stop (ctx )
468
- return err
469
- }
470
- }
451
+ // wait for either the driver to stop or a signal to shut down
452
+ select {
453
+ case driverErr := <- errCh :
454
+ logrus .Infof ("Driver stopped due to error: %q" , driverErr )
455
+ case sig := <- a .signalCh :
456
+ logrus .Infof ("Received %s, shutting down the host agent" , osutil .SignalName (sig ))
457
+ }
458
+ // close the host agent routines before cancelling the context
459
+ if closeErr := a .close (); closeErr != nil {
460
+ logrus .WithError (closeErr ).Warn ("an error during shutting down the host agent" )
461
+ }
462
+ cancelHA ()
463
+ return a .driver .Stop (ctx )
471
464
}
472
465
473
466
func (a * HostAgent ) Info (_ context.Context ) (* hostagentapi.Info , error ) {
@@ -603,6 +596,7 @@ sudo chown -R "${USER}" /run/host-services`
603
596
}
604
597
605
598
// cleanUp registers a cleanup function to be called when the host agent is stopped.
599
+ // The cleanup functions are called before the context is cancelled, in the reverse order of their registration.
606
600
func (a * HostAgent ) cleanUp (fn func () error ) {
607
601
a .onCloseMu .Lock ()
608
602
defer a .onCloseMu .Unlock ()
@@ -674,6 +668,9 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) {
674
668
}
675
669
}()
676
670
671
+ // ensure close before ctx is cancelled
672
+ a .cleanUp (a .grpcPortForwarder .Close )
673
+
677
674
for {
678
675
if a .client == nil || ! isGuestAgentSocketAccessible (ctx , a .client ) {
679
676
if a .driver .ForwardGuestAgent () {
@@ -806,7 +803,6 @@ func (a *HostAgent) processGuestAgentEvents(ctx context.Context, client *guestag
806
803
a .grpcPortForwarder .OnEvent (ctx , client , ev )
807
804
}
808
805
}
809
- defer a .grpcPortForwarder .Close ()
810
806
811
807
if err := client .Events (ctx , onEvent ); err != nil {
812
808
if status .Code (err ) == codes .Canceled {
0 commit comments