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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
// Copyright 2016 LambdaStack All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![allow(unused_imports)]
#![allow(unused_must_use)]
#![allow(unused_variables)]
#![allow(unused_assignments)]

use std::io;
use std::io::{BufReader, Read, Seek, SeekFrom, Write};
use std::path::Path;
use std::fs;
use std::fs::File;
use std::ffi::OsStr;
use std::time::{Duration, Instant};

use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc::{Sender, Receiver};
use std::sync::mpsc;

use md5;
use term;
use rustc_serialize::json;
use rustc_serialize::base64::{STANDARD, ToBase64};
use chrono::{UTC, DateTime};
use clap::ArgMatches;
use pbr::ProgressBar;

use aws_sdk_rust::aws::errors::s3::S3Error;
use aws_sdk_rust::aws::s3::s3client::S3Client;
use aws_sdk_rust::aws::s3::endpoint::*;
use aws_sdk_rust::aws::common::credentials::{AwsCredentialsProvider, DefaultCredentialsProviderSync};
use aws_sdk_rust::aws::common::region::Region;
use aws_sdk_rust::aws::common::request::DispatchSignedRequest;
use aws_sdk_rust::aws::common::common::Operation;
use aws_sdk_rust::aws::s3::acl::*;
use aws_sdk_rust::aws::s3::bucket::*;
use aws_sdk_rust::aws::s3::object::*;

use lsio::system::{ip, hostname};

use Client;
use Output;
use OutputFormat;
use Commands;
use common::get_bucket;

// 5MB minimum size for multipart_uploads. Only last part can be less.
// const PART_SIZE_MIN: u64 = 5242880;

/// Allows you to control Benchmarking output.
///
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BenchOutput {
    /// Defaults to OutputFormat::plain.
    ///
    /// Available formats are json, plain, serialize or none (don't output anything).
    /// If plain is used then you can serialize structures with format! and then pass the output.
    pub format: OutputFormat,
    /// Can be any term color. Defaults to term::color::GREEN.
    pub color: term::color::Color,
}

/// Allows for duration tracking of operations. You should not track time of this app running but
/// of each operation and then the summation of the durations plus latency etc.
///
#[derive(Debug, Default, Clone, RustcEncodable)]
pub struct BenchOperation {
    /// Time operation occured
    //pub time: String,
    pub start_time: String,
    pub end_time: String,
    /// Request (endpoint + path)
    pub request: String,
    /// Endpoint URL
    pub endpoint: String,
    /// GET, PUT, DELETE...
    pub method: String,
    /// If the operation succeeded or not
    pub success: bool,
    /// HTTP return code
    pub code: u16,
    /// Size of payload
    pub payload_size: u64,
    /// Duration of operation
    pub duration: String,
    /// Object name
    pub object: String,
}

/// A summary of all of the operations for a given thread
///
/// start and and end time DO NOT reflect a true duration. ```The total_duration``` does that.
///
#[derive(Debug, Clone, RustcEncodable)]
pub struct BenchThreadSummary {
    // Thread ID/Name
    pub thread_name: String,
    //pub start_time: String,
    // Time the overall benchmarking ended on a given host/instance
    //pub end_time: String,
    pub total_requests: u64,   // Requests are here for compute reasons
    pub total_success: u64,
    pub total_errors: u64,
    pub total_duration: f64,
    pub total_payload: u64,
    pub total_throughput: f64,
    pub operations: Vec<BenchOperation>,
}

impl BenchThreadSummary {
    pub fn new(thread: BenchThread, operations: Vec<BenchOperation>) -> BenchThreadSummary {
        BenchThreadSummary {
            thread_name: thread.thread_name.clone(),
            //start_time: thread.start_time.clone(),
            //end_time: thread.end_time.clone(),
            total_requests: thread.total_requests,
            total_success: thread.total_success,
            total_errors: thread.total_errors,
            total_duration: thread.total_duration,
            total_payload: thread.total_payload,
            total_throughput: thread.total_throughput,
            operations: operations,
        }
    }
}

// Temporary struct to collect totals for a thread before creating the thread summary
// This is here because json encoding does not support &mut Vec...
#[derive(Debug, Default, Clone)]
pub struct BenchThread {
    // Thread ID/Name
    pub thread_name: String,
    //pub start_time: String,
    // Time the overall benchmarking ended on a given host/instance
    //pub end_time: String,
    pub total_requests: u64,   // Requests are here for compute reasons
    pub total_success: u64,
    pub total_errors: u64,
    pub total_duration: f64,
    pub total_payload: u64,
    pub total_throughput: f64,
}

/// A summary of all threads on a given node/instance
///
/// NOTE: The start and end times DO NOT reflect a true duration. They represent the overall time
/// block to execute the operations and compute the results for the given node/instance.
/// ```Total_duration``` is the number of seconds.nanoseconds of actual execution time.
///
/// NOTE: Simple types are used here to make serialization easy.
/// start and and end time DO NOT reflect a true duration. The ```total_duration``` does that.
///
#[derive(Debug, Clone, RustcEncodable)]
pub struct BenchHostInstanceSummary {
    pub host_instance: String,
    pub ip_address: String,
    // Time the benchmarking started on a given host/instance
    pub start_time: String,
    // Time the overall benchmarking ended on a given host/instance
    pub end_time: String,
    pub total_requests: u64,  //Total requests from the sum of the total BenchThreadSummaries
    pub total_success: u64,
    pub total_errors: u64,
    pub total_duration: f64,
    pub total_payload: u64,
    pub total_throughput: f64,
    pub total_threads: u64,
    pub host_duration:f64,
    // Collect metadata of node/vm such as ohai data
    //pub host_instance_metadata: String,
    pub operations: Vec<BenchThreadSummary>
}

