-
Notifications
You must be signed in to change notification settings - Fork 102
/
azure.go
232 lines (197 loc) · 5.32 KB
/
azure.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package azure
import (
"bufio"
"encoding/xml"
"fmt"
"net"
"os"
"strconv"
"strings"
"time"
"github.com/coreos/coreos-metadata/internal/providers"
"github.com/coreos/coreos-metadata/internal/retry"
)
const (
AgentName = "com.coreos.metadata"
FabricProtocolVersion = "2012-11-30"
LeaseRetryInterval = 500 * time.Millisecond
)
type metadata struct {
virtualIPv4 net.IP
dynamicIPv4 net.IP
}
func FetchMetadata() (providers.Metadata, error) {
addr, err := getFabricAddress()
if err != nil {
return providers.Metadata{}, err
}
if err := assertFabricCompatible(addr, FabricProtocolVersion); err != nil {
return providers.Metadata{}, err
}
config, err := fetchSharedConfig(addr)
if err != nil {
return providers.Metadata{}, err
}
return providers.Metadata{
Attributes: map[string]string{
"AZURE_IPV4_DYNAMIC": providers.String(config.dynamicIPv4),
"AZURE_IPV4_VIRTUAL": providers.String(config.virtualIPv4),
},
}, nil
}
func getClient() retry.Client {
client := retry.Client{
InitialBackoff: time.Second,
MaxBackoff: time.Second * 5,
MaxAttempts: 10,
Header: map[string][]string{
"x-ms-agent-name": {AgentName},
"x-ms-version": {FabricProtocolVersion},
"Content-Type": {"text/xml; charset=utf-8"},
},
}
return client
}
func findLease() (*os.File, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("could not list interfaces: %v", err)
}
for {
for _, iface := range ifaces {
lease, err := os.Open(fmt.Sprintf("/run/systemd/netif/leases/%d", iface.Index))
if os.IsNotExist(err) {
continue
} else if err != nil {
return nil, err
} else {
return lease, nil
}
}
fmt.Printf("No leases found. Waiting...")
time.Sleep(LeaseRetryInterval)
}
}
func getFabricAddress() (net.IP, error) {
lease, err := findLease()
if err != nil {
return nil, err
}
defer lease.Close()
var rawEndpoint string
line := bufio.NewScanner(lease)
for line.Scan() {
parts := strings.Split(line.Text(), "=")
if parts[0] == "OPTION_245" && len(parts) == 2 {
rawEndpoint = parts[1]
break
}
}
if len(rawEndpoint) == 0 || len(rawEndpoint) != 8 {
return nil, fmt.Errorf("fabric endpoint not found in leases")
}
octets := make([]byte, 4)
for i := 0; i < 4; i++ {
octet, err := strconv.ParseUint(rawEndpoint[2*i:2*i+2], 16, 8)
if err != nil {
return nil, err
}
octets[i] = byte(octet)
}
return net.IPv4(octets[0], octets[1], octets[2], octets[3]), nil
}
func assertFabricCompatible(endpoint net.IP, desiredVersion string) error {
body, err := getClient().Getf("http://%s/?comp=versions", endpoint)
if err != nil {
return fmt.Errorf("failed to fetch versions: %v", err)
}
versions := struct {
Supported struct {
Versions []string `xml:"Version"`
}
Preferred struct {
Version string
}
}{}
if err := xml.Unmarshal(body, &versions); err != nil {
return fmt.Errorf("failed to unmarshal response: %v", err)
}
for _, version := range versions.Supported.Versions {
if version == desiredVersion {
return nil
}
}
return fmt.Errorf("fabric version %s is not compatible", desiredVersion)
}
func fetchSharedConfig(endpoint net.IP) (metadata, error) {
client := getClient()
body, err := client.Getf("http://%s/machine/?comp=goalstate", endpoint)
if err != nil {
return metadata{}, fmt.Errorf("failed to fetch goal state: %v", err)
}
goal := struct {
Container struct {
RoleInstanceList struct {
RoleInstance struct {
Configuration struct {
SharedConfig string
}
}
}
}
}{}
if err := xml.Unmarshal(body, &goal); err != nil {
return metadata{}, fmt.Errorf("failed to unmarshal response: %v", err)
}
body, err = client.Get(goal.Container.RoleInstanceList.RoleInstance.Configuration.SharedConfig)
if err != nil {
return metadata{}, fmt.Errorf("failed to fetch shared config: %v", err)
}
sharedConfig := struct {
Incarnation struct {
Instance string `xml:"instance,attr"`
}
Instances struct {
Instances []struct {
Id string `xml:"id,attr"`
Address string `xml:"address,attr"`
InputEndpoints struct {
Endpoints []struct {
LoadBalancedPublicAddress string `xml:"loadBalancedPublicAddress,attr"`
} `xml:"Endpoint"`
}
} `xml:"Instance"`
}
}{}
if err := xml.Unmarshal(body, &sharedConfig); err != nil {
return metadata{}, err
}
config := metadata{}
for _, i := range sharedConfig.Instances.Instances {
if i.Id == sharedConfig.Incarnation.Instance {
config.dynamicIPv4 = net.ParseIP(i.Address)
for _, e := range i.InputEndpoints.Endpoints {
host, _, err := net.SplitHostPort(e.LoadBalancedPublicAddress)
if err == nil {
config.virtualIPv4 = net.ParseIP(host)
break
}
}
break
}
}
return config, nil
}