/
servers.go
122 lines (103 loc) · 2.28 KB
/
servers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package devtunnel
import (
"runtime"
"sync"
"time"
"github.com/go-ping/ping"
"golang.org/x/exp/slices"
"golang.org/x/sync/errgroup"
"golang.org/x/xerrors"
"github.com/coder/coder/cryptorand"
)
type Region struct {
ID int
LocationName string
Nodes []Node
}
type Node struct {
ID int `json:"id"`
RegionID int `json:"region_id"`
HostnameHTTPS string `json:"hostname_https"`
AvgLatency time.Duration `json:"-"`
}
var Regions = []Region{
{
ID: 0,
LocationName: "US East Pittsburgh",
Nodes: []Node{
{
ID: 1,
RegionID: 0,
HostnameHTTPS: "pit-1.try.coder.app",
},
},
},
}
// Nodes returns a list of nodes to use for the tunnel. It will pick a random
// node from each region.
//
// If a customNode is provided, it will be returned as the only node with ID
// 9999.
func Nodes(customTunnelHost string) ([]Node, error) {
nodes := []Node{}
if customTunnelHost != "" {
return []Node{
{
ID: 9999,
RegionID: 9999,
HostnameHTTPS: customTunnelHost,
},
}, nil
}
for _, region := range Regions {
// Pick a random node from each region.
i, err := cryptorand.Intn(len(region.Nodes))
if err != nil {
return []Node{}, err
}
nodes = append(nodes, region.Nodes[i])
}
return nodes, nil
}
// FindClosestNode pings each node and returns the one with the lowest latency.
func FindClosestNode(nodes []Node) (Node, error) {
if len(nodes) == 0 {
return Node{}, xerrors.New("no wgtunnel nodes")
}
// Copy the nodes so we don't mutate the original.
nodes = append([]Node{}, nodes...)
var (
nodesMu sync.Mutex
eg = errgroup.Group{}
)
for i, node := range nodes {
i, node := i, node
eg.Go(func() error {
pinger, err := ping.NewPinger(node.HostnameHTTPS)
if err != nil {
return err
}
if runtime.GOOS == "windows" {
pinger.SetPrivileged(true)
}
pinger.Count = 5
pinger.Timeout = 5 * time.Second
err = pinger.Run()
if err != nil {
return err
}
nodesMu.Lock()
nodes[i].AvgLatency = pinger.Statistics().AvgRtt
nodesMu.Unlock()
return nil
})
}
err := eg.Wait()
if err != nil {
return Node{}, err
}
slices.SortFunc(nodes, func(i, j Node) bool {
return i.AvgLatency < j.AvgLatency
})
return nodes[0], nil
}