0

I'm using following code segment to get the XML definition of a virtual machine running on XEN Hypervisor. The code is trying to execute the command virsh dumpxml Ubutnu14 which will give the XML of the VM named Ubuntu14

virshCmd := exec.Command("virsh", "dumpxml", "Ubuntu14")

var virshCmdOutput bytes.Buffer
var stderr bytes.Buffer
virshCmd.Stdout = &virshCmdOutput
virshCmd.Stderr = &stderr
err := virshCmd.Run()
if err != nil {
    fmt.Println(err)
    fmt.Println(stderr.String())
}

fmt.Println(virshCmdOutput.String())

This code always goes into the error condition for the given domain name and I get the following output.

exit status 1
error: failed to get domain 'Ubuntu14'
error: Domain not found: no domain with matching name 'Ubuntu14'

But if I run the standalone command virsh dumpxml Ubuntu14, I get the correct XML definition.

I would appreciate if someone could give me some hints on what I'm doing wrong. My host machine is Ubuntu-16.04 and golang version is go1.6.2 linux/amd64

azizulhakim
  • 658
  • 7
  • 24
  • Does the virsh command rely on any kind of environment variables? When you run a command like that it's not ran in your shell environment – jcbwlkr Jan 18 '17 at 20:53
  • I don't think that is the reason. Because if I run "virsh dumpxml" command from my code, it runs correctly and says "error: command `dumpxml` requires option". I get same output if I run it from shell environment. – azizulhakim Jan 18 '17 at 21:32
  • It's just a hunch but that still might be the problem depending on how it knows where to look for those domains. Just to try it maybe do `virshCmd := exec.Command("sh", "-c", "virsh dumpxml Ubuntu14")` – jcbwlkr Jan 18 '17 at 21:38
  • Tried it. The result is same. – azizulhakim Jan 18 '17 at 22:12

1 Answers1

0

I expect you are running virsh as a different user in these two scenarios, and since you don't provide any URI, it is connecting to a different libvirtd instance. If you run virsh as non-root, then it'll usually connect to qemu:///session, but if you run virsh as root, then it'll usually connect to qemu:///system. VMs registered against one URI, will not be visible when connecting to the other URI.

BTW, if you're using go, you'd be much better off using the native Go library bindings for libvirt instead of exec'ing virsh. Your "virsh dumpxml" invokation is pretty much equivalent to this:

   import (
      "github.com/libvirt/libvirt-go"
   )

   conn, err := libvirt.NewConnect("qemu:///system")

   dom, err := conn.LookupDomainByName("Ubuntu14")

   xml, err := dom.GetXMLDesc(0)

(obviously do error handling too)

DanielB
  • 2,461
  • 1
  • 10
  • 13