-
Notifications
You must be signed in to change notification settings - Fork 122
/
hostinfo.go
325 lines (281 loc) · 9.54 KB
/
hostinfo.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
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//go:build darwin
// +build darwin
package darwin
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/newrelic/infrastructure-agent/internal/agent"
"github.com/newrelic/infrastructure-agent/internal/os/distro"
"github.com/newrelic/infrastructure-agent/pkg/entity"
"github.com/newrelic/infrastructure-agent/pkg/helpers"
"github.com/newrelic/infrastructure-agent/pkg/log"
"github.com/newrelic/infrastructure-agent/pkg/plugins/ids"
"github.com/newrelic/infrastructure-agent/pkg/sysinfo/cloud"
"github.com/shirou/gopsutil/v3/host"
"github.com/sirupsen/logrus"
)
var (
hlog = log.WithComponent("HostInfoPlugin")
kernelVersionRegex = regexp.MustCompile("Version (.*?):")
)
// HostinfoPlugin returns metadata of the host.
type HostinfoPlugin struct {
agent.PluginCommon
cloudHarvester cloud.Harvester // Gather metadata for the cloud instance.
readDataFromCmd func(cmd string, args ...string) (string, error)
}
// HostInfoData is the structure returned to the backend by HostinfoPlugin.
type HostInfoData struct {
System string `json:"id"`
Distro string `json:"distro"`
KernelVersion string `json:"kernel_version"`
HostType string `json:"host_type"`
CpuName string `json:"cpu_name"`
// Number of cores within a single CPU
// It is shown as 'coreCount' in New Relic UI
CpuNum string `json:"cpu_num"`
// Total number of cores in all the CPUs
// It is shown as 'processorCount' in New Relic UI
TotalCpu string `json:"total_cpu"`
Ram string `json:"ram"`
UpSince string `json:"boot_timestamp"`
AgentVersion string `json:"agent_version"`
AgentName string `json:"agent_name"`
AgentMode string `json:"agent_mode"`
OperatingSystem string `json:"operating_system"`
ProductUuid string `json:"product_uuid"`
RegionAWS string `json:"aws_region,omitempty"`
RegionAzure string `json:"region_name,omitempty"`
RegionGCP string `json:"zone,omitempty"`
RegionAlibaba string `json:"region_id,omitempty"`
AWSAccountID string `json:"aws_account_id,omitempty"`
AWSAvailabilityZone string `json:"aws_availability_zone,omitempty"`
AWSImageID string `json:"aws_image_id,omitempty"`
}
func (hip *HostInfoData) SortKey() string {
return hip.System
}
func NewHostinfoPlugin(ctx agent.AgentContext, cloudHarvester cloud.Harvester) agent.Plugin {
return &HostinfoPlugin{
PluginCommon: agent.PluginCommon{
ID: ids.HostInfo,
Context: ctx,
},
cloudHarvester: cloudHarvester,
readDataFromCmd: func(cmd string, args ...string) (string, error) {
return helpers.RunCommand(cmd, "", args...)
},
}
}
// Run the HostinfoPlugin.
func (hip *HostinfoPlugin) Run() {
hip.Context.AddReconnecting(hip)
data := hip.Data()
hip.EmitInventory(data, entity.NewFromNameWithoutID(hip.Context.EntityKey()))
}
// Data collects the hostinfo.
func (hip *HostinfoPlugin) Data() agent.PluginInventoryDataset {
return agent.PluginInventoryDataset{hip.gatherHostinfo(hip.Context)}
}
func (hip *HostinfoPlugin) gatherHostinfo(context agent.AgentContext) *HostInfoData {
ho, err := hip.getHardwareOverview()
if err != nil {
hlog.WithError(err).Error("error reading hardware overview")
}
kernelVersion, err := hip.getKernelRelease()
if err != nil {
hlog.WithError(err).Error("error reading kernel release")
}
numberOfProcessors, err := strconv.Atoi(ho.NumberOfProcessors)
if err != nil {
hlog.WithError(err).Error("error converting number of processors to int")
}
totalNumberOfCores, err := strconv.Atoi(ho.TotalNumberOfCores)
if err != nil {
hlog.WithError(err).Error("error converting total number of cores to int")
}
cpuNum := 0
if numberOfProcessors > 0 {
cpuNum = totalNumberOfCores / numberOfProcessors
}
cpuName := ho.ProcessorName
// arm architectures do not provide processor speed
if ho.ProcessorSpeed != "" {
cpuName = fmt.Sprintf("%s @ %s", ho.ProcessorName, ho.ProcessorSpeed)
}
data := &HostInfoData{
System: "system",
Distro: distro.GetDistro(),
KernelVersion: kernelVersion,
HostType: hip.getHostType(ho),
CpuName: cpuName,
CpuNum: fmt.Sprintf("%d", cpuNum),
TotalCpu: ho.TotalNumberOfCores,
Ram: ho.Memory,
UpSince: getUpSince(),
AgentVersion: context.Version(),
AgentName: "Infrastructure",
AgentMode: context.Config().RunMode,
OperatingSystem: "macOS",
ProductUuid: ho.HardwareUUID,
}
err = hip.setCloudRegion(data)
if err != nil {
hlog.WithError(err).WithField("cloudType", hip.cloudHarvester.GetCloudType()).Debug(
"cloud region couldn't be set")
}
err = hip.setCloudMetadata(data)
if err != nil {
hlog.WithError(err).WithField("cloudType", hip.cloudHarvester.GetCloudType()).Debug(
"cloud metadata couldn't be set")
}
helpers.LogStructureDetails(hlog, data, "HostInfoData", "raw", nil)
return data
}
func (hip *HostinfoPlugin) getHostType(ho hardwareOverview) string {
hostType := "unknown"
if hip.Context.Config().DisableCloudMetadata ||
hip.cloudHarvester.GetCloudType() == cloud.TypeNoCloud ||
hip.cloudHarvester.GetCloudType() == cloud.TypeInProgress {
hostType = fmt.Sprintf("%s %s", ho.ModelName, ho.ModelIdentifier)
}
if response, err := hip.cloudHarvester.GetHostType(); err != nil {
hlog.WithError(err).WithField("cloudType", hip.cloudHarvester.GetCloudType()).Debug(
"error getting host type from cloud metadata")
} else {
hostType = response
}
return hostType
}
func (hip *HostinfoPlugin) getKernelRelease() (string, error) {
out, err := hip.readDataFromCmd("uname", "-v")
if err != nil {
return "", err
}
if kernelVersion := kernelVersionRegex.FindStringSubmatch(out); len(kernelVersion) > 1 {
return kernelVersion[1], nil
}
return "", fmt.Errorf("failed to detect kernel version in: '%s'", out)
}
func getUpSince() string {
info, err := host.Info()
if err != nil {
hlog.WithError(err).Warn("unable to read host info for uptime")
return ""
}
return time.Now().Add(time.Second * -time.Duration(info.Uptime)).Format("2006-01-02 15:04:05")
}
func (hip *HostinfoPlugin) setCloudRegion(data *HostInfoData) (err error) {
if hip.Context.Config().DisableCloudMetadata ||
hip.cloudHarvester.GetCloudType() == cloud.TypeNoCloud {
return
}
region, err := hip.cloudHarvester.GetRegion()
if err != nil {
return fmt.Errorf("couldn't retrieve cloud region: %v", err)
}
switch hip.cloudHarvester.GetCloudType() {
case cloud.TypeAWS:
data.RegionAWS = region
case cloud.TypeAzure:
data.RegionAzure = region
case cloud.TypeGCP:
data.RegionGCP = region
case cloud.TypeAlibaba:
data.RegionAlibaba = region
default:
}
return
}
// Only for AWS cloud instances
func (self *HostinfoPlugin) setCloudMetadata(data *HostInfoData) (err error) {
if self.Context.Config().DisableCloudMetadata ||
self.cloudHarvester.GetCloudType() == cloud.TypeNoCloud {
return
}
if self.cloudHarvester.GetCloudType() == cloud.TypeAWS {
imageID, err := self.cloudHarvester.GetInstanceImageID()
if err != nil {
return fmt.Errorf("couldn't retrieve cloud image ID: %v", err)
}
data.AWSImageID = imageID
awsAccountID, err := self.cloudHarvester.GetAccountID()
if err != nil {
return fmt.Errorf("couldn't retrieve cloud account ID: %v", err)
}
data.AWSAccountID = awsAccountID
availabilityZone, err := self.cloudHarvester.GetZone()
if err != nil {
return fmt.Errorf("couldn't retrieve cloud availability zone: %v", err)
}
data.AWSAvailabilityZone = availabilityZone
}
return
}
// hardwareOverview structure keeps the values extracted from osX system_profiler.
type hardwareOverview struct {
ModelName string
ModelIdentifier string
Memory string
HardwareUUID string
processorInfo
}
// processorInfo structure keeps the values extracted from osX system_profiler
// for the processor information.
type processorInfo struct {
ProcessorName string
ProcessorSpeed string
NumberOfProcessors string
TotalNumberOfCores string
}
func (hip *HostinfoPlugin) getHardwareOverview() (hardwareOverview, error) {
out, err := hip.readDataFromCmd("system_profiler", "SPHardwareDataType")
if err != nil {
return hardwareOverview{}, err
}
cpuInfo := getProcessorData(out)
memory, err := memoryToKb(helpers.SplitRightSubstring(out, "Memory: ", "\n"))
if err != nil {
hlog.WithFields(logrus.Fields{
"line": helpers.SplitRightSubstring(out, "Memory: ", "\n"),
}).Debug("Unexpected format for 'Memory' field.")
}
uuid := helpers.SplitRightSubstring(out, "Hardware UUID: ", "\n")
if !validateHardwareUUID(uuid) {
hlog.WithError(err).Debug("Error detecting hardware UUID")
uuid = "unknown"
}
return hardwareOverview{
helpers.SplitRightSubstring(out, "Model Name: ", "\n"),
helpers.SplitRightSubstring(out, "Model Identifier: ", "\n"),
memory,
uuid,
cpuInfo,
}, nil
}
func validateHardwareUUID(uuid string) bool {
matched, err := regexp.MatchString("^[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}$", uuid)
if err != nil {
return false
}
return matched
}
func memoryToKb(line string) (string, error) {
fields := strings.Fields(strings.TrimPrefix(line, "Memory: "))
if len(fields) != 2 {
return "", fmt.Errorf("expected 2 fields but got: %d", len(fields))
}
if strings.ToLower(fields[1]) != "gb" {
return "", fmt.Errorf("unexpected unit '%s'", fields[1])
}
mem, err := strconv.Atoi(fields[0])
if err != nil {
return "", fmt.Errorf("failed to parse memory field: %s", err)
}
return fmt.Sprintf("%d kB", mem*1024*1024), nil
}