Python kubernetes.client.ExtensionsV1beta1Api() Examples

The following are 21 code examples of kubernetes.client.ExtensionsV1beta1Api(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module kubernetes.client , or try the search function .
Example #1
Source File: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 6 votes vote down vote up
def scale_deployment(name: str, replicas: int, ns: str = "default",
                     secrets: Secrets = None):
    """
    Scale a deployment up or down. The `name` is the name of the deployment.
    """
    api = create_k8s_api_client(secrets)

    v1 = client.ExtensionsV1beta1Api(api)
    body = {"spec": {"replicas": replicas}}
    try:
        v1.patch_namespaced_deployment_scale(name, namespace=ns, body=body)
    except ApiException as e:
        raise ActivityFailed(
            "failed to scale '{s}' to {r} replicas: {e}".format(
                s=name, r=replicas, e=str(e))) 
Example #2
Source File: kubeapi.py    From kqueen with MIT License 6 votes vote down vote up
def __init__(self, **kwargs):
        """
        Set cluster and prepare clients for all used resource types.

        Args:
            **kwargs: Keyword arguments (cluster is required)
        """
        # load configuration
        try:
            self.cluster = kwargs['cluster']
        except KeyError:
            raise ValueError('Missing parameter cluster')

        logger.debug('Initialized KubernetesAPI for {}'.format(self.cluster))

        # set apis
        api_client = self.get_api_client()

        self.api_corev1 = client.CoreV1Api(api_client=api_client)
        self.api_storagev1 = client.StorageV1Api(api_client=api_client)
        self.api_extensionsv1beta1 = client.ExtensionsV1beta1Api(api_client=api_client)
        self.api_version = client.VersionApi(api_client=api_client) 
Example #3
Source File: actions.py    From chaostoolkit-kubernetes with Apache License 2.0 6 votes vote down vote up
def delete_replica_set(name: str, ns: str = "default",
                       label_selector: str = "name in ({name})",
                       secrets: Secrets = None):
    """
    Delete a replica set by `name` in the namespace `ns`.

    The replica set is deleted without a graceful period to trigger an abrupt
    termination.

    The selected resources are matched by the given `label_selector`.
    """
    label_selector = label_selector.format(name=name)
    api = create_k8s_api_client(secrets)
    v1 = client.ExtensionsV1beta1Api(api)
    if label_selector:
        ret = v1.list_namespaced_replica_set(ns, label_selector=label_selector)
    else:
        ret = v1.list_namespaced_replica_set(ns)

    logger.debug("Found {d} replica sets named '{n}'".format(
        d=len(ret.items), n=name))

    body = client.V1DeleteOptions()
    for r in ret.items:
        v1.delete_namespaced_replica_set(r.metadata.name, ns, body=body) 
Example #4
Source File: install_gpu_driver.py    From aws-eks-deep-learning-benchmark with Apache License 2.0 6 votes vote down vote up
def install_gpu_drivers(api_client):
  """Install GPU drivers on the cluster."""
  logging.info("Install GPU Drivers.")
  # Fetch the daemonset to install the drivers.
  # TODO: Get cluster version and then install compatible driver version
  link = "https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.11/nvidia-device-plugin.yml"  # pylint: disable=line-too-long
  logging.info("Using daemonset file: %s", link)
  f = urllib.urlopen(link)
  daemonset_spec = yaml.load(f)
  ext_client = k8s_client.ExtensionsV1beta1Api(api_client)
  try:
    namespace = daemonset_spec["metadata"]["namespace"]
    ext_client.create_namespaced_daemon_set(namespace, daemonset_spec)
  except rest.ApiException as e:
    # Status appears to be a string.
    if e.status == 409:
      logging.info("GPU driver daemon set has already been installed")
    else:
      raise 
Example #5
Source File: k8s.py    From sparrow with GNU General Public License v3.0 6 votes vote down vote up
def ingress():
    try:
        valus = []
        v1 = client.ExtensionsV1beta1Api()
        keys = tables = ('name','request','domain', 'service_name', 'service_port')
        ret = v1.list_ingress_for_all_namespaces()
        for i in ret.items:
            try:
                for rule in i.spec.rules:
                    valus.append([i.metadata.name,
                                  'http',
                                  rule.host,
                                  rule.http.paths[0].backend.service_name,
                                  rule.http.paths[0].backend.service_port
                                  ])
            except Exception as e:
                logging.error(e)
        return render_template('k8s-resource.html', valus=valus, tables=tables, keys=keys, resource='Ingress')
    except Exception as e:
        logging.error(e) 
Example #6
Source File: k8s.py    From armada with Apache License 2.0 6 votes vote down vote up
def __init__(self):
        '''
        Initialize connection to Kubernetes
        '''
        try:
            config.load_incluster_config()
        except config.config_exception.ConfigException:
            config.load_kube_config()

        self.client = client.CoreV1Api()
        self.batch_api = client.BatchV1Api()
        self.batch_v1beta1_api = client.BatchV1beta1Api()
        self.extension_api = client.ExtensionsV1beta1Api() 
Example #7
Source File: k8s.py    From armada with Apache License 2.0 6 votes vote down vote up
def __init__(self, bearer_token=None):
        '''
        Initialize connection to Kubernetes
        '''
        self.bearer_token = bearer_token
        api_client = None

        try:
            config.load_incluster_config()
        except config.config_exception.ConfigException:
            config.load_kube_config()

        if self.bearer_token:
            # Configure API key authorization: Bearer Token
            configuration = client.Configuration()
            configuration.api_key_prefix['authorization'] = 'Bearer'
            configuration.api_key['authorization'] = self.bearer_token
            api_client = client.ApiClient(configuration)

        self.client = client.CoreV1Api(api_client)
        self.batch_api = client.BatchV1Api(api_client)
        self.batch_v1beta1_api = client.BatchV1beta1Api(api_client)
        self.custom_objects = client.CustomObjectsApi(api_client)
        self.api_extensions = client.ApiextensionsV1beta1Api(api_client)
        self.extension_api = client.ExtensionsV1beta1Api(api_client)
        self.apps_v1_api = client.AppsV1Api(api_client) 
Example #8
Source File: conftest.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def get_endpoint_ingress(name, namespace):
    extensions_api_instance = client.ExtensionsV1beta1Api(config.load_kube_config())
    api_response = extensions_api_instance.read_namespaced_ingress(name, namespace)
    return api_response 
Example #9
Source File: kubernetes_resources.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def get_k8s_extensions_api_client():
    apps_api_client = client.ExtensionsV1beta1Api(client.ApiClient(get_k8s_configuration()))
    return apps_api_client 
Example #10
Source File: k8s_resource.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def export_ingress(self,domains,ingress_port):
        try:
            db_ingress = db_op.k8s_ingress
            # ingress信息写入数据库
            for ingress_domain in domains:
                path = None
                if '/' in ingress_domain:
                    ingress_domain = ingress_domain.split('/')[0]
                    path = '/{}'.format('/'.join(ingress_domain.split('/')[1:]))
                v = db_ingress(name='nginx-ingress',context=self.context, namespace=self.namespace, domain=ingress_domain, path=path,
                               serviceName=self.dm_name, servicePort=int(ingress_port))
                db_op.DB.session.add(v)
                db_op.DB.session.commit()
        except Exception as e:
            logging.error(e)
        else:
            # 从数据库读取ingress信息
            api_instance = client.ExtensionsV1beta1Api()
            Rules = []
            domain_infos = db_ingress.query.with_entities(distinct(db_ingress.domain)).filter(db_ingress.context==self.context).all()
            domain_infos = [domain[0] for domain in domain_infos]
            for domain in domain_infos:
                paths = []
                Rules_infos = db_ingress.query.with_entities(db_ingress.path,
                                                             db_ingress.serviceName, db_ingress.servicePort
                                                             ).filter(and_(db_ingress.domain == domain,
                                                                           db_ingress.context == self.context)).all()
                for infos in Rules_infos:
                    path, serviceName, servicePort = infos
                    if path:
                        paths.append(client.V1beta1HTTPIngressPath(client.V1beta1IngressBackend(
                            service_name=serviceName,
                            service_port=int(servicePort)
                        ), path=path))
                if paths:
                    Rules.append(client.V1beta1IngressRule(host=domain,
                                                           http=client.V1beta1HTTPIngressRuleValue(
                                                               paths=paths)))
                else:
                    if Rules_infos:
                        path, serviceName, servicePort = Rules_infos[0]
                        Rules.append(client.V1beta1IngressRule(host=domain,
                                                               http=client.V1beta1HTTPIngressRuleValue(
                                                                   paths=[client.V1beta1HTTPIngressPath(
                                                                       client.V1beta1IngressBackend(
                                                                           service_name=serviceName,
                                                                           service_port=int(servicePort)
                                                                       ))])
                                                               ))
            spec = client.V1beta1IngressSpec(rules=Rules)
            ingress = client.V1beta1Ingress(
                api_version='extensions/v1beta1',
                kind='Ingress',
                metadata=client.V1ObjectMeta(name='nginx-ingress',
                                             namespace=self.namespace,
                                             annotations={'kubernetes.io/ingress.class': 'nginx'}), spec=spec)
            api_instance.patch_namespaced_ingress(body=ingress, namespace=self.namespace, name='nginx-ingress')
            return True
        finally:
            db_op.DB.session.remove() 
Example #11
Source File: k8s_resource.py    From sparrow with GNU General Public License v3.0 5 votes vote down vote up
def delete_deployment(self):
        try:
            api_instance = client.ExtensionsV1beta1Api()
            body = client.V1DeleteOptions(propagation_policy='Foreground', grace_period_seconds=5)
            api_instance.delete_namespaced_deployment(name=self.dm_name, namespace=self.namespace, body=body)
            return True
        except Exception as e:
            logging.error(e)
            return False 
Example #12
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def extensions_client_from_config(config):
    if config is None:
        k8sconfig.load_incluster_config()
        return k8sclient.ExtensionsV1beta1Api()
    else:
        client = k8sclient.ApiClient(configuration=config)
        return k8sclient.ExtensionsV1beta1Api(api_client=client) 
Example #13
Source File: ctx.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def create_extensions_v1beta1_api(self):
        cfg = self.get_kubecfg()
        return client.ExtensionsV1beta1Api(cfg) 
Example #14
Source File: kubewatch.py    From ambassador with Apache License 2.0 5 votes vote down vote up
def check_ingresses():
    status = False

    k8s_v1b1 = client.ExtensionsV1beta1Api(client.ApiClient(client.Configuration()))

    if k8s_v1b1:
        try:
            if ambassador_single_namespace:
                k8s_v1b1.list_namespaced_ingress(ambassador_namespace)
            else:
                k8s_v1b1.list_ingress_for_all_namespaces()
            status = True
        except ApiException as e:
            logger.debug(f'Ingress check got {e.status}')

    return status 
Example #15
Source File: client.py    From kube-shell with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(__name__)
        try:
            config_file = os.path.expanduser(kubeconfig_filepath)
            config.load_kube_config(config_file=config_file)
        except:
            self.logger.warning("unable to load kube-config")

        self.v1 = client.CoreV1Api()
        self.v1Beta1 = client.AppsV1beta1Api()
        self.extensionsV1Beta1 = client.ExtensionsV1beta1Api()
        self.autoscalingV1Api = client.AutoscalingV1Api()
        self.rbacApi = client.RbacAuthorizationV1beta1Api()
        self.batchV1Api = client.BatchV1Api()
        self.batchV2Api = client.BatchV2alpha1Api() 
Example #16
Source File: kubernetes_utils.py    From tacker with Apache License 2.0 5 votes vote down vote up
def get_extension_api_client(self, auth):
        k8s_client = self.get_k8s_client(auth_plugin=auth)
        return client.ExtensionsV1beta1Api(api_client=k8s_client) 
Example #17
Source File: manager.py    From polyaxon with Apache License 2.0 5 votes vote down vote up
def k8s_beta_api(self):
        if not self._k8s_beta_api:
            self._k8s_beta_api = client.ExtensionsV1beta1Api(self.api_client)
        return self._k8s_beta_api 
Example #18
Source File: kube-lambda.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def lambda_handler(event, context):

    cplJobId = event['CodePipeline.job']['id']
    cplKey = event['CodePipeline.job']['data']['inputArtifacts'][0]['location']['s3Location']['objectKey']
    cplBucket = event['CodePipeline.job']['data']['inputArtifacts'][0]['location']['s3Location']['bucketName']

    s3.meta.client.download_file(cplBucket,cplKey,'/tmp/build.zip')

    zip_ref = zipfile.ZipFile('/tmp/build.zip', 'r')
    zip_ref.extractall('/tmp/')
    zip_ref.close()

    with open('/tmp/build.json') as json_data:
        d = json.load(json_data)

    s3.meta.client.download_file(d["template-bucket"], 'web-server-deployment.yml', '/tmp/web-server-deployment.yml')
    s3.meta.client.download_file(d["template-bucket"], 'config', '/tmp/config')
    print(d["repository-uri"], d["tag"], d["deployment-name"])

    inplace_change("/tmp/web-server-deployment.yml", "$REPOSITORY_URI", d["repository-uri"])
    inplace_change("/tmp/web-server-deployment.yml", "$TAG", d["tag"])

    # Build config file from template and secrets in SSM
    CA = ssm.get_parameter(Name='CA', WithDecryption=True)["Parameter"]["Value"]
    CLIENT_CERT = ssm.get_parameter(Name='ClientCert', WithDecryption=True)["Parameter"]["Value"]
    CLIENT_KEY = ssm.get_parameter(Name='ClientKey', WithDecryption=True)["Parameter"]["Value"]

    inplace_change("/tmp/config", "$ENDPOINT", d["cluster-endpoint"])
    inplace_change("/tmp/config", "$CA", CA)
    inplace_change("/tmp/config", "$CLIENT_CERT", CLIENT_CERT)
    inplace_change("/tmp/config", "$CLIENT_KEY", CLIENT_KEY)

    config.load_kube_config('/tmp/config')
    try:
        with open(path.join(path.dirname(__file__), "/tmp/web-server-deployment.yml")) as f:
            dep = yaml.load(f)
            k8s_beta = client.ExtensionsV1beta1Api()
            resp = k8s_beta.patch_namespaced_deployment(name=d["deployment-name"],
                                                        body=dep, namespace="default")
            print("Deployment created. status='%s'" % str(resp.status))

        code_pipeline.put_job_success_result(jobId=cplJobId)
        return 'Success'
    except Exception as e:
        code_pipeline.put_job_failure_result(jobId=cplJobId, failureDetails={'message': 'Job Failed', 'type': 'JobFailed'})
        print(e)
        raise e 
Example #19
Source File: __init__.py    From kcli with Apache License 2.0 4 votes vote down vote up
def __init__(self, token=None, ca_file=None, context=None, host='127.0.0.1', port=443, user='root', debug=False,
                 namespace=None, readwritemany=False):
        self.host = host
        self.port = port
        self.user = user
        self.ca_file = ca_file
        self.readwritemany = readwritemany
        self.context = context
        self.accessmode = 'ReadWriteMany' if readwritemany else 'ReadWriteOnce'
        self.conn = 'OK'
        self.namespace = namespace
        self.token = token
        api_client = None
        if host is not None and port is not None and token is not None:
            configuration = client.Configuration()
            configuration.host = "https://%s:%s" % (host, port)
            configuration.api_key = {"authorization": "Bearer " + token}
            if ca_file is not None:
                configuration.ssl_ca_cert = ca_file
            else:
                configuration.verify_ssl = False
            api_client = client.ApiClient(configuration)
        else:
            contexts, current = config.list_kube_config_contexts()
            if context is not None:
                contexts = [entry for entry in contexts if entry['name'] == context]
                if contexts:
                    context = contexts[0]
                    contextname = context['name']
                else:
                    self.conn = None
            else:
                context = current
                contextname = current['name']
            self.contextname = contextname
            config.load_kube_config(context=contextname)
            if namespace is None and 'namespace' in context['context']:
                self.namespace = context['context']['namespace']
            if 'cluster' in context['context'] and ':' in context['context']['cluster']:
                self.host = context['context']['cluster'].split(':')[0].replace('-', '.')
        self.core = client.CoreV1Api(api_client=api_client)
        self.v1beta = client.ExtensionsV1beta1Api(api_client=api_client)
        self.storageapi = client.StorageV1Api(api_client=api_client)
        self.api_client = api_client
        self.debug = debug
        if self.namespace is None:
            self.namespace = 'default'
        return 
Example #20
Source File: nodereport.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 4 votes vote down vote up
def nodereport(conf_dir, seconds, publish):
    if seconds is None:
        seconds = 0
    else:
        seconds = int(seconds)
    should_exit = (seconds <= 0)

    while True:
        report = generate_report(conf_dir)

        print(report.json())

        if publish and report is not None:
            logging.debug("Publishing node report to Kubernetes API server")
            k8sconfig.load_incluster_config()
            v1beta = k8sclient.ExtensionsV1beta1Api()

            version = util.parse_version(k8s.get_kube_version(None))

            if version >= util.parse_version("v1.7.0"):
                node_report_type = \
                    custom_resource.CustomResourceDefinitionType(
                        v1beta,
                        "intel.com",
                        "cmk-nodereport",
                        ["cmk-nr"]
                    )
                # custom_resource throws an exception if the environment
                # variable is not set.
                node_name = os.getenv("NODE_NAME")
                node_report = node_report_type.create(node_name)
                node_report.body["spec"]["report"] = report.as_dict()
                node_report.save()
            else:
                node_report_type = third_party.ThirdPartyResourceType(
                    v1beta,
                    "cmk.intel.com",
                    "Nodereport")
                # third_party throws an exception if the environment
                # variable is not set.
                node_name = os.getenv("NODE_NAME")
                node_report = node_report_type.create(node_name)
                node_report.body["report"] = report.as_dict()
                node_report.save()

        if should_exit:
            break

        logging.info(
                "Waiting {} seconds until next node report...".format(seconds))
        time.sleep(seconds) 
Example #21
Source File: reconcile.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 4 votes vote down vote up
def reconcile(conf_dir, seconds, publish):
    conf = config.Config(conf_dir)
    report = None

    if seconds is None:
        seconds = 0
    else:
        seconds = int(seconds)

    should_exit = (seconds <= 0)

    while True:
        with conf.lock():
            report = generate_report(conf)
            print(report.json())
            reclaim_cpu_lists(conf, report)

        if publish and report is not None:
            logging.debug("Publishing reconcile report to "
                          "Kubernetes API server")
            k8sconfig.load_incluster_config()
            v1beta = k8sclient.ExtensionsV1beta1Api()

            version = util.parse_version(k8s.get_kube_version(None))

            if version >= util.parse_version("v1.7.0"):
                reconcile_report_type = \
                    custom_resource.CustomResourceDefinitionType(
                        v1beta,
                        "intel.com",
                        "cmk-reconcilereport",
                        ["cmk-rr"]
                    )

                node_name = os.getenv("NODE_NAME")
                reconcile_report = reconcile_report_type.create(node_name)
                reconcile_report.body["spec"]["report"] = report
                reconcile_report.save()
            else:
                reconcile_report_type = third_party.ThirdPartyResourceType(
                    v1beta,
                    "cmk.intel.com",
                    "Reconcilereport")

                node_name = os.getenv("NODE_NAME")
                reconcile_report = reconcile_report_type.create(node_name)
                reconcile_report.body["report"] = report
                reconcile_report.save()

        if should_exit:
            break

        logging.info(
            "Waiting %d seconds until next reconciliation..." % seconds)
        time.sleep(seconds)