impl BenchHostInstanceSummary {
    pub fn new(operations: Vec<BenchThreadSummary>) -> BenchHostInstanceSummary {
        BenchHostInstanceSummary {
            host_instance: "".to_string(),
            ip_address: "".to_string(),
            start_time: "".to_string(),
            end_time: "".to_string(),
            total_requests: 0,
            total_success: 0,
            total_errors: 0,
            total_duration: 0.0,
            total_payload: 0,
            total_throughput: 0.0,
            total_threads: 0,
            host_duration: 0.0,
            operations: operations,
        }
    }
}

/// A summary of all of the hosts used in the benchmarking process.
///
/// start and and end time DO NOT reflect a true duration. The ```total_duration``` does that.
///
#[derive(Debug, Clone, RustcEncodable)]
pub struct BenchSummary {
    // Earliest time benchmarking started on a given host/instance
    pub start_time: String,
    // Time the overall benchmarking ended on a given host/instance
    pub end_time: String,
    pub total_requests: u64,   // Total requests from all of the nodes/instances
    pub total_success: u64,
    pub total_errors: u64,
    pub total_duration: f64,
    pub total_payload: u64,
    pub total_host_instances: u64,
    pub total_threads: u64,    // Total threads that were part of the benchmarking
    pub total_throughput: f64,
    pub operations: Option<Vec<BenchHostInstanceSummary>>,
}

/// BenchSummary::new
///
impl BenchSummary {
    pub fn new(operations: Vec<BenchHostInstanceSummary>) -> BenchSummary {
        BenchSummary {
            start_time: "".to_string(),
            end_time: "".to_string(),
            total_requests: 0,
            total_success: 0,
            total_errors: 0,
            total_duration: 0.0,
            total_payload: 0,
            total_host_instances: 0,
            total_threads: 0,
            total_throughput: 0.0,
            operations: Some(operations),
        }
    }
}

/// Metadata for the Benchmarking request.
///
/// iterations - how many iterations to perform. This should be 0 if duration is not 0
/// duration - how many seconds to perform operations. This should be 0 if iterations is not 0
/// ```virtual_users``` - how many simulated users (threads to perform)
/// nodes - how many hosts/VMs to run these operations on
#[derive(Debug, Clone, RustcEncodable)]
pub struct BenchRequest {
    pub date_time: String,
    pub description: String,
    pub endpoint: String,
    pub report: String,
    pub iterations: u64,
    pub duration: u64,
    pub virtual_users: u32,
    pub rampup: u32,
    pub request_type: String,
    pub size: u64,
    pub size_of_parts: u64,
    pub nodes: u32,
    pub virtual_buckets: bool,
    pub keep_alive: bool,
}

/// Allows for duration tracking of operations. You should not track time of this app running but
/// of each operation and then the summation of the durations plus latency etc.
///
#[derive(Debug, Clone, RustcEncodable)]
pub struct BenchResults {
    pub request: BenchRequest,
    pub summary: BenchSummary,
}

/// BenchResults::new
///
impl BenchResults {
    pub fn new(request: BenchRequest, summary: BenchSummary) -> BenchResults {
        BenchResults {
            request: request,
            summary: summary,
        }
    }
}

/// Benchmarking - Function that starts the benchmarking process with values passed in
///
pub fn benchmarking<'a, P, D>(matches: &ArgMatches,
                              bench: Option<&str>,
                              ep_str: Option<&str>,
                              is_bucket_virtual: bool,
                              keep_alive: bool,
                              bench_output: BenchOutput,
                              client: &Client<P, D>)
                              -> Result<(), S3Error>
                              where P: AwsCredentialsProvider + Sync + Send,
                                    D: DispatchSignedRequest + Sync + Send,
{
    let endpoint_clone = client.s3client.endpoint().clone();
    let mut bench_tmp_dir: &str = "";
    let options: Vec<&str> = bench.unwrap().split(':').collect();

    // NB: Duration tests create one s3client per thread while iteration tests create a new s3client per requests per thread.
    // NOTE: Fix - Iterate over this and create defaults...
    let duration: u64 = options[0].parse().unwrap_or(0);
    let iterations: u64 = options[1].parse().unwrap_or(0);
    let virtual_users: u32 = options[2].parse().unwrap_or(0);
    let nodes: u32 = options[3].parse().unwrap_or(1);
    let rampup: u32 = options[4].parse().unwrap_or(0);
    let mut report: &str = options[5];
    if report.is_empty() {
        report = "d"; // Detail
    }
    let report_desc = match report {
        "s" | "S" => "Summary Report",
        _ => "Detail Report",
    };

    // Just default to AWS S3 Standard for now if nothing else
    let ep = match ep_str {
        Some(val) => val,
        _ => "https://s3.amazonaws.com",
    };

    let res = match matches.subcommand() {
        ("get", Some(sub_matches)) => {
            // This part would go into each host instance
            let bench_request = BenchRequest{description: "Benchmarking GET requests...".to_string(),
                                             date_time: UTC::now().to_string(),
                                             endpoint: ep.to_string(),
                                             report: report_desc.to_string(),
                                             iterations: iterations,
                                             duration: duration,
                                             virtual_users: virtual_users,
                                             request_type: "GET".to_string(),
                                             rampup: rampup,
                                             size: 0,
                                             size_of_parts: 0,
                                             virtual_buckets: is_bucket_virtual,
                                             keep_alive: keep_alive,
                                             nodes: nodes};
            let bench_host_instance_summary = host_controller(sub_matches, Commands::get, duration, nodes, iterations, keep_alive, virtual_users, 0, endpoint_clone);
            // It would then send the bench_host_instance_summary back to the master and process
            if bench_host_instance_summary.is_some() {
                master_benchmark(bench_request, bench_output, bench_host_instance_summary.unwrap());
            }
            Ok(())
        },
        ("put", Some(sub_matches)) => {
            let size: u64 = sub_matches.value_of("size").unwrap_or("4096").parse().unwrap_or(4096);
            let size_of_parts: u64 = sub_matches.value_of("size_of_parts").unwrap_or("5242880").parse().unwrap();
            let bench_request = BenchRequest{description: "Benchmarking PUT requests...".to_string(),
                                             date_time: UTC::now().to_string(),
                                             endpoint: ep.to_string(),
                                             report: report_desc.to_string(),
                                             iterations: iterations,
                                             duration: duration,
                                             virtual_users: virtual_users,
                                             request_type: "PUT".to_string(),
                                             rampup: rampup,
                                             size: size,
                                             size_of_parts: size_of_parts,
                                             virtual_buckets: is_bucket_virtual,
                                             keep_alive: keep_alive,
                                             nodes: nodes};
            let bench_host_instance_summary = host_controller(sub_matches, Commands::put, duration, nodes, iterations, keep_alive, virtual_users, size, endpoint_clone);
            if bench_host_instance_summary.is_some() {
                master_benchmark(bench_request, bench_output, bench_host_instance_summary.unwrap());
            }
            Ok(())
        },
        ("gen", Some(sub_matches)) => {
            // NB: Not really needed unless you want to keep files around OR you want to
            // generate a lot files and then shard the put or get requests so that each
            // thread gets or puts a group of files.
            bench_tmp_dir = sub_matches.value_of("path").unwrap_or(".s3lsio_tmp");
            let size: u64 = sub_matches.value_of("size").unwrap_or("4096").parse().unwrap_or(4096);
            let gen_result = gen_files(bench_tmp_dir, "file", iterations, size);
            Ok(())
        }
        ("range", Some(sub_matches)) => {
            let bench_request = BenchRequest{description: "Benchmarking Byte-Range requests...".to_string(),
                                             date_time: UTC::now().to_string(),
                                             endpoint: ep.to_string(),
                                             report: report_desc.to_string(),
                                             iterations: iterations,
                                             duration: duration,
                                             virtual_users: virtual_users,
                                             request_type: "BYTE-RANGE".to_string(),
                                             rampup: rampup,
                                             size: 0,
                                             size_of_parts: 0,
                                             virtual_buckets: is_bucket_virtual,
                                             keep_alive: keep_alive,
                                             nodes: nodes};
            let bench_host_instance_summary = host_controller(sub_matches, Commands::range, duration, nodes, iterations, keep_alive, virtual_users, 0, endpoint_clone);
            if bench_host_instance_summary.is_some() {
                master_benchmark(bench_request, bench_output, bench_host_instance_summary.unwrap());
            }
            Ok(())
        },
        (e, _) => {
            println_color_quiet!(client.is_quiet, term::color::RED, "{}", e);
            Err(S3Error::new("A valid benchmarking instruction is required (inner)"))
        },
    };

    // Clean up
    if !bench_tmp_dir.is_empty() {
        let result = fs::remove_dir_all(bench_tmp_dir);
    }

    Ok(())
}

