/
heuristic.go
77 lines (62 loc) · 1.52 KB
/
heuristic.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
//go:build linux || darwin || windows
// +build linux darwin windows
package heuristic
import (
"context"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"net"
)
func getCloudBuildSubnet(ctx context.Context) string {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return ""
}
defer cli.Close()
network, err := cli.NetworkInspect(ctx, CloudBuildNetworkName, types.NetworkInspectOptions{})
if err != nil {
return ""
}
if len(network.IPAM.Config) != 1 {
return ""
}
return network.IPAM.Config[0].Subnet
}
func GetCloudBuildIP(ctx context.Context) string {
// Are we running in Cloud Build?
cloudBuildSubnet := getCloudBuildSubnet(ctx)
if cloudBuildSubnet == "" {
return ""
}
_, cloudBuildNetwork, err := net.ParseCIDR(cloudBuildSubnet)
if err != nil {
return ""
}
// Pick up first IP address of the interface attached to the Cloud Build network
addrs, err := net.InterfaceAddrs()
if err != nil {
return ""
}
for _, addr := range addrs {
interfaceIP, _, err := net.ParseCIDR(addr.String())
if err != nil {
continue
}
if cloudBuildNetwork.Contains(interfaceIP) {
return interfaceIP.String()
}
}
return ""
}
func IsRunningWindowsContainers(ctx context.Context) bool {
cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
if err != nil {
return false
}
defer cli.Close()
info, err := cli.Info(ctx)
if err != nil {
return false
}
return info.OSType == "windows"
}