File: azure.go

package info (click to toggle)
golang-github-newrelic-go-agent 3.15.2-9
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 8,356 kB
  • sloc: sh: 65; makefile: 6
file content (105 lines) | stat: -rw-r--r-- 2,367 bytes parent folder | download | duplicates (2)
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
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package utilization

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

const (
	azureHostname     = "169.254.169.254"
	azureEndpointPath = "/metadata/instance/compute?api-version=2017-03-01"
	azureEndpoint     = "http://" + azureHostname + azureEndpointPath
)

type azure struct {
	Location string `json:"location,omitempty"`
	Name     string `json:"name,omitempty"`
	VMID     string `json:"vmId,omitempty"`
	VMSize   string `json:"vmSize,omitempty"`
}

func gatherAzure(util *Data, client *http.Client) error {
	az, err := getAzure(client)
	if err != nil {
		// Only return the error here if it is unexpected to prevent
		// warning customers who aren't running Azure about a timeout.
		if _, ok := err.(unexpectedAzureErr); ok {
			return err
		}
		return nil
	}
	util.Vendors.Azure = az

	return nil
}

type unexpectedAzureErr struct{ e error }

func (e unexpectedAzureErr) Error() string {
	return fmt.Sprintf("unexpected Azure error: %v", e.e)
}

func getAzure(client *http.Client) (*azure, error) {
	req, err := http.NewRequest("GET", azureEndpoint, nil)
	if err != nil {
		return nil, err
	}
	req.Header.Add("Metadata", "true")

	response, err := client.Do(req)
	if err != nil {
		// No unexpectedAzureErr here: a timeout isusually going to
		// happen.
		return nil, err
	}
	defer response.Body.Close()

	if response.StatusCode != 200 {
		return nil, unexpectedAzureErr{e: fmt.Errorf("response code %d", response.StatusCode)}
	}

	data, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return nil, unexpectedAzureErr{e: err}
	}

	az := &azure{}
	if err := json.Unmarshal(data, az); err != nil {
		return nil, unexpectedAzureErr{e: err}
	}

	if err := az.validate(); err != nil {
		return nil, unexpectedAzureErr{e: err}
	}

	return az, nil
}

func (az *azure) validate() (err error) {
	az.Location, err = normalizeValue(az.Location)
	if err != nil {
		return fmt.Errorf("Invalid location: %v", err)
	}

	az.Name, err = normalizeValue(az.Name)
	if err != nil {
		return fmt.Errorf("Invalid name: %v", err)
	}

	az.VMID, err = normalizeValue(az.VMID)
	if err != nil {
		return fmt.Errorf("Invalid VM ID: %v", err)
	}

	az.VMSize, err = normalizeValue(az.VMSize)
	if err != nil {
		return fmt.Errorf("Invalid VM size: %v", err)
	}

	return
}