2
2
3
3
import java .io .IOException ;
4
4
import java .io .InputStream ;
5
+ import java .nio .charset .Charset ;
5
6
import java .nio .charset .StandardCharsets ;
6
7
import java .text .MessageFormat ;
7
8
import java .util .ArrayList ;
@@ -22,6 +23,7 @@ public class KubeConfig {
22
23
23
24
private final CertManager certManager ;
24
25
private final BinaryManager binaryManager ;
26
+ private String previousCurrentContext ;
25
27
26
28
public KubeConfig (CertManager certManager , BinaryManager binaryManager ) {
27
29
this .certManager = certManager ;
@@ -30,6 +32,7 @@ public KubeConfig(CertManager certManager, BinaryManager binaryManager) {
30
32
31
33
public void updateKubeConfig (int apiServerPort ) {
32
34
log .debug ("Updating kubeconfig" );
35
+ previousCurrentContext = execWithKubectlConfigAndWait ("current-context" ).trim ();
33
36
execWithKubectlConfigAndWait ("set-cluster" , JENVTEST ,
34
37
"--server=https://127.0.0.1:" + apiServerPort ,
35
38
"--certificate-authority=" + certManager .getAPIServerCertPath ());
@@ -41,12 +44,15 @@ public void updateKubeConfig(int apiServerPort) {
41
44
execWithKubectlConfigAndWait ("use-context" , JENVTEST );
42
45
}
43
46
44
- public void cleanupFromKubeConfig () {
47
+ public void restoreKubeConfig () {
45
48
log .debug ("Cleanig up kubeconfig" );
46
49
unset ("contexts." + JENVTEST );
47
50
unset ("clusters." + JENVTEST );
48
51
unset ("users." + JENVTEST );
49
52
unset ("current-context" );
53
+ if (previousCurrentContext != null && !previousCurrentContext .isEmpty ()) {
54
+ execWithKubectlConfigAndWait ("use-context" , previousCurrentContext );
55
+ }
50
56
}
51
57
52
58
private void unset (String target ) {
@@ -65,14 +71,19 @@ public String generateKubeConfigYaml(int apiServerPort) {
65
71
}
66
72
}
67
73
68
- private void execWithKubectlConfigAndWait (String ... arguments ) {
74
+ private String execWithKubectlConfigAndWait (String ... arguments ) {
69
75
try {
70
76
List <String > args = new ArrayList <>(arguments .length + 2 );
71
77
args .add (binaryManager .binaries ().getKubectl ().getPath ());
72
78
args .add ("config" );
73
79
args .addAll (List .of (arguments ));
74
80
var process = new ProcessBuilder (args ).start ();
81
+ String stdout ;
82
+ try (InputStream is = process .getInputStream ()) {
83
+ stdout = IOUtils .toString (is , Charset .defaultCharset ());
84
+ }
75
85
process .waitFor ();
86
+ return stdout ;
76
87
} catch (IOException e ) {
77
88
throw new JenvtestException (e );
78
89
} catch (InterruptedException e ) {
0 commit comments