diff --git a/examples/virt4.yaml b/examples/virt4.yaml new file mode 100644 index 00000000..efa5fb03 --- /dev/null +++ b/examples/virt4.yaml @@ -0,0 +1,15 @@ +--- +graph: mygraph +resources: + virt: + - name: mgmt4 + uri: 'qemu:///session' + boot: + - hd + disk: + - type: qcow2 + source: "~/.local/share/libvirt/images/fedora-23-scratch.qcow2" + state: running + transient: false +edges: [] +comment: "qemu-img create -b fedora-23.qcow2 -f qcow2 fedora-23-scratch.qcow2" diff --git a/resources/virt.go b/resources/virt.go index 50a89926..64784126 100644 --- a/resources/virt.go +++ b/resources/virt.go @@ -23,6 +23,9 @@ import ( "log" "math/rand" "net/url" + "os/user" + "path" + "strings" "time" "github.com/purpleidea/mgmt/event" @@ -622,20 +625,22 @@ type filesystemDevice struct { } func (d *diskDevice) GetXML(idx int) string { + source, _ := expandHome(d.Source) // TODO: should we handle errors? var b string b += "" b += fmt.Sprintf("", d.Type) - b += fmt.Sprintf("", d.Source) + b += fmt.Sprintf("", source) b += fmt.Sprintf("", (string)(idx+97)) // TODO: 26, 27... should be 'aa', 'ab'... b += "" return b } func (d *cdRomDevice) GetXML(idx int) string { + source, _ := expandHome(d.Source) // TODO: should we handle errors? var b string b += "" b += fmt.Sprintf("", d.Type) - b += fmt.Sprintf("", d.Source) + b += fmt.Sprintf("", source) b += fmt.Sprintf("", (string)(idx+97)) // TODO: 26, 27... should be 'aa', 'ab'... b += "" b += "" @@ -655,13 +660,14 @@ func (d *networkDevice) GetXML(idx int) string { } func (d *filesystemDevice) GetXML(idx int) string { + source, _ := expandHome(d.Source) // TODO: should we handle errors? var b string b += "", d.Source) + b += fmt.Sprintf("", source) b += fmt.Sprintf("", d.Target) if d.ReadOnly { b += "" @@ -785,3 +791,16 @@ func randMAC() string { fmt.Sprintf(":%x", rand.Intn(255)) + fmt.Sprintf(":%x", rand.Intn(255)) } + +// expandHome does a simple expansion of the tilde into your $HOME value. +func expandHome(p string) (string, error) { + // TODO: this doesn't match strings of the form: ~james/... + if !strings.HasPrefix(p, "~/") { + return p, nil + } + usr, err := user.Current() + if err != nil { + return p, fmt.Errorf("can't expand ~ into home directory") + } + return path.Join(usr.HomeDir, p[len("~/"):]), nil +}