pub fn do_get_bench<'a>(bucket: &str,
                        base_object_name: &str,
                        duration: Duration,
                        iterations: u64,
                        keep_alive: bool,
                        range: Option<&'a str>,
                        endpoint: Endpoint,
                        operations: &'a mut Vec<Operation>) -> Result<(), S3Error>
{
    let mut object: String;
    let mut provider: DefaultCredentialsProviderSync;
    let mut local_endpoint: Endpoint;
    let mut s3client: S3Client<_,_>;
    let mut request: GetObjectRequest;

    if iterations > 0 {
        // Allocate here anyway...
        provider = DefaultCredentialsProviderSync::new(None).unwrap();
        local_endpoint = endpoint.clone();
        s3client = S3Client::new(provider, local_endpoint);

        request = GetObjectRequest::default();
        request.bucket = bucket.to_string();
        if range.is_some() {
            request.range = Some(range.unwrap().clone().to_string());
        }

        for i in 0..iterations {
            let mut operation = Operation::default();

            // NB: For benchmarking, the objects are synthetic and in a predictable naming format.
            object = format!("{}{:04}", base_object_name, i+1);

            if !keep_alive {
                provider = DefaultCredentialsProviderSync::new(None).unwrap();
                local_endpoint = endpoint.clone();
                s3client = S3Client::new(provider, local_endpoint);

                request = GetObjectRequest::default();
                request.bucket = bucket.to_string();
                request.key = object.clone();
                if range.is_some() {
                    request.range = Some(range.unwrap().clone().to_string());
                }
            } else {
                request.key = object.clone();
            }

            match s3client.get_object(&request, Some(&mut operation)) {
                Ok(output) => {},
                Err(e) => {
                    println_color_red!("Failed to get [{}/{}] - {}", bucket, object, e);
                },
            }

            operations.push(operation);
        }
    } else if duration.as_secs() > 0 {
        let mut count: u64 = 0;
        let now = Instant::now();

        // Allocate here anyway...
        provider = DefaultCredentialsProviderSync::new(None).unwrap();
        local_endpoint = endpoint.clone();
        s3client = S3Client::new(provider, local_endpoint);

        request = GetObjectRequest::default();
        request.bucket = bucket.to_string();
        if range.is_some() {
            request.range = Some(range.unwrap().clone().to_string());
        }

        loop {
            let mut operation = Operation::default();
            object = format!("{}{:04}", base_object_name, count+1);

            if !keep_alive {
                provider = DefaultCredentialsProviderSync::new(None).unwrap();
                local_endpoint = endpoint.clone();
                s3client = S3Client::new(provider, local_endpoint);

                request = GetObjectRequest::default();
                request.bucket = bucket.to_string();
                request.key = object.clone();
                if range.is_some() {
                    request.range = Some(range.unwrap().clone().to_string());
                }
            } else {
                request.key = object.clone();
            }

            match s3client.get_object(&request, Some(&mut operation)) {
                Ok(output) => {},
                Err(e) => {
                    println_color_red!("Failed to get [{}/{}] - {}", bucket, object, e);
                },
            }

            if now.elapsed() >= duration {
                operations.push(operation);
                break;
            }

            operations.push(operation);
            count += 1;
        }
    }

    Ok(())
}

