Skip to content

Commit

Permalink
Merge pull request #179 from beringresearch/dhcpd-read
Browse files Browse the repository at this point in the history
Dhcpd read
  • Loading branch information
idroz authored Mar 27, 2024
2 parents 4e0bfbe + 1f711ed commit f861380
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 76 deletions.
1 change: 1 addition & 0 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func importMachine(cmd *cobra.Command, args []string) {

machineConfig.Alias = importName
machineConfig.Location = targetDir
machineConfig.MachineIP = "localhost"

err = qemu.SaveMachineConfig(machineConfig)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ require (
require (
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
golang.org/x/sys v0.3.0 // indirect
golang.org/x/sys v0.4.0 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
filippo.io/age v1.1.1 h1:pIpO7l151hCnQ4BdyBujnGP2YlUo0uj6sAVNHGBvXHg=
filippo.io/age v1.1.1/go.mod h1:l03SrzDUrBkdBx8+IILdnn2KZysqQdbEBUQ4p3sqEQE=
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand All @@ -12,6 +14,8 @@ golang.org/x/crypto v0.4.0 h1:UVQgzMY87xqpKNgb+kDsll2Igd33HszWHFLmpaRMq/8=
golang.org/x/crypto v0.4.0/go.mod h1:3quD/ATkf6oY+rnes5c3ExXTbLc8mueNue5/DoinL80=
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18=
golang.org/x/sys v0.4.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.3.0 h1:qoo4akIqOcDME5bhc/NgxUdovd6BSS2uMsVjB56q1xI=
golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
Expand Down
3 changes: 2 additions & 1 deletion host/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ func Info(vmName string) (string, error) {
return "", err
}

info := fmt.Sprintf("Name: %s\nImage: %s\nArch: %s\nDisk size: %s\nMemory size: %s\nCPUs: %s\nMount: %s\nTags: %s\n",
info := fmt.Sprintf("Name: %s\nIP: %s\nImage: %s\nArch: %s\nDisk size: %s\nMemory size: %s\nCPUs: %s\nMount: %s\nTags: %s\n",
machineConfig.Alias,
machineConfig.MachineIP,
machineConfig.Image,
machineConfig.Arch,
machineConfig.Disk,
Expand Down
131 changes: 57 additions & 74 deletions qemu/ops.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,42 @@ func (c *MachineConfig) Exec(cmd string, root bool) error {
if cmd == "" {
return nil
}
host := c.MachineIP + ":" + c.SSHPort
ip := c.MachineIP

if c.VMNet {
if ip == "localhost" || ip == "" {
log.Println("getting instance IP address from DHCP leases")

for {
ip = c.GetIPAddressByMac()

if ip != "" {
break
}
fmt.Print(".")
time.Sleep(4 * time.Second)
}

c.MachineIP = ip
config, err := yaml.Marshal(&c)

if err != nil {
c.Stop()
c.CleanPIDFile()
return err
}

err = os.WriteFile(filepath.Join(c.Location, "config.yaml"), config, 0644)
if err != nil {
c.Stop()
c.CleanPIDFile()
return err
}
}

}

host := ip + ":" + c.SSHPort
user := c.SSHUser
pwd := c.SSHPassword

Expand Down Expand Up @@ -450,36 +485,6 @@ func (c *MachineConfig) Start() error {
return err
}

// fmt.Println(ip)
// c.MachineIP = ip
// }

if c.VMNet {
log.Println("getting instance IP address from DHCP leases")
time.Sleep(4 * time.Second)
ip, err := c.GetIPAddressByMac()
if err != nil {
return errors.New("unable to obtain machine's IP address: " + err.Error())
}

c.MachineIP = ip
config, err := yaml.Marshal(&c)

if err != nil {
c.Stop()
c.CleanPIDFile()
return err
}

err = os.WriteFile(filepath.Join(c.Location, "config.yaml"), config, 0644)
if err != nil {
c.Stop()
c.CleanPIDFile()
return err
}

}

if c.Mount != "" {
basename := filepath.Base(c.Mount)
mntcmd := make([]string, 3)
Expand All @@ -502,51 +507,24 @@ func (c *MachineConfig) Start() error {
return nil
}

func readDHCPLeases(filename string, output chan<- string) {
for {
// Open the dhcpd_leases file
file, err := os.OpenFile(filename, os.O_RDWR, 0644)
if err != nil {
fmt.Println("error opening file:", err)
return
}
defer file.Close()

// Create a scanner to read the file line by line
scanner := bufio.NewScanner(file)

// Read each line of the file
for scanner.Scan() {
line := scanner.Text()
output <- line
}
// AssignIP obtains machine IP address from bootpd.plist. Only applicale to machines created on
// VMNet
func (c *MachineConfig) GetIPAddressByMac() string {
ip := ""
mac := ""

// Check for any errors during scanning
if err := scanner.Err(); err != nil {
fmt.Println("error scanning file:", err)
return
}
file, err := os.Open("/var/db/dhcpd_leases")

// Sleep for some time before reading the file again
time.Sleep(4 * time.Second)
fmt.Print(".")
if err != nil {
log.Fatalf("Error opening file: %v", err)
}
}

// AssignIP obtains machine IP address from bootpd.plist. Only applicale to machines created on
// VMNet
func (c *MachineConfig) GetIPAddressByMac() (string, error) {
var ip, mac string

tries := 0
filename := "/var/db/dhcpd_leases"
scanner := bufio.NewScanner(file)
for scanner.Scan() {

output := make(chan string)
go readDHCPLeases(filename, output)
// Process each line in the dhcpd_leases file
line := scanner.Text()

for {
tries += 1
line := <-output
// Check if the line contains an IP address
if strings.Contains(line, "ip_address") {
ip = strings.Split(strings.Fields(line)[0], "ip_address=")[1]
Expand All @@ -556,13 +534,18 @@ func (c *MachineConfig) GetIPAddressByMac() (string, error) {
if strings.Contains(line, "hw_address") {
mac = strings.Split(strings.Fields(line)[0], "hw_address=1,")[1]
}
if ip != "" && mac != "" {
if mac == c.MACAddress {
return ip, nil
}

if mac == c.MACAddress {
return ip
}

}

// Check for any errors during scanning
if err := scanner.Err(); err != nil {
fmt.Println("error scanning /var/db/dhcpd_lease:", err)
}
return ""
}

// Launch macpine downloads a fresh image and creates a VM directory
Expand Down

0 comments on commit f861380

Please sign in to comment.