@@ -90,6 +90,16 @@ func (s *Server) UpdateConfig(cfg *Config) {
9090//
9191// NOTE: the rpc server is not registered with any grpc server in this function.
9292func (s * Server ) initialize (interceptorChain * rpcperms.InterceptorChain ) error {
93+ var ready bool
94+
95+ // If by the time this function exits we haven't yet given the ready
96+ // signal, we detect it here and signal that the daemon should quit.
97+ defer func () {
98+ if ! ready {
99+ close (s .quit )
100+ }
101+ }()
102+
93103 // Show version at startup.
94104 srvrLog .Infof ("Version: %s, build=%s, logging=%s, " +
95105 "debuglevel=%s, active_network=%v" , Version (), build .Deployment ,
@@ -239,6 +249,7 @@ func (s *Server) initialize(interceptorChain *rpcperms.InterceptorChain) error {
239249 shutdownFuncs = nil
240250
241251 close (s .ready )
252+ ready = true
242253
243254 return nil
244255}
@@ -701,12 +712,23 @@ func (s *Server) waitForReady() error {
701712 // shutdown in case of a startup error). If we shut down after passing
702713 // this part of the code, the called component will handle the quit
703714 // signal.
704- select {
705- case <- s .ready :
706- return nil
707715
716+ // In order to give priority to the quit signal, we wrap the blocking
717+ // select so that we give a chance to the quit signal to be read first.
718+ // This is needed as there is currently no wait to un-set the ready
719+ // signal, so we would have a race between the 2 channels.
720+ select {
708721 case <- s .quit :
709722 return fmt .Errorf ("tapd is shutting down" )
723+
724+ default :
725+ // We now wait for either signal to be provided.
726+ select {
727+ case <- s .ready :
728+ return nil
729+ case <- s .quit :
730+ return fmt .Errorf ("tapd is shutting down" )
731+ }
710732 }
711733}
712734
@@ -820,7 +842,13 @@ func (s *Server) Name() protofsm.EndpointName {
820842//
821843// NOTE: This method is part of the protofsm.MsgEndpoint interface.
822844func (s * Server ) CanHandle (msg protofsm.PeerMsg ) bool {
823- <- s .ready
845+ err := s .waitForReady ()
846+ if err != nil {
847+ srvrLog .Debugf ("Can't handle PeerMsg, server not ready %v" ,
848+ err )
849+ return false
850+ }
851+
824852 return s .cfg .AuxFundingController .CanHandle (msg )
825853}
826854
@@ -829,7 +857,13 @@ func (s *Server) CanHandle(msg protofsm.PeerMsg) bool {
829857//
830858// NOTE: This method is part of the protofsm.MsgEndpoint interface.
831859func (s * Server ) SendMessage (msg protofsm.PeerMsg ) bool {
832- <- s .ready
860+ err := s .waitForReady ()
861+ if err != nil {
862+ srvrLog .Debugf ("Failed to send PeerMsg, server not ready %v" ,
863+ err )
864+ return false
865+ }
866+
833867 return s .cfg .AuxFundingController .SendMessage (msg )
834868}
835869
0 commit comments