forked from cloudfoundry/bosh-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mac_address_detector_unix.go
64 lines (50 loc) · 1.65 KB
/
mac_address_detector_unix.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
// +build !windows
package net
import (
"path"
"strings"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshsys "github.com/cloudfoundry/bosh-utils/system"
)
const (
ifaliasPrefix = "bosh-interface"
)
type linuxMacAddressDetector struct {
fs boshsys.FileSystem
}
func NewMacAddressDetector(fs boshsys.FileSystem) MACAddressDetector {
return linuxMacAddressDetector{
fs: fs,
}
}
func (d linuxMacAddressDetector) DetectMacAddresses() (map[string]string, error) {
addresses := map[string]string{}
filePaths, err := d.fs.Glob("/sys/class/net/*")
if err != nil {
return addresses, bosherr.WrapError(err, "Getting file list from /sys/class/net")
}
var macAddress string
var ifalias string
for _, filePath := range filePaths {
isPhysicalDevice := d.fs.FileExists(path.Join(filePath, "device"))
// For third-party networking plugin case that the physical interface is used as bridge
// interface and a virtual interface is created to replace it, the virtual interface needs
// to be included in the detected result.
// The virtual interface has an ifalias that has the prefix "bosh-interface"
hasBoshPrefix := false
ifalias, err = d.fs.ReadFileString(path.Join(filePath, "ifalias"))
if err == nil {
hasBoshPrefix = strings.HasPrefix(ifalias, ifaliasPrefix)
}
if isPhysicalDevice || hasBoshPrefix {
macAddress, err = d.fs.ReadFileString(path.Join(filePath, "address"))
if err != nil {
return addresses, bosherr.WrapError(err, "Reading mac address from file")
}
macAddress = strings.Trim(macAddress, "\n")
interfaceName := path.Base(filePath)
addresses[macAddress] = interfaceName
}
}
return addresses, nil
}