Files
Reims-Go/internal/qmp/client.go
T

120 lines
3.3 KiB
Go

package qmp
import (
"bufio"
"context"
"encoding/json"
"fmt"
"net"
"time"
)
// Conn is a request/response QMP session. QEMU's QMP chardev serves one
// client at a time, so callers keep a Conn only as long as one job takes.
type Conn struct {
nc net.Conn
scanner *bufio.Scanner
}
// Dial connects to a QMP server ("unix" or "tcp") and negotiates capabilities.
func Dial(ctx context.Context, network, addr string) (*Conn, error) {
d := net.Dialer{Timeout: 3 * time.Second}
nc, err := d.DialContext(ctx, network, addr)
if err != nil {
return nil, fmt.Errorf("connect QMP %s: %w", addr, err)
}
c := &Conn{nc: nc, scanner: bufio.NewScanner(nc)}
c.scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
stopCancel := context.AfterFunc(ctx, func() { _ = nc.Close() })
defer stopCancel()
_ = nc.SetDeadline(time.Now().Add(5 * time.Second))
if !c.scanner.Scan() { // greeting
nc.Close()
if err := c.scanner.Err(); err != nil {
return nil, fmt.Errorf("QMP greeting: %w", err)
}
return nil, fmt.Errorf("QMP greeting: connection closed")
}
if err := c.Execute("qmp_capabilities", nil); err != nil {
nc.Close()
return nil, err
}
if err := ctx.Err(); err != nil {
nc.Close()
return nil, err
}
return c, nil
}
func (c *Conn) Close() error { return c.nc.Close() }
type qmpReply struct {
Return json.RawMessage `json:"return"`
Error *commandError `json:"error"`
Event string `json:"event"`
}
type commandError struct {
Class string `json:"class"`
Desc string `json:"desc"`
}
func (e *commandError) Error() string { return e.Class + ": " + e.Desc }
// Query runs one command with the default 5-second timeout and waits for its
// JSON return value, skipping async events.
func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
return c.QueryWithTimeout(command, args, 5*time.Second)
}
// QueryWithTimeout runs one command and waits up to timeout for its JSON return
// value, skipping async events.
func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) (json.RawMessage, error) {
req := map[string]any{"execute": command}
if args != nil {
req["arguments"] = args
}
b, err := json.Marshal(req)
if err != nil {
return nil, err
}
if timeout <= 0 {
timeout = 5 * time.Second
}
_ = c.nc.SetDeadline(time.Now().Add(timeout))
if _, err := c.nc.Write(append(b, '\n')); err != nil {
return nil, fmt.Errorf("QMP %s: %w", command, err)
}
for c.scanner.Scan() {
var r qmpReply
if err := json.Unmarshal(c.scanner.Bytes(), &r); err != nil || r.Event != "" {
continue
}
if r.Error != nil {
return nil, fmt.Errorf("QMP %s: %w", command, r.Error)
}
if r.Return != nil {
return append(json.RawMessage(nil), r.Return...), nil
}
}
if err := c.scanner.Err(); err != nil {
return nil, fmt.Errorf("QMP %s: %w", command, err)
}
return nil, fmt.Errorf("QMP %s: connection closed", command)
}
// Execute runs one command with the default timeout and waits for its reply,
// skipping async events.
func (c *Conn) Execute(command string, args any) error {
_, err := c.Query(command, args)
return err
}
// ExecuteWithTimeout runs one command and waits up to timeout for its reply,
// skipping async events.
func (c *Conn) ExecuteWithTimeout(command string, args any, timeout time.Duration) error {
_, err := c.QueryWithTimeout(command, args, timeout)
return err
}