Skip to content

Commit

Permalink
Merge pull request #117 from cybozu-go/randomize-mac
Browse files Browse the repository at this point in the history
Randomize MAC address for KVM
  • Loading branch information
ysksuzuki authored Sep 29, 2020
2 parents d480d2a + e19fee2 commit 6e71741
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 6 deletions.
13 changes: 9 additions & 4 deletions node.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package placemat

import (
"context"
"crypto/rand"
"crypto/sha1"
"errors"
"fmt"
Expand Down Expand Up @@ -267,7 +268,7 @@ func (n *Node) Start(ctx context.Context, r *Runtime, nodeCh chan<- bmcInfo) (*N
devParams := []string{
"virtio-net-pci",
fmt.Sprintf("netdev=%s", br.Name),
fmt.Sprintf("mac=%s", generateMACForKVM(n.Name)),
fmt.Sprintf("mac=%s", generateMACForKVM()),
}
if n.UEFI {
// disable iPXE boot
Expand Down Expand Up @@ -380,10 +381,14 @@ func (n *Node) Start(ctx context.Context, r *Runtime, nodeCh chan<- bmcInfo) (*N
return vm, err
}

func generateMACForKVM(name string) string {
func generateMACForKVM() string {
vendorPrefix := "52:54:00" // QEMU's vendor prefix
bytes := sha1.Sum([]byte(name))
return fmt.Sprintf("%s:%02x:%02x:%02x", vendorPrefix, bytes[0], bytes[1], bytes[2])
buf := make([]byte, 3)
_, err := rand.Read(buf)
if err != nil {
panic(err)
}
return fmt.Sprintf("%s:%02x:%02x:%02x", vendorPrefix, buf[0], buf[1], buf[2])
}

func createNVRAM(ctx context.Context, p string) error {
Expand Down
4 changes: 2 additions & 2 deletions node_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import (
)

func TestGenerateRandomMacForKVM(t *testing.T) {
sut := generateMACForKVM("test")
sut := generateMACForKVM()
if len(sut) != 17 {
t.Fatal("length of MAC address string is not 17")
}
if sut == generateMACForKVM("hoge") {
if sut == generateMACForKVM() {
t.Fatal("it should generate unique address")
}
_, err := net.ParseMAC(sut)
Expand Down

0 comments on commit 6e71741

Please sign in to comment.