-
Notifications
You must be signed in to change notification settings - Fork 6
/
zone.go
411 lines (342 loc) · 9.28 KB
/
zone.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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
)
// Define URLs for gathering cloud provider metadata
const (
// Google compute engine
kGCEExternalIP = "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip"
kGCEZoneUrl = "http://metadata.google.internal/computeMetadata/v1/instance/zone"
// AWS
kAWSExternalIP = "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip"
kAWSZoneUrl = "http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/forwarded-ips"
// USING Public geoip API service
geoServiceInternalIPUrl = "http://ipinfo.io/geo"
geoServiceExternalIPUrl = "http://ipinfo.io/%s/geo"
)
// define http client to re-use
var zoneHttpClient http.Client
// defines struct to return to the client
// Contains
// - the virtual machine public IP address
// - the client IP address hitting this virtual machine
// - the virtual machine zone info
// https://cloud.google.com/compute/docs/regions-zones/regions-zones
type zone struct {
CloudProvider CloudProvider
Name string
IpAddress *coordinates
ClientIpAddress *coordinates
Ready bool
Timestamp time.Time
Traffic map[string]int64
mutex sync.RWMutex
}
// coordinates information of the ip address
type coordinates struct {
Ip string `json:"ip"`
Port string `json:"port"`
LatLong string `json:"loc"`
City string `json:"city"`
Region string `json:"region"`
Country string `json:"country"`
Dc string `json:"dc"`
}
// main method which retrieves additional info
func NewZone(provider CloudProvider, clientIp string) *zone {
z := zone{
CloudProvider: provider,
Traffic: make(map[string]int64),
mutex: sync.RWMutex{},
}
getVMInfo(provider, &z)
if clientIp != "" {
host, _, _ := net.SplitHostPort(clientIp)
coord := getIPCoordinates(host)
z.ClientIpAddress = &coord
log.Printf("Got client IP coordinates: %s\n", z.ClientIpAddress)
}
return &z
}
// ========================================================================
// Traffic counter
// func (z *zone) AllZones() map[string]int64 {
// r.mutex.Lock()
// defer r.mutex.Unlock()
// return r.Zones
// }
func (z *zone) ResetCounter() {
for key, _ := range z.Traffic {
z.Traffic[key] = 0
}
}
func (z *zone) Increment(zone string) {
z.mutex.Lock()
defer z.mutex.Unlock()
// if the entry exists, then increment its value
if _, ok := z.Traffic[zone]; ok {
z.Traffic[zone]++
} else {
// otherwise create a new entry
z.Traffic[zone] = 1
}
}
// This is used in the admin to increment the counters for each zones,
// arriving from the heartbeats
func (z *zone) IncrementZones(zones map[string]int64) {
z.mutex.Lock()
defer z.mutex.Unlock()
fmt.Println("COUNTER:", zones)
// loop through the data coming from the parameter
for zone, counter := range zones {
if _, ok := z.Traffic[zone]; ok {
z.Traffic[zone] += counter
} else {
// otherwise create a new entry
z.Traffic[zone] = counter
}
}
}
func (z *zone) Get(zone string) int64 {
z.mutex.RLock()
defer z.mutex.RUnlock()
return z.Traffic[zone]
}
// ========================================================================
func (z *zone) toJson() []byte {
var data []byte
var err error
z.mutex.RLock()
defer z.mutex.RUnlock()
data, err = json.Marshal(z)
if err != nil {
log.Println("Could not serialize zone to JSON", err)
}
return data
}
func ZoneFromJson(data []byte) (*zone, error) {
var z zone
err := json.Unmarshal(data, &z)
return &z, err
}
// helper which fills in all the VM info into the zone struct
func getVMInfo(provider CloudProvider, z *zone) {
var zoneUrl string
var publicIPUrl string
switch provider {
case GCE:
zoneUrl = kGCEZoneUrl
publicIPUrl = kGCEExternalIP
break
case AWS:
zoneUrl = ""
publicIPUrl = ""
break
}
// get the zone information
zoneInfo := getZoneInfo(provider, zoneUrl)
if strings.Contains(zoneInfo, "europe-west1") {
z.Name = "europe-west1"
} else if strings.Contains(zoneInfo, "us-west1") {
z.Name = "us-west1"
} else if strings.Contains(zoneInfo, "us-central1") {
z.Name = "us-central1"
} else if strings.Contains(zoneInfo, "us-east1") {
z.Name = "us-east1"
} else if strings.Contains(zoneInfo, "asia-east1") {
z.Name = "asia-east1"
} else if strings.Contains(zoneInfo, "asia-northeast1") {
z.Name = "asia-northeast1"
} else {
z.Name = "unknown"
}
// gathers the external ip assigned to the VM
ip := fmt.Sprintf("%s:%s", serviceHost, servicePort)
if ip == ":" {
ip = getExternalIP(provider, publicIPUrl)
}
log.Println("Got external VM ip address", ip)
if provider == AWS {
if ip != "" {
// Resolves the geo location info
coord := getIPCoordinates(ip)
z.IpAddress = &coord
log.Printf("Got external VM ip address GEO: %s\n", z.IpAddress)
}
} else {
coord := getZoneInfoFromDataCenter(provider, z.Name, ip)
z.IpAddress = &coord
}
}
// Gets the VM external IP address assigned to it
func getExternalIP(provider CloudProvider, url string) string {
// define vars
var ip string
var bodyBytes []byte
// cerate new request
req, _ := http.NewRequest("GET", url, nil)
// add specific header
switch provider {
case GCE:
req.Header.Set("Metadata-Flavor", "Google")
break
case AWS:
break
}
// make the call
resp, err := zoneHttpClient.Do(req)
if err == nil {
defer resp.Body.Close()
if resp.StatusCode == 200 {
bodyBytes, err = ioutil.ReadAll(resp.Body)
if err == nil {
return string(bodyBytes)
}
} else {
log.Println("VM External IP: got", resp.StatusCode, "status code.")
}
}
log.Println("Failed to get external IP", url, err)
return ip
}
// Calls the geo ip web service to resolve the geolocation info
// http://ipinfo.io/developers/jsonp-requests
func getIPCoordinates(ip string) coordinates {
var coord coordinates
// format the URL
ipAddressUrl := fmt.Sprintf(geoServiceExternalIPUrl, ip)
log.Println("Calling GEO IP Services", ipAddressUrl)
// create request
req, err := http.NewRequest("GET", ipAddressUrl, nil)
if err != nil {
log.Println("Error building request for getting IP coordinates", ipAddressUrl, err)
return coord
}
// add specific CURL user agent header necessary for the api
req.Header.Add("User-Agent", "curl/7.49.1")
// make the request
resp, err := zoneHttpClient.Do(req)
if err != nil {
// not good...
log.Println("Unable to retrieve external GEO IP information:", ipAddressUrl, err)
} else {
// Parse the response
defer resp.Body.Close()
if resp.StatusCode == 200 {
// bodyBytes, err := ioutil.ReadAll(resp.Body)
// if err == nil {
// log.Println("GEO string", string(bodyBytes))
// }
enc := json.NewDecoder(resp.Body)
if err := enc.Decode(&coord); err != nil {
log.Println("Failed to parse external GEO ip json response", ipAddressUrl, err)
return coord
}
} else {
log.Println("IP Coordinates service: got", resp.StatusCode, "status code")
}
log.Printf("Geo IP response: %s\n", coord)
return coord
}
return coord
}
// Gets the provider specific zone information
func getZoneInfo(provider CloudProvider, url string) string {
var zoneInfo string
var bodyBytes []byte
req, _ := http.NewRequest("GET", url, nil)
// add specific headers if necessary
switch provider {
case GCE:
req.Header.Set("Metadata-Flavor", "Google")
break
case AWS:
break
}
resp, err := zoneHttpClient.Do(req)
if err == nil {
defer resp.Body.Close()
bodyBytes, err = ioutil.ReadAll(resp.Body)
if err == nil {
return string(bodyBytes)
}
}
log.Println("Failed to get VM zone information", url)
return zoneInfo
}
func getZoneInfoFromDataCenter(provider CloudProvider, zone, ip string) coordinates {
return getGCEZone(zone, ip)
}
func getGCEZone(zone, ip string) coordinates {
if strings.Contains(zone, "europe-west1") {
return coordinates{
Dc: "europe-west1",
Ip: ip,
City: "Saint-Ghislain",
Country: "Belgium",
Region: "Ghlin",
LatLong: "50.470976, 3.864521",
}
} else if strings.Contains(zone, "us-west1") {
return coordinates{
Dc: "us-west1",
Ip: ip,
City: "The Dalles",
Country: "USA",
Region: "Oregon",
LatLong: "45.632130, -121.200992",
}
} else if strings.Contains(zone, "us-central1") {
return coordinates{
Dc: "us-central1",
Ip: ip,
City: "Council Bluffs",
Country: "USA",
Region: "Iowa",
LatLong: "41.221099, -95.863942",
}
} else if strings.Contains(zone, "us-east1") {
return coordinates{
Dc: "us-east1",
Ip: ip,
City: "Berkeley County",
Country: "USA",
Region: "South Carolina",
LatLong: "33.072657, -80.038877",
}
} else if strings.Contains(zone, "asia-east1") {
return coordinates{
Dc: "asia-east1",
Ip: ip,
City: "Changhua County",
Country: "Taiwan",
Region: "",
LatLong: "23.925895, 120.441405",
}
} else if strings.Contains(zone, "asia-northeast1") {
return coordinates{
Dc: "asia-northeast1",
Ip: ip,
City: "Tokyo",
Country: "Japan",
Region: "",
LatLong: "35.648112, 139.790766",
}
}
return coordinates{
Dc: "unknown",
Ip: ip,
City: "Unknown",
Country: "Unknown",
Region: "Unknown",
LatLong: "0, 0",
}
}