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
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::path::PathBuf;
use std::borrow::Cow;
use std::process::Command;
use std::time::Duration;
use std::net::SocketAddr;
use std::process::Stdio;
use std::fs::File;

use tracing::{info, warn, debug, error, instrument};
use fluvio::{Fluvio, FluvioConfig};
use fluvio::metadata::spg::SpuGroupSpec;
use fluvio::metadata::spu::SpuSpec;
use fluvio::config::{TlsPolicy, TlsConfig, TlsPaths, ConfigFile, Profile};
use flv_util::cmd::CommandExt;
use fluvio_future::timer::sleep;
use fluvio_future::net::{TcpStream, resolve};
use k8_client::K8Client;
use k8_config::K8Config;
use k8_client::metadata::MetadataClient;
use k8_client::core::service::ServiceSpec;
use k8_client::core::metadata::InputObjectMeta;

use crate::helm::{HelmClient, Chart, InstalledChart};
use crate::check::{
    UnrecoverableCheck, InstallCheck, HelmVersion, AlreadyInstalled, SysChart, LoadableConfig,
    LoadBalancer, CheckFailed, RecoverableCheck, CheckResults,
};
use crate::error::K8InstallError;
use crate::{
    ClusterError, StartStatus, DEFAULT_NAMESPACE, DEFAULT_CHART_SYS_REPO, DEFAULT_CHART_APP_REPO,
    CheckStatus,
};
use crate::start::{check_and_fix, ChartLocation, DEFAULT_CHART_REMOTE};

const DEFAULT_REGISTRY: &str = "infinyon";
const DEFAULT_APP_NAME: &str = "fluvio-app";
const DEFAULT_SYS_NAME: &str = "fluvio-sys";
const DEFAULT_CHART_SYS_NAME: &str = "fluvio/fluvio-sys";
const DEFAULT_CHART_APP_NAME: &str = "fluvio/fluvio-app";
const DEFAULT_GROUP_NAME: &str = "main";
const DEFAULT_CLOUD_NAME: &str = "minikube";
const DELAY: u64 = 3000;

/// A builder for cluster startup options
#[derive(Debug)]
pub struct ClusterInstallerBuilder {
    /// The namespace to install under
    namespace: String,
    /// The image tag to use for Fluvio install
    image_tag: Option<String>,
    /// The docker registry to use
    image_registry: String,
    /// The name of the Fluvio helm chart to install
    chart_name: String,
    /// A specific version of the Fluvio helm chart to install
    chart_version: String,
    /// The location to find the fluvio charts
    chart_location: ChartLocation,
    /// The name of the SPU group to create
    group_name: String,
    /// The name of the Fluvio cloud
    cloud: String,
    /// Whether to save an update to the Fluvio profile
    save_profile: bool,
    /// Whether to install fluvio-sys with fluvio-app
    install_sys: bool,
    /// Whether to update the `kubectl` context
    update_context: bool,
    /// How much storage to allocate on SPUs
    spu_spec: SpuGroupSpec,
    /// The logging settings to set in the cluster
    rust_log: Option<String>,
    /// The TLS policy for the SC and SPU servers
    server_tls_policy: TlsPolicy,
    /// The TLS policy for the client
    client_tls_policy: TlsPolicy,
    /// The authorization ConfigMap name
    authorization_config_map: Option<String>,
    /// Should the pre install checks be skipped
    skip_checks: bool,
}

impl ClusterInstallerBuilder {
    /// Creates a [`ClusterInstaller`] with the current configuration.
    ///
    /// This may fail if there is a problem conencting to Kubernetes or
    /// finding the `helm` executable on the local system.
    ///
    /// # Example
    ///
    /// The simplest flow to create a `ClusterInstaller` looks like the
    /// following:
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .build()
    ///     .expect("should create ClusterInstaller");
    /// ```
    ///
    /// [`ClusterInstaller`]: ./struct.ClusterInstaller.html
    pub fn build(self) -> Result<ClusterInstaller, ClusterError> {
        Ok(ClusterInstaller {
            config: self,
            kube_client: K8Client::default().map_err(K8InstallError::K8ClientError)?,
            helm_client: HelmClient::new().map_err(K8InstallError::HelmError)?,
        })
    }

    /// Sets the Kubernetes namespace to install Fluvio into.
    ///
    /// The default namespace is "default".
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_namespace("my-namespace")
    ///     .build()
    ///     .expect("should build installer");
    /// ```
    pub fn with_namespace<S: Into<String>>(mut self, namespace: S) -> Self {
        self.namespace = namespace.into();
        self
    }

