Python kubernetes.client.V1Namespace() Examples

The following are 16 code examples of kubernetes.client.V1Namespace(). 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: config.py    From ray with Apache License 2.0 7 votes vote down vote up
def _configure_namespace(provider_config):
    namespace_field = "namespace"
    if namespace_field not in provider_config:
        raise ValueError("Must specify namespace in Kubernetes config.")

    namespace = provider_config[namespace_field]
    field_selector = "metadata.name={}".format(namespace)
    namespaces = core_api().list_namespace(field_selector=field_selector).items
    if len(namespaces) > 0:
        assert len(namespaces) == 1
        logger.info(log_prefix +
                    using_existing_msg(namespace_field, namespace))
        return namespace

    logger.info(log_prefix + not_found_msg(namespace_field, namespace))
    namespace_config = client.V1Namespace(
        metadata=client.V1ObjectMeta(name=namespace))
    core_api().create_namespace(namespace_config)
    logger.info(log_prefix + created_msg(namespace_field, namespace))
    return namespace 
Example #2
Source File: backend.py    From conu with GNU General Public License v3.0 7 votes vote down vote up
def create_namespace(self):
        """
        Create namespace with random name
        :return: name of new created namespace
        """
        name = 'namespace-{random_string}'.format(random_string=random_str(5))

        namespace = client.V1Namespace(metadata=client.V1ObjectMeta(name=name))

        self.core_api.create_namespace(namespace)

        logger.info("Creating namespace: %s", name)

        # save all namespaces created with this backend
        self.managed_namespaces.append(name)

        # wait for namespace to be ready
        Probe(timeout=30, pause=5, expected_retval=True,
              fnc=self._namespace_ready, namespace=name).run()

        return name 
Example #3
Source File: conftest.py    From kubespawner with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def kube_client(request, kube_ns):
    """fixture for the Kubernetes client object.

    skips test that require kubernetes if kubernetes cannot be contacted
    """
    load_kube_config()
    client = shared_client('CoreV1Api')
    try:
        namespaces = client.list_namespace(_request_timeout=3)
    except Exception as e:
        pytest.skip("Kubernetes not found: %s" % e)
    if not any(ns.metadata.name == kube_ns for ns in namespaces.items):
        print("Creating namespace %s" % kube_ns)
        client.create_namespace(V1Namespace(metadata=dict(name=kube_ns)))
    else:
        print("Using existing namespace %s" % kube_ns)
    # delete the test namespace when we finish
    request.addfinalizer(lambda: client.delete_namespace(kube_ns, body={}))
    return client 
Example #4
Source File: k8s.py    From nephos with Apache License 2.0 6 votes vote down vote up
def ns_create(namespace):
    """Create K8S namespace.

    Args:
        namespace (str): Name of namespace.
    """
    try:
        ns_read(namespace)
    except ApiException:
        ns = client.V1Namespace()
        ns.metadata = client.V1ObjectMeta(name=namespace)
        api.create_namespace(ns)
        logging.info(f'Created namespace "{namespace}"')
        logging.debug(pretty_print(json.dumps(ns.metadata, default=str)))


# TODO: Can we be more precise with the return type annotation? 
Example #5
Source File: namespace_manager_mock.py    From reckoner with Apache License 2.0 5 votes vote down vote up
def namespace(self) -> str:
        """ Namespace object we are managing 
        https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Namespace.md"""
        return self._namespace 
Example #6
Source File: namespace_manager_mock.py    From reckoner with Apache License 2.0 5 votes vote down vote up
def create(self):
        """ Create a namespace in the configured kubernetes cluster if it does not already exist

        Arguments:
        None

        Returns Namespace
        Raises error in case of failure

        """
        return client.V1Namespace(
            metadata=client.V1ObjectMeta(name=self.namespace_name)
        ) 
Example #7
Source File: kube.py    From reckoner with Apache License 2.0 5 votes vote down vote up
def namespace(self) -> str:
        """ Namespace object we are managing 
        https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Namespace.md"""
        return self._namespace 
Example #8
Source File: kube.py    From reckoner with Apache License 2.0 5 votes vote down vote up
def create(self):
        """ Create a namespace in the configured kubernetes cluster if it does not already exist

        Arguments:
        None

        Returns Namespace
        Raises error in case of failure

        """
        _namespaces = [namespace for namespace in self.cluster_namespaces if namespace.metadata.name == self.namespace_name]

        if _namespaces == []:
            logging.info('Namespace {} not found. Creating it now.'.format(self.namespace_name))
            try:
                return self.v1client.create_namespace(
                    client.V1Namespace(
                        metadata=client.V1ObjectMeta(name=self.namespace_name)
                    )
                )

            except Exception as e:
                logging.error("Unable to create namespace in cluster! {}".format(e))
                logging.debug(traceback.format_exc())
                raise e
        else:
            return _namespaces[0] 
