Пример #1
0
 def ensure_namespaced_resource_quota(self, quotaspec):
     '''Create K8s quota object if necessary.
     '''
     with start_action(action_type="ensure_namespaced_resource_quota"):
         self.log.debug("Entering ensure_namespaced_resource_quota()")
         namespace = self.parent.namespace_mgr.namespace
         api = self.parent.api
         if namespace == "default":
             self.log.error("Will not create quota for default namespace!")
             return
         quota = client.V1ResourceQuota(metadata=client.V1ObjectMeta(
             name="quota", ),
                                        spec=quotaspec)
         self.log.info("Creating quota: %r" % quota)
         try:
             api.create_namespaced_resource_quota(namespace, quota)
         except ApiException as e:
             if e.status != 409:
                 self.log.exception(
                     "Create resourcequota '%s'" % quota +
                     "in namespace '%s' " % namespace + "failed: %s",
                     str(e))
                 raise
             else:
                 self.log.debug("Resourcequota '%r' " % quota +
                                "already exists in '%s'." % namespace)
Пример #2
0
def update_quota(name, namespace, maxmem="0Mi", maxcpu="0m", maxpods="0", priorityclass="common"):
    try:
        config.load_kube_config()
    except:
        config.load_incluster_config()

    api = client.CoreV1Api()
    name = namespace
    body = client.V1ResourceQuota(
                api_version='v1',
                kind="ResourceQuota",
                metadata=client.V1ObjectMeta(name=namespace, namespace=namespace),
                spec=client.V1ResourceQuotaSpec(
                    hard={"cpu":maxcpu, "memory":maxmem, "pods":maxpods},
                    scope_selector=client.V1ScopeSelector(match_expressions=[
                        client.V1ScopedResourceSelectorRequirement(operator="In",scope_name="PriorityClass", values=[priorityclass])
                    ])
                )
            )
    pretty = 'true'

    try:
        api_response = api.patch_namespaced_resource_quota(namespace, name, body, pretty=pretty)
    except ApiException as e:
        print("Exception when calling CoreV1Api->create_namespaced_limit_range: %s\n" % e)
Пример #3
0
def create_resource_quota(quota_name, hard_quotas, **kwargs):
    v1 = client.CoreV1Api()

    quota_namespace = kwargs[
        'namespace'] if 'namespace' in kwargs else 'default'
    quota_labels = kwargs['labels'] if 'labels' in kwargs else {}
    quota_annotations = kwargs[
        'annotations'] if 'annotations' in kwargs else {}

    quota = v1.create_namespaced_resource_quota(
        quota_namespace,
        body=client.V1ResourceQuota(
            api_version='v1',
            kind='ResourceQuota',
            metadata=client.V1ObjectMeta(name=quota_name,
                                         namespace=quota_namespace,
                                         annotations=quota_annotations,
                                         labels=quota_labels),
            spec=client.V1ResourceQuotaSpec(
                scope_selector=client.V1ScopeSelector(match_expressions=[
                    # TODO: Selector for namespace and/or user labels
                    #client.V1ScopedResourceSelectorRequirement(
                    # scop
                    #)
                ]),
                hard=hard_quotas)))
    return quota
def create_resource_quota(name, quota, id_token):
    name_object = k8s_client.V1ObjectMeta(name=name)
    resource_quota_spec = k8s_client.V1ResourceQuotaSpec(hard=quota)
    body = k8s_client.V1ResourceQuota(spec=resource_quota_spec,
                                      metadata=name_object)
    api_instance = get_k8s_api_client(id_token)
    try:
        response = api_instance.create_namespaced_resource_quota(name, body)
    except ApiException as apiException:
        raise KubernetesCreateException('resource_quota', apiException)

    logger.info("Resource quota {} created".format(quota))
    return response
Пример #5
0
 def _ensure_namespaced_resource_quota(self, quotaspec):
     self.log.info("Entering ensure_namespaced_resource_quota()")
     namespace = self.get_user_namespace()
     qname = "quota-" + namespace
     quota = client.V1ResourceQuota(
         metadata=client.V1ObjectMeta(name=qname), spec=quotaspec)
     self.log.info("Creating quota: %r" % quota)
     try:
         self.api.create_namespaced_resource_quota(namespace, quota)
     except ApiException as e:
         if e.status != 409:
             self.log.exception(
                 "Create resourcequota '%s'" % quota +
                 "in namespace '%s' " % namespace + "failed: %s", str(e))
             raise
         else:
             self.log.info("Resourcequota '%r' " % quota +
                           "already exists in '%s'." % namespace)
