/
profiles_gcp.go
58 lines (47 loc) · 954 Bytes
/
profiles_gcp.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
package ops
import (
"context"
"net"
"sync"
"time"
)
var (
onGCEOnce sync.Once
onGCE bool
)
func init() {
OnGCE()
}
// OnGCE reports whether this process is running on Google Compute Engine.
func OnGCE() bool {
onGCEOnce.Do(initOnGCE)
return onGCE
}
func initOnGCE() {
onGCE = testOnGCE(&net.Resolver{}, 3*time.Second)
}
type resolver interface {
LookupHost(ctx context.Context, host string) (addrs []string, err error)
}
func testOnGCE(resolver resolver, timeout time.Duration) bool {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
resChan := make(chan bool, 1)
go func() {
addrs, err := resolver.LookupHost(ctx, "metadata.google.internal.")
if err != nil || len(addrs) == 0 {
resChan <- false
return
}
resChan <- true
}()
timer := time.NewTimer(timeout)
defer timer.Stop()
var res bool
select {
case res = <-resChan:
return res
case <-timer.C: // timeout
return false
}
}