pub fn do_put_bench<'a>(bucket: &str,
                        base_object_name: &str,
                        duration: Duration,
                        iterations: u64,
                        keep_alive: bool,
                        size: u64,
                        endpoint: Endpoint,
                        operations: &'a mut Vec<Operation>) -> Result<(), S3Error>
{
    let mut object: String = String::new();
    let mut buffer: Vec<u8>;
    let mut provider: DefaultCredentialsProviderSync;
    let mut local_endpoint: Endpoint;
    let mut s3client: S3Client<_,_>;
    let mut request: PutObjectRequest;

    // Synthetic buffer creation to simulate an on disk object
    zero_fill_buffer!(buffer, size);

    // NB: For iterations we allocate new s3client each time to simulate single user transactions...
    if iterations > 0 {
        // Allocate here anyway...
        provider = DefaultCredentialsProviderSync::new(None).unwrap();
        local_endpoint = endpoint.clone();
        s3client = S3Client::new(provider, local_endpoint);

        request = PutObjectRequest::default();
        request.bucket = bucket.to_string();
        request.key = object.clone();
        request.body = Some(&buffer);

        for i in 0..iterations {
            let mut operation = Operation::default();

            // NB: For benchmarking, the objects are synthetic and in a predictable naming format.
            object = format!("{}{:04}", base_object_name, i+1);

            if !keep_alive {
                request = PutObjectRequest::default();
                request.bucket = bucket.to_string();
                request.key = object.clone();
                request.body = Some(&buffer);

                provider = DefaultCredentialsProviderSync::new(None).unwrap();
                local_endpoint = endpoint.clone();
                s3client = S3Client::new(provider, local_endpoint);
            } else {
                request.key = object.clone();
            }

            match s3client.put_object(&request, Some(&mut operation)) {
                Ok(output) => {},
                Err(e) => {
                    println_color_red!("Failed to put [{}/{}] - {}", bucket, object, e);
                },
            }

            operations.push(operation);
        }
    } else if duration.as_secs() > 0 {
        let mut count: u64 = 0;
        let now = Instant::now();

        // Allocate here anyway...
        provider = DefaultCredentialsProviderSync::new(None).unwrap();
        local_endpoint = endpoint.clone();
        s3client = S3Client::new(provider, local_endpoint);

        request = PutObjectRequest::default();
        request.bucket = bucket.to_string();
        request.key = object.clone();
        request.body = Some(&buffer);

        loop {
            let mut operation = Operation::default();
            object = format!("{}{:04}", base_object_name, count+1);

            // Synthetic buffer creation to simulate an on disk object
            //let mut buffer: Vec<u8>;
            //zero_fill_buffer!(buffer, size);

            if !keep_alive {
                request = PutObjectRequest::default();
                request.bucket = bucket.to_string();
                request.key = object.clone();
                request.body = Some(&buffer);

                provider = DefaultCredentialsProviderSync::new(None).unwrap();
                local_endpoint = endpoint.clone();
                s3client = S3Client::new(provider, local_endpoint);
            } else {
                request.key = object.clone();
            }

            match s3client.put_object(&request, Some(&mut operation)) {
                Ok(output) => {},
                Err(e) => {
                    println_color_red!("Failed to put [{}/{}] - {}", bucket, object, e);
                },
            }

            if now.elapsed() >= duration {
                operations.push(operation);
                break;
            }

            operations.push(operation);
            count += 1;
        }
    }

    Ok(())
}