Пример #6
0
def resource_quota(api_instance, quota={}, namespace=TENANT_NAME):
    name_object = client.V1ObjectMeta(name=namespace)
    resource_quota_spec = client.V1ResourceQuotaSpec(hard=quota)
    body = client.V1ResourceQuota(spec=resource_quota_spec, metadata=name_object)
    api_instance.create_namespaced_resource_quota(namespace=namespace, body=body)
    return quota
    def create_namespace(self, user):
        """
        Creates a namespace for the given user if it doesn't exist
        """
        namestr = "tool-{}".format(user)
        try:
            _ = self.core.create_namespace(body=client.V1Namespace(
                api_version="v1",
                kind="Namespace",
                metadata=client.V1ObjectMeta(
                    name=namestr,
                    labels={
                        "name": namestr,
                        "tenancy": "tool"
                    },
                ),
            ))
        except ApiException as api_ex:
            if api_ex.status == 409 and "AlreadyExists" in api_ex.body:
                logging.info("Namespace tool-%s already exists", user)
                return

            logging.error("Could not create namespace for %s", user)
            raise

        # The above will shortcircuit this function before altering quotas
        # Define default quotas for new namespaces only
        _ = self.core.create_namespaced_resource_quota(
            namespace=namestr,
            body=client.V1ResourceQuota(
                api_version="v1",
                kind="ResourceQuota",
                metadata=client.V1ObjectMeta(name=namestr),
                spec=client.V1ResourceQuotaSpec(
                    hard={
                        "requests.cpu": "2",
                        "requests.memory": "6Gi",
                        "limits.cpu": "2",
                        "limits.memory": "8Gi",
                        "pods": "4",
                        "services": "1",
                        "services.nodeports": "0",
                        "replicationcontrollers": "1",
                        "secrets": "10",
                        "configmaps": "10",
                        "persistentvolumeclaims": "3",
                    }),
            ),
        )
        _ = self.core.create_namespaced_limit_range(
            namespace=namestr,
            body=client.V1LimitRange(
                api_version="v1",
                kind="LimitRange",
                metadata=client.V1ObjectMeta(name=namestr),
                spec=client.V1LimitRangeSpec(limits=[
                    client.V1LimitRangeItem(
                        default={
                            "cpu": "500m",
                            "memory": "512Mi"
                        },
                        default_request={
                            "cpu": "150m",
                            "memory": "256Mi"
                        },
                        type="Container",
                        max={
                            "cpu": "1",
                            "memory": "4Gi"
                        },
                        min={
                            "cpu": "50m",
                            "memory": "100Mi"
                        },
                    )
                ]),
            ),
        )
Пример #8
0
    "account",
    client.V1ServiceAccount(metadata=client.V1ObjectMeta(name="dev001")))
print("create K8s service account 'dev001'")

# delete K8s service account
# delete_namespaced_service_account("ServerAccount","Namespace")
ret = v1.delete_namespaced_service_account("dev001", "account")
print("delete K8s namespace 'account' / service account 'dev001'")

# create K8s ResourceQuota
resource_quota = client.V1ResourceQuota(spec=client.V1ResourceQuotaSpec(
    hard={
        "cpu": "10",
        "memory": "10G",
        "pods": "20",
        "persistentvolumeclaims": "0",
        "resourcequotas": "10",
        "configmaps": "10",
        "secrets": "10",
        "services.nodeports": "10"
    }))
resource_quota.metadata = client.V1ObjectMeta(namespace=namespace,
                                              name="user-quota")
ret = v1.create_namespaced_resource_quota(namespace, resource_quota)
print("create ResourceQuota ")

# get Quota
resource_quota = v1.read_namespaced_resource_quota("user-quota", namespace)
# Update Quota
resource_quota.spec.hard['cpu'] = 20
# replace_namespaced_resource_quota(name, namespace, body)