forked from cloudfoundry-incubator/cflocal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
droplet.go
99 lines (85 loc) · 2.28 KB
/
droplet.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
package remote
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
)
func (a *App) Droplet(name string) (droplet io.ReadCloser, size int64, err error) {
return a.get(name, "/droplet/download")
}
func (a *App) SetDroplet(name string, droplet io.Reader, size int64) error {
fieldname := "droplet"
filename := fmt.Sprintf("%s.droplet", name)
// This is necessary because (similar to S3) CC does not accept chunked multipart MIME
contentLength := emptyMultipartSize(fieldname, filename) + size
readBody, writeBody := io.Pipe()
defer readBody.Close()
form := multipart.NewWriter(writeBody)
errChan := make(chan error, 1)
go func() {
defer writeBody.Close()
dropletPart, err := form.CreateFormFile(fieldname, filename)
if err != nil {
errChan <- err
return
}
if _, err := io.CopyN(dropletPart, droplet, size); err != nil {
errChan <- err
return
}
errChan <- form.Close()
}()
if err := a.putJob(name, "/droplet/upload", readBody, form.FormDataContentType(), contentLength); err != nil {
<-errChan
return err
}
return <-errChan
}
func emptyMultipartSize(fieldname, filename string) int64 {
body := &bytes.Buffer{}
form := multipart.NewWriter(body)
form.CreateFormFile(fieldname, filename)
form.Close()
return int64(body.Len())
}
func (a *App) putJob(name, appEndpoint string, body io.Reader, contentType string, contentLength int64) error {
response, err := a.doAppRequest(name, "PUT", appEndpoint, body, contentType, contentLength, http.StatusCreated)
if err != nil {
return err
}
return a.waitForJob(response.Body)
}
func (a *App) waitForJob(body io.ReadCloser) error {
for {
var job struct {
Entity struct {
GUID string `json:"guid"`
Status string `json:"status"`
} `json:"entity"`
}
if err := decodeJob(body, &job); err != nil {
return err
}
switch job.Entity.Status {
case "queued", "running":
endpoint := fmt.Sprintf("/v2/jobs/%s", job.Entity.GUID)
response, err := a.doRequest("GET", endpoint, nil, "", 0, http.StatusOK)
if err != nil {
return err
}
body = response.Body
case "finished":
return nil
default:
return errors.New("job failed")
}
}
}
func decodeJob(body io.ReadCloser, job interface{}) error {
defer body.Close()
return json.NewDecoder(body).Decode(job)
}