/*
fn put_bench<'a, 'b, P, D>(bucket: &str,
                           path: &str,
                           base_object_name: &str,
                           duration: &'b Duration,
                           iterations: u64,
                           len: u64,
                           operations: &'a mut Vec<Operation>,
                           client: &Client<P, D>) -> Result<(), S3Error>
                           where P: AwsCredentialsProvider,
                                 D: DispatchSignedRequest,
{
    let mut key: String;
    let mut object: String;

    if iterations > 0 {
        for i in 0..iterations {
            let mut operation: Operation;
            operation = Operation::default();
            key = format!("{}{:04}", base_object_name, i+1);
            object = format!("{}/{}", path, key);
            let result = put_object(bucket, &key, &object, len, Some(&mut operation), client);
            operations.push(operation);
        }
    } else if duration.as_secs() > 0 {
        let mut count: u64 = 0;
        let now = Instant::now();

        loop {
            let mut operation: Operation;
            operation = Operation::default();
            key = format!("{}{:04}", base_object_name, count+1);
            object = format!("{}/{}", path, key);
            let result = put_object(bucket, &key, &object, len, Some(&mut operation), client);
            operations.push(operation);
            if now.elapsed() >= *duration {
                break;
            }
            count += 1;
        }
    }

    Ok(())
}

// Limited in file size.
fn get_object<P, D>(bucket: &str,
                    object: &str,
                    operation: Option<&mut Operation>,
                    client: &Client<P, D>) -> Result<(), S3Error>
                    where P: AwsCredentialsProvider,
                          D: DispatchSignedRequest,
{
    let mut request = GetObjectRequest::default();
    request.bucket = bucket.to_string();
    request.key = object.to_string();

    object_get(&request, operation, client)
}

// Common portion of get_object... functions
fn object_get<P, D>(request: &GetObjectRequest,
                    operation: Option<&mut Operation>,
                    client: &Client<P, D>) -> Result<(), S3Error>
                    where P: AwsCredentialsProvider,
                          D: DispatchSignedRequest,
{
    match client.s3client.get_object(&request, operation) {
        Ok(output) => {
            Ok(())
        },
        Err(e) => {
            let error = format!("{:#?}", e);
            println_color_quiet!(client.is_quiet, client.error.color, "{}", error);
            Err(S3Error::new(error))
        },
    }
}

fn get_object_range<P, D>(bucket: &str,
                          object: &str,
                          offset: u64,
                          len: u64,
                          operation: Option<&mut Operation>,
                          client: &Client<P, D>)
                          -> Result<(), S3Error>
                          where P: AwsCredentialsProvider,
                                D: DispatchSignedRequest,
{
    let mut request = GetObjectRequest::default();
    request.bucket = bucket.to_string();
    request.key = object.to_string();
    request.range = Some(format!("bytes={}-{}", offset, len));

    object_get(&request, operation, client)
}

// Limited in file size. Max is 5GB but should use Multipart upload for larger than 15MB.
fn put_object<P, D>(bucket: &str,
                    key: &str,
                    object: &str,
                    len: u64,
                    operation: Option<&mut Operation>,
                    client: &Client<P, D>) -> Result<(), S3Error>
                    where P: AwsCredentialsProvider,
                          D: DispatchSignedRequest,
{
    let mut buffer: Vec<u8>;
    if len == 0 {
        let file = File::open(object).unwrap();
        let metadata = file.metadata().unwrap();

        buffer = Vec::with_capacity(metadata.len() as usize);

        match file.take(metadata.len()).read_to_end(&mut buffer) {
            Ok(_) => {},
            Err(e) => {
                let error = format!("Error reading file {}", e);
                return Err(S3Error::new(error));
            },
        }
    } else {
        zero_fill_buffer!(buffer, len);
    }

    let correct_key = if key.is_empty() {
        let path = Path::new(object);
        path.file_name().unwrap().to_str().unwrap().to_string()
    } else {
        key.to_string()
    };

    let mut request = PutObjectRequest::default();
    request.bucket = bucket.to_string();
    request.key = correct_key;
    request.body = Some(&buffer);

    match client.s3client.put_object(&request, operation) {
        Ok(output) => {
            match client.output.format {
                OutputFormat::Serialize => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                OutputFormat::Plain => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                OutputFormat::JSON => {
                    println_color_quiet!(client.is_quiet,
                                         client.output.color,
                                         "{}",
                                         json::encode(&output).unwrap_or("{}".to_string()));
                },
                OutputFormat::PrettyJSON => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{}", json::as_pretty_json(&output));
                },
                OutputFormat::Simple => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                _ => {},
            }
            Ok(())
        },
        Err(e) => {
            let error = format!("{:#?}", e);
            println_color_quiet!(client.is_quiet, client.error.color, "{}", error);
            Err(S3Error::new(error))
        },
    }
}

fn abort_multipart_upload<P, D>(bucket: &str,
                                object: &str,
                                id: &str,
                                client: &Client<P, D>) -> Result<(), S3Error>
                                where P: AwsCredentialsProvider,
                                      D: DispatchSignedRequest,
{
    let mut request = MultipartUploadAbortRequest::default();
    request.bucket = bucket.to_string();
    request.upload_id = id.to_string();
    request.key = object.to_string();

    match client.s3client.multipart_upload_abort(&request) {
        Ok(output) => {
            match client.output.format {
                OutputFormat::Serialize => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                OutputFormat::Plain => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                OutputFormat::JSON => {
                    println_color_quiet!(client.is_quiet,
                                         client.output.color,
                                         "{}",
                                         json::encode(&output).unwrap_or("{}".to_string()));
                },
                OutputFormat::PrettyJSON => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{}", json::as_pretty_json(&output));
                },
                OutputFormat::Simple => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                _ => {},
            }
        },
        Err(e) => {
            let error = format!("{:#?}", e);
            println_color_quiet!(client.is_quiet, client.error.color, "{}", error);
            return Err(S3Error::new(error));
        },
    }

    Ok(())
}

/// Important - Do not leave incomplete uploads. You will be charged for those parts that have not
/// been completed. You runs ```s3lsio ls s3://<bucket name> multi``` to find out the uploads
/// that have not completed and then you an run ```s3lsio abort <upload_id> s3://<bucket_name>/<object_name>```
/// to abort the upload process.
///
/// You can also apply a bucket policy to automatically abort any uploads that have not completed
/// after so many days.
fn put_multipart_upload<P, D>(bucket: &str,
                              key: &str,
                              object: &str,
                              part_size: u64,
                              compute_hash: bool,
                              client: &Client<P, D>)
                              -> Result<(), S3Error>
                              where P: AwsCredentialsProvider,
                                    D: DispatchSignedRequest,
{
    let correct_key = if key.is_empty() {
        let path = Path::new(object);
        path.file_name().unwrap().to_str().unwrap().to_string()
    } else {
        key.to_string()
    };

    // Create multipart
    let create_multipart_upload: MultipartUploadCreateOutput;
    let mut request = MultipartUploadCreateRequest::default();
    request.bucket = bucket.to_string();
    request.key = correct_key.clone();

    match client.s3client.multipart_upload_create(&request) {
        Ok(output) => {
            create_multipart_upload = output;
        },
        Err(e) => {
            let error = format!("Multipart-Upload: {:#?}", e);
            return Err(S3Error::new(error));
        },
    }

    let upload_id: &str = &create_multipart_upload.upload_id;
    let mut parts_list: Vec<String> = Vec::new();

    // NB: To begin with the multipart will be a sequential upload in this thread! Aftwards, it will
    // be split out to a multiple of threads...

    let file = File::open(object).unwrap();
    let metadata = file.metadata().unwrap();

    let mut part_buffer: Vec<u8> = Vec::with_capacity(metadata.len() as usize);

    match file.take(metadata.len()).read_to_end(&mut part_buffer) {
        Ok(_) => {},
        Err(e) => {
            let error = format!("Multipart-Upload: Error reading file {}", e);
            return Err(S3Error::new(error));
        },
    }

    let mut request = MultipartUploadPartRequest::default();
    request.bucket = bucket.to_string();
    request.upload_id = upload_id.to_string();
    request.key = correct_key.clone();

    request.body = Some(&part_buffer);
    request.part_number = 1;
    // Compute hash - Hash is slow

    if compute_hash {
        let hash = md5::compute(request.body.unwrap()).to_base64(STANDARD);
        request.content_md5 = Some(hash);
    }

    match client.s3client.multipart_upload_part(&request) {
        Ok(output) => {
            // Collecting the partid in a list.
            let new_output = output.clone();
            parts_list.push(output);

            match client.output.format {
                OutputFormat::Serialize => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", new_output);
                },
                OutputFormat::Plain => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", new_output);
                },
                OutputFormat::JSON => {
                    println_color_quiet!(client.is_quiet,
                                         client.output.color,
                                         "{}",
                                         json::encode(&new_output).unwrap_or("{}".to_string()));
                },
                OutputFormat::PrettyJSON => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{}", json::as_pretty_json(&new_output));
                },
                OutputFormat::Simple => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", new_output);
                },
                _ => {},
            }
        },
        Err(e) => {
            let error = format!("Multipart-Upload Part: {:#?}", e);
            println_color_quiet!(client.is_quiet, client.error.color, "{}", error);
            return Err(S3Error::new(error));
        },
    }
    // End of upload

    // Complete multipart
    let item_list: Vec<u8>;

    let mut request = MultipartUploadCompleteRequest::default();
    request.bucket = bucket.to_string();
    request.upload_id = upload_id.to_string();
    request.key = correct_key;

    // parts_list gets converted to XML and sets the item_list.
    match multipart_upload_finish_xml(&parts_list) {
        Ok(parts_in_xml) => item_list = parts_in_xml,
        Err(e) => {
            let error = format!("Multipart-Upload XML: {:#?}", e);
            println_color_quiet!(client.is_quiet, client.error.color, "{}", error);
            return Err(S3Error::new(error));
        },
    }

    request.multipart_upload = Some(&item_list);

    match client.s3client.multipart_upload_complete(&request) {
        Ok(output) => {
            match client.output.format {
                OutputFormat::Serialize => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                OutputFormat::Plain => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                OutputFormat::JSON => {
                    println_color_quiet!(client.is_quiet,
                                         client.output.color,
                                         "{}",
                                         json::encode(&output).unwrap_or("{}".to_string()));
                },
                OutputFormat::PrettyJSON => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{}", json::as_pretty_json(&output));
                },
                OutputFormat::Simple => {
                    println_color_quiet!(client.is_quiet, client.output.color, "{:#?}", output);
                },
                _ => {},
            }
        },
        Err(e) => {
            let error = format!("Multipart-Upload Complete: {:#?}", e);
            println_color_quiet!(client.is_quiet, client.error.color, "{}", error);
            return Err(S3Error::new(error));
        },
    }

    Ok(())
}
*/

