Beispiel #1
0
def get_service_url(v1_service):
    print("Getting service url...")
    node_port = v1_service.spec.ports[0].node_port
    #print("node_port", node_port)
    cluster_ip = v1_service.spec.cluster_ip
    #print("cluster_ip", cluster_ip)
    #lb_ip = v1_service.spec.load_balancer_ip
    #print("lb_ip", lb_ip)

    config = k8s_config.Configuration()
    client1 = api_client.ApiClient(configuration=config)
    v1 = core_v1_api.CoreV1Api(client1)
    nodes = v1.list_node()
    addresses = nodes.items[0].status.addresses
    node_ip = None
    for addr in addresses:
        if addr.type == 'ExternalIP':
            node_ip = addr.address
    #        print(node_ip)

    #print("trying internal ips")
    if not node_ip:
        for addr in addresses:
            if addr.type == 'InternalIP':
                node_ip = addr.address
    #            print(node_ip)

    pod_service_url = 'http://%s:%s' % (node_ip, node_port)
    return (pod_service_url)
Beispiel #2
0
def pickKubeConfigContext():
    """
    Allows you to pick a context and then lists all pods in the chosen context.
    :return:
    """
    contexts, active_context = config.list_kube_config_contexts()
    if not contexts:
        print("Cannot find any context in kube-config file.")
        return
    contexts = [context['name'] for context in contexts]
    active_index = contexts.index(active_context['name'])
    option, _ = pick(contexts,
                     title="Pick the context to load",
                     default_index=active_index)
    # Configs can be set in Configuration class directly or using helper
    # utility
    config.load_kube_config(context=option)

    print("Active host is %s" % configuration.Configuration().host)

    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    ret = v1.list_pod_for_all_namespaces(watch=False)
    for item in ret.items:
        print(
            "%s\t%s\t%s" %
            (item.status.pod_ip, item.metadata.namespace, item.metadata.name))
Beispiel #3
0
def get_kubectl_host(replace_https=True, with_port=True) -> str:
    config.load_kube_config()
    kubectl_host = configuration.Configuration().host
    if replace_https:
        kubectl_host = kubectl_host.replace('https://', '').replace('http://', '')
    if not with_port:
        kubectl_host = kubectl_host.split(':')[0]

    return kubectl_host
Beispiel #4
0
def launch_app(k8s_app_name: NAUTAAppNames,
               no_launch: bool = False,
               port: int = None,
               app_name: str = None,
               number_of_retries: int = 0,
               url_end: str = "",
               namespace: str = None):
    try:
        with spinner(text=Texts.LAUNCHING_APP_MSG) as proxy_spinner, \
             K8sProxy(nauta_app_name=k8s_app_name, port=port, app_name=app_name,
                      number_of_retries=number_of_retries, namespace=namespace) as proxy:
            url = FORWARDED_URL.format(proxy.tunnel_port, url_end)

            if k8s_app_name == NAUTAAppNames.INGRESS:
                config.load_kube_config()
                user_token = configuration.Configuration().api_key.get(
                    'authorization')
                prepared_user_token = user_token.replace('Bearer ', '')
                url = f'{url}?token={prepared_user_token}'

            if not no_launch:

                if is_gui_browser_available():
                    wait_for_connection(url)
                    webbrowser.open_new(url)
                    proxy_spinner.stop()
                else:
                    click.echo(Texts.NO_WEB_BROWSER_ERROR_MSG)

            if port and port != proxy.tunnel_port:
                click.echo(
                    Texts.CANNOT_USE_PORT.format(
                        required_port=port, random_port=proxy.tunnel_port))

            proxy_spinner.stop()
            click.echo(Texts.GO_TO_MSG.format(url=url))
            click.echo(Texts.PROXY_CREATED_MSG)
            wait_for_ctrl_c()
    except K8sProxyCloseError:
        err_message = Texts.PROXY_CLOSE_ERROR_MSG.format(app_name=k8s_app_name)
        raise ProxyClosingError(err_message)
    except LocalPortOccupiedError as exe:
        err_message = Texts.PROXY_CREATED_EXTENDED_ERROR_MSG.format(
            app_name=k8s_app_name, reason=exe.message)
        raise LaunchError(err_message)
    except K8sProxyOpenError:
        error_msg = Texts.PROXY_CREATED_ERROR_MSG.format(app_name=k8s_app_name)
        logger.exception(error_msg)
        raise LaunchError(error_msg)
    except LaunchError as e:
        raise e
    except Exception:
        err_message = Texts.WEB_APP_LAUCH_FAIL_MSG
        logger.exception(err_message)
        raise LaunchError(err_message)
