mirror of
https://github.com/tailscale/tailscale.git
synced 2024-11-26 03:25:35 +00:00
b9c92b90db
Do json formatting once, rather than on every request. Use an atomic.Value. name old time/op new time/op delta HandleBootstrapDNS-10 6.35µs ± 0% 0.10µs ± 4% -98.35% (p=0.000 n=14+15) name old alloc/op new alloc/op delta HandleBootstrapDNS-10 3.20kB ± 0% 0.42kB ± 0% -86.99% (p=0.000 n=12+15) name old allocs/op new allocs/op delta HandleBootstrapDNS-10 41.0 ± 0% 3.0 ± 0% -92.68% (p=0.000 n=15+15) Signed-off-by: Josh Bleecher Snyder <josh@tailscale.com>
64 lines
1.3 KiB
Go
64 lines
1.3 KiB
Go
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
|
|
// Use of this source code is governed by a BSD-style
|
|
// license that can be found in the LICENSE file.
|
|
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"expvar"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
"sync/atomic"
|
|
"time"
|
|
)
|
|
|
|
var dnsCache atomic.Value // of []byte
|
|
|
|
var bootstrapDNSRequests = expvar.NewInt("counter_bootstrap_dns_requests")
|
|
|
|
func refreshBootstrapDNSLoop() {
|
|
if *bootstrapDNS == "" {
|
|
return
|
|
}
|
|
for {
|
|
refreshBootstrapDNS()
|
|
time.Sleep(10 * time.Minute)
|
|
}
|
|
}
|
|
|
|
func refreshBootstrapDNS() {
|
|
if *bootstrapDNS == "" {
|
|
return
|
|
}
|
|
dnsEntries := make(map[string][]net.IP)
|
|
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
|
defer cancel()
|
|
names := strings.Split(*bootstrapDNS, ",")
|
|
var r net.Resolver
|
|
for _, name := range names {
|
|
addrs, err := r.LookupIP(ctx, "ip", name)
|
|
if err != nil {
|
|
log.Printf("bootstrap DNS lookup %q: %v", name, err)
|
|
continue
|
|
}
|
|
dnsEntries[name] = addrs
|
|
}
|
|
j, err := json.MarshalIndent(dnsCache, "", "\t")
|
|
if err != nil {
|
|
// leave the old values in place
|
|
return
|
|
}
|
|
dnsCache.Store(j)
|
|
}
|
|
|
|
func handleBootstrapDNS(w http.ResponseWriter, r *http.Request) {
|
|
bootstrapDNSRequests.Add(1)
|
|
w.Header().Set("Content-Type", "application/json")
|
|
j, _ := dnsCache.Load().([]byte)
|
|
w.Write(j)
|
|
}
|