Merge pull request #566 from eyakubovich/macvlan

net: added macvlan plugin
This commit is contained in:
Eugene Yakubovich
2015-03-03 11:09:38 -08:00
26 changed files with 844 additions and 123 deletions
+7 -1
View File
@@ -42,8 +42,14 @@ Like the veth type, `bridge` will also create a veth pair and place one end into
- **mtu** (integer): the size of the MTU in bytes for bridge and veths.
- **ipMasq** (boolean): whether to setup IP masquerading on the host.
### macvlan
macvlan "clones" a real interface by assigning a made up MAC address to the "cloned" interface. The real and macvlan interfaces share the same physical device but have distinct MAC and IP addresses. With multiple macvlan interfaces sharing the same device, it behaves similarly to a bridge. Since macvlan interface has its own MAC and is located on the same link segment as the host, it makes it especially a good choice for using the DHCP server to acquire an IP address. With the IP address allocated by the real network infrastructure, this makes the container IP routable in the same way as the host IP. `macvlan` specific configuration fields are:
- **master** (string): the name of host interface to "clone". This field is required.
- **mode** (string): One of "bridge", "private", "vepa", or "passthru". This controls how traffic is handled between different macvlan interfaces on the same host. See (this guide)[http://www.pocketnix.org/posts/Linux%20Networking:%20MAC%20VLANs%20and%20Virtual%20Ethernets] for discussion of modes. Defaults to "bridge".
- **mtu** (integer): the size of the MTU in bytes for bridge and veths. Defaults to MTU of the master device.
- **ipMasq** (boolean): whether to setup IP masquerading on the host. Defaults to false.
### Coming soon
- [macvlan](https://github.com/coreos/rocket/issues/478)
- [ipvlan](https://github.com/coreos/rocket/issues/479)
## IP Address Management
+1 -1
View File
@@ -114,7 +114,7 @@
},
{
"ImportPath": "github.com/vishvananda/netlink",
"Rev": "a59b20a4021ab57ec6a89a4ad5fccfaede1fee77"
"Rev": "ae3e7dba57271b4e976c4f91637861ee477135e2"
},
{
"ImportPath": "golang.org/x/crypto/cast5",
+45 -7
View File
@@ -1,8 +1,6 @@
package netlink
import (
"net"
)
import "net"
// Link represents a link device from netlink. Shared link attributes
// like name may be retrieved using the Attrs() method. Unique data
@@ -12,6 +10,11 @@ type Link interface {
Type() string
}
type (
NsPid int
NsFd int
)
// LinkAttrs represents data shared by most link types
type LinkAttrs struct {
Index int
@@ -20,8 +23,9 @@ type LinkAttrs struct {
Name string
HardwareAddr net.HardwareAddr
Flags net.Flags
ParentIndex int // index of the parent link device
MasterIndex int // must be the index of a bridge
ParentIndex int // index of the parent link device
MasterIndex int // must be the index of a bridge
Namespace interface{} // nil | NsPid | NsFd
}
// Device links cannot be created via netlink. These links
@@ -78,9 +82,21 @@ func (vlan *Vlan) Type() string {
return "vlan"
}
type MacvlanMode uint16
const (
MACVLAN_MODE_DEFAULT MacvlanMode = iota
MACVLAN_MODE_PRIVATE
MACVLAN_MODE_VEPA
MACVLAN_MODE_BRIDGE
MACVLAN_MODE_PASSTHRU
MACVLAN_MODE_SOURCE
)
// Macvlan links have ParentIndex set in their Attrs()
type Macvlan struct {
LinkAttrs
Mode MacvlanMode
}
func (macvlan *Macvlan) Attrs() *LinkAttrs {
@@ -149,7 +165,29 @@ func (vxlan *Vxlan) Type() string {
return "vxlan"
}
type IPVlanMode uint16
const (
IPVLAN_MODE_L2 IPVlanMode = iota
IPVLAN_MODE_L3
IPVLAN_MODE_MAX
)
type IPVlan struct {
LinkAttrs
Mode IPVlanMode
}
func (ipvlan *IPVlan) Attrs() *LinkAttrs {
return &ipvlan.LinkAttrs
}
func (ipvlan *IPVlan) Type() string {
return "ipvlan"
}
// iproute2 supported devices;
// vlan | veth | vcan | dummy | ifb | macvlan | macvtap |
// can | bridge | bond | ipoib | ip6tnl | ipip | sit |
// vxlan | gre | gretap | ip6gre | ip6gretap | vti
// bridge | bond | ipoib | ip6tnl | ipip | sit | vxlan |
// gre | gretap | ip6gre | ip6gretap | vti | nlmon |
// bond_slave | ipvlan
+119 -1
View File
@@ -13,6 +13,15 @@ import (
var native = nl.NativeEndian()
var lookupByDump = false
var macvlanModes = [...]uint32{
0,
nl.MACVLAN_MODE_PRIVATE,
nl.MACVLAN_MODE_VEPA,
nl.MACVLAN_MODE_BRIDGE,
nl.MACVLAN_MODE_PASSTHRU,
nl.MACVLAN_MODE_SOURCE,
}
func ensureIndex(link *LinkAttrs) {
if link != nil && link.Index == 0 {
newlink, _ := LinkByName(link.Name)
@@ -300,6 +309,8 @@ func LinkAdd(link Link) error {
native.PutUint32(b, uint32(base.ParentIndex))
data := nl.NewRtAttr(syscall.IFLA_LINK, b)
req.AddData(data)
} else if link.Type() == "ipvlan" {
return fmt.Errorf("Can't create ipvlan link without ParentIndex")
}
nameData := nl.NewRtAttr(syscall.IFLA_IFNAME, nl.ZeroTerminated(base.Name))
@@ -310,6 +321,20 @@ func LinkAdd(link Link) error {
req.AddData(mtu)
}
if base.Namespace != nil {
var attr *nl.RtAttr
switch base.Namespace.(type) {
case NsPid:
val := nl.Uint32Attr(uint32(base.Namespace.(NsPid)))
attr = nl.NewRtAttr(syscall.IFLA_NET_NS_PID, val)
case NsFd:
val := nl.Uint32Attr(uint32(base.Namespace.(NsFd)))
attr = nl.NewRtAttr(nl.IFLA_NET_NS_FD, val)
}
req.AddData(attr)
}
linkInfo := nl.NewRtAttr(syscall.IFLA_LINKINFO, nil)
nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_KIND, nl.NonZeroTerminated(link.Type()))
@@ -331,6 +356,14 @@ func LinkAdd(link Link) error {
}
} else if vxlan, ok := link.(*Vxlan); ok {
addVxlanAttrs(vxlan, linkInfo)
} else if ipv, ok := link.(*IPVlan); ok {
data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
nl.NewRtAttrChild(data, nl.IFLA_IPVLAN_MODE, nl.Uint16Attr(uint16(ipv.Mode)))
} else if macv, ok := link.(*Macvlan); ok {
if macv.Mode != MACVLAN_MODE_DEFAULT {
data := nl.NewRtAttrChild(linkInfo, nl.IFLA_INFO_DATA, nil)
nl.NewRtAttrChild(data, nl.IFLA_MACVLAN_MODE, nl.Uint32Attr(macvlanModes[macv.Mode]))
}
}
req.AddData(linkInfo)
@@ -350,7 +383,7 @@ func LinkAdd(link Link) error {
return nil
}
// LinkAdd adds a new link device. Either Index or Name must be set in
// LinkDel deletes link device. Either Index or Name must be set in
// the link object for it to be deleted. The other values are ignored.
// Equivalent to: `ip link del $link`
func LinkDel(link Link) error {
@@ -476,6 +509,10 @@ func linkDeserialize(m []byte) (Link, error) {
link = &Veth{}
case "vxlan":
link = &Vxlan{}
case "ipvlan":
link = &IPVlan{}
case "macvlan":
link = &Macvlan{}
default:
link = &Generic{LinkType: linkType}
}
@@ -489,6 +526,10 @@ func linkDeserialize(m []byte) (Link, error) {
parseVlanData(link, data)
case "vxlan":
parseVxlanData(link, data)
case "ipvlan":
parseIPVlanData(link, data)
case "macvlan":
parseMacvlanData(link, data)
}
}
}
@@ -551,6 +592,52 @@ func LinkList() ([]Link, error) {
return res, nil
}
func LinkSetHairpin(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_MODE)
}
func LinkSetGuard(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_GUARD)
}
func LinkSetFastLeave(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_FAST_LEAVE)
}
func LinkSetLearning(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_LEARNING)
}
func LinkSetRootBlock(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_PROTECT)
}
func LinkSetFlood(link Link, mode bool) error {
return setProtinfoAttr(link, mode, nl.IFLA_BRPORT_UNICAST_FLOOD)
}
func setProtinfoAttr(link Link, mode bool, attr int) error {
base := link.Attrs()
ensureIndex(base)
req := nl.NewNetlinkRequest(syscall.RTM_SETLINK, syscall.NLM_F_ACK)
msg := nl.NewIfInfomsg(syscall.AF_BRIDGE)
msg.Type = syscall.RTM_SETLINK
msg.Flags = syscall.NLM_F_REQUEST
msg.Index = int32(base.Index)
msg.Change = nl.DEFAULT_CHANGE
req.AddData(msg)
br := nl.NewRtAttr(syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED, nil)
nl.NewRtAttrChild(br, attr, boolToByte(mode))
req.AddData(br)
_, err := req.Execute(syscall.NETLINK_ROUTE, 0)
if err != nil {
return err
}
return nil
}
func parseVlanData(link Link, data []syscall.NetlinkRouteAttr) {
vlan := link.(*Vlan)
for _, datum := range data {
@@ -609,6 +696,37 @@ func parseVxlanData(link Link, data []syscall.NetlinkRouteAttr) {
}
}
func parseIPVlanData(link Link, data []syscall.NetlinkRouteAttr) {
ipv := link.(*IPVlan)
for _, datum := range data {
if datum.Attr.Type == nl.IFLA_IPVLAN_MODE {
ipv.Mode = IPVlanMode(native.Uint32(datum.Value[0:4]))
return
}
}
}
func parseMacvlanData(link Link, data []syscall.NetlinkRouteAttr) {
macv := link.(*Macvlan)
for _, datum := range data {
if datum.Attr.Type == nl.IFLA_MACVLAN_MODE {
switch native.Uint32(datum.Value[0:4]) {
case nl.MACVLAN_MODE_PRIVATE:
macv.Mode = MACVLAN_MODE_PRIVATE
case nl.MACVLAN_MODE_VEPA:
macv.Mode = MACVLAN_MODE_VEPA
case nl.MACVLAN_MODE_BRIDGE:
macv.Mode = MACVLAN_MODE_BRIDGE
case nl.MACVLAN_MODE_PASSTHRU:
macv.Mode = MACVLAN_MODE_PASSTHRU
case nl.MACVLAN_MODE_SOURCE:
macv.Mode = MACVLAN_MODE_SOURCE
}
return
}
}
}
// copied from pkg/net_linux.go
func linkFlags(rawFlags uint32) net.Flags {
var f net.Flags
+99 -19
View File
@@ -62,10 +62,10 @@ func testLinkAddDel(t *testing.T, link Link) {
var peer *Veth
other, err := LinkByName(veth.PeerName)
if err != nil {
t.Fatal("Peer %s not created", veth.PeerName)
t.Fatalf("Peer %s not created", veth.PeerName)
}
if peer, ok = other.(*Veth); !ok {
t.Fatal("Peer %s is incorrect type", veth.PeerName)
t.Fatalf("Peer %s is incorrect type", veth.PeerName)
}
if peer.TxQLen != testTxQLen {
t.Fatalf("TxQLen of peer is %d, should be %d", peer.TxQLen, testTxQLen)
@@ -81,6 +81,26 @@ func testLinkAddDel(t *testing.T, link Link) {
compareVxlan(t, vxlan, other)
}
if ipv, ok := link.(*IPVlan); ok {
other, ok := result.(*IPVlan)
if !ok {
t.Fatal("Result of create is not a ipvlan")
}
if ipv.Mode != other.Mode {
t.Fatalf("Got unexpected mode: %d, expected: %d", other.Mode, ipv.Mode)
}
}
if macv, ok := link.(*Macvlan); ok {
other, ok := result.(*Macvlan)
if !ok {
t.Fatal("Result of create is not a macvlan")
}
if macv.Mode != other.Mode {
t.Fatalf("Got unexpected mode: %d, expected: %d", other.Mode, macv.Mode)
}
}
if err = LinkDel(link); err != nil {
t.Fatal(err)
}
@@ -98,54 +118,54 @@ func testLinkAddDel(t *testing.T, link Link) {
func compareVxlan(t *testing.T, expected, actual *Vxlan) {
if actual.VxlanId != expected.VxlanId {
t.Fatalf("Vxlan.VxlanId doesn't match")
t.Fatal("Vxlan.VxlanId doesn't match")
}
if expected.SrcAddr != nil && !actual.SrcAddr.Equal(expected.SrcAddr) {
t.Fatalf("Vxlan.SrcAddr doesn't match")
t.Fatal("Vxlan.SrcAddr doesn't match")
}
if expected.Group != nil && !actual.Group.Equal(expected.Group) {
t.Fatalf("Vxlan.Group doesn't match")
t.Fatal("Vxlan.Group doesn't match")
}
if expected.TTL != -1 && actual.TTL != expected.TTL {
t.Fatalf("Vxlan.TTL doesn't match")
t.Fatal("Vxlan.TTL doesn't match")
}
if expected.TOS != -1 && actual.TOS != expected.TOS {
t.Fatalf("Vxlan.TOS doesn't match")
t.Fatal("Vxlan.TOS doesn't match")
}
if actual.Learning != expected.Learning {
t.Fatalf("Vxlan.Learning doesn't match")
t.Fatal("Vxlan.Learning doesn't match")
}
if actual.Proxy != expected.Proxy {
t.Fatalf("Vxlan.Proxy doesn't match")
t.Fatal("Vxlan.Proxy doesn't match")
}
if actual.RSC != expected.RSC {
t.Fatalf("Vxlan.RSC doesn't match", actual, expected)
t.Fatal("Vxlan.RSC doesn't match")
}
if actual.L2miss != expected.L2miss {
t.Fatalf("Vxlan.L2miss doesn't match")
t.Fatal("Vxlan.L2miss doesn't match")
}
if actual.L3miss != expected.L3miss {
t.Fatalf("Vxlan.L3miss doesn't match")
t.Fatal("Vxlan.L3miss doesn't match")
}
if expected.NoAge {
if !actual.NoAge {
t.Fatalf("Vxlan.NoAge doesn't match")
t.Fatal("Vxlan.NoAge doesn't match")
}
} else if expected.Age > 0 && actual.Age != expected.Age {
t.Fatalf("Vxlan.Age doesn't match")
t.Fatal("Vxlan.Age doesn't match")
}
if expected.Limit > 0 && actual.Limit != expected.Limit {
t.Fatalf("Vxlan.Limit doesn't match")
t.Fatal("Vxlan.Limit doesn't match")
}
if expected.Port > 0 && actual.Port != expected.Port {
t.Fatalf("Vxlan.Port doesn't match")
t.Fatal("Vxlan.Port doesn't match")
}
if expected.PortLow > 0 || expected.PortHigh > 0 {
if actual.PortLow != expected.PortLow {
t.Fatalf("Vxlan.PortLow doesn't match")
t.Fatal("Vxlan.PortLow doesn't match")
}
if actual.PortHigh != expected.PortHigh {
t.Fatalf("Vxlan.PortHigh doesn't match")
t.Fatal("Vxlan.PortHigh doesn't match")
}
}
}
@@ -189,7 +209,10 @@ func TestLinkAddDelMacvlan(t *testing.T) {
t.Fatal(err)
}
testLinkAddDel(t, &Macvlan{LinkAttrs{Name: "bar", ParentIndex: parent.Attrs().Index}})
testLinkAddDel(t, &Macvlan{
LinkAttrs: LinkAttrs{Name: "bar", ParentIndex: parent.Attrs().Index},
Mode: MACVLAN_MODE_PRIVATE,
})
if err := LinkDel(parent); err != nil {
t.Fatal(err)
@@ -378,6 +401,63 @@ func TestLinkAddDelVxlan(t *testing.T) {
}
}
func TestLinkAddDelIPVlanL2(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
ipv := IPVlan{
LinkAttrs: LinkAttrs{
Name: "bar",
ParentIndex: parent.Index,
},
Mode: IPVLAN_MODE_L2,
}
testLinkAddDel(t, &ipv)
}
func TestLinkAddDelIPVlanL3(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
parent := &Dummy{LinkAttrs{Name: "foo"}}
if err := LinkAdd(parent); err != nil {
t.Fatal(err)
}
ipv := IPVlan{
LinkAttrs: LinkAttrs{
Name: "bar",
ParentIndex: parent.Index,
},
Mode: IPVLAN_MODE_L3,
}
testLinkAddDel(t, &ipv)
}
func TestLinkAddDelIPVlanNoParent(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
ipv := IPVlan{
LinkAttrs: LinkAttrs{
Name: "bar",
},
Mode: IPVLAN_MODE_L3,
}
err := LinkAdd(&ipv)
if err == nil {
t.Fatal("Add should fail if ipvlan creating without ParentIndex")
}
if err.Error() != "Can't create ipvlan link without ParentIndex" {
t.Fatalf("Error should be about missing ParentIndex, got %q", err)
}
}
func TestLinkByIndex(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
+10 -10
View File
@@ -9,16 +9,16 @@ import (
)
const (
NDA_UNSPEC = iota
NDA_DST = iota
NDA_LLADDR = iota
NDA_CACHEINFO = iota
NDA_PROBES = iota
NDA_VLAN = iota
NDA_PORT = iota
NDA_VNI = iota
NDA_IFINDEX = iota
NDA_MAX = NDA_IFINDEX
NDA_UNSPEC = iota
NDA_DST
NDA_LLADDR
NDA_CACHEINFO
NDA_PROBES
NDA_VLAN
NDA_PORT
NDA_VNI
NDA_IFINDEX
NDA_MAX = NDA_IFINDEX
)
// Neighbor Cache Entry States.
+11 -12
View File
@@ -72,8 +72,6 @@ func TestNeighAddDel(t *testing.T) {
}
}
return
// Delete the arpTable
for _, entry := range arpTable {
err := NeighDel(&Neigh{
@@ -87,17 +85,18 @@ func TestNeighAddDel(t *testing.T) {
}
}
// Dump and see that none of deleted entries are there
dump, err = NeighList(dummy.Index, 0)
if err != nil {
t.Errorf("Failed to NeighList: %v", err)
}
// TODO: seems not working because of cache
//// Dump and see that none of deleted entries are there
//dump, err = NeighList(dummy.Index, 0)
//if err != nil {
//t.Errorf("Failed to NeighList: %v", err)
//}
for _, entry := range arpTable {
if dumpContains(dump, entry) {
t.Errorf("Dump contains: %v", entry)
}
}
//for _, entry := range arpTable {
//if dumpContains(dump, entry) {
//t.Errorf("Dump contains: %v", entry)
//}
//}
if err := LinkDel(&dummy); err != nil {
t.Fatal(err)
+2 -2
View File
@@ -30,10 +30,10 @@ func ParseIPNet(s string) (*net.IPNet, error) {
if err != nil {
return nil, err
}
return &net.IPNet{ip, ipNet.Mask}, nil
return &net.IPNet{IP: ip, Mask: ipNet.Mask}, nil
}
// NewIPNet generates an IPNet from an ip address using a netmask of 32.
func NewIPNet(ip net.IP) *net.IPNet {
return &net.IPNet{ip, net.CIDRMask(32, 32)}
return &net.IPNet{IP: ip, Mask: net.CIDRMask(32, 32)}
}
+2 -1
View File
@@ -1,11 +1,12 @@
package netlink
import (
"github.com/vishvananda/netns"
"log"
"os"
"runtime"
"testing"
"github.com/vishvananda/netns"
)
type tearDownNetlinkTest func()
@@ -42,6 +42,30 @@ func LinkDel(link *Link) error {
return ErrNotImplemented
}
func SetHairpin(link Link, mode bool) error {
return ErrNotImplemented
}
func SetGuard(link Link, mode bool) error {
return ErrNotImplemented
}
func SetFastLeave(link Link, mode bool) error {
return ErrNotImplemented
}
func SetLearning(link Link, mode bool) error {
return ErrNotImplemented
}
func SetRootBlock(link Link, mode bool) error {
return ErrNotImplemented
}
func SetFlood(link Link, mode bool) error {
return ErrNotImplemented
}
func LinkList() ([]Link, error) {
return nil, ErrNotImplemented
}
+72 -32
View File
@@ -6,51 +6,91 @@ const (
const (
IFLA_INFO_UNSPEC = iota
IFLA_INFO_KIND = iota
IFLA_INFO_DATA = iota
IFLA_INFO_XSTATS = iota
IFLA_INFO_MAX = IFLA_INFO_XSTATS
IFLA_INFO_KIND
IFLA_INFO_DATA
IFLA_INFO_XSTATS
IFLA_INFO_MAX = IFLA_INFO_XSTATS
)
const (
IFLA_VLAN_UNSPEC = iota
IFLA_VLAN_ID = iota
IFLA_VLAN_FLAGS = iota
IFLA_VLAN_EGRESS_QOS = iota
IFLA_VLAN_INGRESS_QOS = iota
IFLA_VLAN_PROTOCOL = iota
IFLA_VLAN_MAX = IFLA_VLAN_PROTOCOL
IFLA_VLAN_UNSPEC = iota
IFLA_VLAN_ID
IFLA_VLAN_FLAGS
IFLA_VLAN_EGRESS_QOS
IFLA_VLAN_INGRESS_QOS
IFLA_VLAN_PROTOCOL
IFLA_VLAN_MAX = IFLA_VLAN_PROTOCOL
)
const (
VETH_INFO_UNSPEC = iota
VETH_INFO_PEER = iota
VETH_INFO_MAX = VETH_INFO_PEER
VETH_INFO_PEER
VETH_INFO_MAX = VETH_INFO_PEER
)
const (
IFLA_VXLAN_UNSPEC = iota
IFLA_VXLAN_ID = iota
IFLA_VXLAN_GROUP = iota
IFLA_VXLAN_LINK = iota
IFLA_VXLAN_LOCAL = iota
IFLA_VXLAN_TTL = iota
IFLA_VXLAN_TOS = iota
IFLA_VXLAN_LEARNING = iota
IFLA_VXLAN_AGEING = iota
IFLA_VXLAN_LIMIT = iota
IFLA_VXLAN_PORT_RANGE = iota
IFLA_VXLAN_PROXY = iota
IFLA_VXLAN_RSC = iota
IFLA_VXLAN_L2MISS = iota
IFLA_VXLAN_L3MISS = iota
IFLA_VXLAN_PORT = iota
IFLA_VXLAN_GROUP6 = iota
IFLA_VXLAN_LOCAL6 = iota
IFLA_VXLAN_MAX = IFLA_VXLAN_LOCAL6
IFLA_VXLAN_UNSPEC = iota
IFLA_VXLAN_ID
IFLA_VXLAN_GROUP
IFLA_VXLAN_LINK
IFLA_VXLAN_LOCAL
IFLA_VXLAN_TTL
IFLA_VXLAN_TOS
IFLA_VXLAN_LEARNING
IFLA_VXLAN_AGEING
IFLA_VXLAN_LIMIT
IFLA_VXLAN_PORT_RANGE
IFLA_VXLAN_PROXY
IFLA_VXLAN_RSC
IFLA_VXLAN_L2MISS
IFLA_VXLAN_L3MISS
IFLA_VXLAN_PORT
IFLA_VXLAN_GROUP6
IFLA_VXLAN_LOCAL6
IFLA_VXLAN_MAX = IFLA_VXLAN_LOCAL6
)
const (
BRIDGE_MODE_UNSPEC = iota
BRIDGE_MODE_HAIRPIN
)
const (
IFLA_BRPORT_UNSPEC = iota
IFLA_BRPORT_STATE
IFLA_BRPORT_PRIORITY
IFLA_BRPORT_COST
IFLA_BRPORT_MODE
IFLA_BRPORT_GUARD
IFLA_BRPORT_PROTECT
IFLA_BRPORT_FAST_LEAVE
IFLA_BRPORT_LEARNING
IFLA_BRPORT_UNICAST_FLOOD
IFLA_BRPORT_MAX = IFLA_BRPORT_UNICAST_FLOOD
)
const (
IFLA_IPVLAN_UNSPEC = iota
IFLA_IPVLAN_MODE
IFLA_IPVLAN_MAX = IFLA_IPVLAN_MODE
)
const (
// not defined in syscall
IFLA_NET_NS_FD = 28
)
const (
IFLA_MACVLAN_UNSPEC = iota
IFLA_MACVLAN_MODE
IFLA_MACVLAN_FLAGS
IFLA_MACVLAN_MAX = IFLA_MACVLAN_FLAGS
)
const (
MACVLAN_MODE_PRIVATE = 1
MACVLAN_MODE_VEPA = 2
MACVLAN_MODE_BRIDGE = 4
MACVLAN_MODE_PASSTHRU = 8
MACVLAN_MODE_SOURCE = 16
)
+2 -2
View File
@@ -103,9 +103,9 @@ func (x *XfrmAddress) ToIP() net.IP {
func (x *XfrmAddress) ToIPNet(prefixlen uint8) *net.IPNet {
ip := x.ToIP()
if GetIPFamily(ip) == FAMILY_V4 {
return &net.IPNet{ip, net.CIDRMask(int(prefixlen), 32)}
return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 32)}
} else {
return &net.IPNet{ip, net.CIDRMask(int(prefixlen), 128)}
return &net.IPNet{IP: ip, Mask: net.CIDRMask(int(prefixlen), 128)}
}
}
+53
View File
@@ -0,0 +1,53 @@
package netlink
import (
"strings"
)
// Protinfo represents bridge flags from netlink.
type Protinfo struct {
Hairpin bool
Guard bool
FastLeave bool
RootBlock bool
Learning bool
Flood bool
}
// String returns a list of enabled flags
func (prot *Protinfo) String() string {
boolStrings := make([]string, 0)
if prot.Hairpin {
boolStrings = append(boolStrings, "Hairpin")
}
if prot.Guard {
boolStrings = append(boolStrings, "Guard")
}
if prot.FastLeave {
boolStrings = append(boolStrings, "FastLeave")
}
if prot.RootBlock {
boolStrings = append(boolStrings, "RootBlock")
}
if prot.Learning {
boolStrings = append(boolStrings, "Learning")
}
if prot.Flood {
boolStrings = append(boolStrings, "Flood")
}
return strings.Join(boolStrings, " ")
}
func boolToByte(x bool) []byte {
if x {
return []byte{1}
}
return []byte{0}
}
func byteToBool(x byte) bool {
if uint8(x) != 0 {
return true
}
return false
}
+60
View File
@@ -0,0 +1,60 @@
package netlink
import (
"fmt"
"syscall"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/vishvananda/netlink/nl"
)
func LinkGetProtinfo(link Link) (Protinfo, error) {
base := link.Attrs()
ensureIndex(base)
var pi Protinfo
req := nl.NewNetlinkRequest(syscall.RTM_GETLINK, syscall.NLM_F_DUMP)
msg := nl.NewIfInfomsg(syscall.AF_BRIDGE)
req.AddData(msg)
msgs, err := req.Execute(syscall.NETLINK_ROUTE, 0)
if err != nil {
return pi, err
}
for _, m := range msgs {
ans := nl.DeserializeIfInfomsg(m)
if int(ans.Index) != base.Index {
continue
}
attrs, err := nl.ParseRouteAttr(m[ans.Len():])
if err != nil {
return pi, err
}
for _, attr := range attrs {
if attr.Attr.Type != syscall.IFLA_PROTINFO|syscall.NLA_F_NESTED {
continue
}
infos, err := nl.ParseRouteAttr(attr.Value)
if err != nil {
return pi, err
}
var pi Protinfo
for _, info := range infos {
switch info.Attr.Type {
case nl.IFLA_BRPORT_MODE:
pi.Hairpin = byteToBool(info.Value[0])
case nl.IFLA_BRPORT_GUARD:
pi.Guard = byteToBool(info.Value[0])
case nl.IFLA_BRPORT_FAST_LEAVE:
pi.FastLeave = byteToBool(info.Value[0])
case nl.IFLA_BRPORT_PROTECT:
pi.RootBlock = byteToBool(info.Value[0])
case nl.IFLA_BRPORT_LEARNING:
pi.Learning = byteToBool(info.Value[0])
case nl.IFLA_BRPORT_UNICAST_FLOOD:
pi.Flood = byteToBool(info.Value[0])
}
}
return pi, nil
}
}
return pi, fmt.Errorf("Device with index %d not found", base.Index)
}
+98
View File
@@ -0,0 +1,98 @@
package netlink
import "testing"
func TestProtinfo(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
master := &Bridge{LinkAttrs{Name: "foo"}}
if err := LinkAdd(master); err != nil {
t.Fatal(err)
}
iface1 := &Dummy{LinkAttrs{Name: "bar1", MasterIndex: master.Index}}
iface2 := &Dummy{LinkAttrs{Name: "bar2", MasterIndex: master.Index}}
iface3 := &Dummy{LinkAttrs{Name: "bar3"}}
if err := LinkAdd(iface1); err != nil {
t.Fatal(err)
}
if err := LinkAdd(iface2); err != nil {
t.Fatal(err)
}
if err := LinkAdd(iface3); err != nil {
t.Fatal(err)
}
oldpi1, err := LinkGetProtinfo(iface1)
if err != nil {
t.Fatal(err)
}
oldpi2, err := LinkGetProtinfo(iface2)
if err != nil {
t.Fatal(err)
}
if err := LinkSetHairpin(iface1, true); err != nil {
t.Fatal(err)
}
if err := LinkSetRootBlock(iface1, true); err != nil {
t.Fatal(err)
}
pi1, err := LinkGetProtinfo(iface1)
if err != nil {
t.Fatal(err)
}
if !pi1.Hairpin {
t.Fatalf("Hairpin mode is not enabled for %s, but should", iface1.Name)
}
if !pi1.RootBlock {
t.Fatalf("RootBlock is not enabled for %s, but should", iface1.Name)
}
if pi1.Guard != oldpi1.Guard {
t.Fatalf("Guard field was changed for %s but shouldn't", iface1.Name)
}
if pi1.FastLeave != oldpi1.FastLeave {
t.Fatalf("FastLeave field was changed for %s but shouldn't", iface1.Name)
}
if pi1.Learning != oldpi1.Learning {
t.Fatalf("Learning field was changed for %s but shouldn't", iface1.Name)
}
if pi1.Flood != oldpi1.Flood {
t.Fatalf("Flood field was changed for %s but shouldn't", iface1.Name)
}
if err := LinkSetGuard(iface2, true); err != nil {
t.Fatal(err)
}
if err := LinkSetLearning(iface2, false); err != nil {
t.Fatal(err)
}
pi2, err := LinkGetProtinfo(iface2)
if err != nil {
t.Fatal(err)
}
if pi2.Hairpin {
t.Fatalf("Hairpin mode is enabled for %s, but shouldn't", iface2.Name)
}
if !pi2.Guard {
t.Fatalf("Guard is not enabled for %s, but should", iface2.Name)
}
if pi2.Learning {
t.Fatalf("Learning is enabled for %s, but shouldn't", iface2.Name)
}
if pi2.RootBlock != oldpi2.RootBlock {
t.Fatalf("RootBlock field was changed for %s but shouldn't", iface2.Name)
}
if pi2.FastLeave != oldpi2.FastLeave {
t.Fatalf("FastLeave field was changed for %s but shouldn't", iface2.Name)
}
if pi2.Flood != oldpi2.Flood {
t.Fatalf("Flood field was changed for %s but shouldn't", iface2.Name)
}
if err := LinkSetHairpin(iface3, true); err == nil || err.Error() != "operation not supported" {
t.Fatalf("Set protinfo attrs for link without master is not supported, but err: %s", err)
}
}
+2 -2
View File
@@ -25,7 +25,7 @@ func RouteDel(route *Route) error {
}
func routeHandle(route *Route, req *nl.NetlinkRequest) error {
if route.Dst.IP == nil && route.Src == nil && route.Gw == nil {
if (route.Dst == nil || route.Dst.IP == nil) && route.Src == nil && route.Gw == nil {
return fmt.Errorf("one of Dst.IP, Src, or Gw must not be nil")
}
@@ -34,7 +34,7 @@ func routeHandle(route *Route, req *nl.NetlinkRequest) error {
family := -1
var rtAttrs []*nl.RtAttr
if route.Dst.IP != nil {
if route.Dst != nil && route.Dst.IP != nil {
dstLen, _ := route.Dst.Mask.Size()
msg.Dst_len = uint8(dstLen)
dstFamily := nl.GetIPFamily(route.Dst.IP)
+21
View File
@@ -61,3 +61,24 @@ func TestRouteAddDel(t *testing.T) {
}
}
func TestRouteAddIncomplete(t *testing.T) {
tearDown := setUpNetlinkTest(t)
defer tearDown()
// get loopback interface
link, err := LinkByName("lo")
if err != nil {
t.Fatal(err)
}
// bring the interface up
if err = LinkSetUp(link); err != nil {
t.Fatal(err)
}
route := Route{LinkIndex: link.Attrs().Index}
if err := RouteAdd(&route); err == nil {
t.Fatal("Adding incomplete route should fail")
}
}
+6 -6
View File
@@ -39,12 +39,12 @@ func (p Proto) String() string {
type Mode uint8
const (
XFRM_MODE_TRANSPORT Mode = iota
XFRM_MODE_TUNNEL Mode = iota
XFRM_MODE_ROUTEOPTIMIZATION Mode = iota
XFRM_MODE_IN_TRIGGER Mode = iota
XFRM_MODE_BEET Mode = iota
XFRM_MODE_MAX Mode = iota
XFRM_MODE_TRANSPORT Mode = iota
XFRM_MODE_TUNNEL
XFRM_MODE_ROUTEOPTIMIZATION
XFRM_MODE_IN_TRIGGER
XFRM_MODE_BEET
XFRM_MODE_MAX
)
func (m Mode) String() string {
+6 -6
View File
@@ -9,12 +9,12 @@ import (
type Dir uint8
const (
XFRM_DIR_IN Dir = iota
XFRM_DIR_OUT Dir = iota
XFRM_DIR_FWD Dir = iota
XFRM_SOCKET_IN Dir = iota
XFRM_SOCKET_OUT Dir = iota
XFRM_SOCKET_FWD Dir = iota
XFRM_DIR_IN Dir = iota
XFRM_DIR_OUT
XFRM_DIR_FWD
XFRM_SOCKET_IN
XFRM_SOCKET_OUT
XFRM_SOCKET_FWD
)
func (d Dir) String() string {
+2 -3
View File
@@ -15,9 +15,8 @@ type XfrmStateAlgo struct {
type EncapType uint8
const (
_ = iota
XFRM_ENCAP_ESPINUDP_NONIKE EncapType = iota
XFRM_ENCAP_ESPINUDP EncapType = iota
XFRM_ENCAP_ESPINUDP_NONIKE EncapType = iota + 1
XFRM_ENCAP_ESPINUDP
)
func (e EncapType) String() string {
+5 -1
View File
@@ -145,7 +145,11 @@ func ExecPluginDel(plugin string) error {
func ApplyIPConfig(ifName string, ipConf *IPConfig) error {
link, err := netlink.LinkByName(ifName)
if err != nil {
return err
return fmt.Errorf("failed to lookup %q: %v", ifName, err)
}
if err := netlink.LinkSetUp(link); err != nil {
return fmt.Errorf("failed too set %q UP: %v", ifName, err)
}
addr := &netlink.Addr{IPNet: ipConf.IP, Label: ""}
+1 -8
View File
@@ -209,7 +209,7 @@ func cmdAdd(args *util.CmdArgs) error {
if n.IPMasq {
chain := "RKT-" + n.Name
if err = util.SetupIPMasq(network(ipConf.IP), chain); err != nil {
if err = util.SetupIPMasq(util.Network(ipConf.IP), chain); err != nil {
return err
}
}
@@ -219,13 +219,6 @@ func cmdAdd(args *util.CmdArgs) error {
})
}
func network(ipn *net.IPNet) *net.IPNet {
return &net.IPNet{
IP: ipn.IP.Mask(ipn.Mask),
Mask: ipn.Mask,
}
}
func cmdDel(args *util.CmdArgs) error {
n, err := loadConf(args.NetConf)
if err != nil {
+174
View File
@@ -0,0 +1,174 @@
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"os"
"runtime"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/vishvananda/netlink"
"github.com/coreos/rocket/networking/ipam"
rktnet "github.com/coreos/rocket/networking/net"
"github.com/coreos/rocket/networking/util"
)
type Net struct {
rktnet.Net
Master string `json:"master"`
Mode string `json:"mode"`
IPMasq bool `json:"ipMasq"`
MTU int `json:"mtu"`
}
func init() {
// this ensures that main runs only on main thread (thread group leader).
// since namespace ops (unshare, setns) are done for a single thread, we
// must ensure that the goroutine does not jump from OS thread to thread
runtime.LockOSThread()
}
func loadConf(path string) (*Net, error) {
n := &Net{}
if err := rktnet.LoadNet(path, n); err != nil {
return nil, fmt.Errorf("failed to load %q: %v", path, err)
}
if n.Master == "" {
return nil, fmt.Errorf(`"master" field is required. It specifies the host interface name to virtualize`)
}
return n, nil
}
func modeFromString(s string) (netlink.MacvlanMode, error) {
switch s {
case "":
return netlink.MACVLAN_MODE_BRIDGE, nil
case "private":
return netlink.MACVLAN_MODE_PRIVATE, nil
case "vepa":
return netlink.MACVLAN_MODE_VEPA, nil
case "bridge":
return netlink.MACVLAN_MODE_BRIDGE, nil
case "passthru":
return netlink.MACVLAN_MODE_PASSTHRU, nil
default:
return 0, fmt.Errorf("unknown macvlan mode: %q", s)
}
}
func createMacvlan(conf *Net, ifName string, netns *os.File) error {
mode, err := modeFromString(conf.Mode)
if err != nil {
return err
}
m, err := netlink.LinkByName(conf.Master)
if err != nil {
return fmt.Errorf("failed to lookup master %q: %v", conf.Master, err)
}
mv := &netlink.Macvlan{
LinkAttrs: netlink.LinkAttrs{
MTU: conf.MTU,
Name: ifName,
ParentIndex: m.Attrs().Index,
Namespace: netlink.NsFd(int(netns.Fd())),
},
Mode: mode,
}
if err := netlink.LinkAdd(mv); err != nil {
return fmt.Errorf("failed to create macvlan: %v", err)
}
return err
}
func cmdAdd(args *util.CmdArgs) error {
n, err := loadConf(args.NetConf)
if err != nil {
return err
}
netns, err := os.Open(args.Netns)
if err != nil {
return fmt.Errorf("failed to open netns %q: %v", netns, err)
}
defer netns.Close()
tmpName := "veth" + args.ContID.String()[:4]
if err = createMacvlan(n, tmpName, netns); err != nil {
return err
}
// run the IPAM plugin and get back the config to apply
ipConf, err := ipam.ExecPluginAdd(n.Net.IPAM.Type)
if err != nil {
return err
}
err = util.WithNetNS(netns, func(_ *os.File) error {
err := renameLink(tmpName, args.IfName)
if err != nil {
return fmt.Errorf("failed to rename macvlan to %q: %v", args.IfName, err)
}
return ipam.ApplyIPConfig(args.IfName, ipConf)
})
if err != nil {
return err
}
if n.IPMasq {
chain := "RKT-" + n.Name
if err = util.SetupIPMasq(util.Network(ipConf.IP), chain); err != nil {
return err
}
}
return rktnet.PrintIfConfig(&rktnet.IfConfig{
IP: ipConf.IP.IP,
})
}
func cmdDel(args *util.CmdArgs) error {
n, err := loadConf(args.NetConf)
if err != nil {
return err
}
err = ipam.ExecPluginDel(n.Net.IPAM.Type)
if err != nil {
return err
}
return util.WithNetNSPath(args.Netns, func(hostNS *os.File) error {
return util.DelLinkByName(args.IfName)
})
}
func renameLink(curName, newName string) error {
link, err := netlink.LinkByName(curName)
if err != nil {
return err
}
return netlink.LinkSetName(link, newName)
}
func main() {
util.PluginMain(cmdAdd, cmdDel)
}
+7
View File
@@ -50,3 +50,10 @@ func ipToInt(ip net.IP) *big.Int {
func intToIP(i *big.Int) net.IP {
return net.IP(i.Bytes())
}
func Network(ipn *net.IPNet) *net.IPNet {
return &net.IPNet{
IP: ipn.IP.Mask(ipn.Mask),
Mask: ipn.Mask,
}
}
+14 -8
View File
@@ -49,13 +49,6 @@ func SetNS(f *os.File, flags uintptr) error {
// WithNetNSPath executes the passed closure under the given network
// namespace, restoring the original namespace afterwards.
func WithNetNSPath(nspath string, f func(*os.File) error) error {
// save a handle to current (host) network namespace
thisNS, err := os.Open("/proc/self/ns/net")
if err != nil {
return fmt.Errorf("Failed to open /proc/self/ns/net: %v", err)
}
defer thisNS.Close()
// switch to the container namespace
ns, err := os.Open(nspath)
if err != nil {
@@ -63,8 +56,21 @@ func WithNetNSPath(nspath string, f func(*os.File) error) error {
}
defer ns.Close()
return WithNetNS(ns, f)
}
// WithNetNS executes the passed closure under the given network
// namespace, restoring the original namespace afterwards.
func WithNetNS(ns *os.File, f func(*os.File) error) error {
// save a handle to current (host) network namespace
thisNS, err := os.Open("/proc/self/ns/net")
if err != nil {
return fmt.Errorf("Failed to open /proc/self/ns/net: %v", err)
}
defer thisNS.Close()
if err = SetNS(ns, syscall.CLONE_NEWNET); err != nil {
return fmt.Errorf("Error switching to ns %v: %v", nspath, err)
return fmt.Errorf("Error switching to ns %v: %v", ns.Name(), err)
}
if err = f(thisNS); err != nil {
+1 -1
View File
@@ -1,4 +1,4 @@
PLUGINS=bin/veth bin/bridge bin/static
PLUGINS=bin/veth bin/bridge bin/macvlan bin/static
../aggregate/install.d/30net-plugins: Makefile install $(PLUGINS)
@cp install ../aggregate/install.d/30net-plugins