forked from rancher/convoy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
221 lines (197 loc) · 4.91 KB
/
client.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package client
import (
"encoding/json"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/codegangsta/cli"
"github.com/rancher/convoy/api"
"github.com/rancher/convoy/util"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"os"
"time"
)
type convoyClient struct {
addr string
scheme string
transport *http.Transport
}
var (
verboseFlag = "verbose"
log = logrus.WithFields(logrus.Fields{"pkg": "client"})
client convoyClient
)
func (c *convoyClient) call(method, path string, data interface{}, headers map[string][]string) (io.ReadCloser, int, error) {
params, err := util.EncodeData(data)
if err != nil {
return nil, -1, err
}
if data != nil {
if headers == nil {
headers = make(map[string][]string)
}
headers["Context-Type"] = []string{"application/json"}
}
body, _, statusCode, err := c.clientRequest(method, path, params, headers)
return body, statusCode, err
}
func (c *convoyClient) httpClient() *http.Client {
return &http.Client{Transport: c.transport}
}
func getRequestPath(path string) string {
return fmt.Sprintf("/v1%s", path)
}
func (c *convoyClient) clientRequest(method, path string, in io.Reader, headers map[string][]string) (io.ReadCloser, string, int, error) {
req, err := http.NewRequest(method, getRequestPath(path), in)
if err != nil {
return nil, "", -1, err
}
req.Header.Set("User-Agent", "Convoy-Client/"+api.API_VERSION)
req.URL.Host = c.addr
req.URL.Scheme = c.scheme
resp, err := c.httpClient().Do(req)
statusCode := -1
if resp != nil {
statusCode = resp.StatusCode
}
if err != nil {
return nil, "", statusCode, err
}
if statusCode < 200 || statusCode >= 400 {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, "", statusCode, err
}
if len(body) == 0 {
return nil, "", statusCode, fmt.Errorf("Incompatable version")
}
return nil, "", statusCode, fmt.Errorf("Error response from server, %v", string(body))
}
return resp.Body, resp.Header.Get("Context-Type"), statusCode, nil
}
func sendRequest(method, request string, data interface{}) (io.ReadCloser, error) {
log.Debugf("Sending request %v %v", method, request)
if data != nil {
log.Debugf("With data %+v", data)
}
rc, _, err := client.call(method, request, data, nil)
if err != nil {
return nil, err
}
return rc, nil
}
func sendRequestAndPrint(method, request string, data interface{}) error {
rc, err := sendRequest(method, request, data)
if err != nil {
return err
}
defer rc.Close()
b, err := ioutil.ReadAll(rc)
if err != nil {
return err
}
fmt.Println(string(b))
return nil
}
func cmdNotFound(c *cli.Context, command string) {
panic(fmt.Errorf("Unrecognized command: %s", command))
}
// NewCli would generate Convoy CLI
func NewCli(version string) *cli.App {
app := cli.NewApp()
app.Name = "convoy"
app.Version = version
app.Author = "Sheng Yang <sheng.yang@rancher.com>"
app.Usage = "A volume manager capable of snapshot and delta backup"
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "socket, s",
Value: "/var/run/convoy/convoy.sock",
Usage: "Specify unix domain socket for communication between server and client",
},
cli.BoolFlag{
Name: "debug, d",
Usage: "Enable debug level log with client or not",
},
cli.BoolFlag{
Name: "verbose",
Usage: "Verbose level output for client, for create volume/snapshot etc",
},
}
app.CommandNotFound = cmdNotFound
app.Before = initClient
app.Commands = []cli.Command{
daemonCmd,
infoCmd,
volumeCreateCmd,
volumeDeleteCmd,
volumeMountCmd,
volumeUmountCmd,
volumeListCmd,
volumeInspectCmd,
snapshotCmd,
backupCmd,
}
return app
}
func initClient(c *cli.Context) error {
sockFile := c.GlobalString("socket")
if sockFile == "" {
return fmt.Errorf("Require unix domain socket location")
}
logrus.SetOutput(os.Stderr)
debug := c.GlobalBool("debug")
if debug {
logrus.SetLevel(logrus.DebugLevel)
}
client.addr = sockFile
client.scheme = "http"
client.transport = &http.Transport{
DisableCompression: true,
Dial: func(_, _ string) (net.Conn, error) {
return net.DialTimeout("unix", sockFile, 10*time.Second)
},
}
return nil
}
func getOrRequestUUID(c *cli.Context, key string, required bool) (string, error) {
var err error
var id string
if key == "" {
id = c.Args().First()
} else {
id, err = util.GetFlag(c, key, required, err)
if err != nil {
return "", err
}
}
if id == "" && !required {
return "", nil
}
if util.ValidateUUID(id) {
return id, nil
}
return requestUUID(id)
}
func requestUUID(id string) (string, error) {
// Identify by name
v := url.Values{}
v.Set(api.KEY_NAME, id)
request := "/uuid?" + v.Encode()
rc, err := sendRequest("GET", request, nil)
if err != nil {
return "", err
}
defer rc.Close()
resp := &api.UUIDResponse{}
if err := json.NewDecoder(rc).Decode(resp); err != nil {
return "", err
}
if resp.UUID == "" {
return "", fmt.Errorf("Cannot find volume with name or id %v", id)
}
return resp.UUID, nil
}