    /// Sets the docker image tag of the Fluvio image to install.
    ///
    /// If this is not specified, the installer will use the chart version
    /// as the image tag. This should correspond to the image tags of the
    /// official published Fluvio images.
    ///
    /// # Example
    ///
    /// Suppose you would like to install version `0.6.0` of Fluvio from
    /// Docker Hub, where the image is tagged as `infinyon/fluvio:0.6.0`.
    /// You can do that like this:
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_image_tag("0.6.0")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_image_tag<S: Into<String>>(mut self, image_tag: S) -> Self {
        self.image_tag = Some(image_tag.into());
        self
    }

    /// Sets the docker image registry to use to download Fluvio images.
    ///
    /// This defaults to `infinyon` to pull from Infinyon's official Docker Hub
    /// registry. This can be used to specify a private registry or a local
    /// registry as a source of Fluvio images.
    ///
    /// # Example
    ///
    /// You can create a local Docker registry to publish images to during
    /// development. Suppose you have a local registry running such as the following:
    ///
    /// ```bash
    /// docker run -d -p 5000:5000 --restart=always --name registry registry:2
    /// ```
    ///
    /// Suppose you tagged your image as `infinyon/fluvio:0.1.0` and pushed it
    /// to your `localhost:5000` registry. Your image is now located at
    /// `localhost:5000/infinyon`. You can specify that to the installer like so:
    ///
    /// > **NOTE**: See [`with_image_tag`] to see how to specify the `0.1.0` shown here.
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_image_registry("localhost:5000/infinyon")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    /// Then, when you use `installer.install_fluvio()`, it will pull the images
    /// from your local docker registry.
    ///
    /// [`with_image_tag`]: ./struct.ClusterInstaller.html#method.with_image_tag
    pub fn with_image_registry<S: Into<String>>(mut self, image_registry: S) -> Self {
        self.image_registry = image_registry.into();
        self
    }

    /// Sets a specific version of the Fluvio helm chart to install.
    ///
    /// When working with published Fluvio images, the chart version will appear
    /// to be a [Semver] version, such as `0.6.0`.
    ///
    /// When developing for Fluvio, chart versions are named after the git hash
    /// of the revision a chart was built on.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_chart_version("0.6.0")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    /// [Semver]: https://docs.rs/semver/0.10.0/semver/
    pub fn with_chart_version<S: Into<String>>(mut self, chart_version: S) -> Self {
        self.chart_version = chart_version.into();
        self
    }

    /// Sets a local helm chart location to search for Fluvio charts.
    ///
    /// This is often desirable when developing for Fluvio locally and making
    /// edits to the chart. When using this option, the argument is expected to be
    /// a local filesystem path. The path given is expected to be the parent directory
    /// of both the `fluvio-app` and `fluvio-sys` charts.
    ///
    /// This option is mutually exclusive from [`with_remote_chart`]; if both are used,
    /// the latest one defined is the one that's used.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_local_chart("./k8-util/helm")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    /// [`with_remote_chart`]: ./struct.ClusterInstallerBuilder#method.with_remote_chart
    pub fn with_local_chart<S: Into<PathBuf>>(mut self, local_chart_location: S) -> Self {
        self.chart_location = ChartLocation::Local(local_chart_location.into());
        self
    }

    /// Sets a remote helm chart location to search for Fluvio charts.
    ///
    /// This is the default case, with the default location being `https://charts.fluvio.io`,
    /// where official Fluvio helm charts are located. Remote helm charts are expected
    /// to be a valid URL.
    ///
    /// This option is mutually exclusive from [`with_local_chart`]; if both are used,
    /// the latest one defined is the one that's used.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_remote_chart("https://charts.fluvio.io")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    /// [`with_local_chart`]: ./struct.ClusterInstallerBuilder#method.with_local_chart
    pub fn with_remote_chart<S: Into<String>>(mut self, remote_chart_location: S) -> Self {
        self.chart_location = ChartLocation::Remote(remote_chart_location.into());
        self
    }

