def __init__(self, api_server_urls: list):
        self._clusters = []

        if not api_server_urls:
            try:
                config = KubeConfig.from_service_account()
            except FileNotFoundError:
                # we are not running inside a cluster
                # => assume default kubectl proxy URL
                config = KubeConfig.from_url(DEFAULT_CLUSTERS)
                client = HTTPClient(config)
                cluster = Cluster(
                    generate_cluster_id(DEFAULT_CLUSTERS),
                    DEFAULT_CLUSTER_NAME,
                    DEFAULT_CLUSTERS,
                    client,
                )
            else:
                client = HTTPClient(config)
                cluster = Cluster(
                    generate_cluster_id(config.cluster["server"]),
                    DEFAULT_CLUSTER_NAME,
                    config.cluster["server"],
                    client,
                )
            self._clusters.append(cluster)
        else:
            for api_server_url in api_server_urls:
                config = KubeConfig.from_url(api_server_url)
                client = HTTPClient(config)
                generated_id = generate_cluster_id(api_server_url)
                self._clusters.append(
                    Cluster(generated_id, generated_id, api_server_url, client)
                )
Exemple #2
0
    def __init__(self):
        logging.info('Getting Kubernetes HTTPClient')
        try:
            #if not os.path.exists('/var/run/secrets/kubernetes.io/serviceaccount/ca.crt'):
            #    logging.debug('Stat Kube Config from /serviceaccount')
            #    shutil.copytree('/var/run/secrets/kubernetes.io/serviceaccount', '/serviceaccount')
            #    shutil.copyfile('/ca.crt', '/serviceaccount/ca.crt')
            #    self.api = HTTPClient(KubeConfig.from_service_account('/serviceaccount'))
            #else:
            #    logging.debug('Staty Kube Config from /var/run/secrets/kubernetes.io/serviceaccount')
            self.api = HTTPClient(KubeConfig.from_service_account())
        except Exception as ex:
            logging.exception(
                'Error Getting Kubernetes HTTPClient using ServiceAccount')

            logging.info('Trying with URL')
            kube_host = os.getenv('KUBERNETES_PROXY_API_HOST', '127.0.0.1')
            kube_port = os.getenv('KUBERNETES_PROXY_API_PORT', '8080')
            logging.info('Kubernetes Host: {}, Kubernetes Port: {}'.format(
                kube_host, kube_port))
            try:
                self.api = HTTPClient(
                    KubeConfig.from_url('http://{}:{}'.format(
                        kube_host, kube_port)))
            except Exception as ex:
                logging.exception(
                    'Error Getting Kubernetes HTTPClient using URL')
                self.api = None

        self.kube_objects = {}
Exemple #3
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    api = HTTPClient(KubeConfig.from_service_account())
    while True:
        games = get_games()
        maintain_games(api, games)
        time.sleep(5)
Exemple #4
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    api = HTTPClient(KubeConfig.from_service_account())
    while True:
        games = get_games()
        maintain_games(api, games)
        time.sleep(5)
Exemple #5
0
    def test_bad_ca_certificate(self):
        """
        If no CA certificate is found in the service account directory,
        ``https_policy_from_config`` raises ``ValueError``.
        """
        t = FilePath(self.useFixture(TempDir()).path)
        t = t.asBytesMode()
        serviceaccount = t.child(b"serviceaccount")
        serviceaccount.makedirs()

        serviceaccount.child(b"ca.crt").setContent(
            b"-----BEGIN CERTIFICATE-----\n"
            b"not a cert pem\n"
            b"-----END CERTIFICATE-----\n")
        serviceaccount.child(b"token").setContent(b"token")

        environ = encode_environ({
            u"KUBERNETES_SERVICE_HOST": u"example.invalid.",
            u"KUBERNETES_SERVICE_PORT": u"443",
        })
        self.patch(os, "environ", environ)

        config = KubeConfig.from_service_account(
            path=serviceaccount.asTextMode().path)
        self.assertThat(
            lambda: https_policy_from_config(config),
            raises(
                ValueError(
                    "Invalid certificate authority certificate found.",
                    "[('PEM routines', 'PEM_read_bio', 'bad base64 decode')]",
                )),
        )
