libguestd/cmd/guestrun/guestrun.go

78 lines
1.9 KiB
Go
Raw Normal View History

2024-07-07 18:51:49 +02:00
package main
import (
"encoding/base64"
"flag"
"fmt"
"git.mlody.eu/lmoskala/libguestd/pkg/libguestd"
"github.com/digitalocean/go-libvirt"
"log"
"net/url"
)
func main() {
libvirtUri := flag.String("libvirt", "qemu:///system", "libvirt connection URI")
domainName := flag.String("domain", "", "domain (instance) name")
Cmd := flag.String("cmd", "", "Command (will be run as /bin/sh -c ...)")
flag.Parse()
if *domainName == "" {
log.Fatalf("Domain name must be specified")
}
uri, _ := url.Parse(*libvirtUri)
l, err := libvirt.ConnectToURI(uri)
if err != nil {
log.Fatalf("failed to connect: %v", err)
}
domains, _, err := l.ConnectListAllDomains(1, libvirt.ConnectListDomainsActive)
if err != nil {
log.Fatalf("failed to list all domains: %v", err)
}
for _, domain := range domains {
if domain.Name != *domainName {
continue
}
err = libguestd.GuestPing(l, domain)
if err != nil {
log.Printf("Error(GuestPing): %s", err)
continue
}
agentInfo, err := libguestd.GuestInfo(l, domain)
if err != nil {
log.Printf("Error(GuestInfo): %s", err)
continue
}
pid, err := libguestd.GuestExecStart(l, domain, agentInfo, "/bin/sh", []string{"-c", *Cmd}, []string{}, []byte{})
if err != nil {
log.Printf("Error(GuestExecStart): %s", err)
continue
}
log.Printf("PID: %d", pid)
res, err := libguestd.GuestWaitForCommand(l, domain, agentInfo, pid)
if err != nil {
log.Printf("Error(GuestWaitForCommand): %s", err)
}
log.Printf("Exit status: %d", res.ExitCode)
log.Printf("Stdout follows:")
dec, _ := base64.StdEncoding.DecodeString(res.OutDataB64)
fmt.Println(string(dec))
if res.OutTruncated {
log.Printf("[Output was truncated]")
}
log.Printf("Stderr follows:")
dec, _ = base64.StdEncoding.DecodeString(res.ErrDataB64)
fmt.Println(string(dec))
if res.ErrTruncated {
log.Printf("[Output was truncated]")
}
}
if err = l.Disconnect(); err != nil {
log.Fatalf("failed to disconnect: %v", err)
}
}