-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathclient_cp_chunked_test.go
More file actions
425 lines (403 loc) · 13.8 KB
/
Copy pathclient_cp_chunked_test.go
File metadata and controls
425 lines (403 loc) · 13.8 KB
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
package slicer
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"os"
"path"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
func TestSupportsChunkedCopyAcceptsBothManifestVersions(t *testing.T) {
tests := []struct {
name string
stdout string
want bool
}{
{name: "v1", stdout: "chunked-copy-v1\n", want: true},
{name: "v2", stdout: "chunked-copy-v2\n", want: true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"exit_code": 0, "stdout": test.stdout})
}))
defer server.Close()
client := NewSlicerClient(server.URL, "", "test", server.Client())
got, err := client.SupportsChunkedCopy(context.Background(), "vm-1")
if err != nil {
t.Fatalf("SupportsChunkedCopy: %v", err)
}
if got != test.want {
t.Fatalf("SupportsChunkedCopy = %v, want %v", got, test.want)
}
})
}
}
func TestCpToVMChunkedUploadsManifestAndOrderedChunks(t *testing.T) {
var mu sync.Mutex
uploads := map[string][]byte{}
contentLengths := map[string]int64{}
var execCalls [][]string
activeChunks := 0
maxActiveChunks := 0
completedChunks := 0
manifestArrivedEarly := false
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/exec"):
mu.Lock()
execCalls = append(execCalls, append([]string(nil), r.URL.Query()["args"]...))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"exit_code":0,"stdout":"chunked-copy-v2\n"}`)
case strings.HasSuffix(r.URL.Path, "/cp"):
uploadPath := r.URL.Query().Get("path")
isManifest := path.Base(uploadPath) == "manifest.json"
if !isManifest {
mu.Lock()
activeChunks++
if activeChunks > maxActiveChunks {
maxActiveChunks = activeChunks
}
mu.Unlock()
time.Sleep(20 * time.Millisecond)
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
mu.Lock()
uploads[uploadPath] = body
contentLengths[uploadPath] = r.ContentLength
if isManifest {
manifestArrivedEarly = completedChunks != 3
} else {
activeChunks--
completedChunks++
}
mu.Unlock()
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
source := filepath.Join(t.TempDir(), "tool")
contents := []byte("abcdefghijkl")
if err := os.WriteFile(source, contents, 0o755); err != nil {
t.Fatalf("write source: %v", err)
}
client := NewSlicerClient(server.URL, "token", "test", server.Client())
err := client.CpToVMChunked(context.Background(), "vm-1", source, "/home/ubuntu/bin/tool", ChunkedCopyOptions{
UID: 1000,
GID: 1000,
Permissions: "0755",
Mode: "binary",
ChunkSize: 4,
Concurrency: 2,
})
if err != nil {
t.Fatalf("CpToVMChunked: %v", err)
}
var manifest CopyManifest
var manifestPath string
for uploadPath, body := range uploads {
if path.Base(uploadPath) == "manifest.json" {
manifestPath = uploadPath
if err := json.Unmarshal(body, &manifest); err != nil {
t.Fatalf("decode manifest: %v", err)
}
}
}
if manifestPath == "" {
t.Fatal("manifest was not uploaded")
}
if manifest.Destination != "/home/ubuntu/bin/tool" || manifest.Size != int64(len(contents)) || len(manifest.Chunks) != 3 {
t.Fatalf("manifest = %+v", manifest)
}
if manifest.UID != 1000 || manifest.GID != 1000 {
t.Fatalf("manifest ownership = %d:%d, want 1000:1000", manifest.UID, manifest.GID)
}
if manifest.Version != ChunkedCopyManifestV2 || manifest.CopySemantics != cpCopySemanticsV1 ||
manifest.SourceName != "tool" || manifest.SourceType != copySourceTypeFile || manifest.CopyContents {
t.Fatalf("copy semantics manifest = %+v", manifest)
}
var assembled []byte
for _, chunk := range manifest.Chunks {
chunkPath := path.Join(path.Dir(manifestPath), "chunks", CopyChunkFileName(chunk))
chunkData := uploads[chunkPath]
assembled = append(assembled, chunkData...)
if contentLengths[chunkPath] != chunk.Size {
t.Fatalf("Content-Length for chunk %d = %d, want %d", chunk.Index, contentLengths[chunkPath], chunk.Size)
}
sum := sha256.Sum256(chunkData)
if got := hex.EncodeToString(sum[:]); got != chunk.SHA256 {
t.Fatalf("chunk %d SHA-256 = %s, want %s", chunk.Index, got, chunk.SHA256)
}
}
if string(assembled) != string(contents) {
t.Fatalf("assembled chunks = %q, want %q", assembled, contents)
}
if len(execCalls) != 2 || strings.Join(execCalls[0], " ") != "upload check" || !strings.HasPrefix(strings.Join(execCalls[1], " "), "upload finalise ") {
t.Fatalf("exec calls = %#v", execCalls)
}
if maxActiveChunks < 2 {
t.Fatalf("maximum concurrent chunks = %d, want at least 2", maxActiveChunks)
}
if manifestArrivedEarly {
t.Fatal("manifest arrived before every chunk completed")
}
}
func TestCpToVMChunkedUsesResolvedDestinationWithV1Manifest(t *testing.T) {
var manifest CopyManifest
var execCalls [][]string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/exec"):
execCalls = append(execCalls, append([]string(nil), r.URL.Query()["args"]...))
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"exit_code":0,"stdout":"chunked-copy-v1\n"}`)
case strings.HasSuffix(r.URL.Path, "/fs/stat"):
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"name":"existing","type":"directory"}`)
case strings.HasSuffix(r.URL.Path, "/cp"):
if path.Base(r.URL.Query().Get("path")) == "manifest.json" {
if err := json.NewDecoder(r.Body).Decode(&manifest); err != nil {
t.Errorf("decode manifest: %v", err)
}
}
w.WriteHeader(http.StatusOK)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
source := filepath.Join(t.TempDir(), "tool")
if err := os.WriteFile(source, []byte("contents"), 0o600); err != nil {
t.Fatal(err)
}
client := NewSlicerClient(server.URL, "", "test", server.Client())
err := client.CpToVMChunked(context.Background(), "vm-1", source, "/existing", ChunkedCopyOptions{
Mode: "binary",
ChunkSize: 4,
})
if err != nil {
t.Fatalf("CpToVMChunked: %v", err)
}
if manifest.Version != ChunkedCopyManifestVersion || manifest.Destination != "/existing/tool" {
t.Fatalf("legacy manifest = %+v", manifest)
}
if manifest.CopySemantics != "" || manifest.SourceName != "" || manifest.SourceType != "" || manifest.CopyContents {
t.Fatalf("legacy manifest includes cp-v1 metadata: %+v", manifest)
}
if len(execCalls) != 2 || strings.Join(execCalls[0], " ") != "upload check" || !strings.HasPrefix(strings.Join(execCalls[1], " "), "upload finalise ") {
t.Fatalf("exec calls = %#v", execCalls)
}
}
func TestPrepareChunkedTarStagesOutsideSourceAndCleansUp(t *testing.T) {
root := t.TempDir()
source := filepath.Join(root, "workspace")
if err := os.MkdirAll(source, 0o755); err != nil {
t.Fatalf("create source: %v", err)
}
if err := os.WriteFile(filepath.Join(source, "file.txt"), []byte("contents"), 0o600); err != nil {
t.Fatalf("write source: %v", err)
}
prepared, err := prepareChunkedCopySource(context.Background(), source, ChunkedCopyOptions{Mode: "tar"})
if err != nil {
t.Fatalf("prepareChunkedCopySource: %v", err)
}
stagedPath := prepared.file.Name()
if strings.HasPrefix(stagedPath, root+string(filepath.Separator)) {
t.Fatalf("staged tar %s is inside source tree %s", stagedPath, root)
}
if prepared.size == 0 || prepared.unpackedSize == 0 {
t.Fatalf("staged sizes = %d, %d", prepared.size, prepared.unpackedSize)
}
if err := prepared.cleanup(); err != nil {
t.Fatalf("cleanup staged tar: %v", err)
}
if _, err := os.Stat(stagedPath); !os.IsNotExist(err) {
t.Fatalf("staged tar still exists: %v", err)
}
}
type roundTripFunc func(*http.Request) (*http.Response, error)
func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req)
}
func TestUploadCopyBytesHandlesNilErrorBody(t *testing.T) {
httpClient := &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: http.StatusRequestEntityTooLarge,
Status: "413 Request Entity Too Large",
Header: make(http.Header),
Request: req,
}, nil
})}
client := NewSlicerClient("http://slicer.invalid", "token", "test", httpClient)
err := client.uploadCopyBytes(context.Background(), "vm-1", "/home/ubuntu/chunk", 1000, 1000, []byte("data"))
if err == nil || !strings.Contains(err.Error(), "413 Request Entity Too Large") {
t.Fatalf("error = %v", err)
}
}
func TestCopySessionPathUsesDestinationParent(t *testing.T) {
got, err := copySessionPath("/home/ubuntu/.arkade/bin", strings.Repeat("a", 32))
if err != nil {
t.Fatalf("copySessionPath: %v", err)
}
want := "/home/ubuntu/.arkade/.slicer-upload-" + strings.Repeat("a", 32)
if got != want {
t.Fatalf("copySessionPath() = %q, want %q", got, want)
}
}
func TestCpToVMChunkedAbortsFailedUpload(t *testing.T) {
var mu sync.Mutex
var execCalls [][]string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/exec"):
mu.Lock()
execCalls = append(execCalls, append([]string(nil), r.URL.Query()["args"]...))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"exit_code":0,"stdout":"chunked-copy-v2\n"}`)
case strings.HasSuffix(r.URL.Path, "/cp"):
http.Error(w, "request is too large", http.StatusRequestEntityTooLarge)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
source := filepath.Join(t.TempDir(), "tool")
if err := os.WriteFile(source, []byte("content"), 0o600); err != nil {
t.Fatalf("write source: %v", err)
}
client := NewSlicerClient(server.URL, "token", "test", server.Client())
err := client.CpToVMChunked(context.Background(), "vm-1", source, "/home/ubuntu/tool", ChunkedCopyOptions{
Mode: "binary",
ChunkSize: 4,
})
if err == nil || !strings.Contains(err.Error(), "413 Request Entity Too Large") {
t.Fatalf("error = %v, want request-size failure", err)
}
mu.Lock()
defer mu.Unlock()
if len(execCalls) != 2 || strings.Join(execCalls[0], " ") != "upload check" || !strings.HasPrefix(strings.Join(execCalls[1], " "), "upload abort ") {
t.Fatalf("exec calls = %#v", execCalls)
}
}
func TestCpToVMChunkedCancellationAbortsWithoutManifest(t *testing.T) {
var mu sync.Mutex
var execCalls [][]string
manifestUploaded := false
chunkStarted := make(chan struct{}, 1)
releaseChunks := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, "/exec"):
mu.Lock()
execCalls = append(execCalls, append([]string(nil), r.URL.Query()["args"]...))
mu.Unlock()
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"exit_code":0,"stdout":"chunked-copy-v2\n"}`)
case strings.HasSuffix(r.URL.Path, "/cp"):
if path.Base(r.URL.Query().Get("path")) == "manifest.json" {
mu.Lock()
manifestUploaded = true
mu.Unlock()
w.WriteHeader(http.StatusOK)
return
}
select {
case chunkStarted <- struct{}{}:
default:
}
<-releaseChunks
http.Error(w, "cancelled", http.StatusRequestTimeout)
default:
http.NotFound(w, r)
}
}))
defer server.Close()
source := filepath.Join(t.TempDir(), "tool")
if err := os.WriteFile(source, []byte("abcdefghijkl"), 0o600); err != nil {
t.Fatalf("write source: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
client := NewSlicerClient(server.URL, "token", "test", server.Client())
done := make(chan error, 1)
go func() {
done <- client.CpToVMChunked(ctx, "vm-1", source, "/home/ubuntu/tool", ChunkedCopyOptions{
Mode: "binary",
ChunkSize: 4,
Concurrency: 2,
})
}()
select {
case <-chunkStarted:
cancel()
close(releaseChunks)
case <-time.After(2 * time.Second):
t.Fatal("chunk request did not start")
}
select {
case err := <-done:
if err == nil {
t.Fatal("cancelled copy succeeded")
}
case <-time.After(2 * time.Second):
t.Fatal("cancelled copy did not return promptly")
}
mu.Lock()
defer mu.Unlock()
if manifestUploaded {
t.Fatal("manifest was uploaded after cancellation")
}
if len(execCalls) != 2 || strings.Join(execCalls[0], " ") != "upload check" || !strings.HasPrefix(strings.Join(execCalls[1], " "), "upload abort ") {
t.Fatalf("exec calls = %#v", execCalls)
}
}
func TestCpToVMChunkedCleansStagedTarAfterFailure(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/exec") {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"exit_code":0,"stdout":"chunked-copy-v2\n"}`)
return
}
http.Error(w, "failed", http.StatusBadGateway)
}))
defer server.Close()
root := t.TempDir()
source := filepath.Join(root, "workspace")
if err := os.MkdirAll(source, 0o755); err != nil {
t.Fatalf("create source: %v", err)
}
if err := os.WriteFile(filepath.Join(source, "file.txt"), []byte("contents"), 0o600); err != nil {
t.Fatalf("write source: %v", err)
}
client := NewSlicerClient(server.URL, "token", "test", server.Client())
err := client.CpToVMChunked(context.Background(), "vm-1", source, "/home/ubuntu/workspace", ChunkedCopyOptions{
Mode: "tar",
ChunkSize: 512,
})
if err == nil {
t.Fatal("tar copy succeeded")
}
staged, globErr := filepath.Glob(filepath.Join(root, ".slicer-upload-*.tar"))
if globErr != nil {
t.Fatalf("glob staged tar: %v", globErr)
}
if len(staged) != 0 {
t.Fatalf("staged tar remains: %v", staged)
}
}