-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfs.go
547 lines (501 loc) · 12 KB
/
fs.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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
package main
import (
"bufio"
"context"
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"errors"
"flag"
"fmt"
"hash"
"io"
"net"
"net/http"
"net/url"
"os"
"os/signal"
"path"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/as/log"
)
var (
agent = flag.String("A", "", "user agent")
header = flag.String("H", "", "http header with colon seperated value (like curl)")
tmp = flag.String("tmp", os.TempDir(), "temporary directory location")
partsize = flag.Int("partsize", 0, "temporary file partition size")
secure = flag.Bool("secure", false, "disable https to http downgrade when using bucket optimizations")
slow = flag.Bool("slow", false, "disable parallelism for same-file downloads using temp files (see tmp and partsize)")
sign = flag.Bool("s", false, "presign one or more files (s3 and gs) and output http urls")
maxhttp = flag.Int("maxhttp", 48, "global max http connections allowed")
recurse = flag.Bool("r", false, "assume input is a directory and attempt recursion")
bs = flag.Int("bs", 0, "block size for copy operation (zero means unbuffered)")
dry = flag.Bool("dry", false, "print (and unroll) ccp commands only; no I/O ops")
test = flag.Bool("test", false, "open and create files, but do not read or copy data")
quiet = flag.Bool("q", false, "dont print any progress output")
flaky = flag.Bool("flaky", false, "treat i/o errors as non-fatal")
debug = flag.Bool("debug", false, "print debug logs")
acl = flag.String("acl", "", "apply this acl to the destination, e.g.: private, public-read, public-read-write, aws-exec-read")
deadband = flag.Duration("deadband", 200*time.Second, "for copies, the non-cumulative duration of no io in the process (read+write) after which ccp emits a fatal error (zero means no timeout)")
ls = flag.Bool("ls", false, "list the source files or dirs")
rel = flag.Bool("rel", false, "ls omits scheme and bucket")
stdinlist = flag.Bool("l", false, "treat stdin as a list of sources instead of data")
seek = flag.Int("seek", 0, "source file byte offset to start reading from")
count = flag.Int("count", 0, "source file bytes to read")
version = flag.Bool("v", false, "print version and exit")
hashname = flag.String("hash", "", "hashes outgoing data (md5|sha1|sha256|sha384|sha512)")
nogc = flag.Bool("nogc", false, "dont delete temporary files (debugging only)")
nosort = flag.Bool("nosort", false, "this is a test flag that disables sorting of partition workers; used for debugging only")
ipv4 = flag.Bool("4", false, "forces layer3 ipv4 for s3/http/https files")
del = flag.Bool("d", false, "delete the file provided as the argument (currently not recursive)")
)
var (
errNotImplemented = errors.New("not yet implemented")
)
var ctx = context.Background()
var driver = map[string]interface {
List(string) ([]Info, error)
Delete(string) error
Open(string) (io.ReadCloser, error)
Create(string) (io.WriteCloser, error)
Close() error
}{
"s3": &S3{ctx: ctx},
"gs": &GS{ctx: ctx},
"file": &OS{},
"http": &HTTP{ctx: ctx},
"https": &HTTP{ctx: ctx},
"": &OS{},
}
var killc = make(chan os.Signal, 2)
func init() {
signal.Notify(killc, syscall.SIGINT, syscall.SIGTERM)
}
func closeAll() {
for _, fs := range driver {
fs.Close()
}
}
var hashes = map[string]func() hash.Hash{
"md5": md5.New,
"sha1": sha1.New,
"sha256": sha256.New,
"sha512": sha512.New,
}
func copyhash(dst io.Writer, src io.Reader) (n int64, sum string, err error) {
var h hash.Hash
new := hashes[*hashname]
if new != nil {
h = new()
src = io.TeeReader(src, h)
}
n, err = io.Copy(tx{dst}, rx{src})
if h != nil {
sum = fmt.Sprintf("%x", h.Sum(nil))
}
return
}
func docp(src, dst string, ec chan<- work) {
sfs := driver[uri(src).Scheme]
dfs := driver[uri(dst).Scheme]
{
sfd, err := sfs.Open(src)
if err != nil {
ec <- work{src: src, dst: dst, err: fmt.Errorf("open src: %s: %w", src, err)}
return
}
dfd, err := dfs.Create(dst)
if err != nil {
ec <- work{src: src, dst: dst, err: fmt.Errorf("create dst: %s: %w", dst, err)}
return
}
sum := ""
if !*test {
_, sum, err = copyhash(dfd, sfd)
}
if err == nil {
sfd.Close()
if err = dfd.Close(); err != nil {
err = fmt.Errorf("copy dst: %s: %w", dst, err)
}
}
ec <- work{src: src, dst: dst, sum: sum, err: err}
}
}
func list(src ...string) {
var fatal error
for _, src := range src {
sfs := driver[uri(src).Scheme]
if sfs == nil {
log.Fatal.F("src: scheme not supported: %s", src)
}
dir, err := sfs.List(src)
if err != nil {
log.Error.F("list error: %q: %v", src, err)
fatal = err
continue
}
if *rel {
for _, f := range dir {
fmt.Printf("%d\t%s\n", f.Size, f.Path)
}
} else {
for _, f := range dir {
fmt.Printf("%d\t%s\n", f.Size, f.URL)
}
}
}
if fatal != nil {
log.Fatal.Add("err", fatal).Printf("")
}
}
func dodelete(src ...string) {
var fatal error
for _, src := range src {
sfs := driver[uri(src).Scheme]
if sfs == nil {
log.Fatal.F("src: scheme not supported: %s", src)
}
err := sfs.Delete(src)
if err != nil {
log.Error.F("delete error: %q: %v", src, err)
fatal = err
continue
}
}
if fatal != nil {
log.Fatal.Add("err", fatal).Printf("")
}
}
var temps = []string{}
func main() {
defer log.Trap()
defer closeAll()
flag.Parse()
if *version {
fmt.Println(Version)
os.Exit(0)
}
temps = strings.Split(*tmp, ",")
log.DebugOn = *debug
if *ipv4 {
dial := func(network, addr string) (conn net.Conn, err error) {
conn, err = net.Dial(network, addr)
line := log.Debug.Add("action", "dial", "network", network, "addr", addr)
if err != nil {
line.Error().Printf("connection failed: %s", err)
return
}
line = line.Add("laddr", conn.LocalAddr().String())
line = line.Add("raddr", conn.RemoteAddr().String())
if strings.HasPrefix(conn.RemoteAddr().String(), "[") {
line.Printf("skipping ipv6")
conn.Close()
return nil, errors.New("ipv6 disabled")
}
line.Printf("connected")
return conn, err
}
http.DefaultClient.Transport = &http.Transport{Dial: dial, ForceAttemptHTTP2: true}
}
sema = make(chan bool, *maxhttp)
a := flag.Args()
if *ls {
list(a...)
os.Exit(0)
}
if *del {
dodelete(a...)
os.Exit(0)
}
if *sign {
type S interface {
Sign(uri string) (string, error)
}
for _, src := range a {
s, _ := driver[uri(src).Scheme].(S)
if s != nil {
su, err := s.Sign(src)
if err == nil {
src = su
}
}
fmt.Println(src)
}
os.Exit(0)
}
if len(a) != 2 {
log.Fatal.F("usage: ccp src... dst")
}
sfs, dfs := driver[uri(a[0]).Scheme], driver[uri(a[1]).Scheme]
if sfs == nil {
log.Fatal.F("src: scheme not supported: %s", a[0])
}
if dfs == nil {
log.Fatal.F("dst: scheme not supported: %s", a[1])
}
var (
list []Info
err error
)
if strings.HasSuffix(uri(a[0]).Path, "/") {
// If it ends in a slash, its obviously a directory
// and recursion is implied.
*recurse = true
}
if a[0] == "-" && *stdinlist {
sc := bufio.NewScanner(os.Stdin)
for sc.Scan() {
info := Info{}
v := strings.Split(sc.Text(), "\t")
if len(v) > 1 {
info.Size, _ = strconv.Atoi(v[0])
v[0] = v[1]
}
u := uri(v[0])
info.URL = &u
list = append(list, info)
}
a[0] = commonPrefix(list...)
if len(list) == 1 {
a[0] = path.Dir(a[0])
}
} else if *recurse {
list, err = sfs.List(a[0])
line := log.Error.Add("action", "list", "src", a[0])
if err != nil {
if *flaky {
line.Add("err", err).Printf("list error")
u := uri(a[0])
list = []Info{{URL: &u}}
} else {
line.Fatal().Add("err", err).Printf("")
}
}
} else {
u := uri(a[0])
list = []Info{{URL: &u}}
}
ec := make(chan work)
n := 0
for _, src := range list {
dst := src2dst(a[0], src.String(), a[1])
if *dry {
fmt.Printf("ccp %q %q # %d\n", src, dst.String(), src.Size)
} else {
addquota(src.Size)
go docp(src.String(), dst.String(), ec)
n++
}
}
if *dry {
os.Exit(0)
}
tick := time.NewTicker(time.Second).C
stopmon := make(chan bool)
fatal := make(chan string, 1)
if *deadband != 0 {
go monitor(stopmon, fatal, *deadband)
}
sizecheck := time.After(19 * time.Second)
for i := 0; i < n; {
select {
case <-sizecheck:
if getquota() != 0 {
continue
}
cache.Range(func(key, value interface{}) bool {
n, _ := value.(int)
if *count != 0 {
n = *count
}
addquota(n)
return true
})
case msg := <-fatal:
cleanup()
log.Fatal.F("%s", msg)
case sig := <-killc:
cleanup()
log.Fatal.F("trapped signal: %s", sig)
case w := <-ec:
i++
line := log.Info.Add("action", "copy", "src", w.src, "dst", w.dst, "hashname", *hashname, "hash", w.sum, "err", w.err)
if w.err != nil {
line = log.Error.Add("status", "failed", "err", w.err)
nerr++
if *flaky {
line.Printf("copy error: %s -> %s: %v", w.src, w.dst, w.err)
} else {
cleanup()
line.Fatal().F("copy error: %s -> %s: %v", w.src, w.dst, w.err)
}
} else {
line.Add("status", "done").Printf("")
}
case <-tick:
progress(i, n)
}
}
close(stopmon)
progress(n, n)
if nerr != 0 {
cleanup()
os.Exit(nerr)
}
}
var tmpdir = sync.Map{}
// cleanup removes all registered and undeleted temporary files
func cleanup() {
if *nogc {
return
}
var wg sync.WaitGroup
tmpdir.Range(func(key, value interface{}) bool {
file, _ := key.(string)
if file != "" {
wg.Add(1)
go func() {
log.Debug.F("removing file %s", file)
os.Remove(file)
wg.Done()
}()
}
return true
})
wg.Wait()
}
var nerr = 0
var txquota = int64(0)
var procstart = time.Now()
func monitor(done chan bool, fatal chan string, deadband time.Duration) {
lastn := int64(0)
lastio := time.Now()
exit := func() bool {
select {
case <-done:
return true
default:
}
return false
}
for !exit() {
time.Sleep(time.Second)
rx := atomic.LoadInt64(&iostat.rx)
tx := atomic.LoadInt64(&iostat.tx)
n := rx + tx
if n > lastn {
lastio = time.Now()
lastn = n
continue
}
if time.Since(lastio) < deadband || exit() {
continue
}
fatal <- fmt.Sprintf("io error: pipeline stalled, no rx/tx for %s after %0.3f MiB of io", deadband, float64(n)/1024/1024)
return
}
}
func addquota(n int) {
atomic.AddInt64(&txquota, int64(n))
}
func getquota() int {
return int(atomic.LoadInt64(&txquota))
}
func progress(done, total int) {
rx := atomic.LoadInt64(&iostat.rx)
tx := atomic.LoadInt64(&iostat.tx)
dur := time.Since(procstart)
bps := int64(0)
if s := dur / time.Second; s > 0 {
bps = tx / int64(s)
}
prog := int64(0)
txquota := getquota()
if txquota != 0 {
prog = tx * 100 / int64(txquota)
if prog > 100 {
prog = 100
}
}
if !*quiet {
log.Info.Add(
"rx", rx,
"tx", tx,
"total", txquota,
"file.done", done,
"file.total", total,
"file.errors", nerr,
"mbps", bps/(1024*1024),
"progress", prog,
"uptime", dur.Seconds(),
).Printf("")
}
}
type work struct {
err error
src, dst, sum string
}
func src2dst(prefix, src, dst string) url.URL {
su := uri(src)
du := uri(dst)
su.Path = strings.TrimPrefix(su.Path, uri(prefix).Path)
du.Path = path.Join(du.Path, su.Path)
return du
}
type Info struct {
// invariant: *url.URL is never nil
*url.URL
Size int
}
func prefix(path string) string {
n := strings.IndexAny(path, "*?[")
if n > 0 {
path = path[:n]
}
n = strings.LastIndex(path, "/")
if n > 0 {
path = path[:n]
}
return path
}
func uri(s string) url.URL {
u, _ := url.Parse(s)
if u == nil {
return url.URL{}
}
return *u
}
func paths(file ...Info) (p []string) {
for _, v := range file {
p = append(p, v.Path)
}
return p
}
func commonPrefix(file ...Info) string {
if len(file) == 0 {
return ""
}
list := paths(file...)
min := strings.Split(list[0], "/")
for _, p := range list {
if len(min) == 0 {
break
}
a := strings.Split(p, "/")
if len(a) < len(min) {
a, min = min, a
}
n := 0
for ; n < len(min) && min[n] == a[n]; n++ {
}
min = min[:n]
}
return path.Join(append([]string{"/"}, min...)...)
}