# coding: utf-8

"""
    Kubernetes

    No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

    The version of the OpenAPI document: release-1.37
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from collections.abc import Mapping as _Mapping
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, cast as _cast
from kubernetes.client.models.storage_v1_token_request import StorageV1TokenRequest
from typing import Optional, Set
from typing_extensions import Self
from pydantic_core import to_jsonable_python


_OPENAPI_GENERATOR_TO_DICT = "_openapi_generator_to_dict"


def _get_openapi_to_dict(value: Any) -> Any:
    # Reciprocal function references preserve inherited generated methods
    # without reserving model member names. Checking both directions also
    # rejects overrides whose decorators copy function attributes.
    to_dict = getattr(value, "to_dict", None)
    type_to_dict = getattr(type(value), "to_dict", None)
    if (
        not callable(to_dict)
        or getattr(to_dict, "__func__", None) is not type_to_dict
    ):
        return None

    openapi_to_dict = getattr(
        type_to_dict, _OPENAPI_GENERATOR_TO_DICT, None
    )
    if (
        not callable(openapi_to_dict)
        or getattr(
            openapi_to_dict,
            _OPENAPI_GENERATOR_TO_DICT,
            None,
        ) is not type_to_dict
    ):
        return None
    return openapi_to_dict


def _to_legacy_item(value: Any, serialize: bool) -> Any:
    to_dict = getattr(value, "to_dict", None)
    if _get_openapi_to_dict(value) is not None and callable(to_dict):
        return to_dict(serialize=serialize)
    if callable(to_dict):
        return to_dict()
    return value


def _to_legacy_value(value: Any, serialize: bool) -> Any:
    # python-legacy converted only immediate list elements or dictionary values:
    # https://github.com/OpenAPITools/openapi-generator/blob/c84b949df1a9ec04ba75989cb49b45c940c2f694/modules/openapi-generator/src/main/resources/python-legacy/model.mustache#L203-L231
    if isinstance(value, list):
        return [_to_legacy_item(item, serialize) for item in value]
    if isinstance(value, dict):
        return {
            key: _to_legacy_item(item, serialize)
            for key, item in value.items()
        }
    return _to_legacy_item(value, serialize)


def _to_openapi_value(value: Any) -> Any:
    if isinstance(value, list):
        return [_to_openapi_value(item) for item in value]
    if isinstance(value, dict):
        return {key: _to_openapi_value(item) for key, item in value.items()}

    to_openapi_dict = _get_openapi_to_dict(value)
    if to_openapi_dict is not None:
        return to_openapi_dict(value)

    to_dict = getattr(value, "to_dict", None)
    if callable(to_dict):
        return to_dict()
    return value


class V1CSIDriverSpec(BaseModel):
    """
    CSIDriverSpec is the specification of a CSIDriver.

    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """ # noqa: E501
    attach_required: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("attachRequired", "attach_required"), serialization_alias="attachRequired", description="attachRequired indicates this CSI volume driver requires an attach operation (because it implements the CSI ControllerPublishVolume() method), and that the Kubernetes attach detach controller should call the attach volume interface which checks the volumeattachment status and waits until the volume is attached before proceeding to mounting. The CSI external-attacher coordinates with CSI volume driver and updates the volumeattachment status when the attach operation is complete. If the value is specified to false, the attach operation will be skipped. Otherwise the attach operation will be called.  This field is immutable.")
    fs_group_policy: Optional[StrictStr] = Field(default=None, validation_alias=AliasChoices("fsGroupPolicy", "fs_group_policy"), serialization_alias="fsGroupPolicy", description="fsGroupPolicy defines if the underlying volume supports changing ownership and permission of the volume before being mounted. Refer to the specific FSGroupPolicy values for additional details.  This field was immutable in Kubernetes < 1.29 and now is mutable.  Defaults to ReadWriteOnceWithFSType, which will examine each volume to determine if Kubernetes should modify ownership and permissions of the volume. With the default policy the defined fsGroup will only be applied if a fstype is defined and the volume's access mode contains ReadWriteOnce.")
    node_allocatable_update_period_seconds: Optional[StrictInt] = Field(default=None, validation_alias=AliasChoices("nodeAllocatableUpdatePeriodSeconds", "node_allocatable_update_period_seconds"), serialization_alias="nodeAllocatableUpdatePeriodSeconds", description="nodeAllocatableUpdatePeriodSeconds specifies the interval between periodic updates of the CSINode allocatable capacity for this driver. When set, both periodic updates and updates triggered by capacity-related failures are enabled. If not set, no updates occur (neither periodic nor upon detecting capacity-related failures), and the allocatable.count remains static. The minimum allowed value for this field is 10 seconds.  This feature requires the MutableCSINodeAllocatableCount feature gate to be enabled.  This field is mutable.")
    pod_info_on_mount: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("podInfoOnMount", "pod_info_on_mount"), serialization_alias="podInfoOnMount", description="podInfoOnMount indicates this CSI volume driver requires additional pod information (like podName, podUID, etc.) during mount operations, if set to true. If set to false, pod information will not be passed on mount. Default is false.  The CSI driver specifies podInfoOnMount as part of driver deployment. If true, Kubelet will pass pod information as VolumeContext in the CSI NodePublishVolume() calls. The CSI driver is responsible for parsing and validating the information passed in as VolumeContext.  The following VolumeContext will be passed if podInfoOnMount is set to true. This list might grow, but the prefix will be used. \"csi.storage.k8s.io/pod.name\": pod.Name \"csi.storage.k8s.io/pod.namespace\": pod.Namespace \"csi.storage.k8s.io/pod.uid\": string(pod.UID) \"csi.storage.k8s.io/ephemeral\": \"true\" if the volume is an ephemeral inline volume                                 defined by a CSIVolumeSource, otherwise \"false\"  \"csi.storage.k8s.io/ephemeral\" is a new feature in Kubernetes 1.16. It is only required for drivers which support both the \"Persistent\" and \"Ephemeral\" VolumeLifecycleMode. Other drivers can leave pod info disabled and/or ignore this field. As Kubernetes 1.15 doesn't support this field, drivers can only support one mode when deployed on such a cluster and the deployment determines which mode that is, for example via a command line parameter of the driver.  This field was immutable in Kubernetes < 1.29 and now is mutable.")
    prevent_pod_scheduling_if_missing: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("preventPodSchedulingIfMissing", "prevent_pod_scheduling_if_missing"), serialization_alias="preventPodSchedulingIfMissing", description="preventPodSchedulingIfMissing indicates that the CSI driver wants to prevent pod scheduling if the CSI driver on the node is missing.  Enabling this option will prevent the scheduler (or any other component which embeds default scheduler such as cluster-autoscaler) from scheduling pods to nodes where CSI driver is not installed.  For components(such as cluster-autoscaler) that embed the scheduler and run pod placement simulations using scheduler plugins, they MUST be aware of CSI driver registration information via CSINode object. They must create simulated CSINode objects in addition to Node objects during scheduling simulation, otherwise if PreventPodSchedulingIfMissing is enabled globally for CSIDriver object, any newly created node may be rejected by the scheduler because of missing CSI driver information from the node.  This is a beta feature and requires the VolumeLimitScaling feature gate to be enabled. Default is \"false\".")
    requires_republish: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("requiresRepublish", "requires_republish"), serialization_alias="requiresRepublish", description="requiresRepublish indicates the CSI driver wants `NodePublishVolume` being periodically called to reflect any possible change in the mounted volume. This field defaults to false.  Note: After a successful initial NodePublishVolume call, subsequent calls to NodePublishVolume should only update the contents of the volume. New mount points will not be seen by a running container.")
    se_linux_mount: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("seLinuxMount", "se_linux_mount"), serialization_alias="seLinuxMount", description="seLinuxMount specifies if the CSI driver supports \"-o context\" mount option.  When \"true\", the CSI driver must ensure that all volumes provided by this CSI driver can be mounted separately with different `-o context` options. This is typical for storage backends that provide volumes as filesystems on block devices or as independent shared volumes. Kubernetes will call NodeStage / NodePublish with \"-o context=xyz\" mount option when mounting a ReadWriteOncePod volume used in Pod that has explicitly set SELinux context. In the future, it may be expanded to other volume AccessModes. In any case, Kubernetes will ensure that the volume is mounted only with a single SELinux context.  When \"false\", Kubernetes won't pass any special SELinux mount options to the driver. This is typical for volumes that represent subdirectories of a bigger shared filesystem.  Default is \"false\".")
    service_account_token_in_secrets: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("serviceAccountTokenInSecrets", "service_account_token_in_secrets"), serialization_alias="serviceAccountTokenInSecrets", description="serviceAccountTokenInSecrets is an opt-in for CSI drivers to indicate that service account tokens should be passed via the Secrets field in NodePublishVolumeRequest instead of the VolumeContext field. The CSI specification provides a dedicated Secrets field for sensitive information like tokens, which is the appropriate mechanism for handling credentials. This addresses security concerns where sensitive tokens were being logged as part of volume context.  When \"true\", kubelet will pass the tokens only in the Secrets field with the key \"csi.storage.k8s.io/serviceAccount.tokens\". The CSI driver must be updated to read tokens from the Secrets field instead of VolumeContext.  When \"false\" or not set, kubelet will pass the tokens in VolumeContext with the key \"csi.storage.k8s.io/serviceAccount.tokens\" (existing behavior). This maintains backward compatibility with existing CSI drivers.  This field can only be set when TokenRequests is configured. The API server will reject CSIDriver specs that set this field without TokenRequests.  Default behavior if unset is to pass tokens in the VolumeContext field.")
    storage_capacity: Optional[StrictBool] = Field(default=None, validation_alias=AliasChoices("storageCapacity", "storage_capacity"), serialization_alias="storageCapacity", description="storageCapacity indicates that the CSI volume driver wants pod scheduling to consider the storage capacity that the driver deployment will report by creating CSIStorageCapacity objects with capacity information, if set to true.  The check can be enabled immediately when deploying a driver. In that case, provisioning new volumes with late binding will pause until the driver deployment has published some suitable CSIStorageCapacity object.  Alternatively, the driver can be deployed with the field unset or false and it can be flipped later when storage capacity information has been published.  This field was immutable in Kubernetes <= 1.22 and now is mutable.")
    token_requests: Optional[List[StorageV1TokenRequest]] = Field(default=None, validation_alias=AliasChoices("tokenRequests", "token_requests"), serialization_alias="tokenRequests", description="tokenRequests indicates the CSI driver needs pods' service account tokens it is mounting volume for to do necessary authentication. Kubelet will pass the tokens in VolumeContext in the CSI NodePublishVolume calls. The CSI driver should parse and validate the following VolumeContext: \"csi.storage.k8s.io/serviceAccount.tokens\": {   \"<audience>\": {     \"token\": <token>,     \"expirationTimestamp\": <expiration timestamp in RFC3339>,   },   ... }  Note: Audience in each TokenRequest should be different and at most one token is empty string. To receive a new token after expiry, RequiresRepublish can be used to trigger NodePublishVolume periodically.")
    volume_lifecycle_modes: Optional[List[StrictStr]] = Field(default=None, validation_alias=AliasChoices("volumeLifecycleModes", "volume_lifecycle_modes"), serialization_alias="volumeLifecycleModes", description="volumeLifecycleModes defines what kind of volumes this CSI volume driver supports. The default if the list is empty is \"Persistent\", which is the usage defined by the CSI specification and implemented in Kubernetes via the usual PV/PVC mechanism.  The other mode is \"Ephemeral\". In this mode, volumes are defined inline inside the pod spec with CSIVolumeSource and their lifecycle is tied to the lifecycle of that pod. A driver has to be aware of this because it is only going to get a NodePublishVolume call for such a volume.  For more information about implementing this mode, see https://kubernetes-csi.github.io/docs/ephemeral-local-volumes.html A driver can support one or more of these modes and more modes may be added in the future.  This field is beta. This field is immutable.")
    openapi_types: ClassVar[Dict[str, str]] = {
        "attach_required": "bool",
        "fs_group_policy": "str",
        "node_allocatable_update_period_seconds": "int",
        "pod_info_on_mount": "bool",
        "prevent_pod_scheduling_if_missing": "bool",
        "requires_republish": "bool",
        "se_linux_mount": "bool",
        "service_account_token_in_secrets": "bool",
        "storage_capacity": "bool",
        "token_requests": "List[StorageV1TokenRequest]",
        "volume_lifecycle_modes": "List[str]"
    }

    attribute_map: ClassVar[Dict[str, str]] = {
        "attach_required": "attachRequired",
        "fs_group_policy": "fsGroupPolicy",
        "node_allocatable_update_period_seconds": "nodeAllocatableUpdatePeriodSeconds",
        "pod_info_on_mount": "podInfoOnMount",
        "prevent_pod_scheduling_if_missing": "preventPodSchedulingIfMissing",
        "requires_republish": "requiresRepublish",
        "se_linux_mount": "seLinuxMount",
        "service_account_token_in_secrets": "serviceAccountTokenInSecrets",
        "storage_capacity": "storageCapacity",
        "token_requests": "tokenRequests",
        "volume_lifecycle_modes": "volumeLifecycleModes"
    }
    __properties: ClassVar[List[str]] = ["attachRequired", "fsGroupPolicy", "nodeAllocatableUpdatePeriodSeconds", "podInfoOnMount", "preventPodSchedulingIfMissing", "requiresRepublish", "seLinuxMount", "serviceAccountTokenInSecrets", "storageCapacity", "tokenRequests", "volumeLifecycleModes"]

    @classmethod
    def __preprocess_input_names(
        cls,
        obj: Any,
        remove_hidden_storage_names: bool = True,
    ) -> Any:
        if not isinstance(obj, _Mapping):
            return obj
        obj = dict(obj)
        if "attachRequired" not in obj and "attach_required" in obj:
            obj["attachRequired"] = obj["attach_required"]
        obj.pop("attach_required", None)
        if "fsGroupPolicy" not in obj and "fs_group_policy" in obj:
            obj["fsGroupPolicy"] = obj["fs_group_policy"]
        obj.pop("fs_group_policy", None)
        if "nodeAllocatableUpdatePeriodSeconds" not in obj and "node_allocatable_update_period_seconds" in obj:
            obj["nodeAllocatableUpdatePeriodSeconds"] = obj["node_allocatable_update_period_seconds"]
        obj.pop("node_allocatable_update_period_seconds", None)
        if "podInfoOnMount" not in obj and "pod_info_on_mount" in obj:
            obj["podInfoOnMount"] = obj["pod_info_on_mount"]
        obj.pop("pod_info_on_mount", None)
        if "preventPodSchedulingIfMissing" not in obj and "prevent_pod_scheduling_if_missing" in obj:
            obj["preventPodSchedulingIfMissing"] = obj["prevent_pod_scheduling_if_missing"]
        obj.pop("prevent_pod_scheduling_if_missing", None)
        if "requiresRepublish" not in obj and "requires_republish" in obj:
            obj["requiresRepublish"] = obj["requires_republish"]
        obj.pop("requires_republish", None)
        if "seLinuxMount" not in obj and "se_linux_mount" in obj:
            obj["seLinuxMount"] = obj["se_linux_mount"]
        obj.pop("se_linux_mount", None)
        if "serviceAccountTokenInSecrets" not in obj and "service_account_token_in_secrets" in obj:
            obj["serviceAccountTokenInSecrets"] = obj["service_account_token_in_secrets"]
        obj.pop("service_account_token_in_secrets", None)
        if "storageCapacity" not in obj and "storage_capacity" in obj:
            obj["storageCapacity"] = obj["storage_capacity"]
        obj.pop("storage_capacity", None)
        if "tokenRequests" not in obj and "token_requests" in obj:
            obj["tokenRequests"] = obj["token_requests"]
        obj.pop("token_requests", None)
        if "volumeLifecycleModes" not in obj and "volume_lifecycle_modes" in obj:
            obj["volumeLifecycleModes"] = obj["volume_lifecycle_modes"]
        obj.pop("volume_lifecycle_modes", None)
        return obj

    model_config = ConfigDict(
        validate_by_name=True,
        validate_by_alias=True,
        validate_assignment=True,
        extra="forbid",
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self) -> str:
        """For print and pprint"""
        return self.to_str()

    def __eq__(self, other: object) -> bool:
        """Returns true if both objects are equal"""
        if not isinstance(other, V1CSIDriverSpec):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other: object) -> bool:
        """Returns true if both objects are not equal"""
        if not isinstance(other, V1CSIDriverSpec):
            return True

        return not (self == other)


    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        to_openapi_dict = _get_openapi_to_dict(self)
        if to_openapi_dict is not None:
            return json.dumps(to_jsonable_python(to_openapi_dict(self)))
        return json.dumps(to_jsonable_python(self.to_dict()))

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of V1CSIDriverSpec from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self, serialize: bool = False) -> Dict[str, Any]:
        """Return all declared model fields using public or wire names."""
        return {
            ("attachRequired" if serialize else "attach_required"): _to_legacy_value(getattr(self, "attach_required", None), serialize),
            ("fsGroupPolicy" if serialize else "fs_group_policy"): _to_legacy_value(getattr(self, "fs_group_policy", None), serialize),
            ("nodeAllocatableUpdatePeriodSeconds" if serialize else "node_allocatable_update_period_seconds"): _to_legacy_value(getattr(self, "node_allocatable_update_period_seconds", None), serialize),
            ("podInfoOnMount" if serialize else "pod_info_on_mount"): _to_legacy_value(getattr(self, "pod_info_on_mount", None), serialize),
            ("preventPodSchedulingIfMissing" if serialize else "prevent_pod_scheduling_if_missing"): _to_legacy_value(getattr(self, "prevent_pod_scheduling_if_missing", None), serialize),
            ("requiresRepublish" if serialize else "requires_republish"): _to_legacy_value(getattr(self, "requires_republish", None), serialize),
            ("seLinuxMount" if serialize else "se_linux_mount"): _to_legacy_value(getattr(self, "se_linux_mount", None), serialize),
            ("serviceAccountTokenInSecrets" if serialize else "service_account_token_in_secrets"): _to_legacy_value(getattr(self, "service_account_token_in_secrets", None), serialize),
            ("storageCapacity" if serialize else "storage_capacity"): _to_legacy_value(getattr(self, "storage_capacity", None), serialize),
            ("tokenRequests" if serialize else "token_requests"): _to_legacy_value(getattr(self, "token_requests", None), serialize),
            ("volumeLifecycleModes" if serialize else "volume_lifecycle_modes"): _to_legacy_value(getattr(self, "volume_lifecycle_modes", None), serialize),
        }

    def __openapi_generator_modern_projection(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of each item in token_requests (list)
        _items = []
        if self.token_requests:
            for _item_token_requests in self.token_requests:
                _items.append(_to_openapi_value(_item_token_requests) if _item_token_requests is not None else None)
            _dict['tokenRequests'] = _items
        return _dict

    setattr(
        to_dict,
        _OPENAPI_GENERATOR_TO_DICT,
        __openapi_generator_modern_projection,
    )
    setattr(
        __openapi_generator_modern_projection,
        _OPENAPI_GENERATOR_TO_DICT,
        to_dict,
    )
    del __openapi_generator_modern_projection

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of V1CSIDriverSpec from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        obj = _cast(
            Dict[str, Any],
            cls.__preprocess_input_names(
                obj,
                remove_hidden_storage_names=True,
            ),
        )

        _obj = cls.model_validate({
            "attachRequired": obj.get("attachRequired"),
            "fsGroupPolicy": obj.get("fsGroupPolicy"),
            "nodeAllocatableUpdatePeriodSeconds": obj.get("nodeAllocatableUpdatePeriodSeconds"),
            "podInfoOnMount": obj.get("podInfoOnMount"),
            "preventPodSchedulingIfMissing": obj.get("preventPodSchedulingIfMissing"),
            "requiresRepublish": obj.get("requiresRepublish"),
            "seLinuxMount": obj.get("seLinuxMount"),
            "serviceAccountTokenInSecrets": obj.get("serviceAccountTokenInSecrets"),
            "storageCapacity": obj.get("storageCapacity"),
            "tokenRequests": [StorageV1TokenRequest.from_dict(_item) for _item in obj["tokenRequests"]] if obj.get("tokenRequests") is not None else None,
            "volumeLifecycleModes": obj.get("volumeLifecycleModes")
        })
        return _obj
