2016-04-10 19:36:38 +00:00
|
|
|
// Copyright (C) 2015 The Syncthing Authors.
|
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
|
2017-02-09 06:52:18 +00:00
|
|
|
// You can obtain one at https://mozilla.org/MPL/2.0/.
|
2016-04-10 19:36:38 +00:00
|
|
|
|
|
|
|
package nat
|
|
|
|
|
|
|
|
import (
|
2019-11-21 07:41:15 +00:00
|
|
|
"context"
|
2017-12-07 07:08:24 +00:00
|
|
|
"sync"
|
2016-04-10 19:36:38 +00:00
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2019-11-26 07:39:51 +00:00
|
|
|
type DiscoverFunc func(ctx context.Context, renewal, timeout time.Duration) []Device
|
2016-04-10 19:36:38 +00:00
|
|
|
|
|
|
|
var providers []DiscoverFunc
|
|
|
|
|
|
|
|
func Register(provider DiscoverFunc) {
|
|
|
|
providers = append(providers, provider)
|
|
|
|
}
|
|
|
|
|
2019-11-21 07:41:15 +00:00
|
|
|
func discoverAll(ctx context.Context, renewal, timeout time.Duration) map[string]Device {
|
2017-12-07 07:08:24 +00:00
|
|
|
wg := &sync.WaitGroup{}
|
2016-04-13 18:50:40 +00:00
|
|
|
wg.Add(len(providers))
|
|
|
|
|
|
|
|
c := make(chan Device)
|
|
|
|
done := make(chan struct{})
|
|
|
|
|
2016-04-10 19:36:38 +00:00
|
|
|
for _, discoverFunc := range providers {
|
2016-04-13 18:50:40 +00:00
|
|
|
go func(f DiscoverFunc) {
|
2019-07-19 17:40:40 +00:00
|
|
|
defer wg.Done()
|
2019-11-26 07:39:51 +00:00
|
|
|
for _, dev := range f(ctx, renewal, timeout) {
|
2019-07-19 17:40:40 +00:00
|
|
|
select {
|
|
|
|
case c <- dev:
|
2019-11-21 07:41:15 +00:00
|
|
|
case <-ctx.Done():
|
2019-07-19 17:40:40 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-13 18:50:40 +00:00
|
|
|
}
|
|
|
|
}(discoverFunc)
|
2016-04-10 19:36:38 +00:00
|
|
|
}
|
2016-04-13 18:50:40 +00:00
|
|
|
|
|
|
|
nats := make(map[string]Device)
|
|
|
|
|
|
|
|
go func() {
|
2019-07-19 17:40:40 +00:00
|
|
|
defer close(done)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case dev, ok := <-c:
|
|
|
|
if !ok {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
nats[dev.ID()] = dev
|
2019-11-21 07:41:15 +00:00
|
|
|
case <-ctx.Done():
|
2019-07-19 17:40:40 +00:00
|
|
|
return
|
|
|
|
}
|
2016-04-13 18:50:40 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
close(c)
|
|
|
|
<-done
|
|
|
|
|
2016-04-10 19:36:38 +00:00
|
|
|
return nats
|
|
|
|
}
|