-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathv1alpha1_impl.rs
More file actions
1131 lines (1004 loc) · 34.4 KB
/
v1alpha1_impl.rs
File metadata and controls
1131 lines (1004 loc) · 34.4 KB
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::{collections::BTreeMap, path::PathBuf};
use k8s_openapi::api::core::v1::{
Container, EmptyDirVolumeSource, EnvVar, EnvVarSource, SecretKeySelector, Volume, VolumeMount,
};
use snafu::{ResultExt, Snafu};
use stackable_shared::time::Duration;
use strum::{EnumDiscriminants, IntoStaticStr};
use crate::{
builder::pod::{
container::ContainerBuilder,
resources::ResourceRequirementsBuilder,
volume::{VolumeBuilder, VolumeMountBuilder},
},
commons::product_image_selection::ResolvedProductImage,
crd::git_sync::v1alpha1::GitSync,
product_config_utils::insert_or_update_env_vars,
product_logging::{
framework::capture_shell_output,
spec::{ContainerLogConfig, ContainerLogConfigChoice},
},
utils::COMMON_BASH_TRAP_FUNCTIONS,
};
pub const CONTAINER_NAME_PREFIX: &str = "git-sync";
pub const VOLUME_NAME_PREFIX: &str = "content-from-git";
pub const MOUNT_PATH_PREFIX: &str = "/stackable/app/git";
pub const SSH_VOLUME_NAME_PREFIX: &str = "ssh-keys-info";
pub const SSH_MOUNT_PATH_PREFIX: &str = "/stackable/gitssh";
pub const GIT_SYNC_SAFE_DIR_OPTION: &str = "safe.directory";
pub const GIT_SYNC_ROOT_DIR: &str = "/tmp/git";
pub const GIT_SYNC_LINK: &str = "current";
#[derive(Snafu, Debug, EnumDiscriminants)]
#[strum_discriminants(derive(IntoStaticStr))]
pub enum Error {
#[snafu(display("invalid container name"))]
InvalidContainerName {
source: crate::builder::pod::container::Error,
},
#[snafu(display("failed to add needed volumeMount"))]
AddVolumeMount {
source: crate::builder::pod::container::Error,
},
#[snafu(display("failed to declare unique credentials"))]
MultipleCredentials,
}
impl GitSync {
pub(crate) fn default_branch() -> String {
"main".to_string()
}
pub(crate) fn default_git_folder() -> PathBuf {
PathBuf::from("/")
}
pub(crate) fn default_depth() -> u32 {
1
}
pub(crate) fn default_wait() -> Duration {
Duration::from_secs(20)
}
}
/// Kubernetes resources generated from `GitSync` specifications which should be added to the Pod.
#[derive(Default)]
pub struct GitSyncResources {
/// GitSync containers with regular synchronizations
pub git_sync_containers: Vec<Container>,
/// GitSync init containers with a one-time synchronizations
pub git_sync_init_containers: Vec<Container>,
/// GitSync volumes containing the synchronized repository
pub git_content_volumes: Vec<Volume>,
/// Volume mounts for the GitSync volumes
pub git_content_volume_mounts: Vec<VolumeMount>,
/// Absolute paths to the Git contents in the mounted volumes
pub git_content_folders: Vec<PathBuf>,
/// GitSync volumes containing the synchronized repository
pub git_ssh_volumes: Vec<Volume>,
}
impl GitSyncResources {
const LOG_VOLUME_MOUNT_PATH: &str = "/stackable/log";
/// Returns whether or not GitSync is enabled.
pub fn is_git_sync_enabled(&self) -> bool {
!self.git_sync_containers.is_empty()
}
/// Returns the Git content folders as strings
pub fn git_content_folders_as_string(&self) -> Vec<String> {
self.git_content_folders
.iter()
.map(|path| path.to_str().expect("The path names of the git_content_folders are created as valid UTF-8 strings, so Path::to_str should not fail.").to_owned())
.collect()
}
/// Creates `GitSyncResources` from the given `GitSync` specifications.
pub fn new(
git_syncs: &[GitSync],
resolved_product_image: &ResolvedProductImage,
extra_env_vars: &[EnvVar],
extra_volume_mounts: &[VolumeMount],
log_volume_name: &str,
container_log_config: &ContainerLogConfig,
) -> Result<GitSyncResources, Error> {
let mut resources = GitSyncResources::default();
for (i, git_sync) in git_syncs.iter().enumerate() {
if git_sync.credentials_secret.is_some() && git_sync.ssh_secret.is_some() {
// Gitsync will not allow the declaration of both ssh-key and password/token credentials
return Err(Error::MultipleCredentials);
}
let mut env_vars = vec![];
if let Some(git_credentials_secret) = &git_sync.credentials_secret {
env_vars.push(GitSyncResources::env_var_from_secret(
"GITSYNC_USERNAME",
git_credentials_secret,
"user",
));
env_vars.push(GitSyncResources::env_var_from_secret(
"GITSYNC_PASSWORD",
git_credentials_secret,
"password",
));
}
if git_sync.ssh_secret.is_some() {
env_vars.push(EnvVar {
name: "GITSYNC_SSH_KEY_FILE".to_owned(),
value: Some(format!("{SSH_MOUNT_PATH_PREFIX}-{i}/key").to_owned()),
value_from: None,
});
env_vars.push(EnvVar {
name: "GITSYNC_SSH_KNOWN_HOSTS_FILE".to_owned(),
value: Some(format!("{SSH_MOUNT_PATH_PREFIX}-{i}/knownHosts").to_owned()),
value_from: None,
});
}
env_vars = insert_or_update_env_vars(&env_vars, extra_env_vars);
let volume_name = format!("{VOLUME_NAME_PREFIX}-{i}");
let mount_path = format!("{MOUNT_PATH_PREFIX}-{i}");
let git_sync_root_volume_mount = VolumeMount {
name: volume_name.clone(),
mount_path: GIT_SYNC_ROOT_DIR.to_owned(),
..VolumeMount::default()
};
let log_volume_mount = VolumeMount {
name: log_volume_name.to_string(),
mount_path: Self::LOG_VOLUME_MOUNT_PATH.to_string(),
..VolumeMount::default()
};
let mut git_sync_container_volume_mounts =
vec![git_sync_root_volume_mount, log_volume_mount];
git_sync_container_volume_mounts.extend_from_slice(extra_volume_mounts);
if git_sync.ssh_secret.is_some() {
let ssh_mount_path = format!("{SSH_MOUNT_PATH_PREFIX}-{i}");
let ssh_volume_name = format!("{SSH_VOLUME_NAME_PREFIX}-{i}");
let ssh_volume_mount =
VolumeMountBuilder::new(ssh_volume_name, ssh_mount_path).build();
git_sync_container_volume_mounts.push(ssh_volume_mount);
}
let container = Self::create_git_sync_container(
&format!("{CONTAINER_NAME_PREFIX}-{i}"),
resolved_product_image,
git_sync,
false,
&env_vars,
&git_sync_container_volume_mounts,
container_log_config,
)?;
let init_container = Self::create_git_sync_container(
&format!("{CONTAINER_NAME_PREFIX}-{i}-init"),
resolved_product_image,
git_sync,
true,
&env_vars,
&git_sync_container_volume_mounts,
container_log_config,
)?;
let volume = VolumeBuilder::new(volume_name.clone())
.empty_dir(EmptyDirVolumeSource::default())
.build();
let git_content_volume_mount = VolumeMount {
name: volume_name.clone(),
mount_path: mount_path.clone(),
..VolumeMount::default()
};
let mut git_content_folder = PathBuf::from(mount_path);
let relative_git_folder = git_sync
.git_folder
.strip_prefix("/")
.unwrap_or(&git_sync.git_folder);
git_content_folder.push(GIT_SYNC_LINK);
git_content_folder.push(relative_git_folder);
resources.git_sync_containers.push(container);
resources.git_sync_init_containers.push(init_container);
resources.git_content_volumes.push(volume);
resources
.git_content_volume_mounts
.push(git_content_volume_mount);
resources.git_content_folders.push(git_content_folder);
if let Some(get_ssh_secret) = &git_sync.ssh_secret {
let ssh_volume_name = format!("{SSH_VOLUME_NAME_PREFIX}-{i}");
let ssh_secret_volume = VolumeBuilder::new(&ssh_volume_name)
.with_secret(get_ssh_secret, false)
.build();
resources.git_ssh_volumes.push(ssh_secret_volume);
}
}
Ok(resources)
}
fn create_git_sync_container(
container_name: &str,
resolved_product_image: &ResolvedProductImage,
git_sync: &GitSync,
one_time: bool,
env_vars: &[EnvVar],
volume_mounts: &[VolumeMount],
container_log_config: &ContainerLogConfig,
) -> Result<k8s_openapi::api::core::v1::Container, Error> {
let container = ContainerBuilder::new(container_name)
.context(InvalidContainerNameSnafu)?
.image_from_product_image(resolved_product_image)
.command(vec![
"/bin/bash".to_string(),
"-x".to_string(),
"-euo".to_string(),
"pipefail".to_string(),
"-c".to_string(),
])
.args(vec![Self::create_git_sync_shell_script(
container_name,
git_sync,
one_time,
container_log_config,
)])
.add_env_vars(env_vars.into())
.add_volume_mounts(volume_mounts.to_vec())
.context(AddVolumeMountSnafu)?
.resources(
ResourceRequirementsBuilder::new()
.with_cpu_request("100m")
.with_cpu_limit("200m")
.with_memory_request("64Mi")
.with_memory_limit("64Mi")
.build(),
)
.build();
Ok(container)
}
fn create_git_sync_shell_script(
container_name: &str,
git_sync: &GitSync,
one_time: bool,
container_log_config: &ContainerLogConfig,
) -> String {
let internal_args = BTreeMap::from([
("--repo".to_string(), git_sync.repo.as_str().to_owned()),
("--ref".to_string(), git_sync.branch.to_owned()),
("--depth".to_string(), git_sync.depth.to_string()),
(
"--period".to_string(),
format!("{}s", git_sync.wait.as_secs()),
),
("--link".to_string(), GIT_SYNC_LINK.to_string()),
("--root".to_string(), GIT_SYNC_ROOT_DIR.to_string()),
("--one-time".to_string(), one_time.to_string()),
]);
let internal_git_config = BTreeMap::from([(
GIT_SYNC_SAFE_DIR_OPTION.to_owned(),
GIT_SYNC_ROOT_DIR.to_owned(),
)]);
let mut git_sync_config = git_sync.git_sync_conf.clone();
// The key and value in Git configs are separated by a colon, but both can contain either
// escaped colons or unescaped colons if enclosed in quotes. To avoid parsing, just a String
// is used instead of a key-value pair.
let user_defined_git_config = git_sync_config.remove("--git-config");
if let Some(git_config) = &user_defined_git_config {
// Roughly check if the user defined Git config contains an internally defined config
// and emit a warning in case.
internal_git_config
.keys()
.filter(|key| git_config.contains(*key))
.for_each(|key| {
tracing::warn!(
"The Git config option {git_config:?} contains a value for {key} that \
overrides the value of this operator. Git-sync functionality will probably \
not work as expected!"
);
});
}
// The user-defined Git config is just appended.
// The user is responsible for escaping special characters like `:` and `,`.
let git_config = internal_git_config
.into_iter()
.map(|(key, value)| format!("{key}:{value}"))
.chain(user_defined_git_config)
.collect::<Vec<_>>()
.join(",");
let mut user_defined_args = BTreeMap::new();
for (key, value) in git_sync_config {
if internal_args.contains_key(&key) {
tracing::warn!(
"The git-sync option {key:?} is already internally defined and will be ignored."
);
} else {
// The user-defined arguments are not validated.
user_defined_args.insert(key, value);
}
}
let mut args = internal_args;
args.extend(user_defined_args);
args.insert("--git-config".to_string(), format!("'{git_config}'"));
let args_string = args
.into_iter()
.map(|(key, value)| format!("{key}={value}"))
.collect::<Vec<_>>()
.join(" ");
let mut shell_script = String::new();
if let ContainerLogConfig {
choice: Some(ContainerLogConfigChoice::Automatic(log_config)),
} = container_log_config
{
shell_script.push_str(&capture_shell_output(
Self::LOG_VOLUME_MOUNT_PATH,
container_name,
log_config,
));
shell_script.push('\n');
};
let git_sync_command = format!("/stackable/git-sync {args_string}");
if one_time {
shell_script.push_str(&git_sync_command);
} else {
// Run the git-sync command in the background
shell_script.push_str(&format!(
"{COMMON_BASH_TRAP_FUNCTIONS}
prepare_signal_handlers
{git_sync_command} &
wait_for_termination $!"
))
}
shell_script
}
fn env_var_from_secret(
var_name: impl Into<String>,
secret: impl Into<String>,
secret_key: impl Into<String>,
) -> EnvVar {
EnvVar {
name: var_name.into(),
value_from: Some(EnvVarSource {
secret_key_ref: Some(SecretKeySelector {
name: secret.into(),
key: secret_key.into(),
..Default::default()
}),
..Default::default()
}),
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
config::fragment::validate, product_config_utils::env_vars_from,
product_logging::spec::default_container_log_config, utils::yaml_from_str_singleton_map,
};
#[test]
fn test_no_git_sync() {
let git_syncs = [];
let resolved_product_image = ResolvedProductImage {
image: "oci.stackable.tech/sdp/product:latest".to_string(),
app_version_label_value: "1.0.0-latest"
.parse()
.expect("static app version label is always valid"),
product_version: "1.0.0".to_string(),
image_pull_policy: "Always".to_string(),
pull_secrets: None,
};
let extra_env_vars = [];
let extra_volume_mounts = [];
let git_sync_resources = GitSyncResources::new(
&git_syncs,
&resolved_product_image,
&extra_env_vars,
&extra_volume_mounts,
"log-volume",
&validate(default_container_log_config()).unwrap(),
)
.unwrap();
assert!(!git_sync_resources.is_git_sync_enabled());
assert!(git_sync_resources.git_sync_containers.is_empty());
assert!(git_sync_resources.git_sync_init_containers.is_empty());
assert!(git_sync_resources.git_content_volumes.is_empty());
assert!(git_sync_resources.git_content_volume_mounts.is_empty());
assert!(git_sync_resources.git_content_folders.is_empty());
}
#[test]
fn test_multiple_git_syncs() {
let git_sync_spec = r#"
# GitSync with defaults
- repo: https://github.com/stackabletech/repo1
# GitSync with usual configuration
- repo: https://github.com/stackabletech/repo2
branch: trunk
gitFolder: ""
depth: 3
wait: 1m
credentialsSecret: git-credentials
gitSyncConf:
--rev: HEAD
--git-config: http.sslCAInfo:/tmp/ca-cert/ca.crt
# GitSync with unusual configuration
- repo: https://github.com/stackabletech/repo3
branch: feat/git-sync
# leading slashes should be removed
gitFolder: ////folder
gitSyncConf:
--depth: internal option which should be ignored
--link: internal option which should be ignored
--period: internal option which should be ignored
--ref: internal option which should be ignored
--repo: internal option which should be ignored
--root: internal option which should be ignored
# safe.directory should be accepted but a warning will be emitted
--git-config: key:value,safe.directory:/safe-dir
"#;
let git_syncs: Vec<GitSync> = yaml_from_str_singleton_map(git_sync_spec).unwrap();
let resolved_product_image = ResolvedProductImage {
image: "oci.stackable.tech/sdp/product:latest".to_string(),
app_version_label_value: "1.0.0-latest"
.parse()
.expect("static app version label is always valid"),
product_version: "1.0.0".to_string(),
image_pull_policy: "Always".to_string(),
pull_secrets: None,
};
let extra_env_vars = env_vars_from([
("VAR1", "value1"),
("GITSYNC_USERNAME", "overriden-username"),
]);
let extra_volume_mounts = [VolumeMount {
name: "extra-volume".to_string(),
mount_path: "/mnt/extra-volume".to_string(),
..VolumeMount::default()
}];
let git_sync_resources = GitSyncResources::new(
&git_syncs,
&resolved_product_image,
&extra_env_vars,
&extra_volume_mounts,
"log-volume",
&validate(default_container_log_config()).unwrap(),
)
.unwrap();
assert!(git_sync_resources.is_git_sync_enabled());
assert_eq!(3, git_sync_resources.git_sync_containers.len());
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-0 && exec > >(tee /stackable/log/git-sync-0/container.stdout.log) 2> >(tee /stackable/log/git-sync-0/container.stderr.log >&2)
prepare_signal_handlers()
{
unset term_child_pid
unset term_kill_needed
trap 'handle_term_signal' TERM
}
handle_term_signal()
{
if [ "${term_child_pid}" ]; then
kill -TERM "${term_child_pid}" 2>/dev/null
else
term_kill_needed="yes"
fi
}
wait_for_termination()
{
set +e
term_child_pid=$1
if [[ -v term_kill_needed ]]; then
kill -TERM "${term_child_pid}" 2>/dev/null
fi
wait ${term_child_pid} 2>/dev/null
trap - TERM
wait ${term_child_pid} 2>/dev/null
set -e
}
prepare_signal_handlers
/stackable/git-sync --depth=1 --git-config='safe.directory:/tmp/git' --link=current --one-time=false --period=20s --ref=main --repo=https://github.com/stackabletech/repo1 --root=/tmp/git &
wait_for_termination $!
command:
- /bin/bash
- -x
- -euo
- pipefail
- -c
env:
- name: GITSYNC_USERNAME
value: overriden-username
- name: VAR1
value: value1
image: oci.stackable.tech/sdp/product:latest
imagePullPolicy: Always
name: git-sync-0
resources:
limits:
cpu: 200m
memory: 64Mi
requests:
cpu: 100m
memory: 64Mi
volumeMounts:
- mountPath: /tmp/git
name: content-from-git-0
- mountPath: /stackable/log
name: log-volume
- mountPath: /mnt/extra-volume
name: extra-volume
"#,
serde_yaml::to_string(&git_sync_resources.git_sync_containers.first()).unwrap()
);
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-1 && exec > >(tee /stackable/log/git-sync-1/container.stdout.log) 2> >(tee /stackable/log/git-sync-1/container.stderr.log >&2)
prepare_signal_handlers()
{
unset term_child_pid
unset term_kill_needed
trap 'handle_term_signal' TERM
}
handle_term_signal()
{
if [ "${term_child_pid}" ]; then
kill -TERM "${term_child_pid}" 2>/dev/null
else
term_kill_needed="yes"
fi
}
wait_for_termination()
{
set +e
term_child_pid=$1
if [[ -v term_kill_needed ]]; then
kill -TERM "${term_child_pid}" 2>/dev/null
fi
wait ${term_child_pid} 2>/dev/null
trap - TERM
wait ${term_child_pid} 2>/dev/null
set -e
}
prepare_signal_handlers
/stackable/git-sync --depth=3 --git-config='safe.directory:/tmp/git,http.sslCAInfo:/tmp/ca-cert/ca.crt' --link=current --one-time=false --period=60s --ref=trunk --repo=https://github.com/stackabletech/repo2 --rev=HEAD --root=/tmp/git &
wait_for_termination $!
command:
- /bin/bash
- -x
- -euo
- pipefail
- -c
env:
- name: GITSYNC_PASSWORD
valueFrom:
secretKeyRef:
key: password
name: git-credentials
- name: GITSYNC_USERNAME
value: overriden-username
- name: VAR1
value: value1
image: oci.stackable.tech/sdp/product:latest
imagePullPolicy: Always
name: git-sync-1
resources:
limits:
cpu: 200m
memory: 64Mi
requests:
cpu: 100m
memory: 64Mi
volumeMounts:
- mountPath: /tmp/git
name: content-from-git-1
- mountPath: /stackable/log
name: log-volume
- mountPath: /mnt/extra-volume
name: extra-volume
"#,
serde_yaml::to_string(&git_sync_resources.git_sync_containers.get(1)).unwrap()
);
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-2 && exec > >(tee /stackable/log/git-sync-2/container.stdout.log) 2> >(tee /stackable/log/git-sync-2/container.stderr.log >&2)
prepare_signal_handlers()
{
unset term_child_pid
unset term_kill_needed
trap 'handle_term_signal' TERM
}
handle_term_signal()
{
if [ "${term_child_pid}" ]; then
kill -TERM "${term_child_pid}" 2>/dev/null
else
term_kill_needed="yes"
fi
}
wait_for_termination()
{
set +e
term_child_pid=$1
if [[ -v term_kill_needed ]]; then
kill -TERM "${term_child_pid}" 2>/dev/null
fi
wait ${term_child_pid} 2>/dev/null
trap - TERM
wait ${term_child_pid} 2>/dev/null
set -e
}
prepare_signal_handlers
/stackable/git-sync --depth=1 --git-config='safe.directory:/tmp/git,key:value,safe.directory:/safe-dir' --link=current --one-time=false --period=20s --ref=feat/git-sync --repo=https://github.com/stackabletech/repo3 --root=/tmp/git &
wait_for_termination $!
command:
- /bin/bash
- -x
- -euo
- pipefail
- -c
env:
- name: GITSYNC_USERNAME
value: overriden-username
- name: VAR1
value: value1
image: oci.stackable.tech/sdp/product:latest
imagePullPolicy: Always
name: git-sync-2
resources:
limits:
cpu: 200m
memory: 64Mi
requests:
cpu: 100m
memory: 64Mi
volumeMounts:
- mountPath: /tmp/git
name: content-from-git-2
- mountPath: /stackable/log
name: log-volume
- mountPath: /mnt/extra-volume
name: extra-volume
"#,
serde_yaml::to_string(&git_sync_resources.git_sync_containers.get(2)).unwrap()
);
assert_eq!(3, git_sync_resources.git_sync_init_containers.len());
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-0-init && exec > >(tee /stackable/log/git-sync-0-init/container.stdout.log) 2> >(tee /stackable/log/git-sync-0-init/container.stderr.log >&2)
/stackable/git-sync --depth=1 --git-config='safe.directory:/tmp/git' --link=current --one-time=true --period=20s --ref=main --repo=https://github.com/stackabletech/repo1 --root=/tmp/git
command:
- /bin/bash
- -x
- -euo
- pipefail
- -c
env:
- name: GITSYNC_USERNAME
value: overriden-username
- name: VAR1
value: value1
image: oci.stackable.tech/sdp/product:latest
imagePullPolicy: Always
name: git-sync-0-init
resources:
limits:
cpu: 200m
memory: 64Mi
requests:
cpu: 100m
memory: 64Mi
volumeMounts:
- mountPath: /tmp/git
name: content-from-git-0
- mountPath: /stackable/log
name: log-volume
- mountPath: /mnt/extra-volume
name: extra-volume
"#,
serde_yaml::to_string(&git_sync_resources.git_sync_init_containers.first()).unwrap()
);
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-1-init && exec > >(tee /stackable/log/git-sync-1-init/container.stdout.log) 2> >(tee /stackable/log/git-sync-1-init/container.stderr.log >&2)
/stackable/git-sync --depth=3 --git-config='safe.directory:/tmp/git,http.sslCAInfo:/tmp/ca-cert/ca.crt' --link=current --one-time=true --period=60s --ref=trunk --repo=https://github.com/stackabletech/repo2 --rev=HEAD --root=/tmp/git
command:
- /bin/bash
- -x
- -euo
- pipefail
- -c
env:
- name: GITSYNC_PASSWORD
valueFrom:
secretKeyRef:
key: password
name: git-credentials
- name: GITSYNC_USERNAME
value: overriden-username
- name: VAR1
value: value1
image: oci.stackable.tech/sdp/product:latest
imagePullPolicy: Always
name: git-sync-1-init
resources:
limits:
cpu: 200m
memory: 64Mi
requests:
cpu: 100m
memory: 64Mi
volumeMounts:
- mountPath: /tmp/git
name: content-from-git-1
- mountPath: /stackable/log
name: log-volume
- mountPath: /mnt/extra-volume
name: extra-volume
"#,
serde_yaml::to_string(&git_sync_resources.git_sync_init_containers.get(1)).unwrap()
);
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-2-init && exec > >(tee /stackable/log/git-sync-2-init/container.stdout.log) 2> >(tee /stackable/log/git-sync-2-init/container.stderr.log >&2)
/stackable/git-sync --depth=1 --git-config='safe.directory:/tmp/git,key:value,safe.directory:/safe-dir' --link=current --one-time=true --period=20s --ref=feat/git-sync --repo=https://github.com/stackabletech/repo3 --root=/tmp/git
command:
- /bin/bash
- -x
- -euo
- pipefail
- -c
env:
- name: GITSYNC_USERNAME
value: overriden-username
- name: VAR1
value: value1
image: oci.stackable.tech/sdp/product:latest
imagePullPolicy: Always
name: git-sync-2-init
resources:
limits:
cpu: 200m
memory: 64Mi
requests:
cpu: 100m
memory: 64Mi
volumeMounts:
- mountPath: /tmp/git
name: content-from-git-2
- mountPath: /stackable/log
name: log-volume
- mountPath: /mnt/extra-volume
name: extra-volume
"#,
serde_yaml::to_string(&git_sync_resources.git_sync_init_containers.get(2)).unwrap()
);
assert_eq!(3, git_sync_resources.git_content_volumes.len());
assert_eq!(
"emptyDir: {}
name: content-from-git-0
",
serde_yaml::to_string(&git_sync_resources.git_content_volumes.first()).unwrap()
);
assert_eq!(
"emptyDir: {}
name: content-from-git-1
",
serde_yaml::to_string(&git_sync_resources.git_content_volumes.get(1)).unwrap()
);
assert_eq!(
"emptyDir: {}
name: content-from-git-2
",
serde_yaml::to_string(&git_sync_resources.git_content_volumes.get(2)).unwrap()
);
assert_eq!(3, git_sync_resources.git_content_volume_mounts.len());
assert_eq!(
"mountPath: /stackable/app/git-0
name: content-from-git-0
",
serde_yaml::to_string(&git_sync_resources.git_content_volume_mounts.first()).unwrap()
);
assert_eq!(
"mountPath: /stackable/app/git-1
name: content-from-git-1
",
serde_yaml::to_string(&git_sync_resources.git_content_volume_mounts.get(1)).unwrap()
);
assert_eq!(
"mountPath: /stackable/app/git-2
name: content-from-git-2
",
serde_yaml::to_string(&git_sync_resources.git_content_volume_mounts.get(2)).unwrap()
);
assert_eq!(3, git_sync_resources.git_content_folders.len());
assert_eq!(
"/stackable/app/git-0/current/",
git_sync_resources
.git_content_folders_as_string()
.first()
.unwrap()
);
assert_eq!(
"/stackable/app/git-1/current/",
git_sync_resources
.git_content_folders_as_string()
.get(1)
.unwrap()
);
assert_eq!(
"/stackable/app/git-2/current/folder",
git_sync_resources
.git_content_folders_as_string()
.get(2)
.unwrap()
);
}
#[test]
fn test_git_sync_ssh() {
let git_sync_spec = r#"
# GitSync using SSH
- repo: ssh://git@github.com/stackabletech/repo.git
branch: trunk
gitFolder: ""
depth: 3
wait: 1m
sshSecret: git-sync-ssh
gitSyncConf:
--rev: HEAD
--git-config: http.sslCAInfo:/tmp/ca-cert/ca.crt
"#;
let git_syncs: Vec<GitSync> = yaml_from_str_singleton_map(git_sync_spec).unwrap();
let resolved_product_image = ResolvedProductImage {
image: "oci.stackable.tech/sdp/product:latest".to_string(),
app_version_label_value: "1.0.0-latest"
.parse()
.expect("static app version label is always valid"),
product_version: "1.0.0".to_string(),
image_pull_policy: "Always".to_string(),
pull_secrets: None,
};
let extra_env_vars = env_vars_from([("VAR1", "value1")]);
let extra_volume_mounts = [VolumeMount {
name: "extra-volume".to_string(),
mount_path: "/mnt/extra-volume".to_string(),
..VolumeMount::default()
}];
let git_sync_resources = GitSyncResources::new(
&git_syncs,
&resolved_product_image,
&extra_env_vars,
&extra_volume_mounts,
"log-volume",
&validate(default_container_log_config()).unwrap(),
)
.unwrap();
assert!(git_sync_resources.is_git_sync_enabled());
assert_eq!(1, git_sync_resources.git_sync_containers.len());
assert_eq!(
r#"args:
- |-
mkdir --parents /stackable/log/git-sync-0 && exec > >(tee /stackable/log/git-sync-0/container.stdout.log) 2> >(tee /stackable/log/git-sync-0/container.stderr.log >&2)
prepare_signal_handlers()
{
unset term_child_pid
unset term_kill_needed
trap 'handle_term_signal' TERM
}
handle_term_signal()
{
if [ "${term_child_pid}" ]; then
kill -TERM "${term_child_pid}" 2>/dev/null
else
term_kill_needed="yes"
fi
}
wait_for_termination()
{
set +e
term_child_pid=$1