Ejemplo n.º 1
0
def test_http_do_not_overwrite_auth(monkeypatch):
    cfg = KubeConfig.from_file(GOOD_CONFIG_FILE_PATH)
    api = HTTPClient(cfg)

    mock_send = MagicMock()
    mock_send.side_effect = Exception('MOCK HTTP')
    monkeypatch.setattr('pykube.http.KubernetesHTTPAdapter._do_send', mock_send)

    with pytest.raises(Exception):
        api.get(url='test', headers={'Authorization': 'Bearer testtoken'})

    mock_send.assert_called_once()
    assert mock_send.call_args[0][0].headers['Authorization'] == 'Bearer testtoken'
Ejemplo n.º 2
0
def test_http_with_oidc_auth(monkeypatch):
    cfg = KubeConfig.from_file(CONFIG_WITH_OIDC_AUTH)
    api = HTTPClient(cfg)

    mock_send = MagicMock()
    mock_send.side_effect = Exception('MOCK HTTP')
    monkeypatch.setattr('pykube.http.KubernetesHTTPAdapter._do_send', mock_send)

    with pytest.raises(Exception):
        api.get(url='test')

    mock_send.assert_called_once()
    assert mock_send.call_args[0][0].headers['Authorization'] == 'Bearer some-id-token'
Ejemplo n.º 3
0
def test_http_with_dry_run(monkeypatch):
    cfg = KubeConfig.from_file(GOOD_CONFIG_FILE_PATH)
    api = HTTPClient(cfg, dry_run=True)

    mock_send = MagicMock()
    mock_send.side_effect = Exception('MOCK HTTP')
    monkeypatch.setattr('pykube.http.KubernetesHTTPAdapter._do_send', mock_send)

    with pytest.raises(Exception):
        api.get(url='test')

    mock_send.assert_called_once()
    # check that dry run http parameters were set
    assert mock_send.call_args[0][0].url == "http://localhost/api/v1/test?dryRun=All"
Ejemplo n.º 4
0
def test_http_insecure_skip_tls_verify(monkeypatch):
    cfg = KubeConfig.from_file(CONFIG_WITH_INSECURE_SKIP_TLS_VERIFY)
    api = HTTPClient(cfg)

    mock_send = MagicMock()
    mock_send.side_effect = Exception('MOCK HTTP')
    monkeypatch.setattr('pykube.http.KubernetesHTTPAdapter._do_send', mock_send)

    with pytest.raises(Exception):
        api.get(url='test')

    mock_send.assert_called_once()
    # check that SSL is not verified
    assert not mock_send.call_args[1]['verify']
Ejemplo n.º 5
0
def test_http_do_not_overwrite_auth(monkeypatch):
    cfg = KubeConfig.from_file(GOOD_CONFIG_FILE_PATH)
    api = HTTPClient(cfg)

    mock_send = mock.MagicMock()
    mock_send.side_effect = Exception("MOCK HTTP")
    monkeypatch.setattr("pykube.http.KubernetesHTTPAdapter._do_send",
                        mock_send)

    with pytest.raises(Exception):
        api.get(url="test", headers={"Authorization": "Bearer testtoken"})

    mock_send.assert_called_once()
    assert mock_send.call_args[0][0].headers[
        "Authorization"] == "Bearer testtoken"
Ejemplo n.º 6
0
def test_http(monkeypatch):
    cfg = KubeConfig.from_file(GOOD_CONFIG_FILE_PATH)
    api = HTTPClient(cfg)

    mock_send = MagicMock()
    mock_send.side_effect = Exception('MOCK HTTP')
    monkeypatch.setattr('pykube.http.KubernetesHTTPAdapter._do_send', mock_send)

    with pytest.raises(Exception):
        api.get(url='test')

    mock_send.assert_called_once()
    assert mock_send.call_args[0][0].headers['Authorization'] == 'Basic YWRtOnNvbWVwYXNzd29yZA=='
    assert mock_send.call_args[0][0].headers['User-Agent'] == f'pykube-ng/{__version__}'
    # check that the default HTTP timeout was set
    assert mock_send.call_args[1]['timeout'] == DEFAULT_HTTP_TIMEOUT
Ejemplo n.º 7
0
def test_http_with_oidc_auth_no_refresh(monkeypatch):
    cfg = KubeConfig.from_file(CONFIG_WITH_OIDC_AUTH)
    api = HTTPClient(cfg)

    mock_send = mock.MagicMock()
    mock_send.side_effect = Exception("MOCK HTTP")
    monkeypatch.setattr("pykube.http.KubernetesHTTPAdapter._do_send",
                        mock_send)

    with mock.patch("pykube.http.KubernetesHTTPAdapter._is_valid_jwt",
                    return_value=True) as mock_jwt:
        with pytest.raises(Exception):
            api.get(url="test")
        mock_jwt.assert_called_once_with("some-id-token")

    mock_send.assert_called_once()
    assert mock_send.call_args[0][0].headers[
        "Authorization"] == "Bearer some-id-token"