Beispiel #5
0
def get_k8s_clients(conf):
    config = k8s_config.Configuration()
    config.host = conf.kubernetes.kube_host
    config.verify_ssl = False
    client = api_client.ApiClient(configuration=config)
    v1 = core_v1_api.CoreV1Api(client)
    v1extention = extensions_v1beta1_api.ExtensionsV1beta1Api(client)

    clients = {'v1': v1, 'v1extention': v1extention}

    return clients
Beispiel #6
0
    def __init__(self,
                 configuration=None,
                 header_name=None,
                 header_value=None,
                 cookie=None):
        if configuration is None:
            configuration = k8s_configuration.Configuration()
        self.configuration = configuration

        self.rest_client = rest.RESTClientObject(configuration)
        self.default_headers = {}
        if header_name is not None:
            self.default_headers[header_name] = header_value
        self.cookie = cookie
Beispiel #7
0
def get_k8s_clients(conf):
    config = k8s_config.Configuration()
    config.host = conf.kubernetes.kube_host
    if conf.kubernetes.use_api_certificate:
        config.ssl_ca_cert = conf.kubernetes.ssl_ca_cert
        config.cert_file = conf.kubernetes.cert_file
        config.key_file = conf.kubernetes.key_file
    else:
        config.verify_ssl = False
    client = api_client.ApiClient(configuration=config)
    v1 = core_v1_api.CoreV1Api(client)
    v1extension = extensions_v1beta1_api.ExtensionsV1beta1Api(client)
    # apps_v1 = apps_v1_api.AppsV1Api(client)

    clients = {
        'v1': v1,
        # 'apps_v1': apps_v1
        'v1extension': v1extension
    }

    return clients
Beispiel #8
0
def get_kubectl_host(replace_https=True, with_port=True) -> str:
    config.load_kube_config()
    kubectl_host = configuration.Configuration().host
    parsed_kubectl_host = urlparse(kubectl_host)
    scheme = parsed_kubectl_host.scheme
    hostname = parsed_kubectl_host.hostname
    port = parsed_kubectl_host.port
    if not port:
        if scheme == 'http':
            port = 80
        else:
            port = 443

    if replace_https:
        if with_port:
            return f'{hostname}:{port}'
        else:
            return f'{hostname}'
    else:
        if with_port:
            return f'{scheme}://{hostname}:{port}'
        else:
            return f'{scheme}://{hostname}'
Beispiel #9
0
def main():
    contexts, active_context = config.list_kube_config_contexts()
    if not contexts:
        print("Cannot find any context in kube-config file.")
        return
    contexts = [context['name'] for context in contexts]
    active_index = contexts.index(active_context['name'])
    option, _ = pick(contexts, title="Pick the context to load",
                     default_index=active_index)
    # Configs can be set in Configuration class directly or using helper
    # utility
    config.load_kube_config(context=option)

    print("Active host is %s" % configuration.Configuration().host)

    v1 = client.CoreV1Api()
    print("Listing pods with their IPs:")
    ret = v1.list_pod_for_all_namespaces(field_selector='spec.nodeName=pi-2', watch=False)
    for item in ret.items:
        print(
            "%s\t%s\t%s" %
            (item.status.pod_ip,
             item.metadata.namespace,
             item.metadata.name))
Beispiel #10
0
def get_api_key() -> str:
    config.load_kube_config()
    return configuration.Configuration().api_key.get('authorization')