-
Notifications
You must be signed in to change notification settings - Fork 198
/
k8.rs
1392 lines (1269 loc) · 52.3 KB
/
k8.rs
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
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::borrow::Cow;
use std::process::Command;
use std::time::Duration;
use std::net::SocketAddr;
use std::env;
use derive_builder::Builder;
use tracing::{info, warn, debug, error, instrument};
use once_cell::sync::Lazy;
use tempfile::NamedTempFile;
use fluvio::{Fluvio, FluvioConfig};
use fluvio::metadata::spg::SpuGroupSpec;
use fluvio::metadata::spu::SpuSpec;
use fluvio::config::{TlsPolicy, TlsConfig, TlsPaths, ConfigFile, Profile};
use fluvio_future::timer::sleep;
use fluvio_future::net::{TcpStream, resolve};
use k8_client::K8Client;
use k8_config::K8Config;
use k8_client::meta_client::MetadataClient;
use k8_types::core::service::{LoadBalancerType, ServiceSpec, TargetPort};
use k8_types::core::node::{NodeSpec, NodeAddress};
use crate::helm::{HelmClient, Chart};
use crate::check::{CheckFailed, CheckResults, AlreadyInstalled, SysChartCheck};
use crate::error::K8InstallError;
use crate::{
ClusterError, StartStatus, DEFAULT_NAMESPACE, DEFAULT_CHART_APP_REPO, CheckStatus,
ClusterChecker, CheckStatuses, DEFAULT_CHART_REMOTE, ChartLocation, SysConfig,
};
use crate::check::render::render_check_progress;
use fluvio_command::CommandExt;
use semver::Version;
const DEFAULT_REGISTRY: &str = "infinyon";
const DEFAULT_APP_NAME: &str = "fluvio-app";
const DEFAULT_CHART_APP_NAME: &str = "fluvio/fluvio-app";
const DEFAULT_GROUP_NAME: &str = "main";
const DEFAULT_CLOUD_NAME: &str = "minikube";
const DEFAULT_SPU_REPLICAS: u16 = 1;
const DEFAULT_DEV_CHART: &str = "./k8-util/helm";
const DEFAULT_SERVICE_TYPE: &str = "NodePort";
const FLUVIO_SC_SERVICE: &str = "fluvio-sc-public";
/// maximum time waiting for sc service to come up
static MAX_SC_SERVICE_WAIT: Lazy<u64> = Lazy::new(|| {
let var_value = env::var("FLV_CLUSTER_MAX_SC_SERVICE_WAIT").unwrap_or_default();
var_value.parse().unwrap_or(30)
});
/// maximum time waiting for network check, DNS or network
static MAX_SC_NETWORK_LOOP: Lazy<u16> = Lazy::new(|| {
let var_value = env::var("FLV_CLUSTER_MAX_SC_NETWORK_LOOP").unwrap_or_default();
var_value.parse().unwrap_or(30)
});
const NETWORK_SLEEP_MS: u64 = 2000;
/// maximum tiime for VERSION CHECK
static MAX_SC_VERSION_LOOP: Lazy<u8> = Lazy::new(|| {
let var_value = env::var("FLV_CLUSTER_MAX_SC_VERSION_LOOP").unwrap_or_default();
var_value.parse().unwrap_or(60)
});
/// Describes how to install Fluvio onto Kubernetes
#[derive(Builder, Debug)]
#[builder(build_fn(private, name = "build_impl"))]
pub struct ClusterConfig {
/// Sets the Kubernetes namespace to install Fluvio into.
///
/// The default namespace is "default".
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .namespace("my-namespace")
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(setter(into), default = "DEFAULT_NAMESPACE.to_string()")]
namespace: String,
/// 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:
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .image_tag("0.6.0")
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(setter(into, strip_option), default)]
image_tag: Option<String>,
/// 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 [`image_tag`] to see how to specify the `0.1.0` shown here.
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .image_registry("localhost:5000/infinyon")
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// Then, when you use `installer.install_fluvio()`, it will pull the images
/// from your local docker registry.
///
/// [`image_tag`]: ./struct.ClusterInstaller.html#method.image_tag
#[builder(setter(into), default = "DEFAULT_REGISTRY.to_string()")]
image_registry: String,
/// The name of the Fluvio helm chart to install
#[builder(setter(into), default = "DEFAULT_CHART_APP_NAME.to_string()")]
chart_name: String,
/// 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
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// use semver::Version;
/// let config = builder
/// .chart_version(Version::parse("0.6.0").unwrap())
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// [Semver]: https://docs.rs/semver/0.10.0/semver/
#[builder(setter(into))]
chart_version: Version,
/// The location to search for the Helm charts to install
#[builder(
private,
default = "ChartLocation::Remote(DEFAULT_CHART_REMOTE.to_string())"
)]
chart_location: ChartLocation,
/// Sets a custom SPU group name. The default is `main`.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .group_name("orange")
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(setter(into), default = "DEFAULT_GROUP_NAME.to_string()")]
group_name: String,
/// Sets the K8 cluster cloud environment.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .cloud("minikube")
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
#[builder(setter(into), default = "DEFAULT_CLOUD_NAME.to_string()")]
cloud: String,
/// How many SPUs to provision for this Fluvio cluster. Defaults to 1
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .spu_replicas(2)
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(default = "DEFAULT_SPU_REPLICAS")]
spu_replicas: u16,
/// Sets the [`RUST_LOG`] environment variable for the installation.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .rust_log("debug")
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// [`RUST_LOG`]: https://docs.rs/tracing-subscriber/0.2.11/tracing_subscriber/filter/struct.EnvFilter.html
#[builder(setter(into, strip_option), default)]
rust_log: Option<String>,
/// The TLS policy for the SC and SPU servers
#[builder(default = "TlsPolicy::Disabled")]
server_tls_policy: TlsPolicy,
/// The TLS policy for the client
#[builder(default = "TlsPolicy::Disabled")]
client_tls_policy: TlsPolicy,
/// Set a list of chart value paths.
#[builder(default)]
chart_values: Vec<PathBuf>,
/// Sets the ConfigMap for authorization.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .authorization_config_map("authorization")
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
#[builder(setter(into, strip_option), default)]
authorization_config_map: Option<String>,
/// Whether to save a profile of this installation to `~/.fluvio/config`. Defaults to `false`.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .save_profile(true)
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(default = "false")]
save_profile: bool,
/// 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
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .install_sys(false)
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(default = "true")]
install_sys: bool,
/// 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
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .update_context(false)
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(default = "false")]
update_context: bool,
/// Whether to upgrade an existing installation
#[builder(default = "false")]
upgrade: bool,
/// Whether to skip pre-install checks before installation. Defaults to `false`.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .skip_checks(true)
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(default = "false")]
skip_checks: bool,
/// Use cluster IP instead of load balancer for communication to SC
///
/// This is is useful inside k8 cluster
#[builder(default = "false")]
use_cluster_ip: bool,
/// Use NodePort instead of load balancer for SC and SPU
#[builder(setter(into), default = "DEFAULT_SERVICE_TYPE.to_string()")]
service_type: String,
/// If set, skip spu liveness check
#[builder(default = "false")]
skip_spu_liveness_check: bool,
/// Whether to render pre-install checks to stdout as they are performed.
///
/// Defaults to `false`.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .render_checks(true)
/// .build()?;
/// # Ok(())
/// # }
/// ```
#[builder(default = "false")]
render_checks: bool,
}
impl ClusterConfig {
/// Creates a default [`ClusterConfigBuilder`].
///
/// The required option `chart_version` must be provided when constructing
/// the builder.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::ClusterConfig;
/// use semver::Version;
/// let builder = ClusterConfig::builder(Version::parse("0.7.0-alpha.1").unwrap());
/// ```
pub fn builder(chart_version: Version) -> ClusterConfigBuilder {
let mut builder = ClusterConfigBuilder::default();
builder.chart_version(chart_version);
builder
}
}
impl ClusterConfigBuilder {
/// Creates a [`ClusterConfig`] with the collected configuration options.
///
/// This may fail if there are missing required configuration options.
///
/// # Example
///
/// The simplest flow to create a `ClusterConfig` is the following:
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// use semver::Version;
/// let config = ClusterConfig::builder(Version::parse("0.7.0-alpha.1").unwrap()).build()?;
/// # Ok(())
/// # }
/// ```
///
/// [`ClusterInstaller`]: ./struct.ClusterInstaller.html
pub fn build(&self) -> Result<ClusterConfig, ClusterError> {
let config = self
.build_impl()
.map_err(K8InstallError::MissingRequiredConfig)?;
Ok(config)
}
/// Applies development options to this cluster configuration.
///
/// The following options are applied when using this method.
/// NOTE that these options will be overwritten even if they were
/// previously assigned.
///
/// - Use local_chart "./k8-util/helm"
/// - Use the git hash of HEAD as the image_tag
pub fn development(&mut self) -> Result<&mut Self, ClusterError> {
let output = Command::new("git")
.args(&["rev-parse", "HEAD"])
.result()
.map_err(K8InstallError::CommandError)?;
let git_hash = String::from_utf8(output.stdout).map_err(|e| {
K8InstallError::IoError(IoError::new(
ErrorKind::InvalidData,
format!("failed to get git hash: {}", e),
))
})?;
self.image_tag(git_hash.trim());
self.local_chart(DEFAULT_DEV_CHART);
Ok(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 [`remote_chart`]; if both are used,
/// the latest one defined is the one that's used.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .local_chart("./k8-util/helm")
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// [`remote_chart`]: ./struct.ClusterInstallerBuilder#method.remote_chart
pub fn local_chart<S: Into<PathBuf>>(&mut self, local_chart_location: S) -> &mut Self {
self.chart_location = Some(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 [`local_chart`]; if both are used,
/// the latest one defined is the one that's used.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// let config = builder
/// .remote_chart("https://charts.fluvio.io")
/// .build()?;
/// # Ok(())
/// # }
/// ```
///
/// [`local_chart`]: ./struct.ClusterInstallerBuilder#method.local_chart
pub fn remote_chart<S: Into<String>>(&mut self, remote_chart_location: S) -> &mut Self {
self.chart_location = Some(ChartLocation::Remote(remote_chart_location.into()));
self
}
/// Sets the TLS Policy that the client and server will use to communicate.
///
/// By default, these are set to `TlsPolicy::Disabled`.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterConfigBuilder, ClusterError};
/// # fn example(builder: &mut ClusterConfigBuilder) -> Result<(), ClusterError> {
/// use std::path::PathBuf;
/// use fluvio::config::TlsPaths;
/// use semver::Version;
///
/// 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 config = ClusterConfig::builder(Version::parse("0.7.0-alpha.1").unwrap())
/// .tls(client, server)
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn tls<C: Into<TlsPolicy>, S: Into<TlsPolicy>>(
&mut self,
client: C,
server: S,
) -> &mut 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 = Some(client_policy);
self.server_tls_policy = Some(server_policy);
self
}
/// A builder helper for conditionally setting options
///
/// This is useful for maintaining a builder call chain even when you
/// only want to apply some options conditionally based on a boolean value.
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterError, ClusterConfig};
/// # fn example() -> Result<(), ClusterError> {
/// use semver::Version;
/// let custom_namespace = false;
/// let config = ClusterConfig::builder(Version::parse("0.7.0-alpha.1").unwrap())
/// // Custom namespace is not applied
/// .with_if(custom_namespace, |builder| builder.namespace("my-namespace"))
/// .build()?;
/// # Ok(())
/// # }
/// ```
pub fn with_if<F>(&mut self, cond: bool, f: F) -> &mut Self
where
F: Fn(&mut Self) -> &mut Self,
{
if cond {
f(self)
} else {
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
///
/// ```
/// # use fluvio_cluster::{ClusterInstaller, ClusterConfig, ClusterError};
/// # async fn example() -> Result<(), ClusterError> {
/// use semver::Version;
/// let config = ClusterConfig::builder(Version::parse("0.7.0-alpha.1").unwrap()).build()?;
/// let installer = ClusterInstaller::from_config(config)?;
/// let _status = installer.install_fluvio().await?;
/// # Ok(())
/// # }
/// ```
///
/// [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: ClusterConfig,
/// Shared Kubernetes client for install
kube_client: K8Client,
/// Helm client for performing installs
helm_client: HelmClient,
}
impl ClusterInstaller {
/// Creates a `ClusterInstaller` from a `ClusterConfig`
///
/// # Example
///
/// ```
/// # use fluvio_cluster::{ClusterConfig, ClusterError, ClusterInstaller};
/// # fn example(config: ClusterConfig) -> Result<(), ClusterError> {
/// let installer = ClusterInstaller::from_config(config)?;
/// # Ok(())
/// # }
/// ```
pub fn from_config(config: ClusterConfig) -> Result<Self, ClusterError> {
Ok(Self {
config,
kube_client: K8Client::default().map_err(K8InstallError::K8ClientError)?,
helm_client: HelmClient::new().map_err(K8InstallError::HelmError)?,
})
}
/// 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)
}
/// 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:
///
/// - [`system_chart`]
/// - [`update_context`]
///
/// [`system_chart`]: ./struct.ClusterInstaller.html#method.system_chart
/// [`update_context`]: ./struct.ClusterInstaller.html#method.update_context
#[instrument(skip(self))]
pub async fn setup(&self) -> CheckResults {
let sys_config: SysConfig = SysConfig::builder(self.config.chart_version.clone())
.namespace(&self.config.namespace)
.chart_location(self.config.chart_location.clone())
.cloud(&self.config.cloud)
.build()
.unwrap();
let mut checker = ClusterChecker::empty()
.with_k8_checks()
.with_check(SysChartCheck::new(sys_config));
if !self.config.upgrade {
checker = checker.with_check(AlreadyInstalled);
}
if self.config.render_checks {
let mut progress = checker.run_and_fix_with_progress();
render_check_progress(&mut progress).await
} else {
checker.run_wait_and_fix().await
}
}
/// 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.iter().any(|it| it.is_err()) {
return Err(K8InstallError::PrecheckErrored(check_results).into());
}
let statuses: CheckStatuses =
check_results.into_iter().filter_map(|it| it.ok()).collect();
let mut any_failed = false;
for status in &statuses {
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, port) =
self.wait_for_sc_service(&self.config.namespace).await?;
return Ok(StartStatus {
address,
port,
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().await?;
let namespace = &self.config.namespace;
let (address, port) = 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())?;
}
let cluster =
FluvioConfig::new(address.clone()).with_tls(self.config.client_tls_policy.clone());
if self.config.spu_replicas > 0 && !self.config.upgrade {
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
self.create_managed_spu_group(&cluster).await?;
}
// When upgrading, wait for platform version to match new version
println!(
"Waiting up to {} seconds for Fluvio cluster version check...",
*MAX_SC_VERSION_LOOP * 2
);
self.wait_for_fluvio_version(&cluster).await?;
// Wait for the SPU cluster to spin up
if !self.config.skip_spu_liveness_check {
self.wait_for_spu(namespace).await?;
}
Ok(StartStatus {
address,
port,
checks,
})
}
/// Install Fluvio Core chart on the configured cluster
#[instrument(skip(self))]
async 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
.clone()
.unwrap_or_else(|| self.config.chart_version.to_string());
// Specify common installation settings to pass to helm
let mut install_settings: Vec<(_, Cow<str>)> = vec![
("image.registry", Cow::Borrowed(&self.config.image_registry)),
("image.tag", Cow::Borrowed(&fluvio_tag)),
("cloud", Cow::Borrowed(&self.config.cloud)),
];
// NodePort services need to provide SPU with an external address
// We're going to provide it via annotation on the SPU's K8 service
// We're going to write the annotation to a temp file so Helm can use it
// This is a workaround. More on this later in the function.
let (np_addr_fd, np_conf_path) = NamedTempFile::new()?.into_parts();
let np_pathbuf = vec![np_conf_path.to_path_buf()];
if self.config.service_type == "NodePort" {
debug!("Using NodePort service type");
debug!("Getting external IP from K8s node");
let kube_client = &self.kube_client;
debug!("Trying to query for Nodes");
let nodes = kube_client.retrieve_items::<NodeSpec, _>("").await?;
debug!("Results from Node query: {:#?}", &nodes);
let mut node_addr: Vec<NodeAddress> = Vec::new();
for n in nodes.items.into_iter().map(|x| x.status.addresses) {
node_addr.extend(n)
}
debug!("Node Addresses: {:#?}", node_addr);
let external_addr = node_addr
.into_iter()
.find(|a| a.r#type == "InternalIP")
.ok_or_else(|| K8InstallError::Other("No nodes with InternalIP set".into()))?;
// The following is a workaround for https://github.com/infinyon/fluvio-helm/issues/16
// Defining this annotation via `install_settings` var would be preference
// Set this annotation w/ the external address by overriding this Helm chart value:
let mut ingress_address = BTreeMap::new();
ingress_address.insert("fluvio.io/ingress-address", external_addr.address);
let mut service_annotation = BTreeMap::new();
service_annotation.insert("serviceAnnotations", ingress_address);
let mut helm_lb_config = BTreeMap::new();
helm_lb_config.insert("loadBalancer", service_annotation);
serde_yaml::to_writer(&np_addr_fd, &helm_lb_config)
.map_err(|err| K8InstallError::Other(err.to_string()))?;
}
// 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", Cow::Borrowed("true")));
}
// If RUST_LOG is defined, pass it to SC
if let Some(log) = &self.config.rust_log {
install_settings.push(("scLog", Cow::Borrowed(log)));
}
if let Some(authorization_config_map) = &self.config.authorization_config_map {
install_settings.push((
"authorizationConfigMap",
Cow::Borrowed(authorization_config_map),
));
}
use fluvio_helm::InstallArg;
let install_settings: Vec<(String, String)> = install_settings
.into_iter()
.map(|(k, v)| (k.to_owned(), v.to_string()))
.collect();
debug!("Using helm install settings: {:#?}", &install_settings);
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.to_string(),
)? {
return Err(K8InstallError::HelmChartNotFound(format!(
"{}:{}",
&self.config.chart_name, &self.config.chart_version
)));
}
debug!(
chart_location = &**chart_location,
"Using remote helm chart:"
);
let args = InstallArg::new(DEFAULT_CHART_APP_REPO, &self.config.chart_name)
.namespace(&self.config.namespace)
.opts(install_settings)
.develop()
.values([self.config.chart_values.clone(), np_pathbuf].concat())
.version(&self.config.chart_version.to_string());
debug!("Using helm install args: {:#?}", &args);
if self.config.upgrade {
self.helm_client.upgrade(&args)?;
} else {
self.helm_client.install(&args)?;
}
}
// 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:"
);
let args = InstallArg::new(DEFAULT_CHART_APP_REPO, chart_string)
.namespace(&self.config.namespace)
.opts(install_settings)
.develop()
.values([self.config.chart_values.clone(), np_pathbuf].concat())
.version(&self.config.chart_version.to_string());
debug!("Using helm install args: {:#?}", &args);
if self.config.upgrade {
self.helm_client.upgrade(&args)?;
} else {
self.helm_client.install(&args)?;
}
}
}
info!("Fluvio app chart has been installed");
Ok(())
}
/// Uploads TLS secrets to Kubernetes
fn upload_tls_secrets(&self, tls: &TlsConfig) -> Result<(), K8InstallError> {
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, u16)>, K8InstallError> {
use tokio::select;
use futures_lite::stream::StreamExt;
use fluvio_future::timer::sleep;
use k8_types::K8Watch;
let mut service_stream = self
.kube_client
.watch_stream_now::<ServiceSpec>(ns.to_string());
let mut timer = sleep(Duration::from_secs(*MAX_SC_SERVICE_WAIT));
loop {
select! {
_ = &mut timer => {
debug!(timer = *MAX_SC_SERVICE_WAIT,"timer expired");
return Ok(None)
},
service_next = service_stream.next() => {
if let Some(service_watches) = service_next {
for service_watch in service_watches? {
let service_value = match service_watch? {
K8Watch::ADDED(svc) => Some(svc),
K8Watch::MODIFIED(svc) => Some(svc),
K8Watch::DELETED(_) => None
};
if let Some(service) = service_value {
if service.metadata.name == FLUVIO_SC_SERVICE {
debug!(service = ?service,"found sc service");
let target_port = service.spec
.ports
.iter()
.filter_map(|port| {
match port.target_port {
Some(TargetPort::Number(value)) => Some(value),
Some(TargetPort::Name(_)) => None,
None => None
}
})
.next()
.ok_or_else(|| K8InstallError::Other("target port should be there".into()))?;
let node_port = service.spec
.ports
.iter()
.filter_map(|port| port.node_port)