-
Notifications
You must be signed in to change notification settings - Fork 0
/
virtual_interface.go
110 lines (88 loc) · 2.29 KB
/
virtual_interface.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
package main
import (
"fmt"
"math/rand"
"net"
log "github.com/Sirupsen/logrus"
skvs "github.com/experimental-platform/platform-skvs/client"
"github.com/experimental-platform/platform-utils/netutil"
"github.com/milosgajdos83/tenus"
)
func generateMac() string {
r := make([]byte, 3)
_, err := rand.Read(r)
if err != nil {
panic(fmt.Sprintf("createMac(): Failed to generate random MAC bytes: %s", err.Error()))
}
return fmt.Sprintf("00:11:22:%x:%x:%x", r[0:1], r[1:2], r[2:3])
}
func getAppMac(appName string) string {
var mac string
var err error
macSKVSPath := fmt.Sprintf("apps/%s/mac", appName)
mac, err = skvs.Get(macSKVSPath)
if err != nil {
mac = generateMac()
if err = skvs.Set(macSKVSPath, mac); err != nil {
log.Errorf("Failed to persist MAC address for app '%s' in SKVS: %s", appName, err.Error())
}
}
return mac
}
func appIfName(appName string) string {
return fmt.Sprintf("app_%s0", appName)
}
func createAppInterface(appName string) error {
ifName := appIfName(appName)
_, err := net.InterfaceByName(ifName)
if err == nil {
log.Infof("Interface '%s' already exists.\n", ifName)
return nil
}
mac := getAppMac(appName)
defaultInterface, err := netutil.GetDefaultInterface()
if err != nil {
return err
}
link, err := tenus.NewMacVlanLinkWithOptions(defaultInterface, tenus.MacVlanOptions{Dev: ifName, MacAddr: mac})
if err != nil {
return err
}
err = link.SetLinkUp()
if err != nil {
return err
}
return nil
}
func getInterfaceIP(ifName string) (string, error) {
interf, err := net.InterfaceByName(ifName)
if err != nil {
return "", err
}
addrs, err := interf.Addrs()
if err != nil {
return "", err
}
// iterate over the addresses
// and return first IPv4 addr
for _, address := range addrs {
cidr := address.String()
ip, _, err := net.ParseCIDR(cidr)
if err != nil {
return "", fmt.Errorf("error parsing CIDR '%s'", cidr)
}
if len(ip.To4()) == net.IPv4len {
return ip.String(), nil
}
}
// found no IPv4 addresses, error out
return "", fmt.Errorf("the device %s has no IPv4 addresses", ifName)
}
func getAppExternalIP(appName string) (string, error) {
ifName := appIfName(appName)
return getInterfaceIP(ifName)
}
func deleteAppInterface(appName string) error {
ifName := appIfName(appName)
return tenus.DeleteLink(ifName)
}