Exemple #6
0
    def test_missing_ca_certificate(self):
        """
        If no CA certificate is found in the service account directory,
        ``https_policy_from_config`` raises ``ValueError``.
        """
        t = FilePath(self.useFixture(TempDir()).path)
        t = t.asBytesMode()
        serviceaccount = t.child(b"serviceaccount")
        serviceaccount.makedirs()

        serviceaccount.child(b"ca.crt").setContent(b"not a cert pem")
        serviceaccount.child(b"token").setContent(b"token")

        environ = encode_environ({
            u"KUBERNETES_SERVICE_HOST": u"example.invalid.",
            u"KUBERNETES_SERVICE_PORT": u"443",
        })
        self.patch(os, "environ", environ)

        config = KubeConfig.from_service_account(
            path=serviceaccount.asTextMode().path)
        self.assertThat(
            lambda: https_policy_from_config(config),
            raises(ValueError("No certificate authority certificate found.")),
        )
 def create_from_secrets(cls):
     logging.info("Using service account from kubernetes secrets")
     kube_config = KubeConfig.from_service_account()
     api_client = HTTPClient(kube_config)
     namespace = _get_namespace_from_secrets()
     return Kubernetes(api_client=api_client,
                       kube_config=kube_config,
                       namespace=namespace)
Exemple #8
0
    def __init__(self):
        self._clusters = []

        try:
            config = KubeConfig.from_service_account()
        except FileNotFoundError:
            # we are not running inside a cluster
            raise ServiceAccountNotFound()

        client = HTTPClient(config)
        cluster = Cluster("local", client)
        self._clusters.append(cluster)
def authenticate_with_serviceaccount(reactor, **kw):
    """
    Create an ``IAgent`` which can issue authenticated requests to a
    particular Kubernetes server using a service account token.

    :param reactor: The reactor with which to configure the resulting agent.

    :param bytes path: The location of the service account directory.  The
        default should work fine for normal use within a container.

    :return IAgent: An agent which will authenticate itself to a particular
        Kubernetes server and which will verify that server or refuse to
        interact with it.
    """
    config = KubeConfig.from_service_account(**kw)

    token = config.user["token"]
    base_url = URL.fromText(config.cluster["server"].decode("ascii"))

    ca_certs = pem.parse(config.cluster["certificate-authority"].bytes())
    if not ca_certs:
        raise ValueError("No certificate authority certificate found.")
    ca_cert = ca_certs[0]

    try:
        # Validate the certificate so we have early failures for garbage data.
        ssl.Certificate.load(ca_cert.as_bytes(), FILETYPE_PEM)
    except OpenSSLError as e:
        raise ValueError(
            "Invalid certificate authority certificate found.",
            str(e),
        )

    netloc = NetLocation(host=base_url.host, port=base_url.port)
    policy = ClientCertificatePolicyForHTTPS(
        credentials={},
        trust_roots={
            netloc: ca_cert,
        },
    )

    agent = HeaderInjectingAgent(
        _to_inject=Headers({u"authorization": [u"Bearer {}".format(token)]}),
        _agent=Agent(reactor, contextFactory=policy),
    )
    return agent
Exemple #10
0
def authenticate_with_serviceaccount(reactor, **kw):
    """
    Create an ``IAgent`` which can issue authenticated requests to a
    particular Kubernetes server using a service account token.

    :param reactor: The reactor with which to configure the resulting agent.

    :param bytes path: The location of the service account directory.  The
        default should work fine for normal use within a container.

    :return IAgent: An agent which will authenticate itself to a particular
        Kubernetes server and which will verify that server or refuse to
        interact with it.
    """
    config = KubeConfig.from_service_account(**kw)
    policy = https_policy_from_config(config)
    token = config.user["token"]
    agent = HeaderInjectingAgent(
        _to_inject=Headers({u"authorization": [u"Bearer {}".format(token)]}),
        _agent=Agent(reactor, contextFactory=policy),
    )
    return agent
