From 942659fb06ab1a18dae5a540d8be78cb9db3dc76 Mon Sep 17 00:00:00 2001 From: Simon Frei Date: Tue, 23 Jul 2019 10:49:22 +0200 Subject: [PATCH] lib/model, lib/nat: More service termination speedup (#5884) --- lib/model/folder.go | 12 ++++++++++++ lib/nat/service.go | 12 +++++++++--- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/lib/model/folder.go b/lib/model/folder.go index 6783b732f..e9107d5a3 100644 --- a/lib/model/folder.go +++ b/lib/model/folder.go @@ -423,6 +423,12 @@ func (f *folder) scanSubdirs(subDirs []string) error { var iterError error f.fset.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool { + select { + case <-f.ctx.Done(): + return false + default: + } + file := fi.(db.FileInfoTruncated) if err := batch.flushIfFull(); err != nil { @@ -507,6 +513,12 @@ func (f *folder) scanSubdirs(subDirs []string) error { return true }) + select { + case <-f.ctx.Done(): + return f.ctx.Err() + default: + } + if iterError == nil && len(toIgnore) > 0 { for _, file := range toIgnore { l.Debugln("marking file as ignored", f) diff --git a/lib/nat/service.go b/lib/nat/service.go index c564e2461..e54e25f58 100644 --- a/lib/nat/service.go +++ b/lib/nat/service.go @@ -225,7 +225,7 @@ func (s *Service) verifyExistingMappings(mapping *Mapping, nats map[string]Devic l.Debugf("Renewing %s -> %s mapping on %s", mapping, address, id) - addr, err := s.tryNATDevice(nat, mapping.address.Port, address.Port, leaseTime) + addr, err := s.tryNATDevice(nat, mapping.address.Port, address.Port, leaseTime, stop) if err != nil { l.Debugf("Failed to renew %s -> mapping on %s", mapping, address, id) mapping.removeAddress(id) @@ -274,7 +274,7 @@ func (s *Service) acquireNewMappings(mapping *Mapping, nats map[string]Device, s l.Debugf("Acquiring %s mapping on %s", mapping, id) - addr, err := s.tryNATDevice(nat, mapping.address.Port, 0, leaseTime) + addr, err := s.tryNATDevice(nat, mapping.address.Port, 0, leaseTime, stop) if err != nil { l.Debugf("Failed to acquire %s mapping on %s", mapping, id) continue @@ -291,7 +291,7 @@ func (s *Service) acquireNewMappings(mapping *Mapping, nats map[string]Device, s // tryNATDevice tries to acquire a port mapping for the given internal address to // the given external port. If external port is 0, picks a pseudo-random port. -func (s *Service) tryNATDevice(natd Device, intPort, extPort int, leaseTime time.Duration) (Address, error) { +func (s *Service) tryNATDevice(natd Device, intPort, extPort int, leaseTime time.Duration, stop chan struct{}) (Address, error) { var err error var port int @@ -312,6 +312,12 @@ func (s *Service) tryNATDevice(natd Device, intPort, extPort int, leaseTime time } for i := 0; i < 10; i++ { + select { + case <-stop: + return Address{}, nil + default: + } + // Then try up to ten random ports. extPort = 1024 + predictableRand.Intn(65535-1024) name := fmt.Sprintf("syncthing-%d", extPort)