|
| 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) |
0 commit comments