示例#1
0
 def setUp(self):
     super(TestK8sClient, self).setUp()
     self.base_url = 'http://127.0.0.1:12345'
     self.client = k8s_client.K8sClient(self.base_url)
     default_cert = (None, None)
     self.assertEqual(default_cert, self.client.cert)
     self.assertEqual(False, self.client.verify_server)
示例#2
0
    def test_bearer_token(self, m_cfg, m_get):
        token_content = (
            "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJrdWJlcm5ldGVzL3Nl"
            "cnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc"
            "3BhY2UiOiJrdWJlLXN5c3RlbSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bn"
            "Qvc2VjcmV0Lm5hbWUiOiJkZWZhdWx0LXRva2VuLWh4M3QxIiwia3ViZXJuZXRlcy5"
            "pby9zZXJ2aWNlYWNjb3VudC9zZXJ2aWNlLWFjY291bnQubmFtZSI6ImRlZmF1bHQi"
            "LCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC51a"
            "WQiOiIxYTkyM2ZmNi00MDkyLTExZTctOTMwYi1mYTE2M2VkY2ViMDUiLCJzdWIiOi"
            "JzeXN0ZW06c2VydmljZWFjY291bnQ6a3ViZS1zeXN0ZW06ZGVmYXVsdCJ9.lzcPef"
            "DQ-uzF5cD-5pLwTKpRvtvvxKB4LX8TLymrPLMTth8WGr1vT6jteJPmLiDZM2C5dZI"
            "iFJpOw4LL1XLullik-ls-CmnTWq97NvlW1cZolC0mNyRz6JcL7gkH8WfUSjLA7x80"
            "ORalanUxtl9-ghMGKCtKIACAgvr5gGT4iznGYQQRx_hKURs4O6Js5vhwNM6UuOKeW"
            "GDDAlhgHMG0u59z3bhiBLl6jbQktZsu8c3diXniQb3sYqYQcGKUm1IQFujyA_ByDb"
            "5GUtCv1BOPL_-IjYtvdJD8ZzQ_UnPFoYQklpDyJLB7_7qCGcfVEQbnSCh907NdKo4"
            "w_8Wkn2y-Tg")
        token_file = tempfile.NamedTemporaryFile(mode="w+t", delete=False)
        try:
            m_cfg.kubernetes.token_file = token_file.name
            token_file.write(token_content)
            token_file.close()
            m_cfg.kubernetes.ssl_verify_server_crt = False

            path = '/test'
            client = k8s_client.K8sClient(self.base_url)
            client.get(path)
            headers = {
                'Authorization': 'Bearer {}'.format(token_content)}
            m_get.assert_called_once_with(
                self.base_url + path, cert=(None, None), headers=headers,
                verify=False, timeout=(30, 60))
        finally:
            os.unlink(m_cfg.kubernetes.token_file)
def setup_kubernetes_client():
    if config.CONF.kubernetes.api_root:
        api_root = config.CONF.kubernetes.api_root
    else:
        # NOTE(dulek): This is for containerized deployments, i.e. running in
        #              K8s Pods.
        host = os.environ['KUBERNETES_SERVICE_HOST']
        port = os.environ['KUBERNETES_SERVICE_PORT_HTTPS']
        api_root = "https://%s:%s" % (host, port)
    _clients[_KUBERNETES_CLIENT] = k8s_client.K8sClient(api_root)
示例#4
0
 def test_https_client_init(self, m_cfg, m_exist):
     m_cfg.kubernetes.ssl_client_crt_file = 'dummy_crt_file_path'
     m_cfg.kubernetes.ssl_client_key_file = 'dummy_key_file_path'
     m_cfg.kubernetes.ssl_ca_crt_file = 'dummy_ca_file_path'
     m_cfg.kubernetes.ssl_verify_server_crt = True
     m_exist.return_value = True
     test_client = k8s_client.K8sClient(self.base_url)
     cert = ('dummy_crt_file_path', 'dummy_key_file_path')
     self.assertEqual(cert, test_client.cert)
     self.assertEqual('dummy_ca_file_path', test_client.verify_server)
