@@ -463,26 +463,19 @@ func (a *HostAgent) startRoutinesAndWait(ctx context.Context, errCh <-chan error
463463 stRunning .Running = true
464464 a .emitEvent (ctx , events.Event {Status : stRunning })
465465 }()
466- for {
467- select {
468- case driverErr := <- errCh :
469- logrus .Infof ("Driver stopped due to error: %q" , driverErr )
470- cancelHA ()
471- if closeErr := a .close (); closeErr != nil {
472- logrus .WithError (closeErr ).Warn ("an error during shutting down the host agent" )
473- }
474- err := a .driver .Stop (ctx )
475- return err
476- case sig := <- a .signalCh :
477- logrus .Infof ("Received %s, shutting down the host agent" , osutil .SignalName (sig ))
478- cancelHA ()
479- if closeErr := a .close (); closeErr != nil {
480- logrus .WithError (closeErr ).Warn ("an error during shutting down the host agent" )
481- }
482- err := a .driver .Stop (ctx )
483- return err
484- }
485- }
466+ // wait for either the driver to stop or a signal to shut down
467+ select {
468+ case driverErr := <- errCh :
469+ logrus .Infof ("Driver stopped due to error: %q" , driverErr )
470+ case sig := <- a .signalCh :
471+ logrus .Infof ("Received %s, shutting down the host agent" , osutil .SignalName (sig ))
472+ }
473+ // close the host agent routines before cancelling the context
474+ if closeErr := a .close (); closeErr != nil {
475+ logrus .WithError (closeErr ).Warn ("an error during shutting down the host agent" )
476+ }
477+ cancelHA ()
478+ return a .driver .Stop (ctx )
486479}
487480
488481func (a * HostAgent ) Info (_ context.Context ) (* hostagentapi.Info , error ) {
@@ -618,6 +611,7 @@ sudo chown -R "${USER}" /run/host-services`
618611}
619612
620613// cleanUp registers a cleanup function to be called when the host agent is stopped.
614+ // The cleanup functions are called before the context is cancelled, in the reverse order of their registration.
621615func (a * HostAgent ) cleanUp (fn func () error ) {
622616 a .onCloseMu .Lock ()
623617 defer a .onCloseMu .Unlock ()
@@ -689,6 +683,9 @@ func (a *HostAgent) watchGuestAgentEvents(ctx context.Context) {
689683 }
690684 }()
691685
686+ // ensure close before ctx is cancelled
687+ a .cleanUp (a .grpcPortForwarder .Close )
688+
692689 for {
693690 if a .client == nil || ! isGuestAgentSocketAccessible (ctx , a .client ) {
694691 if a .driver .ForwardGuestAgent () {
@@ -821,7 +818,6 @@ func (a *HostAgent) processGuestAgentEvents(ctx context.Context, client *guestag
821818 a .grpcPortForwarder .OnEvent (ctx , client , ev )
822819 }
823820 }
824- defer a .grpcPortForwarder .Close ()
825821
826822 if err := client .Events (ctx , onEvent ); err != nil {
827823 if status .Code (err ) == codes .Canceled {
0 commit comments