Example #9
Source File: test_utils.py    From python with Apache License 2.0 5 votes vote down vote up
def setUpClass(cls):
        cls.config = base.get_e2e_configuration()
        cls.path_prefix = "kubernetes/e2e_test/test_yaml/"
        cls.test_namespace = "e2e-test-utils"
        k8s_client = client.api_client.ApiClient(configuration=cls.config)
        core_v1 = client.CoreV1Api(api_client=k8s_client)
        body = client.V1Namespace(metadata=client.V1ObjectMeta(name=cls.test_namespace))
        core_v1.create_namespace(body=body) 
Example #10
Source File: kubernetes_tools.py    From paasta with Apache License 2.0 5 votes vote down vote up
def ensure_namespace(kube_client: KubeClient, namespace: str) -> None:
    paasta_namespace = V1Namespace(
        metadata=V1ObjectMeta(name=namespace, labels={"name": namespace})
    )
    namespaces = kube_client.core.list_namespace()
    namespace_names = [item.metadata.name for item in namespaces.items]
    if namespace not in namespace_names:
        log.warning(f"Creating namespace: {namespace} as it does not exist")
        kube_client.core.create_namespace(body=paasta_namespace) 
Example #11
Source File: tenants_utils.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def create_namespace(name, quota, id_token):
    annotations = None
    if 'maxEndpoints' in quota:
        annotations = {'maxEndpoints': str(quota.pop('maxEndpoints'))}
    name_object = k8s_client.V1ObjectMeta(name=name, annotations=annotations,
                                          labels={'created_by': PLATFORM_ADMIN_LABEL})
    namespace = k8s_client.V1Namespace(metadata=name_object)
    api_instance = get_k8s_api_client(id_token=id_token)
    try:
        response = api_instance.create_namespace(namespace)
    except ApiException as apiException:
        raise KubernetesCreateException('namespace', apiException)

    logger.info("Namespace {} created".format(name))
    return response 
Example #12
Source File: deploy_utils.py    From aws-eks-deep-learning-benchmark with Apache License 2.0 5 votes vote down vote up
def _setup_test(api_client, run_label):
  """Create the namespace for the test.
  Returns:
    test_dir: The local test directory.
  """

  api = k8s_client.CoreV1Api(api_client)
  namespace = k8s_client.V1Namespace()
  namespace.api_version = "v1"
  namespace.kind = "Namespace"
  namespace.metadata = k8s_client.V1ObjectMeta(
    name=run_label, labels={
      "app": "kubeflow-e2e-test",
    })

  try:
    logging.info("Creating namespace %s", namespace.metadata.name)
    namespace = api.create_namespace(namespace)
    logging.info("Namespace %s created.", namespace.metadata.name)
  except rest.ApiException as e:
    if e.status == 409:
      logging.info("Namespace %s already exists.", namespace.metadata.name)
    else:
      raise

  return namespace 
Example #13
Source File: k8s.py    From CPU-Manager-for-Kubernetes with Apache License 2.0 5 votes vote down vote up
def create_namespace(config, ns_name):
    metadata = {'name': ns_name}
    namespace = V1Namespace(metadata=metadata)
    k8s_api = client_from_config(config)
    k8s_api.create_namespace(namespace)


# Get available namespaces. 
Example #14
Source File: test_base.py    From node with Apache License 2.0 5 votes vote down vote up
def create_namespace(self, ns_name):
        self.cluster.create_namespace(client.V1Namespace(metadata=client.V1ObjectMeta(name=ns_name))) 
Example #15
Source File: namespace.py    From kubetest with GNU General Public License v3.0 5 votes vote down vote up
def new(cls, name: str) -> 'Namespace':
        """Create a new Namespace with object backing.

        Args:
            name: The name of the new Namespace.

        Returns:
            A new Namespace instance.
        """
        return cls(client.V1Namespace(
            metadata=client.V1ObjectMeta(
                name=name
            )
        )) 
Example #16
Source File: test_eks.py    From coach with Apache License 2.0 5 votes vote down vote up
def create_namespace(self):
        namespace = client.V1Namespace(
            api_version='v1',
            kind="Namespace",
            metadata=client.V1ObjectMeta(name=self.namespace)
        )

        try:
            self.corev1_api.create_namespace(namespace)
        except client.rest.ApiException as e:
            raise RuntimeError("Failed to create namesapce. Got exception: {}".format(e))