66import io .fabric8 .kubernetes .client .ConfigBuilder ;
77import io .fabric8 .kubernetes .client .KubernetesClient ;
88import io .fabric8 .kubernetes .client .KubernetesClientBuilder ;
9+ import java .util .HashMap ;
10+ import java .util .Map ;
911import org .apache .commons .lang3 .StringUtils ;
1012import org .slf4j .Logger ;
1113import org .slf4j .LoggerFactory ;
@@ -16,19 +18,39 @@ public class KubernetesClientProvider {
1618
1719 private static final Logger LOGGER = LoggerFactory .getLogger (KubernetesClientProvider .class );
1820
21+ private static Map <String , KubernetesClient > rootKubernetesClientCache = new HashMap <>();
22+
23+ private static KubernetesClient userKubernetesClientCache = null ;
24+
1925 /**
2026 * This returns the root client which has extended permissions. Currently cluster-admin. User
2127 * calls should be done using the userClient which only has user permissions.
2228 *
2329 * @param region
2430 * @return
2531 */
26- public KubernetesClient getRootClient (Region region ) {
27- final Config config = getDefaultConfiguration (region ).build ();
28- return new KubernetesClientBuilder ().withConfig (config ).build ();
32+ public synchronized KubernetesClient getRootClient (Region region ) {
33+ if (!rootKubernetesClientCache .containsKey (region .getId ())) {
34+ final Config config = getDefaultConfiguration (region ).build ();
35+ rootKubernetesClientCache .put (
36+ region .getId (), new KubernetesClientBuilder ().withConfig (config ).build ());
37+ }
38+ return rootKubernetesClientCache .get (region .getId ());
2939 }
3040
3141 public KubernetesClient getUserClient (Region region , User user ) {
42+ // In case of SERVICEACCOUNT authentication, we can safely mutualize and use a single
43+ // KubernetesClient
44+ if (region .getServices ().getAuthenticationMode ()
45+ == Region .Services .AuthenticationMode .SERVICEACCOUNT ) {
46+ if (userKubernetesClientCache != null ) {
47+ return userKubernetesClientCache ;
48+ }
49+ Config config = getDefaultConfiguration (region ).build ();
50+ KubernetesClient client = new KubernetesClientBuilder ().withConfig (config ).build ();
51+ userKubernetesClientCache = client ;
52+ return client ;
53+ }
3254 final Config config = getDefaultConfiguration (region ).build ();
3355 String username = user .getIdep ();
3456 if (region .getServices ().getUsernamePrefix () != null ) {
0 commit comments