forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
109 lines (89 loc) · 2.24 KB
/
query.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"fmt"
"github.com/lxc/lxd/lxc/config"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/gnuflag"
"github.com/lxc/lxd/shared/i18n"
)
type queryCmd struct {
respWait bool
respRaw bool
action string
data string
}
func (c *queryCmd) showByDefault() bool {
return false
}
func (c *queryCmd) usage() string {
return i18n.G(
`Usage: lxc query [-X <action>] [-d <data>] [--wait] [--raw] [<remote>:]<API path>
Send a raw query to LXD.
*Examples*
lxc query -X DELETE --wait /1.0/containers/c1
Delete local container "c1".`)
}
func (c *queryCmd) flags() {
gnuflag.BoolVar(&c.respWait, "wait", false, i18n.G("Wait for the operation to complete"))
gnuflag.BoolVar(&c.respRaw, "raw", false, i18n.G("Print the raw response"))
gnuflag.StringVar(&c.action, "X", "GET", i18n.G("Action (defaults to GET)"))
gnuflag.StringVar(&c.data, "d", "", i18n.G("Input data"))
}
func (c *queryCmd) pretty(input interface{}) string {
pretty, err := json.MarshalIndent(input, "", "\t")
if err != nil {
return fmt.Sprintf("%v", input)
}
return fmt.Sprintf("%s", pretty)
}
func (c *queryCmd) run(conf *config.Config, args []string) error {
if len(args) != 1 {
return errArgs
}
// Parse the remote
remote, path, err := conf.ParseRemote(args[0])
if err != nil {
return err
}
// Attempt to connect
d, err := conf.GetContainerServer(remote)
if err != nil {
return err
}
// Guess the encoding of the input
var data interface{}
err = json.Unmarshal([]byte(c.data), &data)
if err != nil {
data = c.data
}
// Perform the query
resp, _, err := d.RawQuery(c.action, path, data, "")
if err != nil {
return err
}
if c.respWait && resp.Operation != "" {
resp, _, err = d.RawQuery("GET", fmt.Sprintf("%s/wait", resp.Operation), "", "")
if err != nil {
return err
}
op := api.Operation{}
err = json.Unmarshal(resp.Metadata, &op)
if err == nil && op.Err != "" {
return fmt.Errorf(op.Err)
}
}
if c.respRaw {
fmt.Println(c.pretty(resp))
} else if resp.Metadata != nil && string(resp.Metadata) != "{}" {
var content interface{}
err := json.Unmarshal(resp.Metadata, &content)
if err != nil {
return err
}
if content != nil {
fmt.Println(c.pretty(content))
}
}
return nil
}