-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathquery.go
190 lines (154 loc) · 4.12 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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"github.com/spf13/cobra"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/i18n"
)
type cmdQuery struct {
global *cmdGlobal
flagRespWait bool
flagRespRaw bool
flagAction string
flagData string
}
func (c *cmdQuery) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("query", i18n.G("[<remote>:]<API path>"))
cmd.Short = i18n.G("Send a raw query to LXD")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Send a raw query to LXD`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc query -X DELETE --wait /1.0/instances/c1
Delete local instance "c1".`))
cmd.RunE = c.run
cmd.Flags().BoolVar(&c.flagRespWait, "wait", false, i18n.G("Wait for the operation to complete"))
cmd.Flags().BoolVar(&c.flagRespRaw, "raw", false, i18n.G("Print the raw response"))
cmd.Flags().StringVarP(&c.flagAction, "request", "X", "GET", i18n.G("Action")+"``")
cmd.Flags().StringVarP(&c.flagData, "data", "d", "", i18n.G("Input data")+"``")
return cmd
}
func (c *cmdQuery) pretty(input any) string {
pretty := bytes.NewBufferString("")
enc := json.NewEncoder(pretty)
enc.SetEscapeHTML(false)
enc.SetIndent("", "\t")
err := enc.Encode(input)
if err != nil {
return fmt.Sprint(input)
}
return pretty.String()
}
func (c *cmdQuery) run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 1)
if exit {
return err
}
if c.global.flagProject != "" {
return errors.New(i18n.G("--project cannot be used with the query command"))
}
if !shared.ValueInSlice(c.flagAction, []string{"GET", "PUT", "POST", "PATCH", "DELETE"}) {
return fmt.Errorf(i18n.G("Action %q isn't supported by this tool"), c.flagAction)
}
// Parse the remote
remote, path, err := conf.ParseRemote(args[0])
if err != nil {
return err
}
// Validate path
if !strings.HasPrefix(path, "/") {
return errors.New(i18n.G("Query path must start with /"))
}
// Attempt to connect
d, err := conf.GetInstanceServer(remote)
if err != nil {
return err
}
// Guess the encoding of the input
var data any
err = json.Unmarshal([]byte(c.flagData), &data)
if err != nil {
data = c.flagData
}
// Perform the query
resp, _, err := d.RawQuery(c.flagAction, path, data, "")
if err != nil {
var jsonSyntaxError *json.SyntaxError
var jsonUnmarshalTypeError *json.UnmarshalTypeError
// If not JSON decoding error then fail immediately.
if !errors.As(err, &jsonSyntaxError) && !errors.As(err, &jsonUnmarshalTypeError) && err.Error() != "EOF" {
return err
}
// If JSON decoding error then try a plain request.
cleanErr := err
// Get the URL prefix
httpInfo, err := d.GetConnectionInfo()
if err != nil {
return err
}
// Setup input.
var rs io.ReadSeeker
if c.flagData != "" {
rs = bytes.NewReader([]byte(c.flagData))
}
// Setup the request
req, err := http.NewRequest(c.flagAction, httpInfo.URL+path, rs)
if err != nil {
return err
}
// Set the encoding accordingly
req.Header.Set("Content-Type", "plain/text")
resp, err := d.DoHTTP(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return cleanErr
}
content, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
fmt.Print(string(content))
return nil
}
if c.flagRespWait && resp.Operation != "" {
uri, err := url.ParseRequestURI(resp.Operation)
if err != nil {
return err
}
resp, _, err = d.RawQuery("GET", uri.Path+"/wait?"+uri.RawQuery, "", "")
if err != nil {
return err
}
op := api.Operation{}
err = json.Unmarshal(resp.Metadata, &op)
if err == nil && op.Err != "" {
return errors.New(op.Err)
}
}
if c.flagRespRaw {
fmt.Println(c.pretty(resp))
} else if resp.Metadata != nil && string(resp.Metadata) != "{}" {
var content any
err := json.Unmarshal(resp.Metadata, &content)
if err != nil {
return err
}
if content != nil {
fmt.Println(c.pretty(content))
}
}
return nil
}