# 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.29
    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 typing import Optional
from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr
from .v1_label_selector import V1LabelSelector
from .v1_pod_failure_policy import V1PodFailurePolicy
from .v1_pod_template_spec import V1PodTemplateSpec

class V1JobSpec(BaseModel):
    """
    JobSpec describes how the job execution will look like.  # noqa: E501
    """
    active_deadline_seconds: Optional[StrictInt] = Field(None, alias="activeDeadlineSeconds", description="Specifies the duration in seconds relative to the startTime that the job may be continuously active before the system tries to terminate it; value must be positive integer. If a Job is suspended (at creation or through an update), this timer will effectively be stopped and reset when the Job is resumed again.")
    backoff_limit: Optional[StrictInt] = Field(None, alias="backoffLimit", description="Specifies the number of retries before marking this job failed. Defaults to 6")
    backoff_limit_per_index: Optional[StrictInt] = Field(None, alias="backoffLimitPerIndex", description="Specifies the limit for the number of retries within an index before marking this index as failed. When enabled the number of failures per index is kept in the pod's batch.kubernetes.io/job-index-failure-count annotation. It can only be set when Job's completionMode=Indexed, and the Pod's restart policy is Never. The field is immutable. This field is beta-level. It can be used when the `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default).")
    completion_mode: Optional[StrictStr] = Field(None, alias="completionMode", description="completionMode specifies how Pod completions are tracked. It can be `NonIndexed` (default) or `Indexed`.  `NonIndexed` means that the Job is considered complete when there have been .spec.completions successfully completed Pods. Each Pod completion is homologous to each other.  `Indexed` means that the Pods of a Job get an associated completion index from 0 to (.spec.completions - 1), available in the annotation batch.kubernetes.io/job-completion-index. The Job is considered complete when there is one successfully completed Pod for each index. When value is `Indexed`, .spec.completions must be specified and `.spec.parallelism` must be less than or equal to 10^5. In addition, The Pod name takes the form `$(job-name)-$(index)-$(random-string)`, the Pod hostname takes the form `$(job-name)-$(index)`.  More completion modes can be added in the future. If the Job controller observes a mode that it doesn't recognize, which is possible during upgrades due to version skew, the controller skips updates for the Job.")
    completions: Optional[StrictInt] = Field(None, description="Specifies the desired number of successfully finished pods the job should be run with.  Setting to null means that the success of any pod signals the success of all pods, and allows parallelism to have any positive value.  Setting to 1 means that parallelism is limited to 1 and the success of that pod signals the success of the job. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/")
    manual_selector: Optional[StrictBool] = Field(None, alias="manualSelector", description="manualSelector controls generation of pod labels and pod selectors. Leave `manualSelector` unset unless you are certain what you are doing. When false or unset, the system pick labels unique to this job and appends those labels to the pod template.  When true, the user is responsible for picking unique labels and specifying the selector.  Failure to pick a unique label may cause this and other jobs to not function correctly.  However, You may see `manualSelector=true` in jobs that were created with the old `extensions/v1beta1` API. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/#specifying-your-own-pod-selector")
    max_failed_indexes: Optional[StrictInt] = Field(None, alias="maxFailedIndexes", description="Specifies the maximal number of failed indexes before marking the Job as failed, when backoffLimitPerIndex is set. Once the number of failed indexes exceeds this number the entire Job is marked as Failed and its execution is terminated. When left as null the job continues execution of all of its indexes and is marked with the `Complete` Job condition. It can only be specified when backoffLimitPerIndex is set. It can be null or up to completions. It is required and must be less than or equal to 10^4 when is completions greater than 10^5. This field is beta-level. It can be used when the `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default).")
    parallelism: Optional[StrictInt] = Field(None, description="Specifies the maximum desired number of pods the job should run at any given time. The actual number of pods running in steady state will be less than this number when ((.spec.completions - .status.successful) < .spec.parallelism), i.e. when the work left to do is less than max parallelism. More info: https://kubernetes.io/docs/concepts/workloads/controllers/jobs-run-to-completion/")
    pod_failure_policy: Optional[V1PodFailurePolicy] = Field(None, alias="podFailurePolicy")
    pod_replacement_policy: Optional[StrictStr] = Field(None, alias="podReplacementPolicy", description="podReplacementPolicy specifies when to create replacement Pods. Possible values are: - TerminatingOrFailed means that we recreate pods   when they are terminating (has a metadata.deletionTimestamp) or failed. - Failed means to wait until a previously created Pod is fully terminated (has phase   Failed or Succeeded) before creating a replacement Pod.  When using podFailurePolicy, Failed is the the only allowed value. TerminatingOrFailed and Failed are allowed values when podFailurePolicy is not in use. This is an beta field. To use this, enable the JobPodReplacementPolicy feature toggle. This is on by default.")
    selector: Optional[V1LabelSelector] = None
    suspend: Optional[StrictBool] = Field(None, description="suspend specifies whether the Job controller should create Pods or not. If a Job is created with suspend set to true, no Pods are created by the Job controller. If a Job is suspended after creation (i.e. the flag goes from false to true), the Job controller will delete all active Pods associated with this Job. Users must design their workload to gracefully handle this. Suspending a Job will reset the StartTime field of the Job, effectively resetting the ActiveDeadlineSeconds timer too. Defaults to false.")
    template: V1PodTemplateSpec = Field(...)
    ttl_seconds_after_finished: Optional[StrictInt] = Field(None, alias="ttlSecondsAfterFinished", description="ttlSecondsAfterFinished limits the lifetime of a Job that has finished execution (either Complete or Failed). If this field is set, ttlSecondsAfterFinished after the Job finishes, it is eligible to be automatically deleted. When the Job is being deleted, its lifecycle guarantees (e.g. finalizers) will be honored. If this field is unset, the Job won't be automatically deleted. If this field is set to zero, the Job becomes eligible to be deleted immediately after it finishes.")
    __properties = ["activeDeadlineSeconds", "backoffLimit", "backoffLimitPerIndex", "completionMode", "completions", "manualSelector", "maxFailedIndexes", "parallelism", "podFailurePolicy", "podReplacementPolicy", "selector", "suspend", "template", "ttlSecondsAfterFinished"]

    class Config:
        """Pydantic configuration"""
        allow_population_by_field_name = True
        validate_assignment = True

    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.dict(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        return json.dumps(self.to_dict())

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

    def to_dict(self):
        """Returns the dictionary representation of the model using alias"""
        _dict = self.dict(by_alias=True,
                          exclude={
                          },
                          exclude_none=True)
        # override the default output from pydantic by calling `to_dict()` of pod_failure_policy
        if self.pod_failure_policy:
            _dict['podFailurePolicy'] = self.pod_failure_policy.to_dict()
        # override the default output from pydantic by calling `to_dict()` of selector
        if self.selector:
            _dict['selector'] = self.selector.to_dict()
        # override the default output from pydantic by calling `to_dict()` of template
        if self.template:
            _dict['template'] = self.template.to_dict()
        return _dict

    @classmethod
    def from_dict(cls, obj: dict) -> V1JobSpec:
        """Create an instance of V1JobSpec from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return V1JobSpec.parse_obj(obj)

        _obj = V1JobSpec.parse_obj({
            "active_deadline_seconds": obj.get("activeDeadlineSeconds"),
            "backoff_limit": obj.get("backoffLimit"),
            "backoff_limit_per_index": obj.get("backoffLimitPerIndex"),
            "completion_mode": obj.get("completionMode"),
            "completions": obj.get("completions"),
            "manual_selector": obj.get("manualSelector"),
            "max_failed_indexes": obj.get("maxFailedIndexes"),
            "parallelism": obj.get("parallelism"),
            "pod_failure_policy": V1PodFailurePolicy.from_dict(obj.get("podFailurePolicy")) if obj.get("podFailurePolicy") is not None else None,
            "pod_replacement_policy": obj.get("podReplacementPolicy"),
            "selector": V1LabelSelector.from_dict(obj.get("selector")) if obj.get("selector") is not None else None,
            "suspend": obj.get("suspend"),
            "template": V1PodTemplateSpec.from_dict(obj.get("template")) if obj.get("template") is not None else None,
            "ttl_seconds_after_finished": obj.get("ttlSecondsAfterFinished")
        })
        return _obj


