-
Notifications
You must be signed in to change notification settings - Fork 326
/
instance.go
73 lines (61 loc) · 1.5 KB
/
instance.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
package utils
import (
"io/ioutil"
"net/http"
"github.com/rexray/rexray/libstorage/api/types"
"github.com/rexray/rexray/libstorage/drivers/storage/dobs"
)
const (
metadataBase = "169.254.169.254"
metadataURL = "http://" + metadataBase + "/metadata/v1"
metadataID = metadataURL + "/id"
metadataRegion = metadataURL + "/region"
metadataName = metadataURL + "/hostname"
)
// InstanceID gets the instance information from the droplet
func InstanceID(ctx types.Context) (*types.InstanceID, error) {
id, err := getURL(ctx, metadataID)
if err != nil {
return nil, err
}
region, err := getURL(ctx, metadataRegion)
if err != nil {
return nil, err
}
name, err := getURL(ctx, metadataName)
if err != nil {
return nil, err
}
return &types.InstanceID{
ID: id,
Driver: dobs.Name,
Fields: map[string]string{
dobs.InstanceIDFieldRegion: region,
dobs.InstanceIDFieldName: name,
},
}, nil
}
// IsDroplet is a simple check to see if code is being executed on a DigitalOcean droplet or not
func IsDroplet(ctx types.Context) (bool, error) {
_, err := getURL(ctx, metadataURL)
if err != nil {
return false, nil
}
return true, nil
}
func getURL(ctx types.Context, url string) (string, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
resp, err := doRequest(ctx, req)
if err != nil {
return "", err
}
defer resp.Body.Close()
id, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(id), nil
}