Exemple #11
0
    def test_policy(self):
        """
        ``https_policy_from_config`` returns a ``ClientCertificatePolicyForHTTPS``
        with no credentials but with trust roots taken from the Kubernetes
        *serviceaccount* directory it is pointed at.  It also respects
        *KUBERNETES_...* environment variables to identify the address of the
        server.
        """
        t = FilePath(self.useFixture(TempDir()).path)
        t = t.asBytesMode()
        serviceaccount = t.child(b"serviceaccount")
        serviceaccount.makedirs()

        serviceaccount.child(b"ca.crt").setContent(_CA_CERT_PEM)
        serviceaccount.child(b"token").setContent(b"token")

        netloc = NetLocation(host=u"example.invalid", port=443)
        environ = encode_environ({
            u"KUBERNETES_SERVICE_HOST":
            netloc.host,
            u"KUBERNETES_SERVICE_PORT":
            u"{}".format(netloc.port),
        })
        self.patch(os, "environ", environ)

        config = KubeConfig.from_service_account(
            path=serviceaccount.asTextMode().path)

        policy = https_policy_from_config(config)
        self.expectThat(
            policy,
            Equals(
                ClientCertificatePolicyForHTTPS(
                    credentials={},
                    trust_roots={
                        netloc: pem.parse(_CA_CERT_PEM)[0],
                    },
                ), ),
        )
Exemple #12
0
 def __init__(self, *args, **kwargs):
     self.api = HTTPClient(KubeConfig.from_service_account())
     self.game_id = os.environ['GAME_ID']
     self.game_url = os.environ['GAME_URL']
     super(KubernetesWorkerManager, self).__init__(*args, **kwargs)
Exemple #13
0
 def __init__(self, *args, **kwargs):
     self.api = HTTPClient(KubeConfig.from_service_account())
     self.game_name = os.environ['GAME_NAME']
     self.game_url = os.environ['GAME_URL']
     super(KubernetesWorkerManager, self).__init__(*args, **kwargs)
Exemple #14
0
    file_conf = open('/etc/haproxy/haproxy.cfg', 'w')
    file_conf.write(template_render)
    file_conf.close()
    system('chown haproxy:haproxy /etc/haproxy/haproxy.cfg')
    system('service haproxy reload')

    system('echo [UPDATE] Changes in replicas of %s' % (name_set))


# RUN!
system('echo "Start Slug Load Balancer v.0.0.1"')
# python main.py namespace="default" url_heapster="http://heapster/api/v1/model" autoscaler_count="5" time_query="10"
patch_exec = path.dirname(path.realpath(__file__)) + "/"
#api = HTTPClient(KubeConfig.from_file(patch_exec + "credentials/config"))
api = HTTPClient(KubeConfig.from_service_account())

# Arguments
list_argv = []
argv.remove(argv[0])
for elements in argv:
    variable_entrada = elements.split("=")
    if len(variable_entrada) == 1 or variable_entrada[1] == '':
        raise NameError(
            '[ERROR] Invalid Arguments [python example.py var="text"]')
    list_argv.append(variable_entrada)

dic_argv = argument_to_dic(list_argv)
namespace = dic_argv["namespace"]
# url_heapster = dic_argv["url_heapster"]
time_query = int(dic_argv["time_query"])
Exemple #15
0
"""

import time
import os
import yaml
import json
from datetime import datetime
from time import sleep

import kopf
from pykube import KubeConfig, HTTPClient, Secret, Deployment, all
from pykube.exceptions import PyKubeError, HTTPError, KubernetesError
from pprint import pprint

try:
    cfg = KubeConfig.from_service_account()
except FileNotFoundError:
    cfg = KubeConfig.from_file()

api = HTTPClient(cfg)


@kopf.on.create('bazinga.io', 'v1', 'secretz')
def create_secret(body, meta, spec, status, logger, **kwargs):
    secretName = spec.get('secretName')
    print(f"Create Secret.... {secretName}")

    data = _render_yaml(spec, meta)

    obj = Secret(api, data)
    try:
 def create_from_secrets(cls):
     logging.info("Using service account from kubernetes secrets")
     kube_config = KubeConfig.from_service_account()
     api_client = HTTPClient(kube_config)
     namespace = _get_namespace_from_secrets()
     return Kubernetes(api_client=api_client, kube_config=kube_config, namespace=namespace)