-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcloud66.go
393 lines (336 loc) · 8.57 KB
/
cloud66.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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
package cloud66
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"time"
"github.com/khash/oauth/oauth"
"github.com/pborman/uuid"
)
const (
baseURL = "https://app.cloud66.com"
)
type GenericResponse struct {
Status bool `json:"ok"`
Message string `json:"message"`
}
type ClientConfig struct {
DefaultUserAgent string
AgentPrefix string
BaseAPIURL string
ClientID string
ClientSecret string
RedirectURL string
Scope string
defaultAPIURL string
authURL string
tokenURL string
}
type Client struct {
HTTP *http.Client
URL string
UserAgent string
Hostname string
AccountId *int
Debug bool
AdditionalHeaders http.Header
Config *ClientConfig
}
type Response struct {
Response json.RawMessage
Count int
Pagination json.RawMessage
}
type Pagination struct {
Previous int
Next int
Current int
}
type stackEnvironmentFilterFunction func(item interface{}, environment *string) bool
func (c *Client) Get(v interface{}, path string, queryStrings map[string]string, p *Pagination) error {
return c.APIReq(v, "GET", path, nil, queryStrings, p)
}
func (c *Client) Patch(v interface{}, path string, body interface{}) error {
return c.APIReq(v, "PATCH", path, body, nil, nil)
}
func (c *Client) Post(v interface{}, path string, body interface{}) error {
return c.APIReq(v, "POST", path, body, nil, nil)
}
func (c *Client) Put(v interface{}, path string, body interface{}) error {
return c.APIReq(v, "PUT", path, body, nil, nil)
}
func (c *Client) Delete(path string) error {
return c.APIReq(nil, "DELETE", path, nil, nil, nil)
}
func (c *Client) NewRequest(method, path string, body interface{}, queryStrings map[string]string) (*http.Request, error) {
var ctype string
var rbody io.Reader
switch t := body.(type) {
case nil:
case string:
rbody = bytes.NewBufferString(t)
case io.Reader:
rbody = t
default:
v := reflect.ValueOf(body)
if !v.IsValid() {
break
}
if v.Type().Kind() == reflect.Ptr {
v = reflect.Indirect(v)
if !v.IsValid() {
break
}
}
j, err := json.Marshal(body)
if err != nil {
log.Fatal(err)
}
rbody = bytes.NewReader(j)
ctype = "application/json"
}
apiURL := strings.TrimRight(c.URL, "/")
if apiURL == "" {
apiURL = c.Config.defaultAPIURL
}
var qs string
if (queryStrings != nil) && (len(queryStrings) > 0) {
for key, value := range queryStrings {
if qs == "" {
qs = "?"
} else {
qs = qs + "&"
}
qs = qs + key + "=" + value
}
}
last_url := strings.TrimRight(apiURL+path, "/")
if qs != "" {
last_url = last_url + qs
}
req, err := http.NewRequest(method, last_url, rbody)
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Request-Id", uuid.New())
if os.Getenv("CXTOKEN") != "" {
req.Header.Set("X-CxToken", os.Getenv("CXTOKEN"))
}
if c.AccountId != nil {
req.Header.Set("X-Account", strconv.Itoa(*c.AccountId))
}
useragent := c.UserAgent
if useragent == "" {
useragent = c.Config.DefaultUserAgent
}
req.Header.Set("User-Agent", useragent)
if ctype != "" {
req.Header.Set("Content-Type", ctype)
}
for k, v := range c.AdditionalHeaders {
req.Header[k] = v
}
return req, nil
}
func (c *Client) APIReq(v interface{}, meth, path string, body interface{}, queryStrings map[string]string, p *Pagination) error {
req, err := c.NewRequest(meth, path, body, queryStrings)
if err != nil {
return err
}
return c.DoReq(req, v, p)
}
func (c *Client) DoReq(req *http.Request, v interface{}, p *Pagination) error {
if c.Debug {
dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
log.Println(err)
} else {
os.Stderr.Write(dump)
os.Stderr.Write([]byte{'\n', '\n'})
}
}
var checkPagination bool
if (req.Method == "GET") && (p != nil) {
checkPagination = true
} else {
checkPagination = false
}
httpClient := c.HTTP
if httpClient == nil {
httpClient = http.DefaultClient
}
res, err := httpClient.Do(req)
// headers that have a suffix of "-once" are captured only once for the lifetime of the library
for headerKey := range c.AdditionalHeaders {
if strings.HasSuffix(strings.ToLower(headerKey), "-once") {
delete(c.AdditionalHeaders, headerKey)
}
}
if err != nil {
return err
}
defer res.Body.Close()
if c.Debug {
dump, err := httputil.DumpResponse(res, true)
if err != nil {
log.Println(err)
} else {
os.Stderr.Write(dump)
os.Stderr.Write([]byte{'\n'})
}
}
if err = checkResp(res); err != nil {
return err
}
// open the wrapper
var r Response
err = json.NewDecoder(res.Body).Decode(&r)
if err != nil {
return err
}
buffer := bytes.NewBuffer(r.Response)
switch t := v.(type) {
case nil:
case io.Writer:
_, err = io.Copy(t, buffer)
default:
err = json.NewDecoder(buffer).Decode(v)
}
if (err == nil) && checkPagination {
pagination := bytes.NewBuffer(r.Pagination)
err = json.NewDecoder(pagination).Decode(p)
}
return err
}
type Error struct {
error
Id string
}
type errorResp struct {
Error string `json:"error"`
Description string `json:"error_description"`
Details string `json:"details"`
}
func checkResp(res *http.Response) error {
if res.StatusCode/100 != 2 { // 200, 201, 202, etc
var e errorResp
err := json.NewDecoder(res.Body).Decode(&e)
if err != nil {
return errors.New("Unexpected error: " + res.Status)
}
if e.Details != "" {
return Error{error: errors.New(e.Details), Id: e.Error}
} else {
return Error{error: errors.New(e.Description), Id: e.Error}
}
}
if msg := res.Header.Get("X-Cloud66-Warning"); msg != "" {
fmt.Fprintln(os.Stderr, strings.TrimSpace(msg))
}
return nil
}
func (c *Client) GetAuthorizeURL() string {
config := &oauth.Config{
ClientId: c.Config.ClientID,
ClientSecret: c.Config.ClientSecret,
RedirectURL: c.Config.RedirectURL,
Scope: c.Config.Scope,
AuthURL: c.Config.authURL,
TokenURL: c.Config.tokenURL,
}
return config.AuthCodeURL("")
}
func (c *Client) Authorize(tokenDir, tokenFile, token string) {
err := os.MkdirAll(tokenDir, 0777)
if err != nil {
fmt.Printf("Failed to create directory for the token at %s\n", tokenDir)
}
cachefile := filepath.Join(tokenDir, tokenFile)
config := &oauth.Config{
ClientId: c.Config.ClientID,
ClientSecret: c.Config.ClientSecret,
RedirectURL: c.Config.RedirectURL,
Scope: c.Config.Scope,
AuthURL: c.Config.authURL,
TokenURL: c.Config.tokenURL,
TokenCache: oauth.CacheFile(cachefile),
}
transport := &oauth.Transport{Config: config}
_, err = config.TokenCache.Token()
// do we already have access?
if err != nil {
_, err := transport.Exchange(token)
if err != nil {
log.Fatal("Exchange:", err)
}
log.Printf("token is cached in %v\n", config.TokenCache)
os.Exit(1)
}
}
func GetClient(tokenFile, tokenDir, version string, config *ClientConfig) Client {
c := Client{
Config: config,
}
cachefile := filepath.Join(tokenDir, tokenFile)
config.DefaultUserAgent = config.AgentPrefix + "/" + version + " (" + runtime.GOOS + "; " + runtime.GOARCH + ")"
oauthConfig := &oauth.Config{
ClientId: config.ClientID,
ClientSecret: config.ClientSecret,
RedirectURL: config.RedirectURL,
Scope: config.Scope,
AuthURL: config.authURL,
TokenURL: config.tokenURL,
TokenCache: oauth.CacheFile(cachefile),
}
hostname, err := os.Hostname()
if err != nil {
log.Printf("unable to get the hostname\n", err.Error())
}
transport := &oauth.Transport{Config: oauthConfig}
token, _ := oauthConfig.TokenCache.Token()
transport.Token = token
c.HTTP = transport.Client()
c.Hostname = hostname
return c
}
func NewClientConfig(baseAPIURL string) *ClientConfig {
return &ClientConfig{
defaultAPIURL: baseAPIURL + "/api/3",
authURL: baseAPIURL + "/oauth/authorize",
tokenURL: baseAPIURL + "/oauth/token",
}
}
func FetchTokenFromCallback(timeout time.Duration) (string, error) {
var token string
m := http.NewServeMux()
srv := &http.Server{Addr: "127.0.0.1:34543", Handler: m}
codeCh := make(chan string)
m.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Authorized. You can close this window now!")
codeCh <- r.URL.Query().Get("code")
})
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalf("ListenAndServe(): %s", err)
}
}()
select {
case code := <-codeCh:
srv.Shutdown(context.Background())
token = code
}
return token, nil
}