// NOTE: Will need to refactor this if there are more than one host...
fn master_benchmark(bench_request: BenchRequest,
                    bench_output: BenchOutput,
                    bench_host_instance_summary: BenchHostInstanceSummary) {
    let mut bench_host_instance_operations: Vec<BenchHostInstanceSummary> = Vec::new();
    let mut bench_summary: BenchSummary;

    // This should be called for each host
    bench_host_instance_operations.push(bench_host_instance_summary);
    bench_summary = BenchSummary::new(bench_host_instance_operations);

    // Get results (vec of the hosts results)
    bench_results(bench_request, &mut bench_summary, bench_output);
}

fn host_controller(matches: &ArgMatches,
                   method: Commands,
                   duration: u64,
                   nodes: u32,
                   iterations: u64,
                   keep_alive: bool,
                   virtual_users: u32,
                   size: u64,
                   endpoint: Endpoint) -> Option<BenchHostInstanceSummary>
{
    // Broken out like this since we may want to have a true controller to cause all threads to
    // wait until given the go ahead which will create a thundering heard or create a ramp up
    // controller to be more real world like.

    host_benchmark(matches, method, duration, nodes, iterations, keep_alive, virtual_users, size, endpoint)
}

/*
fn host_controller_trigger(tx: Sender<i32>, millis: u64) {
}
*/

