registry.go 1012 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package nat
  7. import (
  8. "time"
  9. "github.com/syncthing/syncthing/lib/sync"
  10. )
  11. type DiscoverFunc func(renewal, timeout time.Duration) []Device
  12. var providers []DiscoverFunc
  13. func Register(provider DiscoverFunc) {
  14. providers = append(providers, provider)
  15. }
  16. func discoverAll(renewal, timeout time.Duration) map[string]Device {
  17. wg := sync.NewWaitGroup()
  18. wg.Add(len(providers))
  19. c := make(chan Device)
  20. done := make(chan struct{})
  21. for _, discoverFunc := range providers {
  22. go func(f DiscoverFunc) {
  23. for _, dev := range f(renewal, timeout) {
  24. c <- dev
  25. }
  26. wg.Done()
  27. }(discoverFunc)
  28. }
  29. nats := make(map[string]Device)
  30. go func() {
  31. for dev := range c {
  32. nats[dev.ID()] = dev
  33. }
  34. close(done)
  35. }()
  36. wg.Wait()
  37. close(c)
  38. <-done
  39. return nats
  40. }