示例#5
0
 def setUp(self, m_cfg):
     super(TestK8sClient, self).setUp()
     self.base_url = 'http://127.0.0.1:12345'
     m_cfg.kubernetes.ssl_client_crt_file = None
     m_cfg.kubernetes.ssl_client_key_file = None
     m_cfg.kubernetes.ssl_ca_crt_file = None
     m_cfg.kubernetes.token_file = None
     m_cfg.kubernetes.ssl_verify_server_crt = False
     self.client = k8s_client.K8sClient(self.base_url)
     default_cert = (None, None)
     default_token = None
     self.assertEqual(default_cert, self.client.cert)
     self.assertEqual(False, self.client.verify_server)
     self.assertEqual(default_token, self.client.token)
示例#6
0
def setup_kubernetes_client():
    if config.CONF.kubernetes.api_root:
        api_root = config.CONF.kubernetes.api_root
    else:
        # NOTE(dulek): This is for containerized deployments, i.e. running in
        #              K8s Pods.
        host = os.environ['KUBERNETES_SERVICE_HOST']
        port = os.environ['KUBERNETES_SERVICE_PORT_HTTPS']
        try:
            addr = ipaddress.ip_address(host)
            if addr.version == 6:
                host = '[%s]' % host
        except ValueError:
            # It's not an IP addres but a hostname, it's fine, move along.
            pass
        api_root = "https://%s:%s" % (host, port)
    _clients[_KUBERNETES_CLIENT] = k8s_client.K8sClient(api_root)
示例#7
0
def setup_kubernetes_client():
    _clients[_KUBERNETES_CLIENT] = k8s_client.K8sClient(
        config.CONF.kubernetes.api_root)
def webhook():
    global first_request
    if first_request:
        first_request = False
        host = os.environ['KUBERNETES_SERVICE_HOST']
        port = os.environ['KUBERNETES_SERVICE_PORT']
        api_root = "https://%s:%s" % (host, port)
        k8s = k8s_client.K8sClient(api_root)
        # list of namespaces with operators to delete
        for ns in app.config['ns_to_clear']:
            try:
                pods = k8s.get('{}/namespaces/{}/pods'.format(
                    constants.K8S_API_BASE, ns))
            except (exceptions.K8sClientException,
                    exceptions.K8sResourceNotFound):
                # unexpected exception, ensure it gets retried
                first_request = True
                continue
            for pod in pods.get('items'):
                options = pod['spec'].get('dnsConfig', {}).get('options', [])
                if not [o for o in options if o['name'] == 'use-vc']:
                    try:
                        k8s.delete('{}/namespaces/{}/pods/{}'.format(
                            constants.K8S_API_BASE, ns,
                            pod['metadata']['name']))
                    except (exceptions.K8sClientException,
                            exceptions.K8sResourceNotFound):
                        # unexpected exception, ensure it gets retried
                        first_request = True
                        continue

    request_info = request.json

    obj = request_info['request']['object']
    mod = copy.deepcopy(obj)
    patch_str = ""

    if 'dnsConfig' not in mod['spec']:
        mod['spec']['dnsConfig'] = {}

    if 'options' not in mod['spec']['dnsConfig']:
        mod['spec']['dnsConfig']['options'] = []

    if not [o for o in mod['spec']['dnsConfig']['options']
            if o['name'] == 'use-vc']:
        mod['spec']['dnsConfig']['options'].append(
            {'name': 'use-vc', 'value': ''})

        patch = jsonpatch.JsonPatch.from_diff(obj, mod)
        patch_str = base64.b64encode(str(patch).encode()).decode()

    admission_review = {
        'apiVersion': request_info['apiVersion'],
        'kind': request_info['kind'],
        'response': {
            'allowed': True,
            'uid': request_info['request']['uid'],
        },
    }

    if patch_str:
        admission_review['response'].update({
            'patch': patch_str,
            'patchType': 'JSONPatch',
        })

    return jsonify(admission_review)
示例#9
0
 def setUp(self):
     super(TestK8sClient, self).setUp()
     self.base_url = 'http://127.0.0.1:12345'
     self.client = k8s_client.K8sClient(self.base_url)