// Runs in the host_controller thread
fn host_benchmark(matches: &ArgMatches,
                  method: Commands,
                  duration: u64,
                  nodes: u32,
                  iterations: u64,
                  keep_alive: bool,
                  virtual_users: u32,
                  size: u64,
                  endpoint: Endpoint) -> Option<BenchHostInstanceSummary>
{
    let duration2 = Duration::from_secs(duration);
    let bench_thread_operations: Vec<BenchThreadSummary> = Vec::new();
    let mut bench_host_instance_summary: BenchHostInstanceSummary;
    let thread_ops_start_times: Vec<DateTime<UTC>> = Vec::new();
    let thread_ops_end_times: Vec<DateTime<UTC>> = Vec::new();

    let mut handles: Vec<_> = Vec::new();

    let arc = Arc::new(Mutex::new(bench_thread_operations));
    let arc_start_times = Arc::new(Mutex::new(thread_ops_start_times));
    let arc_end_times = Arc::new(Mutex::new(thread_ops_end_times));

    let (scheme, tmp_bucket) = matches.value_of("bucket").unwrap_or("s3:// ").split_at(5);
    let mut bucket = get_bucket(tmp_bucket.to_string()).unwrap_or("".to_string());

    if bucket.is_empty() {
        let (scheme, tmp_bucket) = matches.value_of("path").unwrap_or("s3:// ").split_at(5);
        bucket = get_bucket(tmp_bucket.to_string()).unwrap_or("".to_string());
        if bucket.is_empty() {
            println_color_red!("Bucket is empty. Make sure to follow CLI. Issue s3lsio -h for how-to");
            return None;
        }
    }

    // These are only for Byte-Range requests
    let mut offset: u64 = 0;
    let mut len: u64 = 0;

    if method == Commands::range {
        offset = matches.value_of("offset").unwrap_or("0").parse().unwrap_or(0);
        len = matches.value_of("len").unwrap_or("0").parse().unwrap_or(0);
        if len == 0 {
            println_color_red!("Error: Range Len is 0");
            return None;
        }
    }

    // Creating threads and processing and then destroying threads so 2 x virtual_users
    let mut pbb = ProgressBar::new((virtual_users * 2) as u64);
    pbb.show_time_left = true;
    pbb.message("Benchmarking started ");

    for i in 0..virtual_users {
        let t_arc = arc.clone();
        let t_arc_start_times = arc_start_times.clone();
        let t_arc_end_times = arc_end_times.clone();
        let t_bucket = bucket.clone();
        let t_endpoint = endpoint.clone();

        pbb.inc();

        // Spawn the threads which represent virtual users
        let handle = thread::spawn(move || {
            let mut operations: Vec<Operation> = Vec::new();
            let thread_name = format!("thread_{:04}", i+1);
            let base_object_name = format!("{}/file{:04}", thread_name, i+1);
            // NB: Each thread has it's own virtual directory in S3 for the given bucket.

            match method {
                Commands::get => {
                    let result = do_get_bench(&t_bucket, &base_object_name, duration2, iterations, keep_alive, None, t_endpoint, &mut operations);
                },
                Commands::put => {
                    let result = do_put_bench(&t_bucket, &base_object_name, duration2, iterations, keep_alive, size, t_endpoint, &mut operations);
                },
                Commands::range => {
                    let range = format!("bytes={}-{}", offset, len);
                    let result = do_get_bench(&t_bucket, &base_object_name, duration2, iterations, keep_alive, Some(&range), t_endpoint, &mut operations);
                },
                _ => {},
            }

            // start - The earliest operation of the given thread
            // end - The latest operation of the given thread
            let (bench_thread, bench_operations, start, end) = bench_thread_results(&operations);

            let mut bench_thread_summary = BenchThreadSummary::new(bench_thread, bench_operations);
            bench_thread_summary.thread_name = thread_name.clone();

            let mut bto = t_arc.lock().unwrap();
            bto.push(bench_thread_summary);

            let mut start_times = t_arc_start_times.lock().unwrap();
            let mut end_times = t_arc_end_times.lock().unwrap();
            start_times.push(start);
            end_times.push(end);
        });

        handles.push(handle);
    }

    // Wait on above threads to complete before going on...
    for handle in handles {
        handle.join().unwrap();
        pbb.inc();
    }

    // NOTE: Get the data from Mutex and clone it to create a "new" ownership that can be added
    // to the collections below...
    let bto_mutex = arc.lock().unwrap();
    let mut bto: Vec<BenchThreadSummary> = Vec::new();

    for b in bto_mutex.iter() {
        let nb = b.clone();
        bto.push(nb.clone());
    }

    bench_host_instance_summary = BenchHostInstanceSummary::new(bto);
    bench_host_instance_summary.host_instance = hostname().unwrap_or("".to_string());
    bench_host_instance_summary.ip_address = ip("").unwrap().to_string();

    let start_time_mutex = arc_start_times.lock().unwrap();
    let mut start_time: DateTime<UTC> = UTC::now();

    for s in start_time_mutex.iter() {
        let st = *s; //s.clone();
        if st <= start_time {
            start_time = st;
        }
    }

    let end_time_mutex = arc_end_times.lock().unwrap();
    let mut end_time: DateTime<UTC> = UTC::now();

    for e in end_time_mutex.iter() {
        let et = *e; //e.clone();
        if et >= end_time {
            end_time = et;
        }
    }

    bench_host_instance_summary.start_time = start_time.format("%Y-%m-%d %H:%M:%S%.9f %z").to_string();
    bench_host_instance_summary.end_time = end_time.format("%Y-%m-%d %H:%M:%S%.9f %z").to_string();

    let total_duration: Duration = (end_time - start_time).to_std().unwrap();
    let duration_str: String = format!("{}.{}", total_duration.as_secs(), total_duration.subsec_nanos());
    let duration: f64 =  duration_str.parse::<f64>().unwrap() as f64;

    bench_host_instance_summary.host_duration = duration;

    // Get the earliest start_time and latest end_time of all of the threads for the given host.
    // This is used to determine true throughput for host. This data will then go to a collector
    // that runs the stats for all hosts before presenting final results.

    // NB: Only one host for now...

    // Get host results (vec of the thread results)
    bench_host_instance_results(&mut bench_host_instance_summary);

    // Pass the bench_host_instance_summary of each host back to the master/primary
    // and add them to bench_host_instance_operations

    pbb.finish_println("Benchmarking complete");
    println!(" ");

    Some(bench_host_instance_summary)
}

// Use this function if you want to generate a number of actual files of a given size with a given
// prefix (i.e. 'file').
fn gen_files(tmp_dir: &str, base_object_name: &str, iterations: u64, size: u64) -> Result<(), S3Error> {
    // Remove the tmp directory .s3lsio_tmp
    let result = fs::remove_dir_all(tmp_dir);
    fs::create_dir_all(tmp_dir).unwrap();

    let mut object: String;
    let path: String = format!("{}{}", tmp_dir, if tmp_dir.ends_with('/') {""} else {"/"});

    for i in 0..iterations {
        object = format!("{}{}{}", path, base_object_name, i);
        {
            match File::create(object) {
                Ok(f) => {
                    let result_len = f.set_len(size);
                },
                Err(e) => {
                    let error = format!("{:#?}", e);
                    println_color!(term::color::RED, "{}", error);
                    return Err(S3Error::new(error));
                },
            }
        }
    }

    Ok(())
}

