Merge pull request #212 from crosbymichael/veth-naming

Add more entropy to veth pair creation
This commit is contained in:
Victor Marmol 2014-10-02 15:11:47 -07:00
commit b3570267c7
4 changed files with 87 additions and 13 deletions

View File

@ -11,8 +11,9 @@ import (
)
var (
ErrWrongSockType = errors.New("Wrong socket type")
ErrShortResponse = errors.New("Got short response from netlink")
ErrWrongSockType = errors.New("Wrong socket type")
ErrShortResponse = errors.New("Got short response from netlink")
ErrInterfaceExists = errors.New("Network interface already exists")
)
// A Route is a subnet associated with the interface to reach it.

View File

@ -6,6 +6,7 @@ import (
"io"
"math/rand"
"net"
"os"
"sync/atomic"
"syscall"
"unsafe"
@ -708,7 +709,16 @@ func NetworkCreateVethPair(name1, name2 string) error {
if err := s.Send(wb); err != nil {
return err
}
return s.HandleAck(wb.Seq)
if err := s.HandleAck(wb.Seq); err != nil {
if os.IsExist(err) {
return ErrInterfaceExists
}
return err
}
return nil
}
// Add a new VLAN interface with masterDev as its upper device

View File

@ -5,6 +5,7 @@ package network
import (
"fmt"
"github.com/docker/libcontainer/netlink"
"github.com/docker/libcontainer/utils"
)
@ -96,16 +97,25 @@ func (v *Veth) Initialize(config *Network, networkState *NetworkState) error {
// createVethPair will automatically generage two random names for
// the veth pair and ensure that they have been created
func createVethPair(prefix string) (name1 string, name2 string, err error) {
name1, err = utils.GenerateRandomName(prefix, 4)
if err != nil {
return
}
name2, err = utils.GenerateRandomName(prefix, 4)
if err != nil {
return
}
if err = CreateVethPair(name1, name2); err != nil {
return
for i := 0; i < 10; i++ {
if name1, err = utils.GenerateRandomName(prefix, 7); err != nil {
return
}
if name2, err = utils.GenerateRandomName(prefix, 7); err != nil {
return
}
if err = CreateVethPair(name1, name2); err != nil {
if err == netlink.ErrInterfaceExists {
continue
}
return
}
break
}
return
}

53
network/veth_test.go Normal file
View File

@ -0,0 +1,53 @@
// +build linux
package network
import (
"testing"
"github.com/docker/libcontainer/netlink"
)
func TestGenerateVethNames(t *testing.T) {
if testing.Short() {
return
}
prefix := "veth"
name1, name2, err := createVethPair(prefix)
if err != nil {
t.Fatal(err)
}
if name1 == "" {
t.Fatal("name1 should not be empty")
}
if name2 == "" {
t.Fatal("name2 should not be empty")
}
}
func TestCreateDuplicateVethPair(t *testing.T) {
if testing.Short() {
return
}
prefix := "veth"
name1, name2, err := createVethPair(prefix)
if err != nil {
t.Fatal(err)
}
// retry to create the name interfaces and make sure that we get the correct error
err = CreateVethPair(name1, name2)
if err == nil {
t.Fatal("expected error to not be nil with duplicate interface")
}
if err != netlink.ErrInterfaceExists {
t.Fatalf("expected error to be ErrInterfaceExists but received %q", err)
}
}