    /// Sets a custom SPU group name. The default is `main`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_group_name("orange")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_group_name<S: Into<String>>(mut self, group_name: S) -> Self {
        self.group_name = group_name.into();
        self
    }

    /// Whether to save a profile of this installation to `~/.fluvio/config`. Defaults to `false`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_save_profile(true)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_save_profile(mut self, save_profile: bool) -> Self {
        self.save_profile = save_profile;
        self
    }

    /// Whether to skip pre-install checks before installation. Defaults to `false`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_skip_checks(true)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_skip_checks(mut self, skip_checks: bool) -> Self {
        self.skip_checks = skip_checks;
        self
    }

    /// Whether to install the `fluvio-sys` chart in the full installation. Defaults to `true`.
    ///
    /// # Example
    ///
    /// If you want to disable installing the system chart, you can do this
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_system_chart(false)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_system_chart(mut self, install_sys: bool) -> Self {
        self.install_sys = install_sys;
        self
    }

    /// Whether to update the `kubectl` context to match the Fluvio installation. Defaults to `true`.
    ///
    /// # Example
    ///
    /// If you do not want your Kubernetes contexts to be updated, you can do this
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_update_context(false)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_update_context(mut self, update_context: bool) -> Self {
        self.update_context = update_context;
        self
    }

    /// Sets the number of SPU replicas that should be provisioned. Defaults to 1.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_spu_replicas(2)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_spu_replicas(mut self, spu_replicas: u16) -> Self {
        self.spu_spec.replicas = spu_replicas;
        self
    }

    /// Sets the [`RUST_LOG`] environment variable for the installation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_rust_log("debug")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    /// [`RUST_LOG`]: https://docs.rs/tracing-subscriber/0.2.11/tracing_subscriber/filter/struct.EnvFilter.html
    pub fn with_rust_log<S: Into<String>>(mut self, rust_log: S) -> Self {
        self.rust_log = Some(rust_log.into());
        self
    }

    /// Sets the TLS Policy that the client and server will use to communicate.
    ///
    /// By default, these are set to `TlsPolicy::Disabled`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use std::path::PathBuf;
    /// use fluvio::config::TlsPaths;
    /// use fluvio_cluster::ClusterInstaller;
    ///
    /// let cert_path = PathBuf::from("/tmp/certs");
    /// let client = TlsPaths {
    ///     domain: "fluvio.io".to_string(),
    ///     ca_cert: cert_path.join("ca.crt"),
    ///     cert: cert_path.join("client.crt"),
    ///     key: cert_path.join("client.key"),
    /// };
    /// let server = TlsPaths {
    ///     domain: "fluvio.io".to_string(),
    ///     ca_cert: cert_path.join("ca.crt"),
    ///     cert: cert_path.join("server.crt"),
    ///     key: cert_path.join("server.key"),
    /// };
    ///
    /// let installer = ClusterInstaller::new()
    ///     .with_tls(client, server)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_tls<C: Into<TlsPolicy>, S: Into<TlsPolicy>>(
        mut self,
        client: C,
        server: S,
    ) -> Self {
        let client_policy = client.into();
        let server_policy = server.into();

        use TlsPolicy::*;
        use std::mem::discriminant;
        match (&client_policy, &server_policy) {
            // If the two policies do not have the same variant, they are probably incompatible
            _ if discriminant(&client_policy) != discriminant(&server_policy) => {
                warn!("Client TLS policy type is different than the Server TLS policy type!");
            }
            // If the client and server domains do not match, give a warning
            (Verified(client), Verified(server)) if client.domain() != server.domain() => {
                warn!(
                    client_domain = client.domain(),
                    server_domain = server.domain(),
                    "Client TLS config has a different domain than the Server TLS config!"
                );
            }
            _ => (),
        }

        self.client_tls_policy = client_policy;
        self.server_tls_policy = server_policy;
        self
    }

    /// Sets the K8 cluster cloud environment.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_cloud("minikube")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    pub fn with_cloud<S: Into<String>>(mut self, cloud: S) -> Self {
        self.cloud = cloud.into();
        self
    }

    /// Sets the ConfigMap for authorization.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_authorization_config_map("authorization")
    ///     .build()
    ///     .unwrap();
    /// ```
    ///
    pub fn with_authorization_config_map<S: Into<String>>(
        mut self,
        authorization_config_map: S,
    ) -> Self {
        self.authorization_config_map = Some(authorization_config_map.into());
        self
    }
}

/// Allows installing Fluvio on a Kubernetes cluster
///
/// Fluvio's Kubernetes components are distributed as [Helm Charts],
/// which allow them to be easily installed on any Kubernetes
/// cluster. A `ClusterInstaller` takes care of installing all of
/// the pieces in the right order, with sane defaults.
///
/// If you want to try out Fluvio on Kubernetes, you can use [Minikube]
/// as an installation target. This is the default target that the
/// `ClusterInstaller` uses, so it doesn't require any complex setup.
///
/// # Example
///
/// To install Fluvio using all the default settings, use
/// `ClusterInstaller::new()`
///
/// ```no_run
/// # use fluvio_cluster::ClusterInstaller;
/// let installer = ClusterInstaller::new()
///     .build()
///     .expect("should initialize installer");
///
/// // Installing Fluvio is asynchronous, so you'll need an async runtime
/// let result = fluvio_future::task::run_block_on(async {
///     installer.install_fluvio().await
/// });
/// ```
///
/// [Helm Charts]: https://helm.sh/
/// [Minikube]: https://kubernetes.io/docs/tasks/tools/install-minikube/
#[derive(Debug)]
pub struct ClusterInstaller {
    /// Configuration options for this installation
    config: ClusterInstallerBuilder,
    /// Shared Kubernetes client for install
    kube_client: K8Client,
    /// Helm client for performing installs
    helm_client: HelmClient,
}

