forked from troubling/nectar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.go
2315 lines (2267 loc) · 76.1 KB
/
cli.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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package nectar
import (
"bytes"
"encoding/csv"
"flag"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/gholt/brimtext"
)
type CLIInstance struct {
Arg0 string
fatal func(cli *CLIInstance, err error)
fatalf func(cli *CLIInstance, frmt string, args ...interface{})
verbosef func(cli *CLIInstance, frmt string, args ...interface{})
GlobalFlags *flag.FlagSet
globalFlagAuthURL *string
globalFlagAuthTenant *string
globalFlagAuthUser *string
globalFlagAuthKey *string
globalFlagAuthPassword *string
globalFlagOverrideURLs *string
globalFlagStorageRegion *string
GlobalFlagVerbose *bool
globalFlagContinueOnError *bool
globalFlagConcurrency *int
globalFlagInternalStorage *bool
globalFlagHeaders stringListFlag
BenchDeleteFlags *flag.FlagSet
benchDeleteFlagContainers *int
benchDeleteFlagCount *int
benchDeleteFlagCSV *string
benchDeleteFlagCSVOT *string
BenchGetFlags *flag.FlagSet
benchGetFlagContainers *int
benchGetFlagCount *int
benchGetFlagCSV *string
benchGetFlagCSVOT *string
benchGetFlagIterations *int
BenchHeadFlags *flag.FlagSet
benchHeadFlagContainers *int
benchHeadFlagCount *int
benchHeadFlagCSV *string
benchHeadFlagCSVOT *string
benchHeadFlagIterations *int
BenchMixedFlags *flag.FlagSet
benchMixedFlagContainers *int
benchMixedFlagCSV *string
benchMixedFlagCSVOT *string
benchMixedFlagSize *int
benchMixedFlagTime *string
BenchPostFlags *flag.FlagSet
benchPostFlagContainers *int
benchPostFlagCount *int
benchPostFlagCSV *string
benchPostFlagCSVOT *string
BenchPutFlags *flag.FlagSet
benchPutFlagContainers *int
benchPutFlagCount *int
benchPutFlagCSV *string
benchPutFlagCSVOT *string
benchPutFlagSize *int
benchPutFlagMaxSize *int
DownloadFlags *flag.FlagSet
downloadFlagAccount *bool
GetFlags *flag.FlagSet
getFlagRaw *bool
getFlagNameOnly *bool
getFlagMarker *string
getFlagEndMarker *string
getFlagReverse *bool
getFlagLimit *int
getFlagPrefix *string
getFlagDelimiter *string
}
// CLI runs a nectar command-line-interface with the given args (args[0] should
// have the name of the executable). The fatal, fatalf, and verbosef parameters
// may be nil for the defaults. The default fatal and fatalf functions will
// call os.Exit(1) after emitting error (or help) text.
func CLI(args []string, fatal func(cli *CLIInstance, err error), fatalf func(cli *CLIInstance, frmt string, args ...interface{}), verbosef func(cli *CLIInstance, frmt string, args ...interface{})) {
if fatal == nil {
fatal = cliFatal
}
if fatalf == nil {
fatalf = cliFatalf
}
if verbosef == nil {
verbosef = cliVerbosef
}
cli := &CLIInstance{Arg0: args[0], fatal: fatal, fatalf: fatalf, verbosef: verbosef}
var flagbuf bytes.Buffer
cli.GlobalFlags = flag.NewFlagSet(cli.Arg0, flag.ContinueOnError)
cli.GlobalFlags.SetOutput(&flagbuf)
cli.globalFlagAuthURL = cli.GlobalFlags.String("A", os.Getenv("AUTH_URL"), "|<url>| URL to auth system, example: http://127.0.0.1:8080/auth/v1.0 - Env: AUTH_URL")
cli.globalFlagAuthTenant = cli.GlobalFlags.String("T", os.Getenv("AUTH_TENANT"), "|<tenant>| Tenant name for auth system, example: test - Not all auth systems need this. Env: AUTH_TENANT")
cli.globalFlagAuthUser = cli.GlobalFlags.String("U", os.Getenv("AUTH_USER"), "|<user>| User name for auth system, example: tester - Some auth systems allow tenant:user format here, example: test:tester - Env: AUTH_USER")
cli.globalFlagAuthKey = cli.GlobalFlags.String("K", os.Getenv("AUTH_KEY"), "|<key>| Key for auth system, example: testing - Some auth systems use passwords instead, see -P - Env: AUTH_KEY")
cli.globalFlagAuthPassword = cli.GlobalFlags.String("P", os.Getenv("AUTH_PASSWORD"), "|<password>| Password for auth system, example: testing - Some auth system use keys instead, see -K - Env: AUTH_PASSWORD")
cli.globalFlagOverrideURLs = cli.GlobalFlags.String("O", os.Getenv("OVERRIDE_URLS"), "|<url> [url] ...| Override URLs for service endpoint(s); the service endpoint given by auth will be ignored - Env: OVERRIDE_URLS")
cli.globalFlagStorageRegion = cli.GlobalFlags.String("R", os.Getenv("STORAGE_REGION"), "|<region>| Storage region to use if set, otherwise uses the default. Env: STORAGE_REGION")
cli.GlobalFlagVerbose = cli.GlobalFlags.Bool("v", false, "Will activate verbose output.")
cli.globalFlagContinueOnError = cli.GlobalFlags.Bool("continue-on-error", false, "When possible, continue with additional operations even if one or more fail.")
i32, _ := strconv.ParseInt(os.Getenv("CONCURRENCY"), 10, 32)
cli.globalFlagConcurrency = cli.GlobalFlags.Int("C", int(i32), "|<number>| The maximum number of concurrent operations to perform; default is 1. Env: CONCURRENCY")
b, _ := strconv.ParseBool(os.Getenv("STORAGE_INTERNAL"))
cli.globalFlagInternalStorage = cli.GlobalFlags.Bool("I", b, "Internal storage URL resolution, such as Rackspace ServiceNet. Env: STORAGE_INTERNAL")
cli.GlobalFlags.Var(&cli.globalFlagHeaders, "H", "|<name>:[value]| Sets a header to be sent with the request. Useful mostly for PUTs and POSTs, allowing you to set metadata. This option can be specified multiple times for additional headers.")
cli.BenchDeleteFlags = flag.NewFlagSet("bench-delete", flag.ContinueOnError)
cli.BenchDeleteFlags.SetOutput(&flagbuf)
cli.benchDeleteFlagContainers = cli.BenchDeleteFlags.Int("containers", 1, "|<number>| Number of containers in use.")
cli.benchDeleteFlagCount = cli.BenchDeleteFlags.Int("count", 1000, "|<number>| Number of objects to delete, distributed across containers.")
cli.benchDeleteFlagCSV = cli.BenchDeleteFlags.String("csv", "", "|<filename>| Store the timing of each delete into a CSV file.")
cli.benchDeleteFlagCSVOT = cli.BenchDeleteFlags.String("csvot", "", "|<filename>| Store the number of deletes performed over time into a CSV file.")
cli.BenchGetFlags = flag.NewFlagSet("bench-get", flag.ContinueOnError)
cli.BenchGetFlags.SetOutput(&flagbuf)
cli.benchGetFlagContainers = cli.BenchGetFlags.Int("containers", 1, "|<number>| Number of containers to use.")
cli.benchGetFlagCount = cli.BenchGetFlags.Int("count", 1000, "|<number>| Number of objects to get, distributed across containers.")
cli.benchGetFlagCSV = cli.BenchGetFlags.String("csv", "", "|<filename>| Store the timing of each get into a CSV file.")
cli.benchGetFlagCSVOT = cli.BenchGetFlags.String("csvot", "", "|<filename>| Store the number of gets performed over time into a CSV file.")
cli.benchGetFlagIterations = cli.BenchGetFlags.Int("iterations", 1, "|<number>| Number of iterations to perform.")
cli.BenchHeadFlags = flag.NewFlagSet("bench-head", flag.ContinueOnError)
cli.BenchHeadFlags.SetOutput(&flagbuf)
cli.benchHeadFlagContainers = cli.BenchHeadFlags.Int("containers", 1, "|<number>| Number of containers to use.")
cli.benchHeadFlagCount = cli.BenchHeadFlags.Int("count", 1000, "|<number>| Number of objects to head, distributed across containers.")
cli.benchHeadFlagCSV = cli.BenchHeadFlags.String("csv", "", "|<filename>| Store the timing of each head into a CSV file.")
cli.benchHeadFlagCSVOT = cli.BenchHeadFlags.String("csvot", "", "|<filename>| Store the number of heads performed over time into a CSV file.")
cli.benchHeadFlagIterations = cli.BenchHeadFlags.Int("iterations", 1, "|<number>| Number of iterations to perform.")
cli.BenchMixedFlags = flag.NewFlagSet("bench-mixed", flag.ContinueOnError)
cli.BenchMixedFlags.SetOutput(&flagbuf)
cli.benchMixedFlagContainers = cli.BenchMixedFlags.Int("containers", 1, "|<number>| Number of containers to use.")
cli.benchMixedFlagCSV = cli.BenchMixedFlags.String("csv", "", "|<filename>| Store the timing of each request into a CSV file.")
cli.benchMixedFlagCSVOT = cli.BenchMixedFlags.String("csvot", "", "|<filename>| Store the number of requests performed over time into a CSV file.")
cli.benchMixedFlagSize = cli.BenchMixedFlags.Int("size", 4096, "|<bytes>| Number of bytes for each object.")
cli.benchMixedFlagTime = cli.BenchMixedFlags.String("time", "10m", "|<timespan>| Amount of time to run the test, such as 10m or 1h.")
cli.BenchPostFlags = flag.NewFlagSet("bench-post", flag.ContinueOnError)
cli.BenchPostFlags.SetOutput(&flagbuf)
cli.benchPostFlagContainers = cli.BenchPostFlags.Int("containers", 1, "|<number>| Number of containers in use.")
cli.benchPostFlagCount = cli.BenchPostFlags.Int("count", 1000, "|<number>| Number of objects to post, distributed across containers.")
cli.benchPostFlagCSV = cli.BenchPostFlags.String("csv", "", "|<filename>| Store the timing of each post into a CSV file.")
cli.benchPostFlagCSVOT = cli.BenchPostFlags.String("csvot", "", "|<filename>| Store the number of posts performed over time into a CSV file.")
cli.BenchPutFlags = flag.NewFlagSet("bench-put", flag.ContinueOnError)
cli.BenchPutFlags.SetOutput(&flagbuf)
cli.benchPutFlagContainers = cli.BenchPutFlags.Int("containers", 1, "|<number>| Number of containers to use.")
cli.benchPutFlagCount = cli.BenchPutFlags.Int("count", 1000, "|<number>| Number of objects to PUT, distributed across containers.")
cli.benchPutFlagCSV = cli.BenchPutFlags.String("csv", "", "|<filename>| Store the timing of each PUT into a CSV file.")
cli.benchPutFlagCSVOT = cli.BenchPutFlags.String("csvot", "", "|<filename>| Store the number of PUTs performed over time into a CSV file.")
cli.benchPutFlagSize = cli.BenchPutFlags.Int("size", 4096, "|<bytes>| Number of bytes for each object.")
cli.benchPutFlagMaxSize = cli.BenchPutFlags.Int("maxsize", 0, "|<bytes>| This option will vary object sizes randomly between -size and -maxsize")
cli.DownloadFlags = flag.NewFlagSet("download", flag.ContinueOnError)
cli.DownloadFlags.SetOutput(&flagbuf)
cli.downloadFlagAccount = cli.DownloadFlags.Bool("a", false, "Indicates you truly wish to download the entire account; this is to prevent accidentally doing so when giving a single parameter to download.")
cli.GetFlags = flag.NewFlagSet("get", flag.ContinueOnError)
cli.GetFlags.SetOutput(&flagbuf)
cli.getFlagRaw = cli.GetFlags.Bool("r", false, "Emit raw results")
cli.getFlagNameOnly = cli.GetFlags.Bool("n", false, "In listings, emits the names only")
cli.getFlagMarker = cli.GetFlags.String("marker", "", "|<text>| In listings, sets the start marker")
cli.getFlagEndMarker = cli.GetFlags.String("endmarker", "", "|<text>| In listings, sets the stop marker")
cli.getFlagReverse = cli.GetFlags.Bool("reverse", false, "In listings, reverses the order")
cli.getFlagLimit = cli.GetFlags.Int("limit", 0, "|<number>| In listings, limits the results")
cli.getFlagPrefix = cli.GetFlags.String("prefix", "", "|<text>| In listings, returns only those matching the prefix")
cli.getFlagDelimiter = cli.GetFlags.String("delimiter", "", "|<text>| In listings, sets the delimiter and activates delimiter listings")
if err := cli.GlobalFlags.Parse(args[1:]); err != nil || len(cli.GlobalFlags.Args()) == 0 {
cli.fatal(cli, err)
}
if *cli.globalFlagAuthURL == "" {
cli.fatalf(cli, "No Auth URL set; use -A\n")
}
if *cli.globalFlagAuthUser == "" {
cli.fatalf(cli, "No Auth User set; use -U\n")
}
if *cli.globalFlagAuthKey == "" && *cli.globalFlagAuthPassword == "" {
cli.fatalf(cli, "No Auth Key or Password set; use -K or -P\n")
}
c, resp := NewClient(*cli.globalFlagAuthTenant, *cli.globalFlagAuthUser, *cli.globalFlagAuthPassword, *cli.globalFlagAuthKey, *cli.globalFlagStorageRegion, *cli.globalFlagAuthURL, *cli.globalFlagInternalStorage, strings.Split(*cli.globalFlagOverrideURLs, " "))
if resp != nil {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
cli.fatalf(cli, "Auth responded with %d %s - %s\n", resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
cmd := ""
args = append([]string{}, cli.GlobalFlags.Args()...)
if len(args) > 0 {
cmd = args[0]
args = args[1:]
}
switch cmd {
case "auth":
cli.auth(c, args)
case "bench-delete":
cli.benchDelete(c, args)
case "bench-get":
cli.benchGet(c, args)
case "bench-head":
cli.benchHead(c, args)
case "bench-mixed":
cli.benchMixed(c, args)
case "bench-post":
cli.benchPost(c, args)
case "bench-put":
cli.benchPut(c, args)
case "delete":
cli.delet(c, args)
case "download":
cli.download(c, args)
case "get":
cli.get(c, args)
case "head":
cli.head(c, args)
case "post":
cli.post(c, args)
case "put":
cli.put(c, args)
case "upload":
cli.upload(c, args)
default:
cli.fatalf(cli, "Unknown command: %s\n", cmd)
}
}
func cliFatal(cli *CLIInstance, err error) {
if err == flag.ErrHelp || err == nil {
fmt.Println(cli.Arg0, `[options] <subcommand> ...`)
fmt.Println(brimtext.Wrap(`
Tool for accessing a Hummingbird/Swift cluster. Some global options can also be set via environment variables. These will be noted at the end of the description with Env: NAME. The following global options are available:
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.GlobalFlags))
fmt.Println()
fmt.Println(brimtext.Wrap(`
The following subcommands are available:`, 0, "", ""))
fmt.Println("\nauth")
fmt.Println(brimtext.Wrap(`
Displays information retrieved after authentication, such as the Account URL.
`, 0, " ", " "))
fmt.Println("\nbench-delete [options] <container> [object]")
fmt.Println(brimtext.Wrap(`
Benchmark tests DELETEs. By default, 1000 DELETEs are done against the named <container>. If you specify [object] it will be used as a prefix for the object names, otherwise "bench-" will be used. Generally, you would use bench-put to populate the containers and objects, and then use bench-delete with the same options to test the deletions.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.BenchDeleteFlags))
fmt.Println("\nbench-get [options] <container> [object]")
fmt.Println(brimtext.Wrap(`
Benchmark tests GETs. By default, 1000 GETs are done from the named <container>. If you specify [object] it will be used as the prefix for the object names, otherwise "bench-" will be used. Generally, you would use bench-put to populate the containers and objects, and then use bench-get with the same options with the possible addition of -iterations to lengthen the test time.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.BenchGetFlags))
fmt.Println("\nbench-head [options] <container> [object]")
fmt.Println(brimtext.Wrap(`
Benchmark tests HEADs. By default, 1000 HEADs are done from the named <container>. If you specify [object] it will be used as the prefix for the object names, otherwise "bench-" will be used. Generally, you would use bench-put to populate the containers and objects, and then use bench-head with the same options with the possible addition of -iterations to lengthen the test time.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.BenchHeadFlags))
fmt.Println("\nbench-mixed [options] <container> [object]")
fmt.Println(brimtext.Wrap(`
Benchmark tests mixed request workloads. If you specify [object] it will be used as a prefix for the object names, otherwise "bench-" will be used. This test is made to be run for a specific span of time (10 minutes by default). You probably want to run with the -continue-on-error global flag; due to the eventual consistency model of Swift|Hummingbird, a few requests may 404.
Note: The concurrency setting for this test will be used for each request type separately. So, with five request types (PUT, POST, GET, HEAD, DELETE), this means five times the concurrency value specified.
`, 0, " ", " "))
fmt.Println()
fmt.Print(cli.HelpFlags(cli.BenchMixedFlags))
fmt.Println("\nbench-post [options] <container> [object]")
fmt.Println(brimtext.Wrap(`
Benchmark tests POSTs. By default, 1000 POSTs are done against the named <container>. If you specify [object] it will be used as a prefix for the object names, otherwise "bench-" will be used. Generally, you would use bench-put to populate the containers and objects, and then use bench-post with the same options to test POSTing.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.BenchPostFlags))
fmt.Println("\nbench-put [options] <container> [object]")
fmt.Println(brimtext.Wrap(`
Benchmark tests PUTs. By default, 1000 PUTs are done into the named <container>. If you specify [object] it will be used as a prefix for the object names, otherwise "bench-" will be used.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.BenchPutFlags))
fmt.Println("\ndelete [container] [object]")
fmt.Println(brimtext.Wrap(`
Performs a DELETE request. A DELETE, as probably expected, is used to remove the target.
`, 0, " ", " "))
fmt.Println("\ndownload [options] [container] [object] <destpath>")
fmt.Println(brimtext.Wrap(`
Downloads an object or objects to a local file or files. The <destpath> indicates where you want the file or files to be created. If you don't give [container] [object] the entire account will be downloaded (requires -a for confirmation). If you just give [container] that entire container will be downloaded. Perhaps obviously, if you give [container] [object] just that object will be downloaded.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.DownloadFlags))
fmt.Println("\nget [options] [container] [object]")
fmt.Println(brimtext.Wrap(`
Performs a GET request. A GET on an account or container will output the listing of containers or objects, respectively. A GET on an object will output the content of the object to standard output.
`, 0, " ", " "))
fmt.Print(cli.HelpFlags(cli.GetFlags))
fmt.Println("\nhead [options] [container] [object]")
fmt.Println(brimtext.Wrap(`
Performs a HEAD request, giving overall information about the account, container, or object.
`, 0, " ", " "))
fmt.Println("\npost [container] [object]")
fmt.Println(brimtext.Wrap(`
Performs a POST request. POSTs allow you to update the metadata for the target.
`, 0, " ", " "))
fmt.Println("\nput [container] [object]")
fmt.Println(brimtext.Wrap(`
Performs a PUT request. A PUT to an account or container will create them. A PUT to an object will create it using the content from standard input.
`, 0, " ", " "))
fmt.Println("\nupload [options] <sourcepath> [container] [object]")
fmt.Println(brimtext.Wrap(`
Uploads local files as objects. If you don't specify [container] the name of the current directory will be used. If you don't specify [object] the relative path name from the current directory will be used. If you do specify [object] while uploading a directory, [object] will be used as a prefix to the resulting object names. Note that when uploading a directory, only regular files will be uploaded.
`, 0, " ", " "))
fmt.Println("\n[container] [object] can also be specified as [container]/[object]")
} else {
msg := err.Error()
if strings.HasPrefix(msg, "flag provided but not defined: ") {
msg = "No such option: " + msg[len("flag provided but not defined: "):]
}
fmt.Fprintln(os.Stderr, msg)
}
os.Exit(1)
}
func cliFatalf(cli *CLIInstance, frmt string, args ...interface{}) {
fmt.Fprintf(os.Stderr, frmt, args...)
os.Exit(1)
}
func cliVerbosef(cli *CLIInstance, frmt string, args ...interface{}) {
if *cli.GlobalFlagVerbose {
fmt.Fprintf(os.Stderr, frmt, args...)
}
}
// HelpFlags returns the formatted help text for the FlagSet given.
func (cli *CLIInstance) HelpFlags(flags *flag.FlagSet) string {
var data [][]string
firstWidth := 0
flags.VisitAll(func(f *flag.Flag) {
n := " -" + f.Name
u := strings.TrimSpace(f.Usage)
if u != "" && u[0] == '|' {
s := strings.SplitN(u, "|", 3)
if len(s) == 3 {
n += " " + strings.TrimSpace(s[1])
u = strings.TrimSpace(s[2])
}
}
if len(n) > firstWidth {
firstWidth = len(n)
}
data = append(data, []string{n, u})
})
opts := brimtext.NewDefaultAlignOptions()
opts.Widths = []int{0, brimtext.GetTTYWidth() - firstWidth - 2}
return brimtext.Align(data, opts)
}
func (cli *CLIInstance) auth(c Client, args []string) {
uc, ok := c.(*userClient)
if ok {
surls := uc.GetURLs()
if len(surls) == 0 {
fmt.Println("Account URL:")
} else if len(surls) == 1 {
fmt.Println("Account URL:", surls[0])
} else {
fmt.Println("Account URLs:", strings.Join(surls, " "))
}
} else {
fmt.Println("Account URL:", c.GetURL())
}
if ct, ok := c.(ClientToken); ok {
fmt.Println("Token:", ct.GetToken())
}
}
func (cli *CLIInstance) benchDelete(c Client, args []string) {
if err := cli.BenchDeleteFlags.Parse(args); err != nil {
cli.fatal(cli, err)
}
container, object := parsePath(cli.BenchDeleteFlags.Args())
if container == "" {
cli.fatalf(cli, "bench-delete requires <container>\n")
}
if object == "" {
object = "bench-"
}
containers := *cli.benchDeleteFlagContainers
if containers < 1 {
containers = 1
}
count := *cli.benchDeleteFlagCount
if count < 1 {
count = 1000
}
var csvw *csv.Writer
var csvlk sync.Mutex
if *cli.benchDeleteFlagCSV != "" {
csvf, err := os.Create(*cli.benchDeleteFlagCSV)
if err != nil {
cli.fatal(cli, err)
}
csvw = csv.NewWriter(csvf)
defer func() {
csvw.Flush()
csvf.Close()
}()
csvw.Write([]string{"completion_time_unix_nano", "object_name", "transaction_id", "status", "elapsed_nanoseconds"})
csvw.Flush()
}
var csvotw *csv.Writer
if *cli.benchDeleteFlagCSVOT != "" {
csvotf, err := os.Create(*cli.benchDeleteFlagCSVOT)
if err != nil {
cli.fatal(cli, err)
}
csvotw = csv.NewWriter(csvotf)
defer func() {
csvotw.Flush()
csvotf.Close()
}()
csvotw.Write([]string{"time_unix_nano", "count_since_last_time"})
csvotw.Write([]string{fmt.Sprintf("%d", time.Now().UnixNano()), "0"})
csvotw.Flush()
}
concurrency := *cli.globalFlagConcurrency
if concurrency < 1 {
concurrency = 1
}
benchChan := make(chan int, concurrency)
wg := sync.WaitGroup{}
wg.Add(concurrency)
for x := 0; x < concurrency; x++ {
go func() {
var start time.Time
for {
i := <-benchChan
if i == 0 {
break
}
i--
deleteContainer := container
if containers > 1 {
deleteContainer = fmt.Sprintf("%s%d", deleteContainer, i%containers)
}
deleteObject := fmt.Sprintf("%s%d", object, i)
cli.verbosef(cli, "DELETE %s/%s\n", deleteContainer, deleteObject)
if csvw != nil {
start = time.Now()
}
resp := c.DeleteObject(deleteContainer, deleteObject, cli.globalFlagHeaders.Headers())
if csvw != nil {
stop := time.Now()
elapsed := stop.Sub(start).Nanoseconds()
csvlk.Lock()
csvw.Write([]string{
fmt.Sprintf("%d", stop.UnixNano()),
deleteContainer + "/" + deleteObject,
resp.Header.Get("X-Trans-Id"),
fmt.Sprintf("%d", resp.StatusCode),
fmt.Sprintf("%d", elapsed),
})
csvw.Flush()
csvlk.Unlock()
}
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if *cli.globalFlagContinueOnError {
fmt.Fprintf(os.Stderr, "DELETE %s/%s - %d %s - %s\n", deleteContainer, deleteObject, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
continue
} else {
cli.fatalf(cli, "DELETE %s/%s - %d %s - %s\n", deleteContainer, deleteObject, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
}
resp.Body.Close()
}
wg.Done()
}()
}
if containers == 1 {
fmt.Printf("Bench-DELETE of %d objects from 1 container, at %d concurrency...", count, concurrency)
} else {
fmt.Printf("Bench-DELETE of %d objects, distributed across %d containers, at %d concurrency...", count, containers, concurrency)
}
ticker := time.NewTicker(time.Minute)
start := time.Now()
lastSoFar := 0
for i := 1; i <= count; i++ {
waiting := true
for waiting {
select {
case <-ticker.C:
soFar := i - concurrency
now := time.Now()
elapsed := now.Sub(start)
fmt.Printf("\n%.05fs for %d DELETEs so far, %.05f DELETEs per second...", float64(elapsed)/float64(time.Second), soFar, float64(soFar)/float64(elapsed/time.Second))
if csvotw != nil {
csvotw.Write([]string{
fmt.Sprintf("%d", now.UnixNano()),
fmt.Sprintf("%d", soFar-lastSoFar),
})
csvotw.Flush()
lastSoFar = soFar
}
case benchChan <- i:
waiting = false
}
}
}
close(benchChan)
wg.Wait()
stop := time.Now()
elapsed := stop.Sub(start)
ticker.Stop()
fmt.Println()
if containers == 1 {
fmt.Printf("Attempting to delete container...")
cli.verbosef(cli, "DELETE %s\n", container)
resp := c.DeleteContainer(container, cli.globalFlagHeaders.Headers())
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
fmt.Fprintf(os.Stderr, "DELETE %s - %d %s - %s\n", container, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
resp.Body.Close()
} else {
fmt.Printf("Attempting to delete the %d containers...", containers)
for x := 0; x < containers; x++ {
deleteContainer := fmt.Sprintf("%s%d", container, x)
cli.verbosef(cli, "DELETE %s\n", deleteContainer)
resp := c.DeleteContainer(deleteContainer, cli.globalFlagHeaders.Headers())
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
fmt.Fprintf(os.Stderr, "DELETE %s - %d %s - %s\n", deleteContainer, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
resp.Body.Close()
}
}
fmt.Println()
fmt.Printf("%.05fs total time, %.05f DELETEs per second.\n", float64(elapsed)/float64(time.Second), float64(count)/float64(elapsed/time.Second))
if csvotw != nil {
csvotw.Write([]string{
fmt.Sprintf("%d", stop.UnixNano()),
fmt.Sprintf("%d", count-lastSoFar),
})
csvotw.Flush()
}
}
func (cli *CLIInstance) benchGet(c Client, args []string) {
if err := cli.BenchGetFlags.Parse(args); err != nil {
cli.fatal(cli, err)
}
container, object := parsePath(cli.BenchGetFlags.Args())
if container == "" {
cli.fatalf(cli, "bench-get requires <container>\n")
}
if object == "" {
object = "bench-"
}
containers := *cli.benchGetFlagContainers
if containers < 1 {
containers = 1
}
count := *cli.benchGetFlagCount
if count < 1 {
count = 1000
}
var csvw *csv.Writer
var csvlk sync.Mutex
if *cli.benchGetFlagCSV != "" {
csvf, err := os.Create(*cli.benchGetFlagCSV)
if err != nil {
cli.fatal(cli, err)
}
csvw = csv.NewWriter(csvf)
defer func() {
csvw.Flush()
csvf.Close()
}()
csvw.Write([]string{"completion_time_unix_nano", "object_name", "transaction_id", "status", "headers_elapsed_nanoseconds", "elapsed_nanoseconds"})
csvw.Flush()
}
var csvotw *csv.Writer
if *cli.benchGetFlagCSVOT != "" {
csvotf, err := os.Create(*cli.benchGetFlagCSVOT)
if err != nil {
cli.fatal(cli, err)
}
csvotw = csv.NewWriter(csvotf)
defer func() {
csvotw.Flush()
csvotf.Close()
}()
csvotw.Write([]string{"time_unix_nano", "count_since_last_time"})
csvotw.Write([]string{fmt.Sprintf("%d", time.Now().UnixNano()), "0"})
csvotw.Flush()
}
iterations := *cli.benchGetFlagIterations
if iterations < 1 {
iterations = 1
}
concurrency := *cli.globalFlagConcurrency
if concurrency < 1 {
concurrency = 1
}
benchChan := make(chan int, concurrency)
wg := sync.WaitGroup{}
wg.Add(concurrency)
for x := 0; x < concurrency; x++ {
go func() {
var start time.Time
var headers_elapsed int64
for {
i := <-benchChan
if i == 0 {
break
}
i--
getContainer := container
if containers > 1 {
getContainer = fmt.Sprintf("%s%d", getContainer, i%containers)
}
getObject := fmt.Sprintf("%s%d", object, i)
cli.verbosef(cli, "GET %s/%s\n", getContainer, getObject)
if csvw != nil {
start = time.Now()
}
resp := c.GetObject(getContainer, getObject, cli.globalFlagHeaders.Headers())
if csvw != nil {
headers_elapsed = time.Now().Sub(start).Nanoseconds()
}
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if *cli.globalFlagContinueOnError {
fmt.Fprintf(os.Stderr, "GET %s/%s - %d %s - %s\n", getContainer, getObject, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
continue
} else {
cli.fatalf(cli, "GET %s/%s - %d %s - %s\n", getContainer, getObject, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
} else {
io.Copy(ioutil.Discard, resp.Body)
}
resp.Body.Close()
if csvw != nil {
stop := time.Now()
elapsed := stop.Sub(start).Nanoseconds()
csvlk.Lock()
csvw.Write([]string{
fmt.Sprintf("%d", stop.UnixNano()),
getContainer + "/" + getObject,
resp.Header.Get("X-Trans-Id"),
fmt.Sprintf("%d", resp.StatusCode),
fmt.Sprintf("%d", headers_elapsed),
fmt.Sprintf("%d", elapsed),
})
csvw.Flush()
csvlk.Unlock()
}
}
wg.Done()
}()
}
if containers == 1 {
fmt.Printf("Bench-GET of %d (%d distinct) objects, from 1 container, at %d concurrency...", iterations*count, count, concurrency)
} else {
fmt.Printf("Bench-GET of %d (%d distinct) objects, distributed across %d containers, at %d concurrency...", iterations*count, count, containers, concurrency)
}
ticker := time.NewTicker(time.Minute)
start := time.Now()
lastSoFar := 0
for iteration := 0; iteration < iterations; iteration++ {
for i := 1; i <= count; i++ {
waiting := true
for waiting {
select {
case <-ticker.C:
soFar := iteration*count + i - concurrency
now := time.Now()
elapsed := now.Sub(start)
fmt.Printf("\n%.05fs for %d GETs so far, %.05f GETs per second...", float64(elapsed)/float64(time.Second), soFar, float64(soFar)/float64(elapsed/time.Second))
if csvotw != nil {
csvotw.Write([]string{
fmt.Sprintf("%d", now.UnixNano()),
fmt.Sprintf("%d", soFar-lastSoFar),
})
csvotw.Flush()
lastSoFar = soFar
}
case benchChan <- i:
waiting = false
}
}
}
}
close(benchChan)
wg.Wait()
stop := time.Now()
elapsed := stop.Sub(start)
ticker.Stop()
fmt.Println()
fmt.Printf("%.05fs total time, %.05f GETs per second.\n", float64(elapsed)/float64(time.Second), float64(iterations*count)/float64(elapsed/time.Second))
if csvotw != nil {
csvotw.Write([]string{
fmt.Sprintf("%d", stop.UnixNano()),
fmt.Sprintf("%d", iterations*count-lastSoFar),
})
csvotw.Flush()
}
}
func (cli *CLIInstance) benchHead(c Client, args []string) {
if err := cli.BenchHeadFlags.Parse(args); err != nil {
cli.fatal(cli, err)
}
container, object := parsePath(cli.BenchHeadFlags.Args())
if container == "" {
cli.fatalf(cli, "bench-head requires <container>\n")
}
if object == "" {
object = "bench-"
}
containers := *cli.benchHeadFlagContainers
if containers < 1 {
containers = 1
}
count := *cli.benchHeadFlagCount
if count < 1 {
count = 1000
}
var csvw *csv.Writer
var csvlk sync.Mutex
if *cli.benchHeadFlagCSV != "" {
csvf, err := os.Create(*cli.benchHeadFlagCSV)
if err != nil {
cli.fatal(cli, err)
}
csvw = csv.NewWriter(csvf)
defer func() {
csvw.Flush()
csvf.Close()
}()
csvw.Write([]string{"completion_time_unix_nano", "object_name", "transaction_id", "status", "headers_elapsed_nanoseconds", "elapsed_nanoseconds"})
csvw.Flush()
}
var csvotw *csv.Writer
if *cli.benchHeadFlagCSVOT != "" {
csvotf, err := os.Create(*cli.benchHeadFlagCSVOT)
if err != nil {
cli.fatal(cli, err)
}
csvotw = csv.NewWriter(csvotf)
defer func() {
csvotw.Flush()
csvotf.Close()
}()
csvotw.Write([]string{"time_unix_nano", "count_since_last_time"})
csvotw.Write([]string{fmt.Sprintf("%d", time.Now().UnixNano()), "0"})
csvotw.Flush()
}
iterations := *cli.benchHeadFlagIterations
if iterations < 1 {
iterations = 1
}
concurrency := *cli.globalFlagConcurrency
if concurrency < 1 {
concurrency = 1
}
benchChan := make(chan int, concurrency)
wg := sync.WaitGroup{}
wg.Add(concurrency)
for x := 0; x < concurrency; x++ {
go func() {
var start time.Time
var headers_elapsed int64
for {
i := <-benchChan
if i == 0 {
break
}
i--
headContainer := container
if containers > 1 {
headContainer = fmt.Sprintf("%s%d", headContainer, i%containers)
}
headObject := fmt.Sprintf("%s%d", object, i)
cli.verbosef(cli, "HEAD %s/%s\n", headContainer, headObject)
if csvw != nil {
start = time.Now()
}
resp := c.HeadObject(headContainer, headObject, cli.globalFlagHeaders.Headers())
if csvw != nil {
headers_elapsed = time.Now().Sub(start).Nanoseconds()
}
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if *cli.globalFlagContinueOnError {
fmt.Fprintf(os.Stderr, "HEAD %s/%s - %d %s - %s\n", headContainer, headObject, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
continue
} else {
cli.fatalf(cli, "HEAD %s/%s - %d %s - %s\n", headContainer, headObject, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
} else {
io.Copy(ioutil.Discard, resp.Body)
}
resp.Body.Close()
if csvw != nil {
stop := time.Now()
elapsed := stop.Sub(start).Nanoseconds()
csvlk.Lock()
csvw.Write([]string{
fmt.Sprintf("%d", stop.UnixNano()),
headContainer + "/" + headObject,
resp.Header.Get("X-Trans-Id"),
fmt.Sprintf("%d", resp.StatusCode),
fmt.Sprintf("%d", headers_elapsed),
fmt.Sprintf("%d", elapsed),
})
csvw.Flush()
csvlk.Unlock()
}
}
wg.Done()
}()
}
if containers == 1 {
fmt.Printf("Bench-HEAD of %d (%d distinct) objects, from 1 container, at %d concurrency...", iterations*count, count, concurrency)
} else {
fmt.Printf("Bench-HEAD of %d (%d distinct) objects, distributed across %d containers, at %d concurrency...", iterations*count, count, containers, concurrency)
}
ticker := time.NewTicker(time.Minute)
start := time.Now()
lastSoFar := 0
for iteration := 0; iteration < iterations; iteration++ {
for i := 1; i <= count; i++ {
waiting := true
for waiting {
select {
case <-ticker.C:
soFar := iteration*count + i - concurrency
now := time.Now()
elapsed := now.Sub(start)
fmt.Printf("\n%.05fs for %d HEADs so far, %.05f HEADs per second...", float64(elapsed)/float64(time.Second), soFar, float64(soFar)/float64(elapsed/time.Second))
if csvotw != nil {
csvotw.Write([]string{
fmt.Sprintf("%d", now.UnixNano()),
fmt.Sprintf("%d", soFar-lastSoFar),
})
csvotw.Flush()
lastSoFar = soFar
}
case benchChan <- i:
waiting = false
}
}
}
}
close(benchChan)
wg.Wait()
stop := time.Now()
elapsed := stop.Sub(start)
ticker.Stop()
fmt.Println()
fmt.Printf("%.05fs total time, %.05f HEADs per second.\n", float64(elapsed)/float64(time.Second), float64(iterations*count)/float64(elapsed/time.Second))
if csvotw != nil {
csvotw.Write([]string{
fmt.Sprintf("%d", stop.UnixNano()),
fmt.Sprintf("%d", iterations*count-lastSoFar),
})
csvotw.Flush()
}
}
func (cli *CLIInstance) benchMixed(c Client, args []string) {
if err := cli.BenchMixedFlags.Parse(args); err != nil {
cli.fatal(cli, err)
}
container, object := parsePath(cli.BenchMixedFlags.Args())
if container == "" {
cli.fatalf(cli, "bench-mixed requires <container>\n")
}
if object == "" {
object = "bench-"
}
containers := *cli.benchMixedFlagContainers
if containers < 1 {
containers = 1
}
size := int64(*cli.benchMixedFlagSize)
if size < 0 {
size = 4096
}
timespan, err := time.ParseDuration(*cli.benchMixedFlagTime)
if err != nil {
cli.fatal(cli, err)
}
const (
delet = iota
get
head
post
put
)
methods := []string{
"DELETE",
"GET",
"HEAD",
"POST",
"PUT",
}
var csvw *csv.Writer
var csvlk sync.Mutex
if *cli.benchMixedFlagCSV != "" {
csvf, err := os.Create(*cli.benchMixedFlagCSV)
if err != nil {
cli.fatal(cli, err)
}
csvw = csv.NewWriter(csvf)
defer func() {
csvw.Flush()
csvf.Close()
}()
csvw.Write([]string{"completion_time_unix_nano", "method", "object_name", "transaction_id", "status", "elapsed_nanoseconds"})
csvw.Flush()
}
var csvotw *csv.Writer
if *cli.benchMixedFlagCSVOT != "" {
csvotf, err := os.Create(*cli.benchMixedFlagCSVOT)
if err != nil {
cli.fatal(cli, err)
}
csvotw = csv.NewWriter(csvotf)
defer func() {
csvotw.Flush()
csvotf.Close()
}()
csvotw.Write([]string{"time_unix_nano", "DELETE", "GET", "HEAD", "POST", "PUT"})
csvotw.Write([]string{fmt.Sprintf("%d", time.Now().UnixNano()), "0", "0", "0", "0", "0", "0"})
csvotw.Flush()
}
if containers == 1 {
fmt.Printf("Ensuring container exists...")
cli.verbosef(cli, "PUT %s\n", container)
resp := c.PutContainer(container, cli.globalFlagHeaders.Headers())
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if *cli.globalFlagContinueOnError {
fmt.Fprintf(os.Stderr, "PUT %s - %d %s - %s\n", container, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
} else {
cli.fatalf(cli, "PUT %s - %d %s - %s\n", container, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
}
resp.Body.Close()
} else {
fmt.Printf("Ensuring %d containers exist...", containers)
for x := 0; x < containers; x++ {
putContainer := fmt.Sprintf("%s%d", container, x)
cli.verbosef(cli, "PUT %s\n", putContainer)
resp := c.PutContainer(putContainer, cli.globalFlagHeaders.Headers())
if resp.StatusCode/100 != 2 {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
if *cli.globalFlagContinueOnError {
fmt.Fprintf(os.Stderr, "PUT %s - %d %s - %s\n", putContainer, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
continue
} else {
cli.fatalf(cli, "PUT %s - %d %s - %s\n", putContainer, resp.StatusCode, http.StatusText(resp.StatusCode), string(bodyBytes))
}
}
resp.Body.Close()
}
}
fmt.Println()
concurrency := *cli.globalFlagConcurrency
if concurrency < 1 {
concurrency = 1