1313# limitations under the License.
1414
1515import os
16+ import datetime
1617
1718from kubernetes .client import Configuration
1819
@@ -40,10 +41,11 @@ def __init__(self, token_filename,
4041 self ._token_filename = token_filename
4142 self ._cert_filename = cert_filename
4243 self ._environ = environ
44+ self ._token_refresh_period = datetime .timedelta (minutes = 1 )
4345
44- def load_and_set (self ):
46+ def load_and_set (self , refresh_token = True ):
4547 self ._load_config ()
46- self ._set_config ()
48+ self ._set_config (refresh_token = refresh_token )
4749
4850 def _load_config (self ):
4951 if (SERVICE_HOST_ENV_NAME not in self ._environ or
@@ -61,10 +63,7 @@ def _load_config(self):
6163 if not os .path .isfile (self ._token_filename ):
6264 raise ConfigException ("Service token file does not exists." )
6365
64- with open (self ._token_filename ) as f :
65- self .token = f .read ()
66- if not self .token :
67- raise ConfigException ("Token file exists but empty." )
66+ self ._read_token_file ()
6867
6968 if not os .path .isfile (self ._cert_filename ):
7069 raise ConfigException (
@@ -76,19 +75,37 @@ def _load_config(self):
7675
7776 self .ssl_ca_cert = self ._cert_filename
7877
79- def _set_config (self ):
78+ def _set_config (self , refresh_token ):
8079 configuration = Configuration ()
8180 configuration .host = self .host
8281 configuration .ssl_ca_cert = self .ssl_ca_cert
8382 configuration .api_key ['authorization' ] = "bearer " + self .token
8483 Configuration .set_default (configuration )
84+ if not refresh_token :
85+ return
86+ def wrap (f ):
87+ in_cluster_config = self
88+ def wrapped (self , identifier ):
89+ if identifier == 'authorization' and identifier in self .api_key and in_cluster_config .token_expires_at <= datetime .datetime .now ():
90+ in_cluster_config ._read_token_file ()
91+ self .api_key [identifier ] = "bearer " + in_cluster_config .token
92+ return f (self , identifier )
93+ return wrapped
94+ Configuration .get_api_key_with_prefix = wrap (Configuration .get_api_key_with_prefix )
95+
96+ def _read_token_file (self ):
97+ with open (self ._token_filename ) as f :
98+ self .token = f .read ()
99+ self .token_expires_at = datetime .datetime .now () + self ._token_refresh_period
100+ if not self .token :
101+ raise ConfigException ("Token file exists but empty." )
85102
86103
87- def load_incluster_config ():
104+ def load_incluster_config (refresh_token = True ):
88105 """
89106 Use the service account kubernetes gives to pods to connect to kubernetes
90107 cluster. It's intended for clients that expect to be running inside a pod
91108 running on kubernetes. It will raise an exception if called from a process
92109 not running in a kubernetes environment."""
93110 InClusterConfigLoader (token_filename = SERVICE_TOKEN_FILENAME ,
94- cert_filename = SERVICE_CERT_FILENAME ).load_and_set ()
111+ cert_filename = SERVICE_CERT_FILENAME ).load_and_set (refresh_token = refresh_token )
0 commit comments