impl ClusterInstaller {
    /// Creates a default [`ClusterInstallerBuilder`] which can build a `ClusterInstaller`
    ///
    /// # Example
    ///
    /// The easiest way to build a `ClusterInstaller` is as follows:
    ///
    /// ```no_run
    /// use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new().build().unwrap();
    /// ```
    ///
    /// Building a `ClusterInstaller` may fail if there is trouble connecting to
    /// Kubernetes or if the `helm` executable is not locally installed.
    ///
    /// You may also set custom installation options before calling [`.build()`].
    /// For example, if you wanted to specify a custom namespace and RUST_LOG,
    /// you could use [`with_namespace`] and [`with_rust_log`]. See
    /// [`ClusterInstallerBuilder`] for the full set of options.
    ///
    /// ```no_run
    /// use fluvio_cluster::ClusterInstaller;
    /// let installer = ClusterInstaller::new()
    ///     .with_namespace("my_namespace")
    ///     .with_rust_log("debug")
    ///     .build()
    ///     .expect("should build ClusterInstaller");
    /// ```
    ///
    /// [`ClusterInstallerBuilder`]: ./struct.ClusterInstallerBuilder.html
    /// [`.build()`]: ./struct.ClusterInstallerBuilder.html#build
    /// [`with_namespace`]: ./struct.ClusterInstallerBuilder.html#method.with_namespace
    /// [`with_rust_log`]: ./struct.ClusterInstallerBuilder.html#method.with_rust_log
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> ClusterInstallerBuilder {
        let spu_spec = SpuGroupSpec {
            replicas: 1,
            min_id: 0,
            ..SpuGroupSpec::default()
        };

        ClusterInstallerBuilder {
            namespace: DEFAULT_NAMESPACE.to_string(),
            image_tag: None,
            image_registry: DEFAULT_REGISTRY.to_string(),
            chart_version: crate::VERSION.trim().to_string(),
            chart_name: DEFAULT_CHART_APP_NAME.to_string(),
            chart_location: ChartLocation::Remote(DEFAULT_CHART_REMOTE.to_string()),
            group_name: DEFAULT_GROUP_NAME.to_string(),
            cloud: DEFAULT_CLOUD_NAME.to_string(),
            save_profile: false,
            install_sys: true,
            update_context: false,
            spu_spec,
            rust_log: None,
            server_tls_policy: TlsPolicy::Disabled,
            client_tls_policy: TlsPolicy::Disabled,
            authorization_config_map: None,
            skip_checks: false,
        }
    }

    /// Get all the available versions of fluvio chart
    pub fn versions() -> Result<Vec<Chart>, ClusterError> {
        let helm_client = HelmClient::new().map_err(K8InstallError::HelmError)?;
        let versions = helm_client
            .versions(DEFAULT_CHART_APP_NAME)
            .map_err(K8InstallError::HelmError)?;
        Ok(versions)
    }

    /// Get installed system chart
    pub fn sys_charts() -> Result<Vec<InstalledChart>, K8InstallError> {
        let helm_client = HelmClient::new()?;
        let sys_charts = helm_client.get_installed_chart_by_name(DEFAULT_CHART_SYS_REPO)?;
        Ok(sys_charts)
    }

    /// Checks if all of the prerequisites for installing Fluvio are met
    ///
    /// This will attempt to automatically fix any missing prerequisites,
    /// depending on the installer configuration. See the following options
    /// for more details:
    ///
    /// - [`with_system_chart`]
    /// - [`with_update_context`]
    ///
    /// [`with_system_chart`]: ./struct.ClusterInstaller.html#method.with_system_chart
    /// [`with_update_context`]: ./struct.ClusterInstaller.html#method.with_update_context
    #[allow(unused)]
    pub async fn setup(&self) -> CheckResults {
        let checks: Vec<Box<dyn InstallCheck>> = vec![
            Box::new(LoadableConfig),
            Box::new(HelmVersion),
            Box::new(SysChart),
            Box::new(AlreadyInstalled),
            Box::new(LoadBalancer),
        ];
        let fix = |err| self.pre_install_fix(err);
        check_and_fix(&checks, fix).await
    }

