forked from iron-io/ironcli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
104 lines (91 loc) · 2.27 KB
/
worker.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
package main
import (
"archive/zip"
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"github.com/iron-io/iron_go/api"
"github.com/iron-io/iron_go/worker"
)
// create code package (zip) from parsed .worker info
func pushCodes(zipName string, w *worker.Worker, args worker.Code) (id string, err error) {
// TODO i don't get why i can't write from disk to wire, but I give up
var body bytes.Buffer
mWriter := multipart.NewWriter(&body)
mMetaWriter, err := mWriter.CreateFormField("data")
if err != nil {
return "", err
}
reqMap := map[string]interface{}{
"name": args.Name,
"config": args.Config,
"max_concurrency": args.MaxConcurrency,
"retries": args.Retries,
"retries_delay": args.RetriesDelay.Seconds(),
}
if args.Command != "" {
reqMap["command"] = args.Command
}
if args.Stack != "" {
reqMap["stack"] = args.Stack
}
if args.Image != "" {
reqMap["image"] = args.Image
}
jEncoder := json.NewEncoder(mMetaWriter)
if err := jEncoder.Encode(reqMap); err != nil {
return "", err
}
if zipName != "" {
r, err := zip.OpenReader(zipName)
if err != nil {
return "", err
}
defer r.Close()
mFileWriter, err := mWriter.CreateFormFile("file", "worker.zip")
if err != nil {
return "", err
}
zWriter := zip.NewWriter(mFileWriter)
for _, f := range r.File {
fWriter, err := zWriter.Create(f.Name)
if err != nil {
return "", err
}
rc, err := f.Open()
if err != nil {
return "", err
}
_, err = io.Copy(fWriter, rc)
rc.Close()
if err != nil {
return "", err
}
}
zWriter.Close()
}
mWriter.Close()
req, err := http.NewRequest("POST", api.Action(w.Settings, "codes").URL.String(), &body)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Encoding", "gzip/deflate")
req.Header.Set("Authorization", "OAuth "+w.Settings.Token)
req.Header.Set("Content-Type", mWriter.FormDataContentType())
req.Header.Set("User-Agent", w.Settings.UserAgent)
response, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
if err = api.ResponseAsError(response); err != nil {
return "", err
}
var data struct {
Id string `json:"id"`
}
err = json.NewDecoder(response.Body).Decode(&data)
return data.Id, err
}