forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
application_bits.go
306 lines (255 loc) · 7.79 KB
/
application_bits.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
package api
import (
"archive/zip"
"bytes"
"cf"
"cf/configuration"
"cf/models"
"cf/net"
"encoding/json"
"errors"
"fileutils"
"fmt"
"io"
"mime/multipart"
"net/textproto"
"os"
"path/filepath"
"time"
)
type AppFileResource struct {
Path string `json:"fn"`
Sha1 string `json:"sha1"`
Size int64 `json:"size"`
}
type ApplicationBitsRepository interface {
UploadApp(appGuid, dir string, cb func(path string, zipSize, fileCount uint64)) (apiResponse net.ApiResponse)
}
type CloudControllerApplicationBitsRepository struct {
config configuration.Reader
gateway net.Gateway
zipper cf.Zipper
}
func NewCloudControllerApplicationBitsRepository(config configuration.Reader, gateway net.Gateway, zipper cf.Zipper) (repo CloudControllerApplicationBitsRepository) {
repo.config = config
repo.gateway = gateway
repo.zipper = zipper
return
}
func (repo CloudControllerApplicationBitsRepository) UploadApp(appGuid string, appDir string, cb func(path string, zipSize, fileCount uint64)) (apiResponse net.ApiResponse) {
fileutils.TempDir("apps", func(uploadDir string, err error) {
if err != nil {
apiResponse = net.NewApiResponseWithMessage(err.Error())
return
}
var presentResourcesJson []byte
repo.sourceDir(appDir, func(sourceDir string, sourceErr error) {
if sourceErr != nil {
err = sourceErr
return
}
presentResourcesJson, err = repo.copyUploadableFiles(sourceDir, uploadDir)
})
if err != nil {
apiResponse = net.NewApiResponseWithMessage("%s", err)
return
}
fileutils.TempFile("uploads", func(zipFile *os.File, err error) {
if err != nil {
apiResponse = net.NewApiResponseWithMessage("%s", err.Error())
return
}
err = repo.zipper.Zip(uploadDir, zipFile)
if err != nil {
apiResponse = net.NewApiResponseWithError("Error zipping application", err)
return
}
stat, err := zipFile.Stat()
if err != nil {
apiResponse = net.NewApiResponseWithError("Error zipping application", err)
return
}
cb(appDir, uint64(stat.Size()), cf.CountFiles(uploadDir))
apiResponse = repo.uploadBits(appGuid, zipFile, presentResourcesJson)
if apiResponse.IsNotSuccessful() {
return
}
})
})
return
}
func (repo CloudControllerApplicationBitsRepository) uploadBits(appGuid string, zipFile *os.File, presentResourcesJson []byte) (apiResponse net.ApiResponse) {
url := fmt.Sprintf("%s/v2/apps/%s/bits", repo.config.ApiEndpoint(), appGuid)
fileutils.TempFile("requests", func(requestFile *os.File, err error) {
if err != nil {
apiResponse = net.NewApiResponseWithError("Error creating tmp file: %s", err)
return
}
boundary, err := repo.writeUploadBody(zipFile, requestFile, presentResourcesJson)
if err != nil {
apiResponse = net.NewApiResponseWithError("Error writing to tmp file: %s", err)
return
}
var request *net.Request
request, apiResponse = repo.gateway.NewRequest("PUT", url, repo.config.AccessToken(), requestFile)
if apiResponse.IsNotSuccessful() {
return
}
contentType := fmt.Sprintf("multipart/form-data; boundary=%s", boundary)
request.HttpReq.Header.Set("Content-Type", contentType)
response := &Resource{}
_, apiResponse = repo.gateway.PerformPollingRequestForJSONResponse(request, response, 5*time.Minute)
if apiResponse.IsNotSuccessful() {
return
}
})
return
}
func (repo CloudControllerApplicationBitsRepository) sourceDir(appDir string, cb func(sourceDir string, err error)) {
// If appDir is a zip, first extract it to a temporary directory
zipReader, err := zip.OpenReader(appDir)
if err != nil {
cb(appDir, nil)
return
}
fileutils.TempDir("unzipped-app", func(tmpDir string, err error) {
if err != nil {
cb("", err)
return
}
err = repo.extractZip(zipReader, tmpDir)
zipReader.Close()
cb(tmpDir, err)
})
}
func (repo CloudControllerApplicationBitsRepository) copyUploadableFiles(appDir string, uploadDir string) (presentResourcesJson []byte, err error) {
// Find which files need to be uploaded
allAppFiles, err := cf.AppFilesInDir(appDir)
if err != nil {
return
}
appFilesToUpload, presentResourcesJson, apiResponse := repo.getFilesToUpload(allAppFiles)
if apiResponse.IsNotSuccessful() {
err = errors.New(apiResponse.Message)
return
}
// Copy files into a temporary directory and return it
err = cf.CopyFiles(appFilesToUpload, appDir, uploadDir)
if err != nil {
return
}
return
}
func (repo CloudControllerApplicationBitsRepository) extractZip(r *zip.ReadCloser, destDir string) (err error) {
for _, f := range r.File {
func() {
// Don't try to extract directories
if f.FileInfo().IsDir() {
return
}
if err != nil {
return
}
var rc io.ReadCloser
rc, err = f.Open()
if err != nil {
return
}
defer rc.Close()
destFilePath := filepath.Join(destDir, f.Name)
err = fileutils.CopyReaderToPath(rc, destFilePath)
if err != nil {
return
}
err = fileutils.SetExecutableBits(destFilePath, f.FileInfo())
if err != nil {
return
}
}()
}
return
}
func (repo CloudControllerApplicationBitsRepository) getFilesToUpload(allAppFiles []models.AppFileFields) (appFilesToUpload []models.AppFileFields, presentResourcesJson []byte, apiResponse net.ApiResponse) {
appFilesRequest := []AppFileResource{}
for _, file := range allAppFiles {
appFilesRequest = append(appFilesRequest, AppFileResource{
Path: file.Path,
Sha1: file.Sha1,
Size: file.Size,
})
}
allAppFilesJson, err := json.Marshal(appFilesRequest)
if err != nil {
apiResponse = net.NewApiResponseWithError("Failed to create json for resource_match request", err)
return
}
path := fmt.Sprintf("%s/v2/resource_match", repo.config.ApiEndpoint())
req, apiResponse := repo.gateway.NewRequest("PUT", path, repo.config.AccessToken(), bytes.NewReader(allAppFilesJson))
if apiResponse.IsNotSuccessful() {
return
}
presentResourcesJson, _, apiResponse = repo.gateway.PerformRequestForResponseBytes(req)
fileResource := []AppFileResource{}
err = json.Unmarshal(presentResourcesJson, &fileResource)
if err != nil {
apiResponse = net.NewApiResponseWithError("Failed to unmarshal json response from resource_match request", err)
return
}
appFilesToUpload = make([]models.AppFileFields, len(allAppFiles))
copy(appFilesToUpload, allAppFiles)
for _, file := range fileResource {
appFile := models.AppFileFields{
Path: file.Path,
Sha1: file.Sha1,
Size: file.Size,
}
appFilesToUpload = repo.deleteAppFile(appFilesToUpload, appFile)
}
return
}
func (repo CloudControllerApplicationBitsRepository) deleteAppFile(appFiles []models.AppFileFields, targetFile models.AppFileFields) []models.AppFileFields {
for i, file := range appFiles {
if file.Path == targetFile.Path {
appFiles[i] = appFiles[len(appFiles)-1]
return appFiles[:len(appFiles)-1]
}
}
return appFiles
}
func (repo CloudControllerApplicationBitsRepository) writeUploadBody(zipFile *os.File, body *os.File, presentResourcesJson []byte) (boundary string, err error) {
writer := multipart.NewWriter(body)
defer writer.Close()
boundary = writer.Boundary()
part, err := writer.CreateFormField("resources")
if err != nil {
return
}
_, err = io.Copy(part, bytes.NewBuffer(presentResourcesJson))
if err != nil {
return
}
zipStats, err := zipFile.Stat()
if err != nil {
return
}
if zipStats.Size() == 0 {
return
}
part, err = createZipPartWriter(zipStats, writer)
if err != nil {
return
}
_, err = io.Copy(part, zipFile)
if err != nil {
return
}
return
}
func createZipPartWriter(zipStats os.FileInfo, writer *multipart.Writer) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition", `form-data; name="application"; filename="application.zip"`)
h.Set("Content-Type", "application/zip")
h.Set("Content-Length", fmt.Sprintf("%d", zipStats.Size()))
h.Set("Content-Transfer-Encoding", "binary")
return writer.CreatePart(h)
}