    async fn _try_minikube_tunnel(&self) -> Result<(), K8InstallError> {
        let log_file = File::create("/tmp/tunnel.out")?;
        let error_file = log_file.try_clone()?;

        // run minikube tunnel  > /tmp/tunnel.out 2> /tmp/tunnel.out
        Command::new("minikube")
            .arg("tunnel")
            .stdout(Stdio::from(log_file))
            .stderr(Stdio::from(error_file))
            .spawn()?;
        sleep(Duration::from_millis(DELAY)).await;
        Ok(())
    }

    /// Given a pre-check error, attempt to automatically correct it
    #[instrument(skip(self, error))]
    pub(crate) async fn pre_install_fix(
        &self,
        error: RecoverableCheck,
    ) -> Result<(), UnrecoverableCheck> {
        // Depending on what error occurred, try to fix the error.
        // If we handle the error successfully, return Ok(()) to indicate success
        // If we cannot handle this error, wrap it in UnrecoverableCheck::FailedRecovery
        match error {
            RecoverableCheck::MissingSystemChart if self.config.install_sys => {
                println!("Fluvio system chart not installed. Attempting to install");
                self._install_sys()
                    .map_err(|_| UnrecoverableCheck::FailedRecovery(error))?;
            }
            RecoverableCheck::MinikubeTunnelNotFoundRetry => {
                println!(
                    "Load balancer service is not available, trying to bring up minikube tunnel"
                );
                self._try_minikube_tunnel()
                    .await
                    .map_err(|_| UnrecoverableCheck::FailedRecovery(error))?;
            }
            unhandled => {
                warn!("Pre-install was unable to autofix an error");
                return Err(UnrecoverableCheck::FailedRecovery(unhandled));
            }
        }

        Ok(())
    }

