forked from DataDog/datadog-agent
-
Notifications
You must be signed in to change notification settings - Fork 2
/
azure.go
209 lines (177 loc) · 6.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016-present Datadog, Inc.
package azure
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/StackVista/stackstate-agent/pkg/config"
"github.com/StackVista/stackstate-agent/pkg/util/cachedfetch"
httputils "github.com/StackVista/stackstate-agent/pkg/util/http"
"github.com/StackVista/stackstate-agent/pkg/util/log"
)
// declare these as vars not const to ease testing
var (
metadataURL = "http://169.254.169.254"
timeout = 300 * time.Millisecond
// CloudProviderName contains the inventory name of for EC2
CloudProviderName = "Azure"
)
const hostnameStyleSetting = "azure_hostname_style"
// IsRunningOn returns true if the agent is running on Azure
func IsRunningOn(ctx context.Context) bool {
if _, err := GetHostAlias(ctx); err == nil {
return true
}
return false
}
var vmIDFetcher = cachedfetch.Fetcher{
Name: "Azure vmID",
Attempt: func(ctx context.Context) (interface{}, error) {
res, err := getResponseWithMaxLength(ctx,
metadataURL+"/metadata/instance/compute/vmId?api-version=2017-04-02&format=text",
config.Datadog.GetInt("metadata_endpoints_max_hostname_size"))
if err != nil {
return "", fmt.Errorf("Azure HostAliases: unable to query metadata endpoint: %s", err)
}
return res, nil
},
}
// GetHostAlias returns the VM ID from the Azure Metadata api
func GetHostAlias(ctx context.Context) (string, error) {
return vmIDFetcher.FetchString(ctx)
}
var resourceGroupNameFetcher = cachedfetch.Fetcher{
Name: "Azure Cluster Name",
Attempt: func(ctx context.Context) (interface{}, error) {
rg, err := getResponse(ctx,
metadataURL+"/metadata/instance/compute/resourceGroupName?api-version=2017-08-01&format=text")
if err != nil {
return "", fmt.Errorf("unable to query metadata endpoint: %s", err)
}
return rg, nil
},
}
// GetClusterName returns the name of the cluster containing the current VM by parsing the resource group name.
// It expects the resource group name to have the format (MC|mc)_resource-group_cluster-name_zone
func GetClusterName(ctx context.Context) (string, error) {
all, err := resourceGroupNameFetcher.FetchString(ctx)
if err != nil {
return "", err
}
splitAll := strings.Split(all, "_")
if len(splitAll) < 4 || strings.ToLower(splitAll[0]) != "mc" {
return "", fmt.Errorf("cannot parse the clustername from resource group name: %s", all)
}
return splitAll[len(splitAll)-2], nil
}
// GetNTPHosts returns the NTP hosts for Azure if it is detected as the cloud provider, otherwise an empty array.
// Demo: https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync
func GetNTPHosts(ctx context.Context) []string {
if IsRunningOn(ctx) {
return []string{"time.windows.com"}
}
return nil
}
func getResponseWithMaxLength(ctx context.Context, endpoint string, maxLength int) (string, error) {
result, err := getResponse(ctx, endpoint)
if err != nil {
return result, err
}
if len(result) > maxLength {
return "", fmt.Errorf("%v gave a response with length > to %v", endpoint, maxLength)
}
return result, err
}
func getResponse(ctx context.Context, url string) (string, error) {
if !config.IsCloudProviderEnabled(CloudProviderName) {
return "", fmt.Errorf("cloud provider is disabled by configuration")
}
return httputils.Get(ctx, url, map[string]string{"Metadata": "true"}, timeout)
}
// GetHostname returns hostname based on Azure instance metadata.
func GetHostname(ctx context.Context, options map[string]interface{}) (string, error) {
return getHostnameWithConfig(ctx, config.Datadog)
}
var instanceMetaFetcher = cachedfetch.Fetcher{
Name: "Azure Instance Metadata",
Attempt: func(ctx context.Context) (interface{}, error) {
metadataJSON, err := getResponse(ctx,
metadataURL+"/metadata/instance/compute?api-version=2017-08-01")
if err != nil {
return "", fmt.Errorf("failed to get Azure instance metadata: %s", err)
}
return metadataJSON, nil
},
}
// sts - renamed config variable to avoid conflicting with package
func getHostnameWithConfig(ctx context.Context, conf config.Config) (string, error) {
style := conf.GetString(hostnameStyleSetting)
if style == "os" {
return "", fmt.Errorf("azure_hostname_style is set to 'os'")
}
metadataJSON, err := instanceMetaFetcher.FetchString(ctx)
if err != nil {
return "", err
}
var metadata struct {
VMID string
Name string
ResourceGroupName string
SubscriptionID string
}
if err := json.Unmarshal([]byte(metadataJSON), &metadata); err != nil {
return "", fmt.Errorf("failed to parse Azure instance metadata: %s", err)
}
var name string
switch style {
case "vmid":
name = metadata.VMID
case "name":
name = metadata.Name
case "name_and_resource_group":
name = fmt.Sprintf("%s.%s", metadata.Name, metadata.ResourceGroupName)
case "full":
name = fmt.Sprintf("%s.%s.%s", metadata.Name, metadata.ResourceGroupName, metadata.SubscriptionID)
default:
return "", fmt.Errorf("invalid azure_hostname_style value: %s", style)
}
if err := config.ValidHostname(name); err != nil {
return "", err
}
return name, nil
}
type vmMetadata struct {
Name string `json:"name"`
ResourceID string `json:"resourceId"`
}
func getMetadata(ctx context.Context) (*vmMetadata, error) {
metadataJSON, err := getResponse(ctx, metadataURL+"/metadata/instance/compute?api-version=2021-02-01")
if err != nil {
return nil, fmt.Errorf("failed to get Azure VM metadata: %s", err)
}
var metadata vmMetadata
if err := json.Unmarshal([]byte(metadataJSON), &metadata); err != nil {
return nil, fmt.Errorf("failed to parse Azure VM metadata: %s", err)
}
log.Infof("Azure VM metadata: %v", metadata)
return &metadata, nil
}
// HostnameIdentifiers returns list of Azure-specific identifiers for StackState topology
func HostnameIdentifiers(ctx context.Context) ([]string, error) {
metadata, err := getMetadata(ctx)
if err != nil {
log.Warnf("Can't get Azure VM metadata: %v", err)
return []string{}, err
}
identifiers := make([]string, 0, 2)
if metadata.ResourceID != "" {
identifiers = append(identifiers, "urn:azure:"+metadata.ResourceID)
identifiers = append(identifiers, "urn:azure:"+strings.ToUpper(metadata.ResourceID))
}
return identifiers, nil
}