Skip to content

Commit 033e180

Browse files
committed
Add kube config support
1 parent 634a1b9 commit 033e180

File tree

5 files changed

+193
-1
lines changed

5 files changed

+193
-1
lines changed

.swagger-codegen-ignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
11
.gitignore
22
git_push.sh
33
test/*
4+
requirements.txt
5+
setup.py

k8sutil/__init__.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
from .kube_config import load_kube_config

k8sutil/kube_config.py

Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
# Copyright 2016 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import atexit
16+
import base64
17+
import os
18+
import tempfile
19+
20+
import urllib3
21+
import yaml
22+
from k8sclient import configuration
23+
from oauth2client.client import GoogleCredentials
24+
25+
_temp_files = []
26+
27+
28+
def _cleanup_temp_files():
29+
for f in _temp_files:
30+
os.remove(f)
31+
32+
33+
def _create_temp_file_with_content(content):
34+
if len(_temp_files) == 0:
35+
atexit.register(_cleanup_temp_files)
36+
_, name = tempfile.mkstemp()
37+
_temp_files.append(name)
38+
if isinstance(content, str):
39+
content = content.encode('utf8')
40+
with open(name, 'wb') as fd:
41+
fd.write(base64.decodestring(content))
42+
return name
43+
44+
45+
def _file_from_file_or_data(o, file_key_name, data_key_name=None):
46+
if not data_key_name:
47+
data_key_name = file_key_name + "-data"
48+
if data_key_name in o:
49+
return _create_temp_file_with_content(o[data_key_name])
50+
if file_key_name in o:
51+
return o[file_key_name]
52+
53+
54+
def _data_from_file_or_data(o, file_key_name, data_key_name=None):
55+
if not data_key_name:
56+
data_key_name = file_key_name + "_data"
57+
if data_key_name in o:
58+
return o[data_key_name]
59+
if file_key_name in o:
60+
with open(o[file_key_name], 'r') as f:
61+
data = f.read()
62+
return data
63+
64+
65+
def _load_gcp_token(user):
66+
if 'auth-provider' not in user:
67+
return
68+
if 'name' not in user['auth-provider']:
69+
return
70+
if user['auth-provider']['name'] != 'gcp':
71+
return
72+
# Ignore configs in auth-provider and rely on GoogleCredentials
73+
# caching and refresh mechanism.
74+
# TODO: support gcp command based token ("cmd-path" config).
75+
return (GoogleCredentials
76+
.get_application_default()
77+
.get_access_token()
78+
.access_token)
79+
80+
81+
def _load_authentication(user):
82+
"""Read authentication from kube-config user section.
83+
84+
This function goes through various authetication methods in user section of
85+
kubeconfig and stops if it founds a valid authentication method. The order
86+
of authentication methods is:
87+
88+
1. GCP auth-provider
89+
2. token_data
90+
3. token field (point to a token file)
91+
4. username/password
92+
"""
93+
# Read authentication
94+
token = _load_gcp_token(user)
95+
if not token:
96+
token = _data_from_file_or_data(user, 'tokenFile', 'token')
97+
if token:
98+
configuration.api_key['authorization'] = "bearer " + token
99+
else:
100+
if 'username' in user and 'password' in user:
101+
configuration.api_key['authorization'] = urllib3.util.make_headers(
102+
basic_auth=user['username'] + ':' +
103+
user['password']).get('authorization')
104+
105+
106+
def _load_cluster_info(cluster, user):
107+
"""Loads cluster information from kubeconfig such as host and SSL certs."""
108+
if 'server' in cluster:
109+
configuration.host = cluster['server']
110+
if configuration.host.startswith("https"):
111+
configuration.ssl_ca_cert = _file_from_file_or_data(
112+
cluster, 'certificate-authority')
113+
configuration.cert_file = _file_from_file_or_data(
114+
user, 'client-certificate')
115+
configuration.key_file = _file_from_file_or_data(
116+
user, 'client-key')
117+
118+
119+
class _node:
120+
"""Remembers each key's path and construct a relevant exception message
121+
in case of missing keys."""
122+
123+
def __init__(self, name, value):
124+
self._name = name
125+
self._value = value
126+
127+
def __contains__(self, key):
128+
return key in self._value
129+
130+
def __getitem__(self, key):
131+
if key in self._value:
132+
v = self._value[key]
133+
if isinstance(v, dict) or isinstance(v, list):
134+
return _node('%s/%s' % (self._name, key), v)
135+
else:
136+
return v
137+
raise Exception(
138+
'Invalid kube-config file. Expected key %s in %s'
139+
% (key, self._name))
140+
141+
def get_with_name(self, name):
142+
if not isinstance(self._value, list):
143+
raise Exception(
144+
'Invalid kube-config file. Expected %s to be a list'
145+
% self._name)
146+
for v in self._value:
147+
if 'name' not in v:
148+
raise Exception(
149+
'Invalid kube-config file. '
150+
'Expected all values in %s list to have \'name\' key'
151+
% self._name)
152+
if v['name'] == name:
153+
return _node('%s[name=%s]' % (self._name, name), v)
154+
raise Exception(
155+
"Cannot find object with name %s in %s list" % (name, self._name))
156+
157+
158+
def load_kube_config(config_file):
159+
"""Loads authentication and cluster information from kube-config file
160+
and store them in k8sclient.configuration."""
161+
162+
with open(config_file) as f:
163+
config = _node('kube-config', yaml.load(f))
164+
165+
current_context = config['contexts'].get_with_name(
166+
config['current-context'])['context']
167+
user = config['users'].get_with_name(current_context['user'])['user']
168+
cluster = config['clusters'].get_with_name(
169+
current_context['cluster'])['cluster']
170+
171+
_load_cluster_info(cluster, user)
172+
_load_authentication(user)

requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,6 @@ six == 1.8.0
33
python_dateutil >= 2.5.3
44
setuptools >= 21.0.0
55
urllib3 >= 1.15.1
6+
pyyaml >= 3.12
7+
oauth2client >= 4.0.0
8+

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
# prerequisite: setuptools
3636
# http://pypi.python.org/pypi/setuptools
3737

38-
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil"]
38+
REQUIRES = ["urllib3 >= 1.15", "six >= 1.10", "certifi", "python-dateutil", "pyyaml", "oauth2client"]
3939

4040
setup(
4141
name=NAME,

0 commit comments

Comments
 (0)