    /// Installs Fluvio according to the installer's configuration
    ///
    /// Returns the external address of the new cluster's SC
    #[instrument(
        skip(self),
        fields(namespace = &*self.config.namespace),
    )]
    pub async fn install_fluvio(&self) -> Result<StartStatus, ClusterError> {
        let checks = match self.config.skip_checks {
            true => None,
            // Check if env is ready for install and tries to fix anything it can
            false => {
                let check_results = self.setup().await;
                if check_results.0.iter().any(|it| it.is_err()) {
                    return Err(K8InstallError::PrecheckErrored(check_results).into());
                }

                let statuses = check_results.into_statuses();
                let mut any_failed = false;
                for status in &statuses.0 {
                    match status {
                        // If Fluvio is already installed, return the SC's address
                        CheckStatus::Fail(CheckFailed::AlreadyInstalled) => {
                            debug!("Fluvio is already installed. Getting SC address");
                            let address = self.wait_for_sc_service(&self.config.namespace).await?;
                            return Ok(StartStatus {
                                address,
                                checks: Some(statuses),
                            });
                        }
                        CheckStatus::Fail(_) => any_failed = true,
                        _ => (),
                    }
                }

                // If any of the pre-checks was a straight-up failure, install should fail
                if any_failed {
                    return Err(K8InstallError::FailedPrecheck(statuses).into());
                }
                Some(statuses)
            }
        };

        self.install_app()?;
        let namespace = &self.config.namespace;
        let address = self
            .wait_for_sc_service(namespace)
            .await
            .map_err(|_| K8InstallError::UnableToDetectService)?;
        info!(addr = %address, "Fluvio SC is up:");

        if self.config.save_profile {
            self.update_profile(address.clone())?;
        }

        if self.config.spu_spec.replicas > 0 {
            debug!("waiting for SC to spin up");
            // Wait a little bit for the SC to spin up
            sleep(Duration::from_millis(2000)).await;

            // Create a managed SPU cluster
            let cluster =
                FluvioConfig::new(address.clone()).with_tls(self.config.client_tls_policy.clone());
            self.create_managed_spu_group(&cluster).await?;

            // Wait for the SPU cluster to spin up
            self.wait_for_spu(namespace, self.config.spu_spec.replicas)
                .await?;
        }

        Ok(StartStatus { address, checks })
    }

    /// Install the Fluvio System chart on the configured cluster
    #[doc(hidden)]
    #[instrument(skip(self))]
    pub fn _install_sys(&self) -> Result<(), K8InstallError> {
        let install_settings = &[("cloud", &*self.config.cloud)];
        match &self.config.chart_location {
            ChartLocation::Remote(chart_location) => {
                debug!(
                    chart_location = &**chart_location,
                    "Using remote helm chart:"
                );
                self.helm_client
                    .repo_add(DEFAULT_CHART_APP_REPO, chart_location)?;
                self.helm_client.repo_update()?;
                self.helm_client.install(
                    &self.config.namespace,
                    DEFAULT_CHART_SYS_REPO,
                    DEFAULT_CHART_SYS_NAME,
                    None,
                    install_settings,
                )?;
            }
            ChartLocation::Local(chart_home) => {
                let chart_location = chart_home.join(DEFAULT_SYS_NAME);
                let chart_string = chart_location.to_string_lossy();
                debug!(
                    chart_location = chart_string.as_ref(),
                    "Using local helm chart:"
                );
                self.helm_client.install(
                    &self.config.namespace,
                    DEFAULT_CHART_SYS_REPO,
                    chart_string.as_ref(),
                    None,
                    install_settings,
                )?;
            }
        }

        info!("Fluvio sys chart has been installed");
        Ok(())
    }

    /// Install Fluvio Core chart on the configured cluster
    #[instrument(skip(self))]
    fn install_app(&self) -> Result<(), K8InstallError> {
        debug!(
            "Installing fluvio with the following configuration: {:#?}",
            &self.config
        );

        // If configured with TLS, copy certs to server
        if let TlsPolicy::Verified(tls) = &self.config.server_tls_policy {
            self.upload_tls_secrets(tls)?;
        }

        let fluvio_tag = self
            .config
            .image_tag
            .as_ref()
            .unwrap_or(&self.config.chart_version)
            .to_owned();

        // Specify common installation settings to pass to helm
        let mut install_settings: Vec<(_, &str)> = vec![
            ("image.registry", &self.config.image_registry),
            ("image.tag", &fluvio_tag),
            ("cloud", &self.config.cloud),
        ];

        // If TLS is enabled, set it as a helm variable
        if let TlsPolicy::Anonymous | TlsPolicy::Verified(_) = self.config.server_tls_policy {
            install_settings.push(("tls", "true"));
        }

        // If RUST_LOG is defined, pass it to SC
        if let Some(log) = &self.config.rust_log {
            install_settings.push(("scLog", log));
        }

        if let Some(authorization_config_map) = &self.config.authorization_config_map {
            install_settings.push(("authorizationConfigMap", authorization_config_map));
        }

        match &self.config.chart_location {
            // For remote, we add a repo pointing to the chart location.
            ChartLocation::Remote(chart_location) => {
                self.helm_client
                    .repo_add(DEFAULT_CHART_APP_REPO, chart_location)?;
                self.helm_client.repo_update()?;
                if !self
                    .helm_client
                    .chart_version_exists(&self.config.chart_name, &self.config.chart_version)?
                {
                    return Err(K8InstallError::HelmChartNotFound(format!(
                        "{}:{}",
                        &self.config.chart_name, &self.config.chart_version
                    )));
                }
                debug!(
                    chart_location = &**chart_location,
                    "Using remote helm chart:"
                );
                self.helm_client.install(
                    &self.config.namespace,
                    DEFAULT_CHART_APP_REPO,
                    &self.config.chart_name,
                    Some(&self.config.chart_version),
                    &install_settings,
                )?;
            }
            // For local, we do not use a repo but install from the chart location directly.
            ChartLocation::Local(chart_home) => {
                let chart_location = chart_home.join(DEFAULT_APP_NAME);
                let chart_string = chart_location.to_string_lossy();
                debug!(
                    chart_location = chart_string.as_ref(),
                    "Using local helm chart:"
                );
                self.helm_client.install(
                    &self.config.namespace,
                    DEFAULT_CHART_APP_REPO,
                    chart_string.as_ref(),
                    Some(&self.config.chart_version),
                    &install_settings,
                )?;
            }
        }

        info!("Fluvio app chart has been installed");
        Ok(())
    }

    /// Uploads TLS secrets to Kubernetes
    fn upload_tls_secrets(&self, tls: &TlsConfig) -> Result<(), IoError> {
        let paths: Cow<TlsPaths> = match tls {
            TlsConfig::Files(paths) => Cow::Borrowed(paths),
            TlsConfig::Inline(certs) => Cow::Owned(certs.try_into_temp_files()?),
        };
        self.upload_tls_secrets_from_files(paths.as_ref())?;
        Ok(())
    }

    /// Looks up the external address of a Fluvio SC instance in the given namespace
    #[instrument(skip(self, ns))]
    async fn discover_sc_address(&self, ns: &str) -> Result<Option<String>, K8InstallError> {
        use k8_client::http::status::StatusCode;

        let result = self
            .kube_client
            .retrieve_item::<ServiceSpec, _>(&InputObjectMeta::named("fluvio-sc-public", ns))
            .await;

        let svc = match result {
            Ok(svc) => svc,
            Err(k8_client::ClientError::Client(status)) if status == StatusCode::NOT_FOUND => {
                info!("no SC service found");
                return Ok(None);
            }
            Err(err) => return Err(K8InstallError::from(err)),
        };

        let ingress_addr = svc
            .status
            .load_balancer
            .ingress
            .iter()
            .find(|_| true)
            .and_then(|ingress| ingress.host_or_ip().to_owned());

        let sock_addr = ingress_addr.and_then(|addr| {
            svc.spec
                .ports
                .iter()
                .find(|_| true)
                .and_then(|port| port.target_port)
                .map(|target_port| format!("{}:{}", addr, target_port))
        });

        Ok(sock_addr)
    }

    /// Wait until the Fluvio SC public service appears in Kubernetes
    #[instrument(skip(self, ns))]
    async fn wait_for_sc_service(&self, ns: &str) -> Result<String, K8InstallError> {
        info!("waiting for SC service");
        for i in 0..12 {
            if let Some(sock_addr) = self.discover_sc_address(ns).await? {
                info!(%sock_addr, "found SC service load balancer, discovered SC address");
                self.wait_for_sc_port_check(&sock_addr).await?;
                return Ok(sock_addr);
            }

            let sleep_ms = 1000 * 2u64.pow(i as u32);
            info!(
                attempt = i,
                "no SC service found, sleeping for {} ms", sleep_ms
            );
            sleep(Duration::from_millis(sleep_ms)).await;
        }

        Err(K8InstallError::SCServiceTimeout)
    }

    /// Wait until the Fluvio SC public service appears in Kubernetes
    async fn wait_for_sc_port_check(&self, sock_addr_str: &str) -> Result<(), K8InstallError> {
        info!(sock_addr = %sock_addr_str, "waiting for SC port check");
        for i in 0..12 {
            let sock_addr = self.wait_for_sc_dns(&sock_addr_str).await?;
            if TcpStream::connect(&*sock_addr).await.is_ok() {
                info!(sock_addr = %sock_addr_str, "finished SC port check");
                return Ok(());
            }
            let sleep_ms = 1000 * 2u64.pow(i as u32);
            info!(attempt = i, "sc port closed, sleeping for {} ms", sleep_ms);
            sleep(Duration::from_millis(sleep_ms)).await;
        }
        error!(sock_addr = %sock_addr_str, "timeout for SC port check");
        Err(K8InstallError::SCPortCheckTimeout)
    }

    /// Wait until the Fluvio SC public service appears in Kubernetes
    async fn wait_for_sc_dns(
        &self,
        sock_addr_string: &str,
    ) -> Result<Vec<SocketAddr>, K8InstallError> {
        info!("waiting for SC dns resolution: {}", sock_addr_string);
        for i in 0..12 {
            match resolve(sock_addr_string).await {
                Ok(sock_addr) => {
                    debug!("finished SC dns resolution: {}", sock_addr_string);
                    return Ok(sock_addr);
                }
                Err(err) => {
                    let sleep_ms = 1000 * 2u64.pow(i as u32);
                    info!(
                        attempt = i,
                        "SC dns resoultion failed {}, sleeping for {} ms", err, sleep_ms
                    );
                    sleep(Duration::from_millis(sleep_ms)).await;
                }
            }
        }

        error!("timedout sc dns: {}", sock_addr_string);
        Err(K8InstallError::SCDNSTimeout)
    }

    /// Wait until all SPUs are ready and have ingress
    #[instrument(skip(self, ns))]
    async fn wait_for_spu(&self, ns: &str, spu: u16) -> Result<bool, K8InstallError> {
        info!("waiting for SPU");
        for i in 0..12 {
            debug!("retrieving spu specs");
            let items = self.kube_client.retrieve_items::<SpuSpec, _>(ns).await?;
            let spu_count = items.items.len();

            // Check that all items have ingress
            let ready_spu = items
                .items
                .iter()
                .filter(|spu_obj| {
                    !spu_obj.spec.public_endpoint.ingress.is_empty() && spu_obj.status.is_online()
                })
                .count();

            if spu as usize == ready_spu {
                info!(spu_count, "All SPUs are ready");
                return Ok(true);
            } else {
                debug!(
                    total_expected_spu = spu_count,
                    ready_spu,
                    attempt = i,
                    "Not all SPUs are ready. Waiting",
                );
                let sleep_ms = 1000 * 2u64.pow(i as u32);
                info!(
                    attempt = i,
                    "{} of {} spu ready, sleeping for {} ms", ready_spu, spu, sleep_ms
                );
                sleep(Duration::from_millis(sleep_ms)).await;
            }
        }

        Err(K8InstallError::SPUTimeout)
    }

    /// Install server-side TLS by uploading secrets to kubernetes
    #[instrument(skip(self, paths))]
    fn upload_tls_secrets_from_files(&self, paths: &TlsPaths) -> Result<(), IoError> {
        let ca_cert = paths
            .ca_cert
            .to_str()
            .ok_or_else(|| IoError::new(ErrorKind::InvalidInput, "ca_cert must be a valid path"))?;
        let server_cert = paths.cert.to_str().ok_or_else(|| {
            IoError::new(ErrorKind::InvalidInput, "server_cert must be a valid path")
        })?;
        let server_key = paths.key.to_str().ok_or_else(|| {
            IoError::new(ErrorKind::InvalidInput, "server_key must be a valid path")
        })?;
        debug!("Using TLS from paths: {:?}", paths);

        // Try uninstalling secrets first to prevent duplication error
        Command::new("kubectl")
            .args(&["delete", "secret", "fluvio-ca", "--ignore-not-found=true"])
            .args(&["--namespace", &self.config.namespace])
            .inherit();

        Command::new("kubectl")
            .args(&["delete", "secret", "fluvio-tls", "--ignore-not-found=true"])
            .args(&["--namespace", &self.config.namespace])
            .inherit();

        Command::new("kubectl")
            .args(&["create", "secret", "generic", "fluvio-ca"])
            .args(&["--from-file", ca_cert])
            .args(&["--namespace", &self.config.namespace])
            .inherit();

        Command::new("kubectl")
            .args(&["create", "secret", "tls", "fluvio-tls"])
            .args(&["--cert", server_cert])
            .args(&["--key", server_key])
            .args(&["--namespace", &self.config.namespace])
            .inherit();

        Ok(())
    }

    /// Updates the Fluvio configuration with the newly installed cluster info.
    fn update_profile(&self, external_addr: String) -> Result<(), K8InstallError> {
        debug!("updating profile for: {}", external_addr);
        let mut config_file = ConfigFile::load_default_or_new()?;
        let config = config_file.mut_config();

        let profile_name = self.compute_profile_name()?;

        match config.cluster_mut(&profile_name) {
            Some(cluster) => {
                cluster.addr = external_addr;
                cluster.tls = self.config.client_tls_policy.clone();
            }
            None => {
                let mut local_cluster = FluvioConfig::new(external_addr);
                local_cluster.tls = self.config.client_tls_policy.clone();
                config.add_cluster(local_cluster, profile_name.clone());
            }
        }

        match config.profile_mut(&profile_name) {
            Some(profile) => {
                profile.set_cluster(profile_name.clone());
            }
            None => {
                let profile = Profile::new(profile_name.clone());
                config.add_profile(profile, profile_name.clone());
            }
        };

        config.set_current_profile(&profile_name);
        config_file.save()?;
        Ok(())
    }

    /// Determines a profile name from the name of the active Kubernetes context
    fn compute_profile_name(&self) -> Result<String, K8InstallError> {
        let k8_config = K8Config::load()?;

        let kc_config = match k8_config {
            K8Config::Pod(_) => {
                return Err(K8InstallError::Other(
                    "Pod config is not valid here".to_owned(),
                ));
            }
            K8Config::KubeConfig(config) => config,
        };

        kc_config
            .config
            .current_context()
            .ok_or_else(|| K8InstallError::Other("No context fount".to_owned()))
            .map(|ctx| ctx.name.to_owned())
    }

    /// Provisions a SPU group for the given cluster according to internal config
    #[instrument(
    skip(self, cluster),
    fields(cluster_addr = & * cluster.addr)
    )]
    async fn create_managed_spu_group(&self, cluster: &FluvioConfig) -> Result<(), K8InstallError> {
        debug!("trying to create managed spu: {:#?}", cluster);
        let name = self.config.group_name.clone();
        let fluvio = Fluvio::connect_with_config(cluster).await?;
        let mut admin = fluvio.admin().await;
        admin
            .create(name, false, self.config.spu_spec.clone())
            .await?;

        Ok(())
    }
}