-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathlocalapi.go
More file actions
69 lines (59 loc) · 1.67 KB
/
localapi.go
File metadata and controls
69 lines (59 loc) · 1.67 KB
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
package tailscalesd
import (
"context"
"time"
"github.com/prometheus/client_golang/prometheus"
"tailscale.com/client/local"
"tailscale.com/ipn/ipnstate"
)
// LocalAPIDiscoverer discovers devices from the API served by the Tailscale
// daemon on the local machine.
type LocalAPIDiscoverer struct {
Client local.Client
}
// peerToDevice converts a PeerStatus from the local API to the internal Device format.
func peerToDevice(p *ipnstate.PeerStatus, d *Device) {
for i := range p.TailscaleIPs {
d.Addresses = append(d.Addresses, p.TailscaleIPs[i].String())
}
d.API = "localhost"
d.Authorized = true // localapi returned peer; assume it's authorized enough
d.Hostname = p.HostName
d.ID = string(p.ID)
d.Online = p.Online
d.OS = p.OS
if p.Tags != nil {
d.Tags = p.Tags.AsSlice()
}
}
// Devices reported by the Tailscale local API as peers of the local host.
func (d *LocalAPIDiscoverer) Devices(ctx context.Context) ([]Device, error) {
start := time.Now()
lv := prometheus.Labels{
"api": "local",
"host": "localhost",
}
apiRequestCounter.With(lv).Inc()
defer func() {
apiRequestLatencyHistogram.With(lv).Observe(float64(time.Since(start).Milliseconds()))
}()
status, err := d.Client.Status(ctx)
if err != nil {
apiRequestErrorCounter.With(lv).Inc()
return nil, err
}
ret := make([]Device, len(status.Peer)+1)
var i int
for _, peer := range status.Peer {
peerToDevice(peer, &ret[i])
i++
}
peerToDevice(status.Self, &ret[i])
return ret, nil
}
// LocalAPI returns a Discoverer that interrogates the Tailscale local API for peer devices.
func LocalAPI(socket string) *LocalAPIDiscoverer {
var ret LocalAPIDiscoverer
ret.Client.Socket = socket
return &ret
}