// Moves the Vec Operations into BenchOperations and adds them to thread_summary
//fn bench_thread_results(operations: &Vec<Operation>) -> (BenchThread, Vec<BenchOperation>, DateTime<UTC>, DateTime<UTC>) {
fn bench_thread_results(operations: &[Operation]) -> (BenchThread, Vec<BenchOperation>, DateTime<UTC>, DateTime<UTC>) {
    let mut total_errors: u64 = 0;
    //let mut total_duration: f64 = 0.0;
    let mut total_duration = Duration::new(0,0);
    let mut total_payload: u64 = 0;

    let mut bench_operations: Vec<BenchOperation> = Vec::with_capacity(operations.len());
    let mut bench_thread_summary = BenchThread::default();

    let mut start: DateTime<UTC> = UTC::now();
    let mut end: DateTime<UTC> = UTC::now();

    bench_thread_summary.total_requests = operations.len() as u64;

    for op in operations {
        let mut bop = BenchOperation::default();
        let duration_str: String = format!("{}.{}", op.duration.unwrap().as_secs(), op.duration.unwrap().subsec_nanos());
        let duration = op.duration.unwrap();

        bop.request = op.request.clone();
        bop.endpoint = op.endpoint.clone();
        bop.method = op.method.clone();
        bop.success = op.success;
        bop.code = op.code;
        bop.payload_size = op.payload_size;
        bop.duration = duration_str.clone();
        if op.object.starts_with('/') {
            bop.object = op.object.clone()[1..].to_string();
        } else {
            bop.object = op.object.clone();
        }

        bop.start_time = op.start_time.unwrap().format("%Y-%m-%d %H:%M:%S%.9f %z").to_string();
        bop.end_time = op.end_time.unwrap().format("%Y-%m-%d %H:%M:%S%.9f %z").to_string();

        if op.start_time.unwrap() <= start {
            start = op.start_time.unwrap();
        }

        if op.end_time.unwrap() >= end {
            end = op.end_time.unwrap();
        }

        total_duration += duration;
        total_payload += op.payload_size;

        if !op.success {
            total_errors += 1;
        }

        bench_operations.push(bop);
    }

    let duration_str: String = format!("{}.{}", total_duration.as_secs(), total_duration.subsec_nanos());
    let duration: f64 =  duration_str.parse::<f64>().unwrap() as f64;

    bench_thread_summary.total_duration = duration;
    bench_thread_summary.total_errors = total_errors;
    bench_thread_summary.total_payload = total_payload;
    bench_thread_summary.total_success = bench_thread_summary.total_requests - bench_thread_summary.total_errors;
    bench_thread_summary.total_throughput = (bench_thread_summary.total_success as f64 / duration) as f64;

    (bench_thread_summary, bench_operations, start, end)
}

// Rolls up all of the thread summaries for a given host
fn bench_host_instance_results(bench_host_instance_summary: &mut BenchHostInstanceSummary) -> () {
    let mut total_errors: u64 = 0;
    let mut total_duration: f64 = 0.0;
    let mut total_payload: u64 = 0;
    let mut total_threads: u64 = 0;
    let mut total_success: u64 = 0;
    let mut total_requests: u64 = 0;

    let operations = bench_host_instance_summary.clone();

    // Just rolling up totals...
    for op in operations.operations {
        total_duration += op.total_duration;
        total_payload += op.total_payload;
        total_errors += op.total_errors;
        total_success += op.total_success;
        total_requests += op.total_requests;

        total_threads += 1;
    }

    bench_host_instance_summary.total_duration = total_duration;
    bench_host_instance_summary.total_errors = total_errors;
    bench_host_instance_summary.total_payload = total_payload;
    bench_host_instance_summary.total_threads = total_threads;
    bench_host_instance_summary.total_success = total_success;
    bench_host_instance_summary.total_requests = total_requests;
    bench_host_instance_summary.total_throughput = (total_success as f64 / total_duration) as f64;
}

// Rolls up the hosts for a summary... For now there is only one hosts...
fn bench_results(metadata: BenchRequest,
                 bench_summary: &mut BenchSummary,
                 output: BenchOutput) -> () {
    let mut total_errors: u64 = 0;
    let mut total_duration: f64 = 0.0;
    let mut total_payload: u64 = 0;
    let mut total_host_instances: u64 = 0;
    let mut total_threads: u64 = 0;
    let mut total_success: u64 = 0;
    let mut total_requests: u64 = 0;

    let operations = bench_summary.clone();

    // Just rolling up totals...
    for op in operations.operations.unwrap() {
        total_duration += op.total_duration;
        total_payload += op.total_payload;
        total_errors += op.total_errors;
        total_success += op.total_success;
        total_requests += op.total_requests;
        total_threads += op.total_threads;

        total_host_instances += 1;
    }

    // Only has one host for now so we can cheat :)
    let summary = bench_summary.clone().operations.unwrap();
    bench_summary.start_time = summary[0].start_time.clone();
    bench_summary.end_time = summary[0].end_time.clone();

    // Looks at the earliest thread start time and the latest end time and then recomputes totals
    let start_time = DateTime::parse_from_str(&bench_summary.start_time, "%Y-%m-%d %H:%M:%S%.9f %z");
    let end_time = DateTime::parse_from_str(&bench_summary.end_time, "%Y-%m-%d %H:%M:%S%.9f %z");

    let dur: Duration = (end_time.unwrap() - start_time.unwrap()).to_std().unwrap();
    let duration_str: String = format!("{}.{}", dur.as_secs(), dur.subsec_nanos());
    let duration: f64 =  duration_str.parse::<f64>().unwrap() as f64;

    // Truncates off the decimal portion for duration tests
    if metadata.iterations == 0 {
        bench_summary.total_duration = duration.trunc();
    } else {
        bench_summary.total_duration = duration;
    }
    bench_summary.total_errors = total_errors;
    bench_summary.total_payload = total_payload;
    bench_summary.total_threads = total_threads;
    bench_summary.total_host_instances = total_host_instances;
    bench_summary.total_success = total_success;
    bench_summary.total_requests = total_requests;
    // Only successful requests are used in throughput
    bench_summary.total_throughput = (total_success as f64 / duration) as f64;

    // NB: *If the report type contains summary then make bench_summary.operations = None
    if metadata.report.contains("Summary") {
        bench_summary.operations = None;
    }

    let bench_results = BenchResults::new(metadata, bench_summary.clone());

    match output.format {
        OutputFormat::JSON => {
            println_color!(output.color,
                                 "{}",
                                 json::encode(&bench_results).unwrap_or("{}".to_string()));
        },
        OutputFormat::PrettyJSON => {
            println_color!(output.color, "{}", json::as_pretty_json(&bench_results));
        },
        _ => {
            println_color!(output.color, "{:#?}", bench_results);
        },
    }
}