-
Notifications
You must be signed in to change notification settings - Fork 1
/
api.go
528 lines (480 loc) · 15.9 KB
/
api.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/CodePicnic/codepicnic-go"
"github.com/Jeffail/gabs"
"github.com/go-ini/ini"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"os"
"strings"
)
const ERROR_NOT_AUTHORIZED = "Not Authorized"
const ERROR_NOT_CONNECTED = "Disconnected"
const ERROR_EMPTY_CREDENTIALS = "No Credentials"
const ERROR_EMPTY_TOKEN = "No Token"
const ERROR_INVALID_TOKEN = "Invalid Token"
const ERROR_USAGE_EXCEEDED = "Usage Exceeded"
const ERROR_CACHE_NOT_FOUND = "Cache not Found"
const ERROR_DNS_LOOKUP = "Host not found"
const TOKEN_LEN = 64
type Token struct {
Access string `json:"access_token"`
Type string `json:"token_type"`
Expires string `json:"expires_in"`
Created string `json:"created_at"`
}
type Console struct {
Url string `json:"url"`
ContainerName string `json:"container_name"`
}
type ConsoleExtra struct {
Id int
Title string
Size string
Type string
Hostname string
Mode string
}
type ConsoleJson struct {
Id int `json:"id"`
Content string `json:"content"`
Title string `json:"title"`
Name string `json:"name"`
ContainerName string `json:"container_name"`
ContainerType string `json:"container_type"`
CustomImage string `json:"custom_image"`
CreatedAt string `json:"created_at"`
Permalink string `json:"permalink"`
//Url string `json:"url"`
//TerminalUrl string `json:"terminal_url"`
}
type ConsoleCollection struct {
Consoles []ConsoleJson `json:"consoles"`
}
type StackCollection struct {
Stacks []StackJson `json:"container_types"`
}
type StackJson struct {
Identifier string `json:"identifier"`
Name string `json:"name"`
ShortName string `json:"short_name"`
Version string `json:"version"`
ImageName string `json:"image_name"`
Group string `json:"group"`
}
//Another type of console :(
type ConsoleShowJson struct {
Url string `json:"url"`
EmbedUrl string `json:"embed_url"`
ContainerName string `json:"container_name"`
TerminalUrl string `json:"terminal_url"`
IsHeadless string `json:"is_headless"`
Title string `json:"title"`
Permalink string `json:"permalink"`
}
func GetTokenAccess() (string, error) {
client_id, client_secret := GetCredentialsFromFile()
if client_id == "" || client_secret == "" {
return "", errors.New(ERROR_EMPTY_CREDENTIALS)
}
access_token, err := GetTokenAccessFromCredentials(client_id, client_secret)
return access_token, err
}
func GetTokenAccessFromCredentials(client_id string, client_secret string) (string, error) {
cp_token_url := site + "/oauth/token"
//client_id, client_secret = GetCredentialsFromFile()
cp_payload := `{ "grant_type": "client_credentials","client_id": "` + client_id + `", "client_secret": "` + client_secret + `"}`
var jsonStr = []byte(cp_payload)
req, err := http.NewRequest("POST", cp_token_url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
if strings.Contains(err.Error(), "read: connection refused") {
fmt.Println(color("Can't connect to the CodePicnic API. Please verify your connection or try again.", "error"))
return "", errors.New(ERROR_NOT_CONNECTED)
}
}
//fmt.Println("response Status:", resp.Status)
//fmt.Println("response Status:", resp.StatusCode)
if resp.StatusCode == 401 {
return "", errors.New(ERROR_NOT_AUTHORIZED)
}
defer resp.Body.Close()
var token Token
_ = json.NewDecoder(resp.Body).Decode(&token)
SaveTokenToFile(token.Access)
return token.Access, nil
}
func GetCredentialsFromFile() (client_id string, client_secret string) {
cfg, err := ini.Load(getHomeDir() + "/" + cfg_dir + "/" + cfg_file)
if err != nil {
return
}
client_id = cfg.Section("credentials").Key("client_id").String()
client_secret = cfg.Section("credentials").Key("client_secret").String()
return
}
func GetTokenAccessFromFile() (token string) {
cfg, err := ini.Load(getHomeDir() + "/" + cfg_dir + "/" + cfg_file)
if err != nil {
return
}
token = cfg.Section("credentials").Key("access_token").String()
return
}
func SaveCredentialsToFile(client_id string, client_secret string) error {
cfg, err := ini.Load(getHomeDir() + "/" + cfg_dir + "/" + cfg_file)
if err != nil {
return err
}
cfg.Section("credentials").Key("client_id").SetValue(client_id)
cfg.Section("credentials").Key("client_secret").SetValue(client_secret)
//fmt.Println(getHomeDir() + "/.codepicnic/credentials")
err = cfg.SaveTo(getHomeDir() + "/" + cfg_dir + "/" + cfg_file)
if err != nil {
return err
}
return nil
}
func ListConsoles(access_token string) ([]ConsoleJson, error) {
cp_consoles_url := site + "/api/consoles/all.json"
req, err := http.NewRequest("GET", cp_consoles_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
//fmt.Println(time.Now().Format("20060102150405"))
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == 401 {
return nil, errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return nil, errors.New(ERROR_USAGE_EXCEEDED)
}
//fmt.Println("response Status:", resp.Status)
//fmt.Println("response Status:", resp.StatusCode)
var console_collection ConsoleCollection
//var console_collection []ConsoleJson
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &console_collection)
if err != nil {
fmt.Printf("%+v\n", err)
}
//_ = json.NewDecoder(resp.Body).Decode(&console_collection)
//fmt.Printf("%+v\n", string(body))
//fmt.Printf("%#v\n", console_collection.Consoles[0].Title)
return console_collection.Consoles, nil
}
func isValidConsole(token string, console string) (bool, ConsoleJson, error) {
var console_empty ConsoleJson
consoles, err := ListConsoles(token)
if err != nil {
return false, console_empty, err
}
for i := range consoles {
if console == consoles[i].ContainerName {
return true, consoles[i], nil
}
}
return false, console_empty, nil
}
func IsValidConsole(console codepicnic.Console) (bool, error) {
var consoles []codepicnic.Console
consoles, err := codepicnic.ListConsoles()
if err != nil {
return false, err
}
fmt.Printf("%+v", consoles)
for _, c := range consoles {
fmt.Println(console.ContainerName())
fmt.Println(c.ContainerName())
if console.ContainerName() == c.ContainerName() {
return true, nil
}
}
return false, nil
}
func JsonListConsoles(access_token string) string {
cp_consoles_url := site + "/api/consoles/all"
req, err := http.NewRequest("GET", cp_consoles_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
//panic(err)
return ""
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("%+v\n", err)
}
//fmt.Printf("%+v\n", string(body))
return string(body)
}
type JsonCommand struct {
command string
result string
}
func ExecConsole(token string, console string, command string) ([]JsonCommand, error) {
var CmdCollection []JsonCommand
cp_consoles_url := site + "/api/consoles/" + console + "/exec"
cp_payload := ` { "commands": "` + command + `" }`
var jsonStr = []byte(cp_payload)
req, err := http.NewRequest("POST", cp_consoles_url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if resp.StatusCode == 401 {
return CmdCollection, errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return CmdCollection, errors.New(ERROR_USAGE_EXCEEDED)
}
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
jsonBody, err := gabs.ParseJSON(body)
jsonPaths, _ := jsonBody.ChildrenMap()
for key, child := range jsonPaths {
var cmd JsonCommand
cmd.command = string(key)
cmd.result = child.Data().(string)
//Debug("key, value, type", key, child.Data().(string), jsonTypes[jsonFile.path])
//Debug("key, value, type", key, child.Data().(string), jsonFile.mime)
CmdCollection = append(CmdCollection, cmd)
}
//fmt.Printf("%+v\n", string(body))
return CmdCollection, nil
}
func StartConsole(access_token string, container_name string) error {
cp_consoles_url := site + "/api/consoles/" + container_name + "/start"
req, err := http.NewRequest("POST", cp_consoles_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return errors.New(ERROR_NOT_CONNECTED)
}
if resp.StatusCode == 401 {
return errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return errors.New(ERROR_USAGE_EXCEEDED)
}
defer resp.Body.Close()
var console Console
_ = json.NewDecoder(resp.Body).Decode(&console)
return nil
}
func StopConsole(access_token string, container_name string) error {
cp_consoles_url := site + "/api/consoles/" + container_name + "/stop"
req, err := http.NewRequest("POST", cp_consoles_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return errors.New(ERROR_NOT_CONNECTED)
}
if resp.StatusCode == 401 {
return errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return errors.New(ERROR_USAGE_EXCEEDED)
}
defer resp.Body.Close()
var console Console
_ = json.NewDecoder(resp.Body).Decode(&console)
return nil
}
func RestartConsole(access_token string, container_name string) error {
cp_consoles_url := site + "/api/consoles/" + container_name + "/restart"
req, err := http.NewRequest("POST", cp_consoles_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return errors.New(ERROR_NOT_CONNECTED)
}
if resp.StatusCode == 401 {
return errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return errors.New(ERROR_USAGE_EXCEEDED)
}
defer resp.Body.Close()
var console Console
_ = json.NewDecoder(resp.Body).Decode(&console)
return nil
}
func RemoveConsole(access_token string, console string) error {
cp_consoles_url := site + "/api/consoles" + "/" + console
var jsonStr = []byte("")
req, err := http.NewRequest("DELETE", cp_consoles_url, bytes.NewBuffer(jsonStr))
//req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", user_agent)
req.Header.Set("Authorization", "Bearer "+access_token)
client := &http.Client{}
resp, err := client.Do(req)
if resp.StatusCode == 401 {
return errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return errors.New(ERROR_USAGE_EXCEEDED)
}
if err != nil {
return errors.New(ERROR_NOT_CONNECTED)
}
defer resp.Body.Close()
return nil
}
func ListStacks(access_token string) ([]StackJson, error) {
var stack_collection StackCollection
cp_types_url := site + "/api/container_types.json"
req, err := http.NewRequest("GET", cp_types_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", user_agent)
req.Header.Set("Authorization", "Bearer "+access_token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return stack_collection.Stacks, errors.New(ERROR_NOT_CONNECTED)
}
defer resp.Body.Close()
if resp.StatusCode == 401 {
return nil, errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return nil, errors.New(ERROR_USAGE_EXCEEDED)
}
body, err := ioutil.ReadAll(resp.Body)
err = json.Unmarshal(body, &stack_collection)
if err != nil {
fmt.Printf("%+v\n", err)
}
//_ = json.NewDecoder(resp.Body).Decode(&console_collection)
//fmt.Printf("%+v\n", string(body))
//fmt.Printf("%#v\n", console_collection.Consoles[0].Title)
return stack_collection.Stacks, nil
}
func GetStackInfo(access_token string, mystack string) (StackJson, error) {
var stack StackJson
stacks_list, _ := ListStacks(access_token)
for _, stack := range stacks_list {
if stack.Identifier == mystack {
return stack, nil
}
}
return stack, nil
}
func GetConsoleInfo(access_token string, myconsole string) (ConsoleJson, error) {
var console ConsoleJson
consoles_list, _ := ListConsoles(access_token)
for _, console := range consoles_list {
if console.ContainerName == myconsole {
return console, nil
}
}
return console, nil
}
func CreateConsole(access_token string, console_extra ConsoleExtra) (string, string, error) {
cp_consoles_url := site + "/api/consoles"
//cp_payload := `{ "console: { "grant_type": "client_credentials","client_id": "` + client_id + `", "client_secret": "` + client_secret + `"}`
cp_payload := ` { "console": { "container_size": "` + console_extra.Size + `", "container_type": "` + console_extra.Type + `", "title": "` + console_extra.Title + `" , "hostname": "` + console_extra.Hostname + `", "current_mode": "` + console_extra.Mode + `" } }`
var jsonStr = []byte(cp_payload)
req, err := http.NewRequest("POST", cp_consoles_url, bytes.NewBuffer(jsonStr))
//req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+access_token)
//req.Header.Set("User-Agent", "CodePicnic-CLI/"+version+ " ("+GetOSVersion()+")")
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if resp.StatusCode == 401 {
return "", "", errors.New(ERROR_INVALID_TOKEN)
} else if resp.StatusCode == 429 {
return "", "", errors.New(ERROR_USAGE_EXCEEDED)
}
//fmt.Println("response Status:", resp.Status)
//fmt.Println("response Status:", resp.StatusCode)
if err != nil {
return "", "", errors.New(ERROR_NOT_CONNECTED)
}
defer resp.Body.Close()
var console Console
_ = json.NewDecoder(resp.Body).Decode(&console)
return console.ContainerName, console.Url, nil
}
func DownloadFileFromConsole(token string, console_id string, src string, dst string) error {
if dst == "" {
dst = src
}
//cp_consoles_url := site + "/api/consoles/" + console_id + "/" + src
cp_consoles_url := site + "/api/consoles/" + console_id + "/read_file?path=" + src
req, err := http.NewRequest("GET", cp_consoles_url, nil)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return errors.New(ERROR_NOT_CONNECTED)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
ioutil.WriteFile(dst, body, 0644)
return nil
}
func UploadFileToConsole(token string, console_id string, dst string, src string) (err error) {
if dst == "" {
dst = src
}
cp_consoles_url := site + "/api/consoles/" + console_id + "/upload_file"
var b bytes.Buffer
w := multipart.NewWriter(&b)
temp_file, err := os.Open(src)
fw, err := w.CreateFormFile("file", temp_file.Name())
if _, err = io.Copy(fw, temp_file); err != nil {
return
}
if fw, err = w.CreateFormField("path"); err != nil {
return
}
if _, err = fw.Write([]byte("/app/" + dst)); err != nil {
return
}
w.Close()
req, err := http.NewRequest("POST", cp_consoles_url, &b)
if err != nil {
fmt.Printf("Error 3 %v \n", err)
return err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", w.FormDataContentType())
req.Header.Set("User-Agent", user_agent)
client := &http.Client{}
res, err := client.Do(req)
if err != nil {
return err
}
if res.StatusCode != http.StatusOK {
err = fmt.Errorf("bad status: %s", res.Status)
}
return nil
}