mirror of
https://github.com/outbackdingo/patroni.git
synced 2026-08-25 14:53:37 +00:00
Get rid of kubernetes python module (#1586)
The official python kubernetes client contains a lot of auto-generated code and therefore very heavy, but we need only a little fraction of it. The naive implementation, that covers all API methods we use, takes about 250 LoC, and about half of it is responsible for the handling of configuration files. Disadvantage: If somebody was using the `patronictl` outside of the pod (on his machine), it might not work anymore (depending on the environment).
This commit is contained in:
+97
-22
@@ -2,10 +2,12 @@ import json
|
||||
import time
|
||||
import unittest
|
||||
|
||||
from mock import Mock, patch
|
||||
from patroni.dcs.kubernetes import Kubernetes, KubernetesError, k8s_client, RetryFailedError
|
||||
from mock import Mock, mock_open, patch
|
||||
from patroni.dcs.kubernetes import Kubernetes, KubernetesError, K8sConfig, K8sObject, RetryFailedError,\
|
||||
k8s_client, k8s_config, SERVICE_HOST_ENV_NAME, SERVICE_PORT_ENV_NAME
|
||||
from six.moves import builtins
|
||||
from threading import Thread
|
||||
from . import SleepException
|
||||
from . import MockResponse, SleepException
|
||||
|
||||
|
||||
def mock_list_namespaced_config_map(*args, **kwargs):
|
||||
@@ -51,28 +53,99 @@ def mock_namespaced_kind(*args, **kwargs):
|
||||
return mock
|
||||
|
||||
|
||||
def mock_load_k8s_config(self, *args, **kwargs):
|
||||
self._server = ''
|
||||
|
||||
|
||||
class TestK8sConfig(unittest.TestCase):
|
||||
|
||||
def test_load_incluster_config(self):
|
||||
for env in ({}, {SERVICE_HOST_ENV_NAME: '', SERVICE_PORT_ENV_NAME: ''}):
|
||||
with patch('os.environ', env):
|
||||
self.assertRaises(k8s_config.ConfigException, k8s_config.load_incluster_config)
|
||||
|
||||
with patch('os.environ', {SERVICE_HOST_ENV_NAME: 'a', SERVICE_PORT_ENV_NAME: '1'}),\
|
||||
patch('os.path.isfile', Mock(side_effect=[False, True, True, False, True, True, True, True])),\
|
||||
patch.object(builtins, 'open', Mock(side_effect=[
|
||||
mock_open()(), mock_open(read_data='a')(), mock_open(read_data='a')(),
|
||||
mock_open()(), mock_open(read_data='a')(), mock_open(read_data='a')()])):
|
||||
for _ in range(0, 4):
|
||||
self.assertRaises(k8s_config.ConfigException, k8s_config.load_incluster_config)
|
||||
k8s_config.load_incluster_config()
|
||||
self.assertEqual(k8s_config.server, 'https://a:1')
|
||||
|
||||
def test_load_kube_config(self):
|
||||
config = {
|
||||
"current-context": "local",
|
||||
"contexts": [{"name": "local", "context": {"user": "local", "cluster": "local"}}],
|
||||
"clusters": [{"name": "local", "cluster": {"server": "https://a:1/", "certificate-authority": "a"}}],
|
||||
"users": [{"name": "local", "user": {"username": "a", "password": "b", "client-certificate": "c"}}]
|
||||
}
|
||||
with patch.object(builtins, 'open', mock_open(read_data=json.dumps(config))):
|
||||
k8s_config.load_kube_config()
|
||||
self.assertEqual(k8s_config.server, 'https://a:1')
|
||||
self.assertEqual(k8s_config.pool_config, {'ca_certs': 'a', 'cert_file': 'c', 'cert_reqs': 'CERT_REQUIRED',
|
||||
'maxsize': 10, 'num_pools': 10})
|
||||
|
||||
config["users"][0]["user"]["token"] = "token"
|
||||
with patch.object(builtins, 'open', mock_open(read_data=json.dumps(config))):
|
||||
k8s_config.load_kube_config()
|
||||
self.assertEqual(k8s_config.headers.get('authorization'), 'Bearer token')
|
||||
|
||||
|
||||
class TestCoreV1Api(unittest.TestCase):
|
||||
|
||||
@patch.object(K8sConfig, '_server', '', create=True)
|
||||
def setUp(self):
|
||||
self.a = k8s_client.CoreV1Api()
|
||||
self.a._api_client.set_read_timeout(10)
|
||||
self.a._api_client.pool_manager.request = Mock(return_value=MockResponse())
|
||||
|
||||
def test_create_namespaced_service(self):
|
||||
self.assertEqual(str(self.a.create_namespaced_service('default', {}, _request_timeout=2)), '{}')
|
||||
|
||||
def test_list_namespaced_endpoints(self):
|
||||
self.a._api_client.pool_manager.request.return_value.content = '{"items": [1,2,3]}'
|
||||
self.assertIsInstance(self.a.list_namespaced_endpoints('default'), K8sObject)
|
||||
|
||||
def test_patch_namespaced_config_map(self):
|
||||
self.assertEqual(str(self.a.patch_namespaced_config_map('foo', 'default', {}, _request_timeout=(1, 2))), '{}')
|
||||
|
||||
def test_list_namespaced_pod(self):
|
||||
self.a._api_client.pool_manager.request.return_value.status_code = 409
|
||||
self.a._api_client.pool_manager.request.return_value.content = 'foo'
|
||||
try:
|
||||
self.a.list_namespaced_pod('default', label_selector='foo=bar')
|
||||
self.assertFail()
|
||||
except k8s_client.rest.ApiException as e:
|
||||
self.assertTrue('Reason: ' in str(e))
|
||||
|
||||
def test_delete_namespaced_pod(self):
|
||||
self.assertEqual(str(self.a.delete_namespaced_pod('foo', 'default', _request_timeout=(1, 2), body={})), '{}')
|
||||
|
||||
|
||||
class BaseTestKubernetes(unittest.TestCase):
|
||||
|
||||
@patch('socket.TCP_KEEPIDLE', 4, create=True)
|
||||
@patch('socket.TCP_KEEPINTVL', 5, create=True)
|
||||
@patch('socket.TCP_KEEPCNT', 6, create=True)
|
||||
@patch('kubernetes.config.load_kube_config', Mock())
|
||||
@patch('kubernetes.client.api_client.ThreadPool', Mock(), create=True)
|
||||
@patch.object(Thread, 'start', Mock())
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', mock_list_namespaced_pod)
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map)
|
||||
@patch.object(K8sConfig, 'load_kube_config', mock_load_k8s_config)
|
||||
@patch.object(K8sConfig, 'load_incluster_config', Mock(side_effect=k8s_config.ConfigException))
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_pod', mock_list_namespaced_pod, create=True)
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map, create=True)
|
||||
def setUp(self, config=None):
|
||||
config = config or {}
|
||||
config.update(ttl=30, scope='test', name='p-0', loop_wait=10, retry_timeout=10, labels={'f': 'b'})
|
||||
self.k = Kubernetes(config)
|
||||
self.assertRaises(AttributeError, self.k._pods._build_cache)
|
||||
self.k._pods._is_ready = True
|
||||
self.assertRaises(AttributeError, self.k._kinds._build_cache)
|
||||
self.assertRaises(TypeError, self.k._kinds._build_cache)
|
||||
self.k._kinds._is_ready = True
|
||||
self.k.get_cluster()
|
||||
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map', mock_namespaced_kind)
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map', mock_namespaced_kind, create=True)
|
||||
class TestKubernetesConfigMaps(BaseTestKubernetes):
|
||||
|
||||
@patch('time.time', Mock(side_effect=[1, 10.9, 100]))
|
||||
@@ -95,13 +168,14 @@ class TestKubernetesConfigMaps(BaseTestKubernetes):
|
||||
self.k.take_leader()
|
||||
|
||||
def test_manual_failover(self):
|
||||
with patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map', Mock(side_effect=RetryFailedError(''))):
|
||||
with patch.object(k8s_client.CoreV1Api, 'patch_namespaced_config_map',
|
||||
Mock(side_effect=RetryFailedError('')), create=True):
|
||||
self.k.manual_failover('foo', 'bar')
|
||||
|
||||
def test_set_config_value(self):
|
||||
self.k.set_config_value('{}')
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod')
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', create=True)
|
||||
def test_touch_member(self, mock_patch_namespaced_pod):
|
||||
mock_patch_namespaced_pod.return_value.metadata.resource_version = '10'
|
||||
self.k.touch_member({'role': 'replica'})
|
||||
@@ -119,7 +193,7 @@ class TestKubernetesConfigMaps(BaseTestKubernetes):
|
||||
self.k.cancel_initialization()
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'delete_collection_namespaced_config_map',
|
||||
Mock(side_effect=k8s_client.rest.ApiException(403, '')))
|
||||
Mock(side_effect=k8s_client.rest.ApiException(403, '')), create=True)
|
||||
def test_delete_cluster(self):
|
||||
self.k.delete_cluster()
|
||||
|
||||
@@ -134,11 +208,11 @@ class TestKubernetesConfigMaps(BaseTestKubernetes):
|
||||
|
||||
class TestKubernetesEndpoints(BaseTestKubernetes):
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_endpoints', mock_list_namespaced_endpoints)
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_endpoints', mock_list_namespaced_endpoints, create=True)
|
||||
def setUp(self, config=None):
|
||||
super(TestKubernetesEndpoints, self).setUp({'use_endpoints': True, 'pod_ip': '10.0.0.0'})
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_endpoints')
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_endpoints', create=True)
|
||||
def test_update_leader(self, mock_patch_namespaced_endpoints):
|
||||
self.assertIsNotNone(self.k.update_leader('123'))
|
||||
args = mock_patch_namespaced_endpoints.call_args[0]
|
||||
@@ -148,11 +222,11 @@ class TestKubernetesEndpoints(BaseTestKubernetes):
|
||||
self.k._kinds._object_cache['test'].metadata.annotations['leader'] = 'p-1'
|
||||
self.assertFalse(self.k.update_leader('123'))
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_endpoints', mock_namespaced_kind)
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_endpoints', mock_namespaced_kind, create=True)
|
||||
def test_update_leader_with_restricted_access(self):
|
||||
self.assertIsNotNone(self.k.update_leader('123', True))
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_endpoints')
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_endpoints', create=True)
|
||||
def test__update_leader_with_retry(self, mock_patch):
|
||||
mock_patch.side_effect = k8s_client.rest.ApiException(502, '')
|
||||
self.assertFalse(self.k.update_leader('123'))
|
||||
@@ -168,14 +242,15 @@ class TestKubernetesEndpoints(BaseTestKubernetes):
|
||||
self.assertIsNotNone(self.k._update_leader_with_retry({}, '1', []))
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints',
|
||||
Mock(side_effect=[k8s_client.rest.ApiException(500, ''), k8s_client.rest.ApiException(502, '')]))
|
||||
Mock(side_effect=[k8s_client.rest.ApiException(500, ''),
|
||||
k8s_client.rest.ApiException(502, '')]), create=True)
|
||||
def test_delete_sync_state(self):
|
||||
self.assertFalse(self.k.delete_sync_state())
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', mock_namespaced_kind)
|
||||
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', mock_namespaced_kind)
|
||||
@patch.object(k8s_client.CoreV1Api, 'patch_namespaced_pod', mock_namespaced_kind, create=True)
|
||||
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_endpoints', mock_namespaced_kind, create=True)
|
||||
@patch.object(k8s_client.CoreV1Api, 'create_namespaced_service',
|
||||
Mock(side_effect=[True, False, k8s_client.rest.ApiException(500, '')]))
|
||||
Mock(side_effect=[True, False, k8s_client.rest.ApiException(500, '')]), create=True)
|
||||
def test__create_config_service(self):
|
||||
self.assertIsNotNone(self.k.patch_or_create_config({'foo': 'bar'}))
|
||||
self.assertIsNotNone(self.k.patch_or_create_config({'foo': 'bar'}))
|
||||
@@ -184,7 +259,7 @@ class TestKubernetesEndpoints(BaseTestKubernetes):
|
||||
|
||||
class TestCacheBuilder(BaseTestKubernetes):
|
||||
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map)
|
||||
@patch.object(k8s_client.CoreV1Api, 'list_namespaced_config_map', mock_list_namespaced_config_map, create=True)
|
||||
@patch('patroni.dcs.kubernetes.ObjectCache._watch')
|
||||
def test__build_cache(self, mock_response):
|
||||
mock_response.return_value.read_chunked.return_value = [json.dumps(
|
||||
@@ -195,7 +270,7 @@ class TestCacheBuilder(BaseTestKubernetes):
|
||||
'name': self.k.config_path, 'resourceVersion': '3'}}}
|
||||
) + '\n' + json.dumps(
|
||||
{'type': 'MDIFIED', 'object': {'metadata': {'name': self.k.config_path}}}
|
||||
) + '\n' + json.dumps({'object': {'code': 410}}) + '\n').encode('utf-8')]
|
||||
) + '\n').encode('utf-8'), b'{"object":{', b'"code":410}}\n']
|
||||
self.k._kinds._build_cache()
|
||||
|
||||
@patch('patroni.dcs.kubernetes.logger.error', Mock(side_effect=SleepException))
|
||||
|
||||
Reference in New Issue
Block a user