Ejemplo n.º 8
0
class KubernetesApi(object):
    def __init__(self,filename):
        self.config = KubeConfig(filename)
        self.http_client = HTTPClient(self.config)

    def get_pods(self):
        """Returns a list of the pod names"""
        return self._get_components('pods')

    def get_replication_controllers(self):
        """Returns a list of the rc names"""
        return self._get_components('replicationcontrollers')

    def get_services(self):
        """Returns a list of the service names"""
        return self._get_components('services')

    def start_pod(self, *args, **kwargs):
        filename = '{}/templates/pod.json'.format(os.path.dirname(__file__))
        with open(filename) as f:
            t = jinja2.Template(f.read())
        json_str = t.render(
            podname=kwargs.get('podname'),
            containername=kwargs.get('containername'),
            containerimage=kwargs.get('containerimage'),
            imagepullpolicy=kwargs.get('imagepullpolicy'),
            restartpolicy=kwargs.get('restartpolicy'),
            command=kwargs.get('command')
        )
        json_obj = json.loads(json_str)
        rsp = self.http_client.post(url='/pods', json=json_obj)
        if rsp.status_code != 201: raise KubernetesError

    def start_replicationcontroller(self, *args, **kwargs):
        filename = '{}/templates/rc.json'.format(os.path.dirname(__file__))
        with open(filename) as f:
            t = jinja2.Template(f.read())
        json_str = t.render(
            rcname=kwargs.get('rcname'),
            containername=kwargs.get('containername'),
            containerimage=kwargs.get('containerimage'),
            label=kwargs.get('label'),
            replicas=kwargs.get('replicas')
        )
        json_obj = json.loads(json_str)
        rsp = self.http_client.post(url='/replicationcontrollers', json=json_obj)
        if rsp.status_code != 201: raise KubernetesError


    def _get_components(self, component_type):
        rsp = self.http_client.get(url='/{}'.format(component_type))
        if rsp.status_code != 200: raise KubernetesError
        json_rsp = json.loads(rsp.text)
        if 'items' in json_rsp:
            items = [x['metadata']['name'] for x in json_rsp['items']]
            return items
        raise KubernetesError
Ejemplo n.º 9
0
def test_http(monkeypatch):
    cfg = KubeConfig.from_file(GOOD_CONFIG_FILE_PATH)
    api = HTTPClient(cfg)

    mock_send = mock.MagicMock()
    mock_send.side_effect = Exception("MOCK HTTP")
    monkeypatch.setattr("pykube.http.KubernetesHTTPAdapter._do_send",
                        mock_send)

    with pytest.raises(Exception):
        api.get(url="test")

    mock_send.assert_called_once()
    assert (mock_send.call_args[0][0].headers["Authorization"] ==
            "Basic YWRtOnNvbWVwYXNzd29yZA==")
    assert mock_send.call_args[0][0].headers[
        "User-Agent"] == f"pykube-ng/{__version__}"
    # check that the default HTTP timeout was set
    assert mock_send.call_args[1]["timeout"] == DEFAULT_HTTP_TIMEOUT
Ejemplo n.º 10
0
class Pod(object):
    def __init__(self):
        self.client = HTTPClient(kubeconfig)

    def pod_view(self, pod_name):
        url = "namespaces/default/pods"
        pods = json.loads(self.client.get(url=url).content)['items']
        for pod in pods:
            if pod['metadata']['labels']['run'] == pod_name:
                return pod
        return None

    def delete_pod(self, name):
        url = "namespaces/default/pods"
        pods = json.loads(self.client.get(url=url).content)['items']
        for pod in pods:
            if pod['metadata']['labels']['run'] == name:
                pod_name = pod['metadata']['name']
                del_url = "namespaces/default/pods/{}".format(pod_name)
                delete_result = self.client.delete(url=del_url).content
                return delete_result
        return None
Ejemplo n.º 11
0
class Service(object):
    def __init__(self):
        self.client = HTTPClient(kubeconfig)

    def create_service(self, name):
        ports = list()
        port_22 = {"name": "ssh", "port": 22}
        port_80 = {"name": "http", "port": 80}
        port_443 = {"name": "https", "port": 443}
        ports.append(port_22)
        ports.append(port_80)
        ports.append(port_443)
        #for portNum in range(7000,7010):
        #    port_custom = {"name": portNum, "port": portNum}
        #    ports.append(port_custom)
        body = dict()
        body["kind"] = "Service"
        body["apiVersion"] = "v1"
        body["metadata"] = {"name": name}
        body["spec"] = {"selector": {"run": name}, "type": "NodePort"}
        body["spec"]["ports"] = ports
        data = json.dumps(body)
        service = json.loads(
            self.client.post(url="namespaces/default/services",
                             data=data).content)
        return service

    def view_service(self, name):
        url = "namespaces/{}/services/{}".format("default", name)
        service = json.loads(self.client.get(url=url).content)
        return service

    def delete_service(self, name):
        service_path = "namespaces/{}/services/{}".format("default", name)
        body = {"gracePeriodSeconds": 0}
        data = json.dumps(body)
        delete_result = json.loads(
            self.client.delete(url=service_path, data=data).content)
        return delete_result