diff --git a/.github/workflows/test-e2e.yaml b/.github/workflows/test-e2e.yaml index 194d37e3ae..7a9f51bd67 100644 --- a/.github/workflows/test-e2e.yaml +++ b/.github/workflows/test-e2e.yaml @@ -51,7 +51,7 @@ jobs: - name: Run e2e with Go run: | - make test-e2e + make test-e2e || kubectl logs -n kubeflow-system -l app.kubernetes.io/name=trainer - name: Run e2e test for example Notebooks run: | diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 37346c53e7..cb1ddd21c7 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -25,7 +25,8 @@ exclude: | (?x)^( docs/images/.*| pkg/client/.*| - sdk/kubeflow/trainer/[^/]*.py| + sdk/kubeflow/trainer/__init__.py| + sdk/kubeflow/trainer/api/__init__.py| sdk/kubeflow/trainer/models/.*| sdk/docs/.* )$ diff --git a/Makefile b/Makefile index 884f583b94..05df4f9304 100644 --- a/Makefile +++ b/Makefile @@ -36,11 +36,17 @@ PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) # Tool Binaries LOCALBIN ?= $(PROJECT_DIR)/bin -CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen +GINKGO ?= $(LOCALBIN)/ginkgo ENVTEST ?= $(LOCALBIN)/setup-envtest +CONTROLLER_GEN ?= $(LOCALBIN)/controller-gen KIND ?= $(LOCALBIN)/kind # Instructions to download tools for development. + +.PHONY: ginkgo +ginkgo: ## Download the ginkgo binary if required. + GOBIN=$(LOCALBIN) go install github.com/onsi/ginkgo/v2/ginkgo@$(shell go list -m -f '{{.Version}}' github.com/onsi/ginkgo/v2) + .PHONY: envtest envtest: ## Download the setup-envtest binary if required. GOBIN=$(LOCALBIN) go install sigs.k8s.io/controller-runtime/tools/setup-envtest@release-0.20 @@ -138,8 +144,8 @@ test-e2e-setup-cluster: kind ## Setup Kind cluster for e2e test. KIND=$(KIND) K8S_VERSION=$(K8S_VERSION) ./hack/e2e-setup-cluster.sh .PHONY: test-e2e -test-e2e: ## Run Go e2e test. - go test ./test/e2e/... +test-e2e: ginkgo ## Run Go e2e test. + $(GINKGO) -v ./test/e2e/... # Input and output location for Notebooks executed with Papermill. NOTEBOOK_INPUT=$(PROJECT_DIR)/examples/pytorch/image-classification/mnist.ipynb diff --git a/api/openapi-spec/swagger.json b/api/openapi-spec/swagger.json index 25c7036bd8..20c7ebee28 100644 --- a/api/openapi-spec/swagger.json +++ b/api/openapi-spec/swagger.json @@ -20,7 +20,7 @@ "metadata": { "description": "Standard object's metadata.", "default": {}, - "$ref": "#/definitions/v1.ObjectMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" }, "spec": { "description": "Specification of the desired ClusterTrainingRuntime.", @@ -55,7 +55,7 @@ "metadata": { "description": "Standard list metadata.", "default": {}, - "$ref": "#/definitions/v1.ListMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta" } } }, @@ -89,7 +89,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.EnvVar" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.EnvVar" }, "x-kubernetes-list-map-keys": [ "name" @@ -101,7 +101,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.EnvFromSource" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.EnvFromSource" }, "x-kubernetes-list-type": "atomic" }, @@ -115,7 +115,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.VolumeMount" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.VolumeMount" }, "x-kubernetes-list-map-keys": [ "name" @@ -144,7 +144,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.EnvVar" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.EnvVar" }, "x-kubernetes-list-map-keys": [ "name" @@ -153,7 +153,7 @@ }, "secretRef": { "description": "Reference to the secret with credentials to download dataset. Secret must be created in the TrainJob's namespace.", - "$ref": "#/definitions/v1.LocalObjectReference" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.LocalObjectReference" }, "storageUri": { "description": "Storage uri for the dataset provider.", @@ -170,7 +170,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.EnvVar" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.EnvVar" }, "x-kubernetes-list-map-keys": [ "name" @@ -179,7 +179,7 @@ }, "secretRef": { "description": "Reference to the secret with credentials to download model. Secret must be created in the TrainJob's namespace.", - "$ref": "#/definitions/v1.LocalObjectReference" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.LocalObjectReference" }, "storageUri": { "description": "Storage uri for the model provider.", @@ -194,12 +194,12 @@ "metadata": { "description": "Metadata for custom JobSet's labels and annotations. JobSet name and namespace is equal to the TrainJob's name and namespace.", "default": {}, - "$ref": "#/definitions/v1.ObjectMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" }, "spec": { "description": "Specification of the desired JobSet which will be created from TrainJob.", "default": {}, - "$ref": "#/definitions/jobset.v1alpha2.JobSetSpec" + "$ref": "https://raw.githubusercontent.com/kubernetes-sigs/jobset/d5c7bcebe739a4577e30944370c2d7a68321a929/hack/python-sdk/swagger.json#/definitions/jobset.v1alpha2.JobSetSpec" } } }, @@ -330,7 +330,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.EnvVar" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.EnvVar" }, "x-kubernetes-list-map-keys": [ "name" @@ -339,7 +339,7 @@ }, "secretRef": { "description": "Reference to the secret with credentials to export model. Secret must be created in the TrainJob's namespace.", - "$ref": "#/definitions/v1.LocalObjectReference" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.LocalObjectReference" }, "storageUri": { "description": "Storage uri for the model exporter.", @@ -424,7 +424,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.Toleration" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.Toleration" }, "x-kubernetes-list-type": "atomic" }, @@ -433,7 +433,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.Volume" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.Volume" }, "x-kubernetes-list-map-keys": [ "name" @@ -496,7 +496,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/k8s.io.api.autoscaling.v2.MetricSpec" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.autoscaling.v2.MetricSpec" }, "x-kubernetes-list-type": "atomic" }, @@ -517,7 +517,7 @@ }, "numProcPerNode": { "description": "Number of processes per node. This value is inserted into the `--nproc-per-node` argument of the `torchrun` CLI. Supported values: `auto`, `cpu`, `gpu`, or int value. Defaults to `auto`.", - "$ref": "#/definitions/k8s.io.apimachinery.pkg.util.intstr.IntOrString" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString" } } }, @@ -536,7 +536,7 @@ "metadata": { "description": "Standard object's metadata.", "default": {}, - "$ref": "#/definitions/v1.ObjectMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" }, "spec": { "description": "Specification of the desired TrainJob.", @@ -576,7 +576,7 @@ "metadata": { "description": "Standard list metadata.", "default": {}, - "$ref": "#/definitions/v1.ListMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta" } } }, @@ -648,7 +648,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.Condition" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.Condition" }, "x-kubernetes-list-map-keys": [ "type" @@ -698,7 +698,7 @@ "type": "array", "items": { "default": {}, - "$ref": "#/definitions/v1.EnvVar" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.EnvVar" }, "x-kubernetes-list-map-keys": [ "name" @@ -716,11 +716,11 @@ }, "numProcPerNode": { "description": "Number of processes/workers/slots on every training node. For the Torch runtime: `auto`, `cpu`, `gpu`, or int value can be set. For the MPI runtime only int value can be set.", - "$ref": "#/definitions/k8s.io.apimachinery.pkg.util.intstr.IntOrString" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.util.intstr.IntOrString" }, "resourcesPerNode": { "description": "Compute resources for each training node.", - "$ref": "#/definitions/v1.ResourceRequirements" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.api.core.v1.ResourceRequirements" } } }, @@ -739,7 +739,7 @@ "metadata": { "description": "Standard object's metadata.", "default": {}, - "$ref": "#/definitions/v1.ObjectMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ObjectMeta" }, "spec": { "description": "Specification of the desired TrainingRuntime.", @@ -774,7 +774,7 @@ "metadata": { "description": "Standard list metadata.", "default": {}, - "$ref": "#/definitions/v1.ListMeta" + "$ref": "https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/v1.32.2/api/openapi-spec/swagger.json#/definitions/io.k8s.apimachinery.pkg.apis.meta.v1.ListMeta" } } }, diff --git a/hack/python-sdk/gen-sdk.sh b/hack/python-sdk/gen-sdk.sh index eb3fedc28d..5cfaa97842 100755 --- a/hack/python-sdk/gen-sdk.sh +++ b/hack/python-sdk/gen-sdk.sh @@ -21,41 +21,30 @@ set -o nounset # TODO (andreyvelich): Read this data from the global VERSION file. SDK_VERSION="0.1.0" - SDK_OUTPUT_PATH="sdk" -SWAGGER_JAR_URL="https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.3.1/openapi-generator-cli-4.3.1.jar" -SWAGGER_CODEGEN_JAR="hack/python-sdk/openapi-generator-cli.jar" +OPENAPI_GENERATOR_VERSION="v7.11.0" +TRAINER_ROOT="$(pwd)" SWAGGER_CODEGEN_CONF="hack/python-sdk/swagger_config.json" SWAGGER_CODEGEN_FILE="api/openapi-spec/swagger.json" -if [[ ! -f "$SWAGGER_CODEGEN_JAR" ]]; then - echo "Downloading the openapi-generator-cli JAR package to generate SDK" - wget -O "${SWAGGER_CODEGEN_JAR}" ${SWAGGER_JAR_URL} -fi - echo "Generating Python SDK for Kubeflow Trainer V2 ..." -java -jar "${SWAGGER_CODEGEN_JAR}" generate -i "${SWAGGER_CODEGEN_FILE}" -g python \ - -o "${SDK_OUTPUT_PATH}" \ - -c "${SWAGGER_CODEGEN_CONF}" \ +# We need to add user to allow container override existing files. +docker run --user "$(id -u)":"$(id -g)" --rm \ + -v "${TRAINER_ROOT}:/local" docker.io/openapitools/openapi-generator-cli:${OPENAPI_GENERATOR_VERSION} generate \ + -g python \ + -i "local/${SWAGGER_CODEGEN_FILE}" \ + -c "local/${SWAGGER_CODEGEN_CONF}" \ + -o "local/${SDK_OUTPUT_PATH}" \ -p=packageVersion="${SDK_VERSION}" \ - --global-property apiTests=false,modelTests=false # TODO (andreyvelich): Discuss if we should use these test files. + --global-property models,modelTests=false,modelDocs=false,supportingFiles=__init__.py echo "Removing unused files for the Python SDK" git clean -f ${SDK_OUTPUT_PATH}/.openapi-generator -git clean -f ${SDK_OUTPUT_PATH}/.gitignore -git clean -f ${SDK_OUTPUT_PATH}/.gitlab-ci.yml -git clean -f ${SDK_OUTPUT_PATH}/git_push.sh -git clean -f ${SDK_OUTPUT_PATH}/.openapi-generator-ignore -git clean -f ${SDK_OUTPUT_PATH}/.travis.yml -git clean -f ${SDK_OUTPUT_PATH}/requirements.txt -git clean -f ${SDK_OUTPUT_PATH}/setup.cfg -git clean -f ${SDK_OUTPUT_PATH}/setup.py -git clean -f ${SDK_OUTPUT_PATH}/test-requirements.txt -git clean -f ${SDK_OUTPUT_PATH}/tox.ini +git clean -f ${SDK_OUTPUT_PATH}/.github +git clean -f ${SDK_OUTPUT_PATH}/test -# Revert the README since it is manually created. -git checkout ${SDK_OUTPUT_PATH}/README.md +# Revert manually created files. git checkout ${SDK_OUTPUT_PATH}/kubeflow/trainer/__init__.py # Manually modify the SDK version in the __init__.py file. @@ -65,7 +54,15 @@ else sed -i -e "s/__version__.*/__version__ = \"${SDK_VERSION}\"/" ${SDK_OUTPUT_PATH}/kubeflow/trainer/__init__.py fi -# Kubeflow models must have Kubernetes models to perform serialization. -printf "\n# Import Kubernetes and JobSet models for the serialization. \n" >>${SDK_OUTPUT_PATH}/kubeflow/trainer/models/__init__.py -printf "from kubernetes.client import *\n" >>${SDK_OUTPUT_PATH}/kubeflow/trainer/models/__init__.py -printf "from jobset.models import *\n" >>${SDK_OUTPUT_PATH}/kubeflow/trainer/models/__init__.py +# The `model_config` property conflicts with Pydantic name. +# Therefore, we rename it to `model_config_crd` +TRAINJOB_SPEC_MODEL=${SDK_OUTPUT_PATH}/kubeflow/trainer/models/trainer_v1alpha1_train_job_spec.py +if [[ $(uname) == "Darwin" ]]; then + sed -i '' -e "s/model_config/model_config_crd/" ${TRAINJOB_SPEC_MODEL} + sed -i '' -e "s/model_config_crd = ConfigDict/model_config = ConfigDict/" ${TRAINJOB_SPEC_MODEL} + sed -i '' -e "s/kubeflow.trainer.models.trainer_v1alpha1_model_config_crd/kubeflow.trainer.models.trainer_v1alpha1_model_config/" ${TRAINJOB_SPEC_MODEL} +else + sed -i -e "s/model_config/model_config_crd/" ${TRAINJOB_SPEC_MODEL} + sed -i -e "s/model_config_crd = ConfigDict/model_config = ConfigDict/" ${TRAINJOB_SPEC_MODEL} + sed -i -e "s/kubeflow.trainer.models.trainer_v1alpha1_model_config_crd/kubeflow.trainer.models.trainer_v1alpha1_model_config/" ${TRAINJOB_SPEC_MODEL} +fi diff --git a/hack/python-sdk/swagger_config.json b/hack/python-sdk/swagger_config.json index 1b2cd30fc2..0d54228481 100644 --- a/hack/python-sdk/swagger_config.json +++ b/hack/python-sdk/swagger_config.json @@ -1,8 +1,4 @@ { "packageName": "kubeflow.trainer", - "typeMappings": { - "K8sIoApiAutoscalingV2MetricSpec": "V2MetricSpec", - "K8sIoApimachineryPkgUtilIntstrIntOrString": "object", - "V1Time": "datetime" - } + "typeMappings": {} } diff --git a/hack/swagger/main.go b/hack/swagger/main.go index 935a369ab2..bf56526ff8 100644 --- a/hack/swagger/main.go +++ b/hack/swagger/main.go @@ -19,6 +19,7 @@ package main import ( "encoding/json" "fmt" + "runtime/debug" "strings" "k8s.io/klog/v2" @@ -30,12 +31,44 @@ import ( // Generate Kubeflow Training OpenAPI specification. func main() { + // Get Kubernetes and JobSet version + var k8sVersion string + var jobSetVersion string + + info, ok := debug.ReadBuildInfo() + if !ok { + fmt.Println("Failed to read build info") + return + } + + for _, dep := range info.Deps { + if dep.Path == "k8s.io/api" { + k8sVersion = strings.Replace(dep.Version, "v0.", "v1.", -1) + } else if dep.Path == "sigs.k8s.io/jobset" { + jobSetVersion = dep.Version + } + } + if k8sVersion == "" || jobSetVersion == "" { + fmt.Println("OpenAPI spec generation failed. Unable to get Kubernetes and JobSet version") + return + } + + k8sOpenAPISpec := fmt.Sprintf("https://raw.githubusercontent.com/kubernetes/kubernetes/refs/tags/%s/api/openapi-spec/swagger.json", k8sVersion) + // TODO (andreyvelich): Use the release version once this JobSet commit is released: d5c7bce. + // jobSetOpenAPISpec := fmt.Sprintf("https://raw.githubusercontent.com/kubernetes-sigs/jobset/refs/tags/%s/hack/python-sdk/swagger.json", jobSetVersion) + jobSetOpenAPISpec := "https://raw.githubusercontent.com/kubernetes-sigs/jobset/d5c7bcebe739a4577e30944370c2d7a68321a929/hack/python-sdk/swagger.json" var oAPIDefs = map[string]common.OpenAPIDefinition{} defs := spec.Definitions{} refCallback := func(name string) spec.Ref { - return spec.MustCreateRef("#/definitions/" + common.EscapeJsonPointer(swaggify(name))) + if strings.HasPrefix(name, "k8s.io") { + return spec.MustCreateRef(k8sOpenAPISpec + "#/definitions/" + swaggify(name)) + } else if strings.HasPrefix(name, "sigs.k8s.io/jobset") { + return spec.MustCreateRef(jobSetOpenAPISpec + "#/definitions/" + swaggify(name)) + } + return spec.MustCreateRef("#/definitions/" + swaggify(name)) + } for k, v := range trainer.GetOpenAPIDefinitions(refCallback) { @@ -67,8 +100,7 @@ func main() { func swaggify(name string) string { name = strings.Replace(name, "github.com/kubeflow/trainer/pkg/apis/", "", -1) name = strings.Replace(name, "sigs.k8s.io/jobset/api/", "", -1) - name = strings.Replace(name, "k8s.io/api/core/", "", -1) - name = strings.Replace(name, "k8s.io/apimachinery/pkg/apis/meta/", "", -1) + name = strings.Replace(name, "k8s.io", "io.k8s", -1) name = strings.Replace(name, "/", ".", -1) return name } diff --git a/sdk/docs/TrainerV1alpha1ClusterTrainingRuntime.md b/sdk/docs/TrainerV1alpha1ClusterTrainingRuntime.md deleted file mode 100644 index d276b92ca6..0000000000 --- a/sdk/docs/TrainerV1alpha1ClusterTrainingRuntime.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1ClusterTrainingRuntime - -ClusterTrainingRuntime represents a training runtime which can be referenced as part of `runtimeRef` API in TrainJob. This resource is a cluster-scoped and can be referenced by TrainJob that created in *any* namespace. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | [optional] -**kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional] -**metadata** | [**V1ObjectMeta**](V1ObjectMeta.md) | | [optional] -**spec** | [**TrainerV1alpha1TrainingRuntimeSpec**](TrainerV1alpha1TrainingRuntimeSpec.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1ClusterTrainingRuntimeList.md b/sdk/docs/TrainerV1alpha1ClusterTrainingRuntimeList.md deleted file mode 100644 index 992d513bce..0000000000 --- a/sdk/docs/TrainerV1alpha1ClusterTrainingRuntimeList.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1ClusterTrainingRuntimeList - -ClusterTrainingRuntimeList is a collection of cluster training runtimes. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | [optional] -**items** | [**list[TrainerV1alpha1ClusterTrainingRuntime]**](TrainerV1alpha1ClusterTrainingRuntime.md) | List of ClusterTrainingRuntimes. | -**kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional] -**metadata** | [**V1ListMeta**](V1ListMeta.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1ContainerOverride.md b/sdk/docs/TrainerV1alpha1ContainerOverride.md deleted file mode 100644 index 85dd48956f..0000000000 --- a/sdk/docs/TrainerV1alpha1ContainerOverride.md +++ /dev/null @@ -1,16 +0,0 @@ -# TrainerV1alpha1ContainerOverride - -ContainerOverride represents parameters that can be overridden using PodSpecOverrides. Parameters from the Trainer, DatasetConfig, and ModelConfig will take precedence. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**args** | **list[str]** | Arguments to the entrypoint for the training container. | [optional] -**command** | **list[str]** | Entrypoint commands for the training container. | [optional] -**env** | [**list[V1EnvVar]**](V1EnvVar.md) | List of environment variables to set in the container. These values will be merged with the TrainingRuntime's environments. | [optional] -**env_from** | [**list[V1EnvFromSource]**](V1EnvFromSource.md) | List of sources to populate environment variables in the container. These values will be merged with the TrainingRuntime's environments. | [optional] -**name** | **str** | Name for the container. TrainingRuntime must have this container. | [default to ''] -**volume_mounts** | [**list[V1VolumeMount]**](V1VolumeMount.md) | Pod volumes to mount into the container's filesystem. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1CoschedulingPodGroupPolicySource.md b/sdk/docs/TrainerV1alpha1CoschedulingPodGroupPolicySource.md deleted file mode 100644 index 9818be7a15..0000000000 --- a/sdk/docs/TrainerV1alpha1CoschedulingPodGroupPolicySource.md +++ /dev/null @@ -1,11 +0,0 @@ -# TrainerV1alpha1CoschedulingPodGroupPolicySource - -CoschedulingPodGroupPolicySource represents configuration for coscheduling plugin. The number of min members in the PodGroupSpec is always equal to the number of nodes. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**schedule_timeout_seconds** | **int** | Time threshold to schedule PodGroup for gang-scheduling. If the scheduling timeout is equal to 0, the default value is used. Defaults to 60 seconds. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1DatasetConfig.md b/sdk/docs/TrainerV1alpha1DatasetConfig.md deleted file mode 100644 index 2722d17d07..0000000000 --- a/sdk/docs/TrainerV1alpha1DatasetConfig.md +++ /dev/null @@ -1,13 +0,0 @@ -# TrainerV1alpha1DatasetConfig - -DatasetConfig represents the desired dataset configuration. When this API is used, the training runtime must have the `dataset-initializer` container in the `Initializer` Job. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**env** | [**list[V1EnvVar]**](V1EnvVar.md) | List of environment variables to set in the dataset initializer container. These values will be merged with the TrainingRuntime's dataset initializer environments. | [optional] -**secret_ref** | [**V1LocalObjectReference**](V1LocalObjectReference.md) | | [optional] -**storage_uri** | **str** | Storage uri for the dataset provider. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1InputModel.md b/sdk/docs/TrainerV1alpha1InputModel.md deleted file mode 100644 index 38eda5234a..0000000000 --- a/sdk/docs/TrainerV1alpha1InputModel.md +++ /dev/null @@ -1,13 +0,0 @@ -# TrainerV1alpha1InputModel - -InputModel represents the desired pre-trained model configuration. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**env** | [**list[V1EnvVar]**](V1EnvVar.md) | List of environment variables to set in the model initializer container. These values will be merged with the TrainingRuntime's model initializer environments. | [optional] -**secret_ref** | [**V1LocalObjectReference**](V1LocalObjectReference.md) | | [optional] -**storage_uri** | **str** | Storage uri for the model provider. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1JobSetTemplateSpec.md b/sdk/docs/TrainerV1alpha1JobSetTemplateSpec.md deleted file mode 100644 index d8282c52f5..0000000000 --- a/sdk/docs/TrainerV1alpha1JobSetTemplateSpec.md +++ /dev/null @@ -1,12 +0,0 @@ -# TrainerV1alpha1JobSetTemplateSpec - -JobSetTemplateSpec represents a template of the desired JobSet. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**metadata** | [**V1ObjectMeta**](V1ObjectMeta.md) | | [optional] -**spec** | [**JobsetV1alpha2JobSetSpec**](JobsetV1alpha2JobSetSpec.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1JobStatus.md b/sdk/docs/TrainerV1alpha1JobStatus.md deleted file mode 100644 index 6586993f34..0000000000 --- a/sdk/docs/TrainerV1alpha1JobStatus.md +++ /dev/null @@ -1,15 +0,0 @@ -# TrainerV1alpha1JobStatus - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**active** | **int** | Active is the number of child Jobs with at least 1 pod in a running or pending state which are not marked for deletion. | [default to 0] -**failed** | **int** | Failed is the number of failed child Jobs. | [default to 0] -**name** | **str** | Name of the child Job. | [default to ''] -**ready** | **int** | Ready is the number of child Jobs where the number of ready pods and completed pods is greater than or equal to the total expected pod count for the child Job. | [default to 0] -**succeeded** | **int** | Succeeded is the number of successfully completed child Jobs. | [default to 0] -**suspended** | **int** | Suspended is the number of child Jobs which are in a suspended state. | [default to 0] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1MLPolicy.md b/sdk/docs/TrainerV1alpha1MLPolicy.md deleted file mode 100644 index 6c7b0fc654..0000000000 --- a/sdk/docs/TrainerV1alpha1MLPolicy.md +++ /dev/null @@ -1,13 +0,0 @@ -# TrainerV1alpha1MLPolicy - -MLPolicy represents configuration for the model trining with ML-specific parameters. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mpi** | [**TrainerV1alpha1MPIMLPolicySource**](TrainerV1alpha1MPIMLPolicySource.md) | | [optional] -**num_nodes** | **int** | Number of training nodes. Defaults to 1. | [optional] -**torch** | [**TrainerV1alpha1TorchMLPolicySource**](TrainerV1alpha1TorchMLPolicySource.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1MLPolicySource.md b/sdk/docs/TrainerV1alpha1MLPolicySource.md deleted file mode 100644 index 1bff3f8e83..0000000000 --- a/sdk/docs/TrainerV1alpha1MLPolicySource.md +++ /dev/null @@ -1,12 +0,0 @@ -# TrainerV1alpha1MLPolicySource - -MLPolicySource represents the runtime-specific configuration for various technologies. One of the following specs can be set. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mpi** | [**TrainerV1alpha1MPIMLPolicySource**](TrainerV1alpha1MPIMLPolicySource.md) | | [optional] -**torch** | [**TrainerV1alpha1TorchMLPolicySource**](TrainerV1alpha1TorchMLPolicySource.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1MPIMLPolicySource.md b/sdk/docs/TrainerV1alpha1MPIMLPolicySource.md deleted file mode 100644 index f1d46cfad0..0000000000 --- a/sdk/docs/TrainerV1alpha1MPIMLPolicySource.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1MPIMLPolicySource - -MPIMLPolicySource represents a MPI runtime configuration. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**mpi_implementation** | **str** | Implementation name for the MPI to create the appropriate hostfile. Defaults to OpenMPI. | [optional] -**num_proc_per_node** | **int** | Number of processes per node. This value is equal to the number of slots for each node in the hostfile. | [optional] -**run_launcher_as_node** | **bool** | Whether to run training process on the launcher Job. Defaults to false. | [optional] -**ssh_auth_mount_path** | **str** | Directory where SSH keys are mounted. Defaults to /root/.ssh. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1ModelConfig.md b/sdk/docs/TrainerV1alpha1ModelConfig.md deleted file mode 100644 index 38d4be7c73..0000000000 --- a/sdk/docs/TrainerV1alpha1ModelConfig.md +++ /dev/null @@ -1,12 +0,0 @@ -# TrainerV1alpha1ModelConfig - -ModelConfig represents the desired model configuration. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**input** | [**TrainerV1alpha1InputModel**](TrainerV1alpha1InputModel.md) | | [optional] -**output** | [**TrainerV1alpha1OutputModel**](TrainerV1alpha1OutputModel.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1OutputModel.md b/sdk/docs/TrainerV1alpha1OutputModel.md deleted file mode 100644 index 3c39d09524..0000000000 --- a/sdk/docs/TrainerV1alpha1OutputModel.md +++ /dev/null @@ -1,13 +0,0 @@ -# TrainerV1alpha1OutputModel - -OutputModel represents the desired trained model configuration. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**env** | [**list[V1EnvVar]**](V1EnvVar.md) | List of environment variables to set in the model exporter container. These values will be merged with the TrainingRuntime's model exporter environments. | [optional] -**secret_ref** | [**V1LocalObjectReference**](V1LocalObjectReference.md) | | [optional] -**storage_uri** | **str** | Storage uri for the model exporter. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1PodGroupPolicy.md b/sdk/docs/TrainerV1alpha1PodGroupPolicy.md deleted file mode 100644 index eb90bfddfd..0000000000 --- a/sdk/docs/TrainerV1alpha1PodGroupPolicy.md +++ /dev/null @@ -1,11 +0,0 @@ -# TrainerV1alpha1PodGroupPolicy - -PodGroupPolicy represents a PodGroup configuration for gang-scheduling. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**coscheduling** | [**TrainerV1alpha1CoschedulingPodGroupPolicySource**](TrainerV1alpha1CoschedulingPodGroupPolicySource.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1PodGroupPolicySource.md b/sdk/docs/TrainerV1alpha1PodGroupPolicySource.md deleted file mode 100644 index f76395de2b..0000000000 --- a/sdk/docs/TrainerV1alpha1PodGroupPolicySource.md +++ /dev/null @@ -1,11 +0,0 @@ -# TrainerV1alpha1PodGroupPolicySource - -PodGroupPolicySource represents supported plugins for gang-scheduling. Only one of its members may be specified. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**coscheduling** | [**TrainerV1alpha1CoschedulingPodGroupPolicySource**](TrainerV1alpha1CoschedulingPodGroupPolicySource.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1PodSpecOverride.md b/sdk/docs/TrainerV1alpha1PodSpecOverride.md deleted file mode 100644 index b9a3cce513..0000000000 --- a/sdk/docs/TrainerV1alpha1PodSpecOverride.md +++ /dev/null @@ -1,17 +0,0 @@ -# TrainerV1alpha1PodSpecOverride - -PodSpecOverride represents the custom overrides that will be applied for the TrainJob's resources. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**containers** | [**list[TrainerV1alpha1ContainerOverride]**](TrainerV1alpha1ContainerOverride.md) | Overrides for the containers in the desired job templates. | [optional] -**init_containers** | [**list[TrainerV1alpha1ContainerOverride]**](TrainerV1alpha1ContainerOverride.md) | Overrides for the init container in the desired job templates. | [optional] -**node_selector** | **dict(str, str)** | Override for the node selector to place Pod on the specific mode. | [optional] -**service_account_name** | **str** | Override for the service account. | [optional] -**target_jobs** | [**list[TrainerV1alpha1PodSpecOverrideTargetJob]**](TrainerV1alpha1PodSpecOverrideTargetJob.md) | TrainJobs is the training job replicas in the training runtime template to apply the overrides. | -**tolerations** | [**list[V1Toleration]**](V1Toleration.md) | Override for the Pod's tolerations. | [optional] -**volumes** | [**list[V1Volume]**](V1Volume.md) | Overrides for the Pod volume configuration. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1PodSpecOverrideTargetJob.md b/sdk/docs/TrainerV1alpha1PodSpecOverrideTargetJob.md deleted file mode 100644 index 97be4e877e..0000000000 --- a/sdk/docs/TrainerV1alpha1PodSpecOverrideTargetJob.md +++ /dev/null @@ -1,10 +0,0 @@ -# TrainerV1alpha1PodSpecOverrideTargetJob - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**name** | **str** | Name is the target training job name for which the PodSpec is overridden. | [default to ''] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1RuntimeRef.md b/sdk/docs/TrainerV1alpha1RuntimeRef.md deleted file mode 100644 index 5d8b921dd6..0000000000 --- a/sdk/docs/TrainerV1alpha1RuntimeRef.md +++ /dev/null @@ -1,13 +0,0 @@ -# TrainerV1alpha1RuntimeRef - -RuntimeRef represents the reference to the existing training runtime. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_group** | **str** | APIGroup of the runtime being referenced. Defaults to `trainer.kubeflow.org`. | [optional] -**kind** | **str** | Kind of the runtime being referenced. Defaults to ClusterTrainingRuntime. | [optional] -**name** | **str** | Name of the runtime being referenced. When namespaced-scoped TrainingRuntime is used, the TrainJob must have the same namespace as the deployed runtime. | [default to ''] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TorchElasticPolicy.md b/sdk/docs/TrainerV1alpha1TorchElasticPolicy.md deleted file mode 100644 index cccba79150..0000000000 --- a/sdk/docs/TrainerV1alpha1TorchElasticPolicy.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1TorchElasticPolicy - -TorchElasticPolicy represents a configuration for the PyTorch elastic training. If this policy is set, the `.spec.numNodes` parameter must be omitted, since min and max node is used to configure the `torchrun` CLI argument: `--nnodes=minNodes:maxNodes`. Only `c10d` backend is supported for the Rendezvous communication. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**max_nodes** | **int** | Upper limit for the number of nodes to which training job can scale up. | [optional] -**max_restarts** | **int** | How many times the training job can be restarted. This value is inserted into the `--max-restarts` argument of the `torchrun` CLI and the `.spec.failurePolicy.maxRestarts` parameter of the training Job. | [optional] -**metrics** | [**list[V2MetricSpec]**](K8sIoApiAutoscalingV2MetricSpec.md) | Specification which are used to calculate the desired number of nodes. See the individual metric source types for more information about how each type of metric must respond. The HPA will be created to perform auto-scaling. | [optional] -**min_nodes** | **int** | Lower limit for the number of nodes to which training job can scale down. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TorchMLPolicySource.md b/sdk/docs/TrainerV1alpha1TorchMLPolicySource.md deleted file mode 100644 index 18f539d5ed..0000000000 --- a/sdk/docs/TrainerV1alpha1TorchMLPolicySource.md +++ /dev/null @@ -1,12 +0,0 @@ -# TrainerV1alpha1TorchMLPolicySource - -TorchMLPolicySource represents a PyTorch runtime configuration. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**elastic_policy** | [**TrainerV1alpha1TorchElasticPolicy**](TrainerV1alpha1TorchElasticPolicy.md) | | [optional] -**num_proc_per_node** | [**object**](K8sIoApimachineryPkgUtilIntstrIntOrString.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainJob.md b/sdk/docs/TrainerV1alpha1TrainJob.md deleted file mode 100644 index 9cad6bb269..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainJob.md +++ /dev/null @@ -1,15 +0,0 @@ -# TrainerV1alpha1TrainJob - -TrainJob represents configuration of a training job. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | [optional] -**kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional] -**metadata** | [**V1ObjectMeta**](V1ObjectMeta.md) | | [optional] -**spec** | [**TrainerV1alpha1TrainJobSpec**](TrainerV1alpha1TrainJobSpec.md) | | [optional] -**status** | [**TrainerV1alpha1TrainJobStatus**](TrainerV1alpha1TrainJobStatus.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainJobList.md b/sdk/docs/TrainerV1alpha1TrainJobList.md deleted file mode 100644 index b091c7af50..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainJobList.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1TrainJobList - -TrainJobList is a collection of training jobs. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | [optional] -**items** | [**list[TrainerV1alpha1TrainJob]**](TrainerV1alpha1TrainJob.md) | List of TrainJobs. | -**kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional] -**metadata** | [**V1ListMeta**](V1ListMeta.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainJobSpec.md b/sdk/docs/TrainerV1alpha1TrainJobSpec.md deleted file mode 100644 index 54ff57759c..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainJobSpec.md +++ /dev/null @@ -1,19 +0,0 @@ -# TrainerV1alpha1TrainJobSpec - -TrainJobSpec represents specification of the desired TrainJob. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**annotations** | **dict(str, str)** | Annotations to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values. | [optional] -**dataset_config** | [**TrainerV1alpha1DatasetConfig**](TrainerV1alpha1DatasetConfig.md) | | [optional] -**labels** | **dict(str, str)** | Labels to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values. | [optional] -**managed_by** | **str** | ManagedBy is used to indicate the controller or entity that manages a TrainJob. The value must be either an empty, `trainer.kubeflow.org/trainjob-controller` or `kueue.x-k8s.io/multikueue`. The built-in TrainJob controller reconciles TrainJob which don't have this field at all or the field value is the reserved string `trainer.kubeflow.org/trainjob-controller`, but delegates reconciling TrainJobs with a 'kueue.x-k8s.io/multikueue' to the Kueue. The field is immutable. Defaults to `trainer.kubeflow.org/trainjob-controller` | [optional] -**model_config** | [**TrainerV1alpha1ModelConfig**](TrainerV1alpha1ModelConfig.md) | | [optional] -**pod_spec_overrides** | [**list[TrainerV1alpha1PodSpecOverride]**](TrainerV1alpha1PodSpecOverride.md) | Custom overrides for the training runtime. | [optional] -**runtime_ref** | [**TrainerV1alpha1RuntimeRef**](TrainerV1alpha1RuntimeRef.md) | | -**suspend** | **bool** | Whether the controller should suspend the running TrainJob. Defaults to false. | [optional] -**trainer** | [**TrainerV1alpha1Trainer**](TrainerV1alpha1Trainer.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainJobStatus.md b/sdk/docs/TrainerV1alpha1TrainJobStatus.md deleted file mode 100644 index 865c4329e8..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainJobStatus.md +++ /dev/null @@ -1,12 +0,0 @@ -# TrainerV1alpha1TrainJobStatus - -TrainJobStatus represents the current status of TrainJob. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**conditions** | [**list[V1Condition]**](V1Condition.md) | Conditions for the TrainJob. | [optional] -**jobs_status** | [**list[TrainerV1alpha1JobStatus]**](TrainerV1alpha1JobStatus.md) | JobsStatus tracks the child Jobs in TrainJob. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1Trainer.md b/sdk/docs/TrainerV1alpha1Trainer.md deleted file mode 100644 index 601c799e0f..0000000000 --- a/sdk/docs/TrainerV1alpha1Trainer.md +++ /dev/null @@ -1,17 +0,0 @@ -# TrainerV1alpha1Trainer - -Trainer represents the desired trainer configuration. Every training runtime contains `trainer` container which represents Trainer. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**args** | **list[str]** | Arguments to the entrypoint for the training container. | [optional] -**command** | **list[str]** | Entrypoint commands for the training container. | [optional] -**env** | [**list[V1EnvVar]**](V1EnvVar.md) | List of environment variables to set in the training container. These values will be merged with the TrainingRuntime's trainer environments. | [optional] -**image** | **str** | Docker image for the training container. | [optional] -**num_nodes** | **int** | Number of training nodes. | [optional] -**num_proc_per_node** | [**object**](K8sIoApimachineryPkgUtilIntstrIntOrString.md) | | [optional] -**resources_per_node** | [**V1ResourceRequirements**](V1ResourceRequirements.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainingRuntime.md b/sdk/docs/TrainerV1alpha1TrainingRuntime.md deleted file mode 100644 index 0e37b0ef47..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainingRuntime.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1TrainingRuntime - -TrainingRuntime represents a training runtime which can be referenced as part of `runtimeRef` API in TrainJob. This resource is a namespaced-scoped and can be referenced by TrainJob that created in the *same* namespace as the TrainingRuntime. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | [optional] -**kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional] -**metadata** | [**V1ObjectMeta**](V1ObjectMeta.md) | | [optional] -**spec** | [**TrainerV1alpha1TrainingRuntimeSpec**](TrainerV1alpha1TrainingRuntimeSpec.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainingRuntimeList.md b/sdk/docs/TrainerV1alpha1TrainingRuntimeList.md deleted file mode 100644 index 3e812b77cb..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainingRuntimeList.md +++ /dev/null @@ -1,14 +0,0 @@ -# TrainerV1alpha1TrainingRuntimeList - -TrainingRuntimeList is a collection of training runtimes. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**api_version** | **str** | APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources | [optional] -**items** | [**list[TrainerV1alpha1TrainingRuntime]**](TrainerV1alpha1TrainingRuntime.md) | List of TrainingRuntimes. | -**kind** | **str** | Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds | [optional] -**metadata** | [**V1ListMeta**](V1ListMeta.md) | | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/docs/TrainerV1alpha1TrainingRuntimeSpec.md b/sdk/docs/TrainerV1alpha1TrainingRuntimeSpec.md deleted file mode 100644 index 05ecc46182..0000000000 --- a/sdk/docs/TrainerV1alpha1TrainingRuntimeSpec.md +++ /dev/null @@ -1,13 +0,0 @@ -# TrainerV1alpha1TrainingRuntimeSpec - -TrainingRuntimeSpec represents a specification of the desired training runtime. -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ml_policy** | [**TrainerV1alpha1MLPolicy**](TrainerV1alpha1MLPolicy.md) | | [optional] -**pod_group_policy** | [**TrainerV1alpha1PodGroupPolicy**](TrainerV1alpha1PodGroupPolicy.md) | | [optional] -**template** | [**TrainerV1alpha1JobSetTemplateSpec**](TrainerV1alpha1JobSetTemplateSpec.md) | | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/kubeflow/trainer/__init__.py b/sdk/kubeflow/trainer/__init__.py index e4a71c0cc6..937aa06402 100644 --- a/sdk/kubeflow/trainer/__init__.py +++ b/sdk/kubeflow/trainer/__init__.py @@ -17,19 +17,17 @@ __version__ = "0.1.0" -# Import the public API client. +# Import the Kubeflow Trainer client. from kubeflow.trainer.api.trainer_client import TrainerClient -# Import the Trainer configs. -from kubeflow.trainer.types.types import Trainer -from kubeflow.trainer.types.types import FineTuningConfig -from kubeflow.trainer.types.types import LoraConfig - -# Import the Dataset configs. -from kubeflow.trainer.types.types import HuggingFaceDatasetConfig - -# Import the Model configs. -from kubeflow.trainer.types.types import HuggingFaceModelInputConfig - -# Import constants for users. +# Import the Kubeflow Trainer constants. from kubeflow.trainer.constants.constants import DATASET_PATH, MODEL_PATH + +# Import the Kubeflow Trainer types. +from kubeflow.trainer.types.types import ( + FineTuningConfig, + HuggingFaceDatasetConfig, + HuggingFaceModelInputConfig, + LoraConfig, + Trainer, +) diff --git a/sdk/kubeflow/trainer/api/__init__.py b/sdk/kubeflow/trainer/api/__init__.py index 36dce7fe22..c3bb408f11 100644 --- a/sdk/kubeflow/trainer/api/__init__.py +++ b/sdk/kubeflow/trainer/api/__init__.py @@ -1,5 +1,4 @@ -from __future__ import absolute_import - # flake8: noqa # import apis into api package + diff --git a/sdk/kubeflow/trainer/api/trainer_client.py b/sdk/kubeflow/trainer/api/trainer_client.py index 723a3be0ac..f7a1895ad2 100644 --- a/sdk/kubeflow/trainer/api/trainer_client.py +++ b/sdk/kubeflow/trainer/api/trainer_client.py @@ -20,8 +20,7 @@ import uuid from typing import Dict, List, Optional -from kubeflow.trainer import models -from kubeflow.trainer.api_client import ApiClient +import kubeflow.trainer.models as models from kubeflow.trainer.constants import constants from kubeflow.trainer.types import types from kubeflow.trainer.utils import utils @@ -71,7 +70,6 @@ def __init__( k8s_client = client.ApiClient(client_configuration) self.custom_api = client.CustomObjectsApi(k8s_client) self.core_api = client.CoreV1Api(k8s_client) - self.api_client = ApiClient() self.namespace = namespace @@ -100,12 +98,12 @@ def list_runtimes(self) -> List[types.Runtime]: response = thread.get(constants.DEFAULT_TIMEOUT) for item in response["items"]: - runtime = self.api_client.deserialize( - utils.FakeResponse(item), - models.TrainerV1alpha1ClusterTrainingRuntime, + runtime = models.TrainerV1alpha1ClusterTrainingRuntime.from_dict(item) + + ml_policy: models.TrainerV1alpha1MLPolicy = runtime.spec.ml_policy # type: ignore + metadata: models.IoK8sApimachineryPkgApisMetaV1ObjectMeta = ( + runtime.metadata # type: ignore ) - ml_policy = runtime.spec.ml_policy # type: ignore - metadata = runtime.metadata # type: ignore # TODO (andreyvelich): Currently, the labels must be presented. if metadata.labels: @@ -113,7 +111,10 @@ def list_runtimes(self) -> List[types.Runtime]: resources = None for job in runtime.spec.template.spec.replicated_jobs: # type: ignore if job.name == constants.JOB_TRAINER_NODE: - pod_spec = job.template.spec.template.spec + pod_spec: models.IoK8sApiCoreV1PodSpec = ( + job.template.spec.template.spec # type: ignore + ) + for container in pod_spec.containers: if container.name == constants.CONTAINER_TRAINER: resources = container.resources @@ -131,12 +132,12 @@ def list_runtimes(self) -> List[types.Runtime]: ) if accelerator_count != constants.UNKNOWN: accelerator_count = str( - int(accelerator_count) * int(ml_policy.num_nodes) + int(accelerator_count) * int(ml_policy.num_nodes) # type: ignore ) result.append( types.Runtime( - name=metadata.name, + name=metadata.name, # type: ignore phase=( metadata.labels[constants.PHASE_KEY] if constants.PHASE_KEY in metadata.labels @@ -230,18 +231,20 @@ def train( ) train_job = models.TrainerV1alpha1TrainJob( - api_version=constants.API_VERSION, + apiVersion=constants.API_VERSION, kind=constants.TRAINJOB_KIND, - metadata=client.V1ObjectMeta(name=train_job_name), + metadata=models.IoK8sApimachineryPkgApisMetaV1ObjectMeta( + name=train_job_name + ), spec=models.TrainerV1alpha1TrainJobSpec( - runtime_ref=models.TrainerV1alpha1RuntimeRef(name=runtime_ref), + runtimeRef=models.TrainerV1alpha1RuntimeRef(name=runtime_ref), trainer=( trainer_crd if trainer_crd != models.TrainerV1alpha1Trainer() else None ), - dataset_config=utils.get_dataset_config(dataset_config), - model_config=utils.get_model_config(model_config), + datasetConfig=utils.get_dataset_config(dataset_config), + modelConfig=utils.get_model_config(model_config), ), ) @@ -252,7 +255,7 @@ def train( constants.VERSION, self.namespace, constants.TRAINJOB_PLURAL, - train_job, + train_job.to_dict(), ) except multiprocessing.TimeoutError: raise TimeoutError( @@ -299,10 +302,8 @@ def list_jobs(self, runtime_ref: Optional[str] = None) -> List[types.TrainJob]: and item["spec"]["runtimeRef"]["name"] != runtime_ref ): continue - trainjob = self.api_client.deserialize( - utils.FakeResponse(item), - models.TrainerV1alpha1TrainJob, - ) + + trainjob = models.TrainerV1alpha1TrainJob.from_dict(item) result.append(self.__get_trainjob_from_crd(trainjob)) # type: ignore except multiprocessing.TimeoutError: @@ -329,9 +330,8 @@ def get_job(self, name: str) -> types.TrainJob: async_req=True, ) - trainjob = self.api_client.deserialize( - utils.FakeResponse(thread.get(constants.DEFAULT_TIMEOUT)), # type: ignore - models.TrainerV1alpha1TrainJob, + trainjob = models.TrainerV1alpha1TrainJob.from_dict( + thread.get(constants.DEFAULT_TIMEOUT) # type: ignore ) except multiprocessing.TimeoutError: @@ -484,8 +484,8 @@ def __get_trainjob_from_crd( trainjob_crd: models.TrainerV1alpha1TrainJob, ) -> types.TrainJob: - name = trainjob_crd.metadata.name # type: ignore - namespace = trainjob_crd.metadata.namespace # type: ignore + name: str = trainjob_crd.metadata.name # type: ignore + namespace: str = trainjob_crd.metadata.namespace # type: ignore # Construct the TrainJob from the CRD. train_job = types.TrainJob( @@ -563,8 +563,8 @@ def __get_trainjob_from_crd( # Add the TrainJob status. # TODO (andreyvelich): Discuss how we should show TrainJob status to SDK users. - if trainjob_crd.status: - for c in trainjob_crd.status.conditions: # type: ignore + if trainjob_crd.status and trainjob_crd.status.conditions: + for c in trainjob_crd.status.conditions: if c.type == "Created" and c.status == "True": status = "Created" elif c.type == "Complete" and c.status == "True": diff --git a/sdk/kubeflow/trainer/api_client.py b/sdk/kubeflow/trainer/api_client.py deleted file mode 100644 index ea6709f531..0000000000 --- a/sdk/kubeflow/trainer/api_client.py +++ /dev/null @@ -1,666 +0,0 @@ -# coding: utf-8 -""" - Kubeflow Trainer OpenAPI Spec - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - -from __future__ import absolute_import - -import atexit -import datetime -from dateutil.parser import parse -import json -import mimetypes -from multiprocessing.pool import ThreadPool -import os -import re -import tempfile - -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote - -from kubeflow.trainer.configuration import Configuration -import kubeflow.trainer.models -from kubeflow.trainer import rest -from kubeflow.trainer.exceptions import ApiValueError, ApiException - - -class ApiClient(object): - """Generic API client for OpenAPI client library builds. - - OpenAPI generic API client. This client handles the client- - server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the OpenAPI - templates. - - NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param configuration: .Configuration object for this client - :param header_name: a header to pass when making calls to the API. - :param header_value: a header value to pass when making calls to - the API. - :param cookie: a cookie to include in the header when making calls - to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. - """ - - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types - NATIVE_TYPES_MAPPING = { - 'int': int, - 'long': int if six.PY3 else long, # noqa: F821 - 'float': float, - 'str': str, - 'bool': bool, - 'date': datetime.date, - 'datetime': datetime.datetime, - 'object': object, - } - _pool = None - - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1): - if configuration is None: - configuration = Configuration.get_default_copy() - self.configuration = configuration - self.pool_threads = pool_threads - - self.rest_client = rest.RESTClientObject(configuration) - self.default_headers = {} - if header_name is not None: - self.default_headers[header_name] = header_value - self.cookie = cookie - # Set default User-Agent. - self.user_agent = 'OpenAPI-Generator/0.1.0/python' - self.client_side_validation = configuration.client_side_validation - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool - - @property - def user_agent(self): - """User agent for this API client""" - return self.default_headers['User-Agent'] - - @user_agent.setter - def user_agent(self, value): - self.default_headers['User-Agent'] = value - - def set_default_header(self, header_name, header_value): - self.default_headers[header_name] = header_value - - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None): - - config = self.configuration - - # header parameters - header_params = header_params or {} - header_params.update(self.default_headers) - if self.cookie: - header_params['Cookie'] = self.cookie - if header_params: - header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) - - # path parameters - if path_params: - path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) - for k, v in path_params: - # specified safe chars, encode everything - resource_path = resource_path.replace( - '{%s}' % k, - quote(str(v), safe=config.safe_chars_for_path_param) - ) - - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - - # post parameters - if post_params or files: - post_params = post_params if post_params else [] - post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) - post_params.extend(self.files_parameters(files)) - - # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) - - # body - if body: - body = self.sanitize_for_serialization(body) - - # request url - if _host is None: - url = self.configuration.host + resource_path - else: - # use server/host defined in path or operation instead - url = _host + resource_path - - try: - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - except ApiException as e: - e.body = e.body.decode('utf-8') if six.PY3 else e.body - raise e - - content_type = response_data.getheader('content-type') - - self.last_response = response_data - - return_data = response_data - - if not _preload_content: - return return_data - - if six.PY3 and response_type not in ["file", "bytes"]: - match = None - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s\;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return (return_data) - else: - return (return_data, response_data.status, - response_data.getheaders()) - - def sanitize_for_serialization(self, obj): - """Builds a JSON POST object. - - If obj is None, return None. - If obj is str, int, long, float, bool, return directly. - If obj is datetime.datetime, datetime.date - convert to string in iso8601 format. - If obj is list, sanitize each element in the list. - If obj is dict, return the dict. - If obj is OpenAPI model, return the properties dict. - - :param obj: The data to serialize. - :return: The serialized form of data. - """ - if obj is None: - return None - elif isinstance(obj, self.PRIMITIVE_TYPES): - return obj - elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] - elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) - elif isinstance(obj, (datetime.datetime, datetime.date)): - return obj.isoformat() - - if isinstance(obj, dict): - obj_dict = obj - else: - # Convert model obj to dict except - # attributes `openapi_types`, `attribute_map` - # and attributes which value is not None. - # Convert attribute name to json key in - # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.openapi_types) - if getattr(obj, attr) is not None} - - return {key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict)} - - def deserialize(self, response, response_type): - """Deserializes response into an object. - - :param response: RESTResponse object to be deserialized. - :param response_type: class literal for - deserialized object, or string of class name. - - :return: deserialized object. - """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) - - # fetch data from response object - try: - data = json.loads(response.data) - except ValueError: - data = response.data - - return self.__deserialize(data, response_type) - - def __deserialize(self, data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if type(klass) == str: - if klass.startswith('list['): - sub_kls = re.match(r'list\[(.*)\]', klass).group(1) - return [self.__deserialize(sub_data, sub_kls) - for sub_data in data] - - if klass.startswith('dict('): - sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2) - return {k: self.__deserialize(v, sub_kls) - for k, v in six.iteritems(data)} - - # convert str to class - if klass in self.NATIVE_TYPES_MAPPING: - klass = self.NATIVE_TYPES_MAPPING[klass] - else: - klass = getattr(kubeflow.trainer.models, klass) - - if klass in self.PRIMITIVE_TYPES: - return self.__deserialize_primitive(data, klass) - elif klass == object: - return self.__deserialize_object(data) - elif klass == datetime.date: - return self.__deserialize_date(data) - elif klass == datetime.datetime: - return self.__deserialize_datetime(data) - else: - return self.__deserialize_model(data, klass) - - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, async_req=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout, _host) - - return self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, - query_params, - header_params, body, - post_params, files, - response_type, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host)) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.POST(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - - def parameters_to_tuples(self, params, collection_formats): - """Get parameters as list of tuples, formatting collections. - - :param params: Parameters as dict or list of two-tuples - :param dict collection_formats: Parameter collection formats - :return: Parameters as list of tuples, collections formatted - """ - new_params = [] - if collection_formats is None: - collection_formats = {} - for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 - if k in collection_formats: - collection_format = collection_formats[k] - if collection_format == 'multi': - new_params.extend((k, value) for value in v) - else: - if collection_format == 'ssv': - delimiter = ' ' - elif collection_format == 'tsv': - delimiter = '\t' - elif collection_format == 'pipes': - delimiter = '|' - else: # csv is the default - delimiter = ',' - new_params.append( - (k, delimiter.join(str(value) for value in v))) - else: - new_params.append((k, v)) - return new_params - - def files_parameters(self, files=None): - """Builds form parameters. - - :param files: File parameters. - :return: Form parameters with files. - """ - params = [] - - if files: - for k, v in six.iteritems(files): - if not v: - continue - file_names = v if type(v) is list else [v] - for n in file_names: - with open(n, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') - params.append( - tuple([k, tuple([filename, filedata, mimetype])])) - - return params - - def select_header_accept(self, accepts): - """Returns `Accept` based on an array of accepts provided. - - :param accepts: List of headers. - :return: Accept (e.g. application/json). - """ - if not accepts: - return - - accepts = [x.lower() for x in accepts] - - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) - - def select_header_content_type(self, content_types): - """Returns `Content-Type` based on an array of content_types provided. - - :param content_types: List of content-types. - :return: Content-Type (e.g. application/json). - """ - if not content_types: - return 'application/json' - - content_types = [x.lower() for x in content_types] - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] - - def update_params_for_auth(self, headers, querys, auth_settings): - """Updates header and query params based on authentication setting. - - :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. - :param auth_settings: Authentication setting identifiers list. - """ - if not auth_settings: - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if auth_setting['in'] == 'cookie': - headers['Cookie'] = auth_setting['value'] - elif auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys.append((auth_setting['key'], auth_setting['value'])) - else: - raise ApiValueError( - 'Authentication token must be in `query` or `header`' - ) - - def __deserialize_file(self, response): - """Deserializes body to file - - Saves response body into a file in a temporary folder, - using the filename from the `Content-Disposition` header if provided. - - :param response: RESTResponse. - :return: file path. - """ - fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) - os.close(fd) - os.remove(path) - - content_disposition = response.getheader("Content-Disposition") - if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) - path = os.path.join(os.path.dirname(path), filename) - - with open(path, "wb") as f: - f.write(response.data) - - return path - - def __deserialize_primitive(self, data, klass): - """Deserializes string to primitive type. - - :param data: str. - :param klass: class literal. - - :return: int, long, float, str, bool. - """ - try: - return klass(data) - except UnicodeEncodeError: - return six.text_type(data) - except TypeError: - return data - - def __deserialize_object(self, value): - """Return an original value. - - :return: object. - """ - return value - - def __deserialize_date(self, string): - """Deserializes string to date. - - :param string: str. - :return: date. - """ - try: - return parse(string).date() - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason="Failed to parse `{0}` as date object".format(string) - ) - - def __deserialize_datetime(self, string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :return: datetime. - """ - try: - return parse(string) - except ImportError: - return string - except ValueError: - raise rest.ApiException( - status=0, - reason=( - "Failed to parse `{0}` as datetime object" - .format(string) - ) - ) - - def __deserialize_model(self, data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :param klass: class literal. - :return: model object. - """ - has_discriminator = False - if (hasattr(klass, 'get_real_child_model') - and klass.discriminator_value_class_map): - has_discriminator = True - - if not klass.openapi_types and has_discriminator is False: - return data - - kwargs = {} - if (data is not None and - klass.openapi_types is not None and - isinstance(data, (list, dict))): - for attr, attr_type in six.iteritems(klass.openapi_types): - if klass.attribute_map[attr] in data: - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if has_discriminator: - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance diff --git a/sdk/kubeflow/trainer/configuration.py b/sdk/kubeflow/trainer/configuration.py deleted file mode 100644 index 7b8b527f27..0000000000 --- a/sdk/kubeflow/trainer/configuration.py +++ /dev/null @@ -1,376 +0,0 @@ -# coding: utf-8 - -""" - Kubeflow Trainer OpenAPI Spec - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import copy -import logging -import multiprocessing -import sys -import urllib3 - -import six -from six.moves import http_client as httplib - - -class Configuration(object): - """NOTE: This class is auto generated by OpenAPI Generator - - Ref: https://openapi-generator.tech - Do not edit the class manually. - - :param host: Base url - :param api_key: Dict to store API key(s). - Each entry in the dict specifies an API key. - The dict key is the name of the security scheme in the OAS specification. - The dict value is the API key secret. - :param api_key_prefix: Dict to store API prefix (e.g. Bearer) - The dict key is the name of the security scheme in the OAS specification. - The dict value is an API key prefix when generating the auth data. - :param username: Username for HTTP basic authentication - :param password: Password for HTTP basic authentication - :param discard_unknown_keys: Boolean value indicating whether to discard - unknown properties. A server may send a response that includes additional - properties that are not known by the client in the following scenarios: - 1. The OpenAPI document is incomplete, i.e. it does not match the server - implementation. - 2. The client was generated using an older version of the OpenAPI document - and the server has been upgraded since then. - If a schema in the OpenAPI document defines the additionalProperties attribute, - then all undeclared properties received by the server are injected into the - additional properties map. In that case, there are undeclared properties, and - nothing to discard. - - """ - - _default = None - - def __init__(self, host="http://localhost", - api_key=None, api_key_prefix=None, - username=None, password=None, - discard_unknown_keys=False, - ): - """Constructor - """ - self.host = host - """Default Base url - """ - self.temp_folder_path = None - """Temp file folder for downloading files - """ - # Authentication Settings - self.api_key = {} - if api_key: - self.api_key = api_key - """dict to store API key(s) - """ - self.api_key_prefix = {} - if api_key_prefix: - self.api_key_prefix = api_key_prefix - """dict to store API prefix (e.g. Bearer) - """ - self.refresh_api_key_hook = None - """function hook to refresh API key if expired - """ - self.username = username - """Username for HTTP basic authentication - """ - self.password = password - """Password for HTTP basic authentication - """ - self.discard_unknown_keys = discard_unknown_keys - self.logger = {} - """Logging Settings - """ - self.logger["package_logger"] = logging.getLogger("kubeflow.trainer") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - self.logger_format = '%(asctime)s %(levelname)s %(message)s' - """Log format - """ - self.logger_stream_handler = None - """Log stream handler - """ - self.logger_file_handler = None - """Log file handler - """ - self.logger_file = None - """Debug file location - """ - self.debug = False - """Debug switch - """ - - self.verify_ssl = True - """SSL/TLS verification - Set this to false to skip verifying SSL certificate when calling API - from https server. - """ - self.ssl_ca_cert = None - """Set this to customize the certificate file to verify the peer. - """ - self.cert_file = None - """client certificate file - """ - self.key_file = None - """client key file - """ - self.assert_hostname = None - """Set this to True/False to enable/disable SSL hostname verification. - """ - - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - """urllib3 connection pool's maximum number of connections saved - per pool. urllib3 uses 1 connection as default value, but this is - not the best value when you are making a lot of possibly parallel - requests to the same host, which is often the case here. - cpu_count * 5 is used as default value to increase performance. - """ - - self.proxy = None - """Proxy URL - """ - self.proxy_headers = None - """Proxy headers - """ - self.safe_chars_for_path_param = '' - """Safe chars for path_param - """ - self.retries = None - """Adding retries to override urllib3 default value 3 - """ - # Disable client side validation - self.client_side_validation = True - - def __deepcopy__(self, memo): - cls = self.__class__ - result = cls.__new__(cls) - memo[id(self)] = result - for k, v in self.__dict__.items(): - if k not in ('logger', 'logger_file_handler'): - setattr(result, k, copy.deepcopy(v, memo)) - # shallow copy of loggers - result.logger = copy.copy(self.logger) - # use setters to configure loggers - result.logger_file = self.logger_file - result.debug = self.debug - return result - - def __setattr__(self, name, value): - object.__setattr__(self, name, value) - - @classmethod - def set_default(cls, default): - """Set default instance of configuration. - - It stores default configuration, which can be - returned by get_default_copy method. - - :param default: object of Configuration - """ - cls._default = copy.deepcopy(default) - - @classmethod - def get_default_copy(cls): - """Return new instance of configuration. - - This method returns newly created, based on default constructor, - object of Configuration class or returns a copy of default - configuration passed by the set_default method. - - :return: The configuration object. - """ - if cls._default is not None: - return copy.deepcopy(cls._default) - return Configuration() - - @property - def logger_file(self): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - return self.__logger_file - - @logger_file.setter - def logger_file(self, value): - """The logger file. - - If the logger_file is None, then add stream handler and remove file - handler. Otherwise, add file handler and remove stream handler. - - :param value: The logger_file path. - :type: str - """ - self.__logger_file = value - if self.__logger_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logger_file_handler = logging.FileHandler(self.__logger_file) - self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_file_handler) - - @property - def debug(self): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - return self.__debug - - @debug.setter - def debug(self, value): - """Debug status - - :param value: The debug status, True or False. - :type: bool - """ - self.__debug = value - if self.__debug: - # if debug status is True, turn on debug logging - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.DEBUG) - # turn on httplib debug - httplib.HTTPConnection.debuglevel = 1 - else: - # if debug status is False, turn off debug logging, - # setting log level to default `logging.WARNING` - for _, logger in six.iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logger_format(self): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - return self.__logger_format - - @logger_format.setter - def logger_format(self, value): - """The logger format. - - The logger_formatter will be updated when sets logger_format. - - :param value: The format string. - :type: str - """ - self.__logger_format = value - self.logger_formatter = logging.Formatter(self.__logger_format) - - def get_api_key_with_prefix(self, identifier): - """Gets API key (with prefix if set). - - :param identifier: The identifier of apiKey. - :return: The token for api key authentication. - """ - if self.refresh_api_key_hook is not None: - self.refresh_api_key_hook(self) - key = self.api_key.get(identifier) - if key: - prefix = self.api_key_prefix.get(identifier) - if prefix: - return "%s %s" % (prefix, key) - else: - return key - - def get_basic_auth_token(self): - """Gets HTTP basic authentication header (string). - - :return: The token for basic HTTP authentication. - """ - username = "" - if self.username is not None: - username = self.username - password = "" - if self.password is not None: - password = self.password - return urllib3.util.make_headers( - basic_auth=username + ':' + password - ).get('authorization') - - def auth_settings(self): - """Gets Auth Settings dict for api client. - - :return: The Auth Settings information dict. - """ - auth = {} - return auth - - def to_debug_report(self): - """Gets the essential information for debugging. - - :return: The report for debugging. - """ - return "Python SDK Debug Report:\n"\ - "OS: {env}\n"\ - "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.0\n"\ - "SDK Package Version: 0.1.0".\ - format(env=sys.platform, pyversion=sys.version) - - def get_host_settings(self): - """Gets an array of host settings - - :return: An array of host settings - """ - return [ - { - 'url': "/", - 'description': "No description provided", - } - ] - - def get_host_from_settings(self, index, variables=None): - """Gets host URL based on the index and variables - :param index: array index of the host settings - :param variables: hash of variable and the corresponding value - :return: URL based on host settings - """ - variables = {} if variables is None else variables - servers = self.get_host_settings() - - try: - server = servers[index] - except IndexError: - raise ValueError( - "Invalid index {0} when selecting the host settings. " - "Must be less than {1}".format(index, len(servers))) - - url = server['url'] - - # go through variables and replace placeholders - for variable_name, variable in server['variables'].items(): - used_value = variables.get( - variable_name, variable['default_value']) - - if 'enum_values' in variable \ - and used_value not in variable['enum_values']: - raise ValueError( - "The variable `{0}` in the host URL has invalid value " - "{1}. Must be {2}.".format( - variable_name, variables[variable_name], - variable['enum_values'])) - - url = url.replace("{" + variable_name + "}", used_value) - - return url diff --git a/sdk/kubeflow/trainer/exceptions.py b/sdk/kubeflow/trainer/exceptions.py deleted file mode 100644 index 212027d04d..0000000000 --- a/sdk/kubeflow/trainer/exceptions.py +++ /dev/null @@ -1,120 +0,0 @@ -# coding: utf-8 - -""" - Kubeflow Trainer OpenAPI Spec - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import six - - -class OpenApiException(Exception): - """The base exception class for all OpenAPIExceptions""" - - -class ApiTypeError(OpenApiException, TypeError): - def __init__(self, msg, path_to_item=None, valid_classes=None, - key_type=None): - """ Raises an exception for TypeErrors - - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list): a list of keys an indices to get to the - current_item - None if unset - valid_classes (tuple): the primitive classes that current item - should be an instance of - None if unset - key_type (bool): False if our value is a value in a dict - True if it is a key in a dict - False if our item is an item in a list - None if unset - """ - self.path_to_item = path_to_item - self.valid_classes = valid_classes - self.key_type = key_type - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiTypeError, self).__init__(full_msg) - - -class ApiValueError(OpenApiException, ValueError): - def __init__(self, msg, path_to_item=None): - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (list) the path to the exception in the - received_data dict. None if unset - """ - - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiValueError, self).__init__(full_msg) - - -class ApiKeyError(OpenApiException, KeyError): - def __init__(self, msg, path_to_item=None): - """ - Args: - msg (str): the exception message - - Keyword Args: - path_to_item (None/list) the path to the exception in the - received_data dict - """ - self.path_to_item = path_to_item - full_msg = msg - if path_to_item: - full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) - super(ApiKeyError, self).__init__(full_msg) - - -class ApiException(OpenApiException): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message - - -def render_path(path_to_item): - """Returns a string representation of a path""" - result = "" - for pth in path_to_item: - if isinstance(pth, six.integer_types): - result += "[{0}]".format(pth) - else: - result += "['{0}']".format(pth) - return result diff --git a/sdk/kubeflow/trainer/models/__init__.py b/sdk/kubeflow/trainer/models/__init__.py index 6975f4f47d..8185a700bd 100644 --- a/sdk/kubeflow/trainer/models/__init__.py +++ b/sdk/kubeflow/trainer/models/__init__.py @@ -4,16 +4,149 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -from __future__ import absolute_import # import models into model package +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_container_resource_metric_source import IoK8sApiAutoscalingV2ContainerResourceMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_cross_version_object_reference import IoK8sApiAutoscalingV2CrossVersionObjectReference +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_external_metric_source import IoK8sApiAutoscalingV2ExternalMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_identifier import IoK8sApiAutoscalingV2MetricIdentifier +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_spec import IoK8sApiAutoscalingV2MetricSpec +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_target import IoK8sApiAutoscalingV2MetricTarget +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_object_metric_source import IoK8sApiAutoscalingV2ObjectMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_pods_metric_source import IoK8sApiAutoscalingV2PodsMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_resource_metric_source import IoK8sApiAutoscalingV2ResourceMetricSource +from kubeflow.trainer.models.io_k8s_api_batch_v1_job_spec import IoK8sApiBatchV1JobSpec +from kubeflow.trainer.models.io_k8s_api_batch_v1_job_template_spec import IoK8sApiBatchV1JobTemplateSpec +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy import IoK8sApiBatchV1PodFailurePolicy +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy_on_exit_codes_requirement import IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy_on_pod_conditions_pattern import IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy_rule import IoK8sApiBatchV1PodFailurePolicyRule +from kubeflow.trainer.models.io_k8s_api_batch_v1_success_policy import IoK8sApiBatchV1SuccessPolicy +from kubeflow.trainer.models.io_k8s_api_batch_v1_success_policy_rule import IoK8sApiBatchV1SuccessPolicyRule +from kubeflow.trainer.models.io_k8s_api_core_v1_aws_elastic_block_store_volume_source import IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_affinity import IoK8sApiCoreV1Affinity +from kubeflow.trainer.models.io_k8s_api_core_v1_app_armor_profile import IoK8sApiCoreV1AppArmorProfile +from kubeflow.trainer.models.io_k8s_api_core_v1_azure_disk_volume_source import IoK8sApiCoreV1AzureDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_azure_file_volume_source import IoK8sApiCoreV1AzureFileVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_csi_volume_source import IoK8sApiCoreV1CSIVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_capabilities import IoK8sApiCoreV1Capabilities +from kubeflow.trainer.models.io_k8s_api_core_v1_ceph_fs_volume_source import IoK8sApiCoreV1CephFSVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_cinder_volume_source import IoK8sApiCoreV1CinderVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_cluster_trust_bundle_projection import IoK8sApiCoreV1ClusterTrustBundleProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_env_source import IoK8sApiCoreV1ConfigMapEnvSource +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_key_selector import IoK8sApiCoreV1ConfigMapKeySelector +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_projection import IoK8sApiCoreV1ConfigMapProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_volume_source import IoK8sApiCoreV1ConfigMapVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_container import IoK8sApiCoreV1Container +from kubeflow.trainer.models.io_k8s_api_core_v1_container_port import IoK8sApiCoreV1ContainerPort +from kubeflow.trainer.models.io_k8s_api_core_v1_container_resize_policy import IoK8sApiCoreV1ContainerResizePolicy +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_projection import IoK8sApiCoreV1DownwardAPIProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_volume_file import IoK8sApiCoreV1DownwardAPIVolumeFile +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_volume_source import IoK8sApiCoreV1DownwardAPIVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_empty_dir_volume_source import IoK8sApiCoreV1EmptyDirVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_env_from_source import IoK8sApiCoreV1EnvFromSource +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var_source import IoK8sApiCoreV1EnvVarSource +from kubeflow.trainer.models.io_k8s_api_core_v1_ephemeral_container import IoK8sApiCoreV1EphemeralContainer +from kubeflow.trainer.models.io_k8s_api_core_v1_ephemeral_volume_source import IoK8sApiCoreV1EphemeralVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_exec_action import IoK8sApiCoreV1ExecAction +from kubeflow.trainer.models.io_k8s_api_core_v1_fc_volume_source import IoK8sApiCoreV1FCVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_flex_volume_source import IoK8sApiCoreV1FlexVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_flocker_volume_source import IoK8sApiCoreV1FlockerVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_gce_persistent_disk_volume_source import IoK8sApiCoreV1GCEPersistentDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_grpc_action import IoK8sApiCoreV1GRPCAction +from kubeflow.trainer.models.io_k8s_api_core_v1_git_repo_volume_source import IoK8sApiCoreV1GitRepoVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_glusterfs_volume_source import IoK8sApiCoreV1GlusterfsVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_http_get_action import IoK8sApiCoreV1HTTPGetAction +from kubeflow.trainer.models.io_k8s_api_core_v1_http_header import IoK8sApiCoreV1HTTPHeader +from kubeflow.trainer.models.io_k8s_api_core_v1_host_alias import IoK8sApiCoreV1HostAlias +from kubeflow.trainer.models.io_k8s_api_core_v1_host_path_volume_source import IoK8sApiCoreV1HostPathVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_iscsi_volume_source import IoK8sApiCoreV1ISCSIVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_image_volume_source import IoK8sApiCoreV1ImageVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_key_to_path import IoK8sApiCoreV1KeyToPath +from kubeflow.trainer.models.io_k8s_api_core_v1_lifecycle import IoK8sApiCoreV1Lifecycle +from kubeflow.trainer.models.io_k8s_api_core_v1_lifecycle_handler import IoK8sApiCoreV1LifecycleHandler +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from kubeflow.trainer.models.io_k8s_api_core_v1_nfs_volume_source import IoK8sApiCoreV1NFSVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_node_affinity import IoK8sApiCoreV1NodeAffinity +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector import IoK8sApiCoreV1NodeSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector_requirement import IoK8sApiCoreV1NodeSelectorRequirement +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector_term import IoK8sApiCoreV1NodeSelectorTerm +from kubeflow.trainer.models.io_k8s_api_core_v1_object_field_selector import IoK8sApiCoreV1ObjectFieldSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_persistent_volume_claim_spec import IoK8sApiCoreV1PersistentVolumeClaimSpec +from kubeflow.trainer.models.io_k8s_api_core_v1_persistent_volume_claim_template import IoK8sApiCoreV1PersistentVolumeClaimTemplate +from kubeflow.trainer.models.io_k8s_api_core_v1_persistent_volume_claim_volume_source import IoK8sApiCoreV1PersistentVolumeClaimVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_photon_persistent_disk_volume_source import IoK8sApiCoreV1PhotonPersistentDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_affinity import IoK8sApiCoreV1PodAffinity +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_affinity_term import IoK8sApiCoreV1PodAffinityTerm +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_anti_affinity import IoK8sApiCoreV1PodAntiAffinity +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_dns_config import IoK8sApiCoreV1PodDNSConfig +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_dns_config_option import IoK8sApiCoreV1PodDNSConfigOption +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_os import IoK8sApiCoreV1PodOS +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_readiness_gate import IoK8sApiCoreV1PodReadinessGate +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_resource_claim import IoK8sApiCoreV1PodResourceClaim +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_scheduling_gate import IoK8sApiCoreV1PodSchedulingGate +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_security_context import IoK8sApiCoreV1PodSecurityContext +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_spec import IoK8sApiCoreV1PodSpec +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_template_spec import IoK8sApiCoreV1PodTemplateSpec +from kubeflow.trainer.models.io_k8s_api_core_v1_portworx_volume_source import IoK8sApiCoreV1PortworxVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_preferred_scheduling_term import IoK8sApiCoreV1PreferredSchedulingTerm +from kubeflow.trainer.models.io_k8s_api_core_v1_probe import IoK8sApiCoreV1Probe +from kubeflow.trainer.models.io_k8s_api_core_v1_projected_volume_source import IoK8sApiCoreV1ProjectedVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_quobyte_volume_source import IoK8sApiCoreV1QuobyteVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_rbd_volume_source import IoK8sApiCoreV1RBDVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_claim import IoK8sApiCoreV1ResourceClaim +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_field_selector import IoK8sApiCoreV1ResourceFieldSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_requirements import IoK8sApiCoreV1ResourceRequirements +from kubeflow.trainer.models.io_k8s_api_core_v1_se_linux_options import IoK8sApiCoreV1SELinuxOptions +from kubeflow.trainer.models.io_k8s_api_core_v1_scale_io_volume_source import IoK8sApiCoreV1ScaleIOVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_seccomp_profile import IoK8sApiCoreV1SeccompProfile +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_env_source import IoK8sApiCoreV1SecretEnvSource +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_key_selector import IoK8sApiCoreV1SecretKeySelector +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_projection import IoK8sApiCoreV1SecretProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_volume_source import IoK8sApiCoreV1SecretVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_security_context import IoK8sApiCoreV1SecurityContext +from kubeflow.trainer.models.io_k8s_api_core_v1_service_account_token_projection import IoK8sApiCoreV1ServiceAccountTokenProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_sleep_action import IoK8sApiCoreV1SleepAction +from kubeflow.trainer.models.io_k8s_api_core_v1_storage_os_volume_source import IoK8sApiCoreV1StorageOSVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_sysctl import IoK8sApiCoreV1Sysctl +from kubeflow.trainer.models.io_k8s_api_core_v1_tcp_socket_action import IoK8sApiCoreV1TCPSocketAction +from kubeflow.trainer.models.io_k8s_api_core_v1_toleration import IoK8sApiCoreV1Toleration +from kubeflow.trainer.models.io_k8s_api_core_v1_topology_spread_constraint import IoK8sApiCoreV1TopologySpreadConstraint +from kubeflow.trainer.models.io_k8s_api_core_v1_typed_local_object_reference import IoK8sApiCoreV1TypedLocalObjectReference +from kubeflow.trainer.models.io_k8s_api_core_v1_typed_object_reference import IoK8sApiCoreV1TypedObjectReference +from kubeflow.trainer.models.io_k8s_api_core_v1_volume import IoK8sApiCoreV1Volume +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_device import IoK8sApiCoreV1VolumeDevice +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_mount import IoK8sApiCoreV1VolumeMount +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_projection import IoK8sApiCoreV1VolumeProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_resource_requirements import IoK8sApiCoreV1VolumeResourceRequirements +from kubeflow.trainer.models.io_k8s_api_core_v1_vsphere_virtual_disk_volume_source import IoK8sApiCoreV1VsphereVirtualDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_weighted_pod_affinity_term import IoK8sApiCoreV1WeightedPodAffinityTerm +from kubeflow.trainer.models.io_k8s_api_core_v1_windows_security_context_options import IoK8sApiCoreV1WindowsSecurityContextOptions +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_condition import IoK8sApimachineryPkgApisMetaV1Condition +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement import IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_list_meta import IoK8sApimachineryPkgApisMetaV1ListMeta +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry import IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference import IoK8sApimachineryPkgApisMetaV1OwnerReference +from kubeflow.trainer.models.jobset_v1alpha2_coordinator import JobsetV1alpha2Coordinator +from kubeflow.trainer.models.jobset_v1alpha2_depends_on import JobsetV1alpha2DependsOn +from kubeflow.trainer.models.jobset_v1alpha2_failure_policy import JobsetV1alpha2FailurePolicy +from kubeflow.trainer.models.jobset_v1alpha2_failure_policy_rule import JobsetV1alpha2FailurePolicyRule +from kubeflow.trainer.models.jobset_v1alpha2_job_set_spec import JobsetV1alpha2JobSetSpec +from kubeflow.trainer.models.jobset_v1alpha2_network import JobsetV1alpha2Network +from kubeflow.trainer.models.jobset_v1alpha2_replicated_job import JobsetV1alpha2ReplicatedJob +from kubeflow.trainer.models.jobset_v1alpha2_startup_policy import JobsetV1alpha2StartupPolicy +from kubeflow.trainer.models.jobset_v1alpha2_success_policy import JobsetV1alpha2SuccessPolicy from kubeflow.trainer.models.trainer_v1alpha1_cluster_training_runtime import TrainerV1alpha1ClusterTrainingRuntime from kubeflow.trainer.models.trainer_v1alpha1_cluster_training_runtime_list import TrainerV1alpha1ClusterTrainingRuntimeList from kubeflow.trainer.models.trainer_v1alpha1_container_override import TrainerV1alpha1ContainerOverride @@ -42,7 +175,3 @@ from kubeflow.trainer.models.trainer_v1alpha1_training_runtime import TrainerV1alpha1TrainingRuntime from kubeflow.trainer.models.trainer_v1alpha1_training_runtime_list import TrainerV1alpha1TrainingRuntimeList from kubeflow.trainer.models.trainer_v1alpha1_training_runtime_spec import TrainerV1alpha1TrainingRuntimeSpec - -# Import Kubernetes and JobSet models for the serialization. -from kubernetes.client import * -from jobset.models import * diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_container_resource_metric_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_container_resource_metric_source.py new file mode 100644 index 0000000000..5a4be29556 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_container_resource_metric_source.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_target import IoK8sApiAutoscalingV2MetricTarget +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2ContainerResourceMetricSource(BaseModel): + """ + ContainerResourceMetricSource indicates how to scale on a resource metric known to Kubernetes, as specified in requests and limits, describing each pod in the current scale target (e.g. CPU or memory). The values will be averaged together before being compared to the target. Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source. Only one \"target\" type should be set. + """ # noqa: E501 + container: StrictStr = Field(description="container is the name of the container in the pods of the scaling target") + name: StrictStr = Field(description="name is the name of the resource in question.") + target: IoK8sApiAutoscalingV2MetricTarget + __properties: ClassVar[List[str]] = ["container", "name", "target"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ContainerResourceMetricSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ContainerResourceMetricSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "container": obj.get("container"), + "name": obj.get("name"), + "target": IoK8sApiAutoscalingV2MetricTarget.from_dict(obj["target"]) if obj.get("target") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_cross_version_object_reference.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_cross_version_object_reference.py new file mode 100644 index 0000000000..e98298ce74 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_cross_version_object_reference.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2CrossVersionObjectReference(BaseModel): + """ + CrossVersionObjectReference contains enough information to let you identify the referred resource. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="apiVersion is the API version of the referent", alias="apiVersion") + kind: StrictStr = Field(description="kind is the kind of the referent; More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + name: StrictStr = Field(description="name is the name of the referent; More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + __properties: ClassVar[List[str]] = ["apiVersion", "kind", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2CrossVersionObjectReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2CrossVersionObjectReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "kind": obj.get("kind"), + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_external_metric_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_external_metric_source.py new file mode 100644 index 0000000000..61f1a0c367 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_external_metric_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_identifier import IoK8sApiAutoscalingV2MetricIdentifier +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_target import IoK8sApiAutoscalingV2MetricTarget +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2ExternalMetricSource(BaseModel): + """ + ExternalMetricSource indicates how to scale on a metric not associated with any Kubernetes object (for example length of queue in cloud messaging service, or QPS from loadbalancer running outside of cluster). + """ # noqa: E501 + metric: IoK8sApiAutoscalingV2MetricIdentifier + target: IoK8sApiAutoscalingV2MetricTarget + __properties: ClassVar[List[str]] = ["metric", "target"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ExternalMetricSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 metric + if self.metric: + _dict['metric'] = self.metric.to_dict() + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ExternalMetricSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metric": IoK8sApiAutoscalingV2MetricIdentifier.from_dict(obj["metric"]) if obj.get("metric") is not None else None, + "target": IoK8sApiAutoscalingV2MetricTarget.from_dict(obj["target"]) if obj.get("target") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_identifier.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_identifier.py new file mode 100644 index 0000000000..b47cc4a2fe --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_identifier.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2MetricIdentifier(BaseModel): + """ + MetricIdentifier defines the name and optionally selector for a metric + """ # noqa: E501 + name: StrictStr = Field(description="name is the name of the given metric") + selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = None + __properties: ClassVar[List[str]] = ["name", "selector"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2MetricIdentifier from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 selector + if self.selector: + _dict['selector'] = self.selector.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2MetricIdentifier from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "selector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["selector"]) if obj.get("selector") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_spec.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_spec.py new file mode 100644 index 0000000000..a372e3e5b0 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_spec.py @@ -0,0 +1,117 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_container_resource_metric_source import IoK8sApiAutoscalingV2ContainerResourceMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_external_metric_source import IoK8sApiAutoscalingV2ExternalMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_object_metric_source import IoK8sApiAutoscalingV2ObjectMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_pods_metric_source import IoK8sApiAutoscalingV2PodsMetricSource +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_resource_metric_source import IoK8sApiAutoscalingV2ResourceMetricSource +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2MetricSpec(BaseModel): + """ + MetricSpec specifies how to scale based on a single metric (only `type` and one other matching field should be set at once). + """ # noqa: E501 + container_resource: Optional[IoK8sApiAutoscalingV2ContainerResourceMetricSource] = Field(default=None, alias="containerResource") + external: Optional[IoK8sApiAutoscalingV2ExternalMetricSource] = None + object: Optional[IoK8sApiAutoscalingV2ObjectMetricSource] = None + pods: Optional[IoK8sApiAutoscalingV2PodsMetricSource] = None + resource: Optional[IoK8sApiAutoscalingV2ResourceMetricSource] = None + type: StrictStr = Field(description="type is the type of metric source. It should be one of \"ContainerResource\", \"External\", \"Object\", \"Pods\" or \"Resource\", each mapping to a matching field in the object.") + __properties: ClassVar[List[str]] = ["containerResource", "external", "object", "pods", "resource", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2MetricSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 container_resource + if self.container_resource: + _dict['containerResource'] = self.container_resource.to_dict() + # override the default output from pydantic by calling `to_dict()` of external + if self.external: + _dict['external'] = self.external.to_dict() + # override the default output from pydantic by calling `to_dict()` of object + if self.object: + _dict['object'] = self.object.to_dict() + # override the default output from pydantic by calling `to_dict()` of pods + if self.pods: + _dict['pods'] = self.pods.to_dict() + # override the default output from pydantic by calling `to_dict()` of resource + if self.resource: + _dict['resource'] = self.resource.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2MetricSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "containerResource": IoK8sApiAutoscalingV2ContainerResourceMetricSource.from_dict(obj["containerResource"]) if obj.get("containerResource") is not None else None, + "external": IoK8sApiAutoscalingV2ExternalMetricSource.from_dict(obj["external"]) if obj.get("external") is not None else None, + "object": IoK8sApiAutoscalingV2ObjectMetricSource.from_dict(obj["object"]) if obj.get("object") is not None else None, + "pods": IoK8sApiAutoscalingV2PodsMetricSource.from_dict(obj["pods"]) if obj.get("pods") is not None else None, + "resource": IoK8sApiAutoscalingV2ResourceMetricSource.from_dict(obj["resource"]) if obj.get("resource") is not None else None, + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_target.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_target.py new file mode 100644 index 0000000000..5f00c86b54 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_metric_target.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2MetricTarget(BaseModel): + """ + MetricTarget defines the target value, average value, or average utilization of a specific metric + """ # noqa: E501 + average_utilization: Optional[StrictInt] = Field(default=None, description="averageUtilization is the target value of the average of the resource metric across all relevant pods, represented as a percentage of the requested value of the resource for the pods. Currently only valid for Resource metric source type", alias="averageUtilization") + average_value: Optional[StrictStr] = Field(default=None, description="Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors. The serialization format is: ``` ::= (Note that may be empty, from the \"\" case in .) ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html) ::= m | \"\" | k | M | G | T | P | E (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.) ::= \"e\" | \"E\" ``` No matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities. When a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized. Before serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that: - No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible. The sign will be omitted unless the number is negative. Examples: - 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\" Note that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise. Non-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.) This format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", alias="averageValue") + type: StrictStr = Field(description="type represents whether the metric type is Utilization, Value, or AverageValue") + value: Optional[StrictStr] = Field(default=None, description="Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors. The serialization format is: ``` ::= (Note that may be empty, from the \"\" case in .) ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html) ::= m | \"\" | k | M | G | T | P | E (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.) ::= \"e\" | \"E\" ``` No matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities. When a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized. Before serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that: - No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible. The sign will be omitted unless the number is negative. Examples: - 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\" Note that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise. Non-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.) This format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.") + __properties: ClassVar[List[str]] = ["averageUtilization", "averageValue", "type", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2MetricTarget from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2MetricTarget from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "averageUtilization": obj.get("averageUtilization"), + "averageValue": obj.get("averageValue"), + "type": obj.get("type"), + "value": obj.get("value") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_object_metric_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_object_metric_source.py new file mode 100644 index 0000000000..f3ff7a0545 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_object_metric_source.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_cross_version_object_reference import IoK8sApiAutoscalingV2CrossVersionObjectReference +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_identifier import IoK8sApiAutoscalingV2MetricIdentifier +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_target import IoK8sApiAutoscalingV2MetricTarget +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2ObjectMetricSource(BaseModel): + """ + ObjectMetricSource indicates how to scale on a metric describing a kubernetes object (for example, hits-per-second on an Ingress object). + """ # noqa: E501 + described_object: IoK8sApiAutoscalingV2CrossVersionObjectReference = Field(alias="describedObject") + metric: IoK8sApiAutoscalingV2MetricIdentifier + target: IoK8sApiAutoscalingV2MetricTarget + __properties: ClassVar[List[str]] = ["describedObject", "metric", "target"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ObjectMetricSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 described_object + if self.described_object: + _dict['describedObject'] = self.described_object.to_dict() + # override the default output from pydantic by calling `to_dict()` of metric + if self.metric: + _dict['metric'] = self.metric.to_dict() + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ObjectMetricSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "describedObject": IoK8sApiAutoscalingV2CrossVersionObjectReference.from_dict(obj["describedObject"]) if obj.get("describedObject") is not None else None, + "metric": IoK8sApiAutoscalingV2MetricIdentifier.from_dict(obj["metric"]) if obj.get("metric") is not None else None, + "target": IoK8sApiAutoscalingV2MetricTarget.from_dict(obj["target"]) if obj.get("target") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_pods_metric_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_pods_metric_source.py new file mode 100644 index 0000000000..bb5f7c9ba5 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_pods_metric_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_identifier import IoK8sApiAutoscalingV2MetricIdentifier +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_target import IoK8sApiAutoscalingV2MetricTarget +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2PodsMetricSource(BaseModel): + """ + PodsMetricSource indicates how to scale on a metric describing each pod in the current scale target (for example, transactions-processed-per-second). The values will be averaged together before being compared to the target value. + """ # noqa: E501 + metric: IoK8sApiAutoscalingV2MetricIdentifier + target: IoK8sApiAutoscalingV2MetricTarget + __properties: ClassVar[List[str]] = ["metric", "target"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2PodsMetricSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 metric + if self.metric: + _dict['metric'] = self.metric.to_dict() + # override the default output from pydantic by calling `to_dict()` of target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2PodsMetricSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metric": IoK8sApiAutoscalingV2MetricIdentifier.from_dict(obj["metric"]) if obj.get("metric") is not None else None, + "target": IoK8sApiAutoscalingV2MetricTarget.from_dict(obj["target"]) if obj.get("target") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_resource_metric_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_resource_metric_source.py new file mode 100644 index 0000000000..5d3a07794e --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_autoscaling_v2_resource_metric_source.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_target import IoK8sApiAutoscalingV2MetricTarget +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiAutoscalingV2ResourceMetricSource(BaseModel): + """ + ResourceMetricSource indicates how to scale on a resource metric known to Kubernetes, as specified in requests and limits, describing each pod in the current scale target (e.g. CPU or memory). The values will be averaged together before being compared to the target. Such metrics are built in to Kubernetes, and have special scaling options on top of those available to normal per-pod metrics using the \"pods\" source. Only one \"target\" type should be set. + """ # noqa: E501 + name: StrictStr = Field(description="name is the name of the resource in question.") + target: IoK8sApiAutoscalingV2MetricTarget + __properties: ClassVar[List[str]] = ["name", "target"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ResourceMetricSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 target + if self.target: + _dict['target'] = self.target.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiAutoscalingV2ResourceMetricSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "target": IoK8sApiAutoscalingV2MetricTarget.from_dict(obj["target"]) if obj.get("target") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_job_spec.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_job_spec.py new file mode 100644 index 0000000000..a8f62ef3d2 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_job_spec.py @@ -0,0 +1,133 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy import IoK8sApiBatchV1PodFailurePolicy +from kubeflow.trainer.models.io_k8s_api_batch_v1_success_policy import IoK8sApiBatchV1SuccessPolicy +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_template_spec import IoK8sApiCoreV1PodTemplateSpec +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1JobSpec(BaseModel): + """ + JobSpec describes how the job execution will look like. + """ # noqa: E501 + active_deadline_seconds: Optional[StrictInt] = Field(default=None, 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.", alias="activeDeadlineSeconds") + backoff_limit: Optional[StrictInt] = Field(default=None, description="Specifies the number of retries before marking this job failed. Defaults to 6", alias="backoffLimit") + backoff_limit_per_index: Optional[StrictInt] = Field(default=None, 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).", alias="backoffLimitPerIndex") + completion_mode: Optional[StrictStr] = Field(default=None, 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.", alias="completionMode") + completions: Optional[StrictInt] = Field(default=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/") + managed_by: Optional[StrictStr] = Field(default=None, description="ManagedBy field indicates the controller that manages a Job. The k8s Job controller reconciles jobs which don't have this field at all or the field value is the reserved string `kubernetes.io/job-controller`, but skips reconciling Jobs with a custom value for this field. The value must be a valid domain-prefixed path (e.g. acme.io/foo) - all characters before the first \"/\" must be a valid subdomain as defined by RFC 1123. All characters trailing the first \"/\" must be valid HTTP Path characters as defined by RFC 3986. The value cannot exceed 63 characters. This field is immutable. This field is beta-level. The job controller accepts setting the field when the feature gate JobManagedBy is enabled (enabled by default).", alias="managedBy") + manual_selector: Optional[StrictBool] = Field(default=None, 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", alias="manualSelector") + max_failed_indexes: Optional[StrictInt] = Field(default=None, 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).", alias="maxFailedIndexes") + parallelism: Optional[StrictInt] = Field(default=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[IoK8sApiBatchV1PodFailurePolicy] = Field(default=None, alias="podFailurePolicy") + pod_replacement_policy: Optional[StrictStr] = Field(default=None, 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.", alias="podReplacementPolicy") + selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = None + success_policy: Optional[IoK8sApiBatchV1SuccessPolicy] = Field(default=None, alias="successPolicy") + suspend: Optional[StrictBool] = Field(default=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: IoK8sApiCoreV1PodTemplateSpec + ttl_seconds_after_finished: Optional[StrictInt] = Field(default=None, 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.", alias="ttlSecondsAfterFinished") + __properties: ClassVar[List[str]] = ["activeDeadlineSeconds", "backoffLimit", "backoffLimitPerIndex", "completionMode", "completions", "managedBy", "manualSelector", "maxFailedIndexes", "parallelism", "podFailurePolicy", "podReplacementPolicy", "selector", "successPolicy", "suspend", "template", "ttlSecondsAfterFinished"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1JobSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 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 success_policy + if self.success_policy: + _dict['successPolicy'] = self.success_policy.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: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1JobSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "activeDeadlineSeconds": obj.get("activeDeadlineSeconds"), + "backoffLimit": obj.get("backoffLimit"), + "backoffLimitPerIndex": obj.get("backoffLimitPerIndex"), + "completionMode": obj.get("completionMode"), + "completions": obj.get("completions"), + "managedBy": obj.get("managedBy"), + "manualSelector": obj.get("manualSelector"), + "maxFailedIndexes": obj.get("maxFailedIndexes"), + "parallelism": obj.get("parallelism"), + "podFailurePolicy": IoK8sApiBatchV1PodFailurePolicy.from_dict(obj["podFailurePolicy"]) if obj.get("podFailurePolicy") is not None else None, + "podReplacementPolicy": obj.get("podReplacementPolicy"), + "selector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["selector"]) if obj.get("selector") is not None else None, + "successPolicy": IoK8sApiBatchV1SuccessPolicy.from_dict(obj["successPolicy"]) if obj.get("successPolicy") is not None else None, + "suspend": obj.get("suspend"), + "template": IoK8sApiCoreV1PodTemplateSpec.from_dict(obj["template"]) if obj.get("template") is not None else None, + "ttlSecondsAfterFinished": obj.get("ttlSecondsAfterFinished") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_job_template_spec.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_job_template_spec.py new file mode 100644 index 0000000000..1de9785e57 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_job_template_spec.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_batch_v1_job_spec import IoK8sApiBatchV1JobSpec +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1JobTemplateSpec(BaseModel): + """ + JobTemplateSpec describes the data a Job should have when created from a template + """ # noqa: E501 + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: Optional[IoK8sApiBatchV1JobSpec] = None + __properties: ClassVar[List[str]] = ["metadata", "spec"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1JobTemplateSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1JobTemplateSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": IoK8sApiBatchV1JobSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy.py new file mode 100644 index 0000000000..8d80e1116b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy_rule import IoK8sApiBatchV1PodFailurePolicyRule +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1PodFailurePolicy(BaseModel): + """ + PodFailurePolicy describes how failed pods influence the backoffLimit. + """ # noqa: E501 + rules: List[IoK8sApiBatchV1PodFailurePolicyRule] = Field(description="A list of pod failure policy rules. The rules are evaluated in order. Once a rule matches a Pod failure, the remaining of the rules are ignored. When no rule matches the Pod failure, the default handling applies - the counter of pod failures is incremented and it is checked against the backoffLimit. At most 20 elements are allowed.") + __properties: ClassVar[List[str]] = ["rules"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 rules (list) + _items = [] + if self.rules: + for _item_rules in self.rules: + if _item_rules: + _items.append(_item_rules.to_dict()) + _dict['rules'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "rules": [IoK8sApiBatchV1PodFailurePolicyRule.from_dict(_item) for _item in obj["rules"]] if obj.get("rules") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_on_exit_codes_requirement.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_on_exit_codes_requirement.py new file mode 100644 index 0000000000..43c4f0f88a --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_on_exit_codes_requirement.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement(BaseModel): + """ + PodFailurePolicyOnExitCodesRequirement describes the requirement for handling a failed pod based on its container exit codes. In particular, it lookups the .state.terminated.exitCode for each app container and init container status, represented by the .status.containerStatuses and .status.initContainerStatuses fields in the Pod status, respectively. Containers completed with success (exit code 0) are excluded from the requirement check. + """ # noqa: E501 + container_name: Optional[StrictStr] = Field(default=None, description="Restricts the check for exit codes to the container with the specified name. When null, the rule applies to all containers. When specified, it should match one the container or initContainer names in the pod template.", alias="containerName") + operator: StrictStr = Field(description="Represents the relationship between the container exit code(s) and the specified values. Containers completed with success (exit code 0) are excluded from the requirement check. Possible values are: - In: the requirement is satisfied if at least one container exit code (might be multiple if there are multiple containers not restricted by the 'containerName' field) is in the set of specified values. - NotIn: the requirement is satisfied if at least one container exit code (might be multiple if there are multiple containers not restricted by the 'containerName' field) is not in the set of specified values. Additional values are considered to be added in the future. Clients should react to an unknown operator by assuming the requirement is not satisfied.") + values: List[StrictInt] = Field(description="Specifies the set of values. Each returned container exit code (might be multiple in case of multiple containers) is checked against this set of values with respect to the operator. The list of values must be ordered and must not contain duplicates. Value '0' cannot be used for the In operator. At least one element is required. At most 255 elements are allowed.") + __properties: ClassVar[List[str]] = ["containerName", "operator", "values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "containerName": obj.get("containerName"), + "operator": obj.get("operator"), + "values": obj.get("values") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_on_pod_conditions_pattern.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_on_pod_conditions_pattern.py new file mode 100644 index 0000000000..ab4bd175e9 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_on_pod_conditions_pattern.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern(BaseModel): + """ + PodFailurePolicyOnPodConditionsPattern describes a pattern for matching an actual pod condition type. + """ # noqa: E501 + status: StrictStr = Field(description="Specifies the required Pod condition status. To match a pod condition it is required that the specified status equals the pod condition status. Defaults to True.") + type: StrictStr = Field(description="Specifies the required Pod condition type. To match a pod condition it is required that specified type equals the pod condition type.") + __properties: ClassVar[List[str]] = ["status", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "status": obj.get("status"), + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_rule.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_rule.py new file mode 100644 index 0000000000..0e4e5ba730 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_pod_failure_policy_rule.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy_on_exit_codes_requirement import IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement +from kubeflow.trainer.models.io_k8s_api_batch_v1_pod_failure_policy_on_pod_conditions_pattern import IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1PodFailurePolicyRule(BaseModel): + """ + PodFailurePolicyRule describes how a pod failure is handled when the requirements are met. One of onExitCodes and onPodConditions, but not both, can be used in each rule. + """ # noqa: E501 + action: StrictStr = Field(description="Specifies the action taken on a pod failure when the requirements are satisfied. Possible values are: - FailJob: indicates that the pod's job is marked as Failed and all running pods are terminated. - FailIndex: indicates that the pod's index is marked as Failed and will not be restarted. This value is beta-level. It can be used when the `JobBackoffLimitPerIndex` feature gate is enabled (enabled by default). - Ignore: indicates that the counter towards the .backoffLimit is not incremented and a replacement pod is created. - Count: indicates that the pod is handled in the default way - the counter towards the .backoffLimit is incremented. Additional values are considered to be added in the future. Clients should react to an unknown action by skipping the rule.") + on_exit_codes: Optional[IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement] = Field(default=None, alias="onExitCodes") + on_pod_conditions: Optional[List[IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern]] = Field(default=None, description="Represents the requirement on the pod conditions. The requirement is represented as a list of pod condition patterns. The requirement is satisfied if at least one pattern matches an actual pod condition. At most 20 elements are allowed.", alias="onPodConditions") + __properties: ClassVar[List[str]] = ["action", "onExitCodes", "onPodConditions"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicyRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 on_exit_codes + if self.on_exit_codes: + _dict['onExitCodes'] = self.on_exit_codes.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in on_pod_conditions (list) + _items = [] + if self.on_pod_conditions: + for _item_on_pod_conditions in self.on_pod_conditions: + if _item_on_pod_conditions: + _items.append(_item_on_pod_conditions.to_dict()) + _dict['onPodConditions'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1PodFailurePolicyRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "action": obj.get("action"), + "onExitCodes": IoK8sApiBatchV1PodFailurePolicyOnExitCodesRequirement.from_dict(obj["onExitCodes"]) if obj.get("onExitCodes") is not None else None, + "onPodConditions": [IoK8sApiBatchV1PodFailurePolicyOnPodConditionsPattern.from_dict(_item) for _item in obj["onPodConditions"]] if obj.get("onPodConditions") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_success_policy.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_success_policy.py new file mode 100644 index 0000000000..c0f4fdd78f --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_success_policy.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_batch_v1_success_policy_rule import IoK8sApiBatchV1SuccessPolicyRule +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1SuccessPolicy(BaseModel): + """ + SuccessPolicy describes when a Job can be declared as succeeded based on the success of some indexes. + """ # noqa: E501 + rules: List[IoK8sApiBatchV1SuccessPolicyRule] = Field(description="rules represents the list of alternative rules for the declaring the Jobs as successful before `.status.succeeded >= .spec.completions`. Once any of the rules are met, the \"SucceededCriteriaMet\" condition is added, and the lingering pods are removed. The terminal state for such a Job has the \"Complete\" condition. Additionally, these rules are evaluated in order; Once the Job meets one of the rules, other rules are ignored. At most 20 elements are allowed.") + __properties: ClassVar[List[str]] = ["rules"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1SuccessPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 rules (list) + _items = [] + if self.rules: + for _item_rules in self.rules: + if _item_rules: + _items.append(_item_rules.to_dict()) + _dict['rules'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1SuccessPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "rules": [IoK8sApiBatchV1SuccessPolicyRule.from_dict(_item) for _item in obj["rules"]] if obj.get("rules") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_success_policy_rule.py b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_success_policy_rule.py new file mode 100644 index 0000000000..a09dd24a72 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_batch_v1_success_policy_rule.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiBatchV1SuccessPolicyRule(BaseModel): + """ + SuccessPolicyRule describes rule for declaring a Job as succeeded. Each rule must have at least one of the \"succeededIndexes\" or \"succeededCount\" specified. + """ # noqa: E501 + succeeded_count: Optional[StrictInt] = Field(default=None, description="succeededCount specifies the minimal required size of the actual set of the succeeded indexes for the Job. When succeededCount is used along with succeededIndexes, the check is constrained only to the set of indexes specified by succeededIndexes. For example, given that succeededIndexes is \"1-4\", succeededCount is \"3\", and completed indexes are \"1\", \"3\", and \"5\", the Job isn't declared as succeeded because only \"1\" and \"3\" indexes are considered in that rules. When this field is null, this doesn't default to any value and is never evaluated at any time. When specified it needs to be a positive integer.", alias="succeededCount") + succeeded_indexes: Optional[StrictStr] = Field(default=None, description="succeededIndexes specifies the set of indexes which need to be contained in the actual set of the succeeded indexes for the Job. The list of indexes must be within 0 to \".spec.completions-1\" and must not contain duplicates. At least one element is required. The indexes are represented as intervals separated by commas. The intervals can be a decimal integer or a pair of decimal integers separated by a hyphen. The number are listed in represented by the first and last element of the series, separated by a hyphen. For example, if the completed indexes are 1, 3, 4, 5 and 7, they are represented as \"1,3-5,7\". When this field is null, this field doesn't default to any value and is never evaluated at any time.", alias="succeededIndexes") + __properties: ClassVar[List[str]] = ["succeededCount", "succeededIndexes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1SuccessPolicyRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiBatchV1SuccessPolicyRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "succeededCount": obj.get("succeededCount"), + "succeededIndexes": obj.get("succeededIndexes") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_affinity.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_affinity.py new file mode 100644 index 0000000000..0cab166906 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_affinity.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_node_affinity import IoK8sApiCoreV1NodeAffinity +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_affinity import IoK8sApiCoreV1PodAffinity +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_anti_affinity import IoK8sApiCoreV1PodAntiAffinity +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Affinity(BaseModel): + """ + Affinity is a group of affinity scheduling rules. + """ # noqa: E501 + node_affinity: Optional[IoK8sApiCoreV1NodeAffinity] = Field(default=None, alias="nodeAffinity") + pod_affinity: Optional[IoK8sApiCoreV1PodAffinity] = Field(default=None, alias="podAffinity") + pod_anti_affinity: Optional[IoK8sApiCoreV1PodAntiAffinity] = Field(default=None, alias="podAntiAffinity") + __properties: ClassVar[List[str]] = ["nodeAffinity", "podAffinity", "podAntiAffinity"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Affinity from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 node_affinity + if self.node_affinity: + _dict['nodeAffinity'] = self.node_affinity.to_dict() + # override the default output from pydantic by calling `to_dict()` of pod_affinity + if self.pod_affinity: + _dict['podAffinity'] = self.pod_affinity.to_dict() + # override the default output from pydantic by calling `to_dict()` of pod_anti_affinity + if self.pod_anti_affinity: + _dict['podAntiAffinity'] = self.pod_anti_affinity.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Affinity from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nodeAffinity": IoK8sApiCoreV1NodeAffinity.from_dict(obj["nodeAffinity"]) if obj.get("nodeAffinity") is not None else None, + "podAffinity": IoK8sApiCoreV1PodAffinity.from_dict(obj["podAffinity"]) if obj.get("podAffinity") is not None else None, + "podAntiAffinity": IoK8sApiCoreV1PodAntiAffinity.from_dict(obj["podAntiAffinity"]) if obj.get("podAntiAffinity") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_app_armor_profile.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_app_armor_profile.py new file mode 100644 index 0000000000..965c5850c0 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_app_armor_profile.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1AppArmorProfile(BaseModel): + """ + AppArmorProfile defines a pod or container's AppArmor settings. + """ # noqa: E501 + localhost_profile: Optional[StrictStr] = Field(default=None, description="localhostProfile indicates a profile loaded on the node that should be used. The profile must be preconfigured on the node to work. Must match the loaded name of the profile. Must be set if and only if type is \"Localhost\".", alias="localhostProfile") + type: StrictStr = Field(description="type indicates which kind of AppArmor profile will be applied. Valid options are: Localhost - a profile pre-loaded on the node. RuntimeDefault - the container runtime's default profile. Unconfined - no AppArmor enforcement.") + __properties: ClassVar[List[str]] = ["localhostProfile", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AppArmorProfile from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AppArmorProfile from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "localhostProfile": obj.get("localhostProfile"), + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_aws_elastic_block_store_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_aws_elastic_block_store_volume_source.py new file mode 100644 index 0000000000..3482a36f76 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_aws_elastic_block_store_volume_source.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource(BaseModel): + """ + Represents a Persistent Disk resource in AWS. An AWS EBS disk must exist before mounting to a container. The disk must also be in the same AWS zone as the kubelet. An AWS EBS disk can only be mounted as read/write once. AWS EBS volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", alias="fsType") + partition: Optional[StrictInt] = Field(default=None, description="partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty).") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly value true will force the readOnly setting in VolumeMounts. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", alias="readOnly") + volume_id: StrictStr = Field(description="volumeID is unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore", alias="volumeID") + __properties: ClassVar[List[str]] = ["fsType", "partition", "readOnly", "volumeID"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "partition": obj.get("partition"), + "readOnly": obj.get("readOnly"), + "volumeID": obj.get("volumeID") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_azure_disk_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_azure_disk_volume_source.py new file mode 100644 index 0000000000..b8bcf6a47e --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_azure_disk_volume_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1AzureDiskVolumeSource(BaseModel): + """ + AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod. + """ # noqa: E501 + caching_mode: Optional[StrictStr] = Field(default=None, description="cachingMode is the Host Caching mode: None, Read Only, Read Write.", alias="cachingMode") + disk_name: StrictStr = Field(description="diskName is the Name of the data disk in the blob storage", alias="diskName") + disk_uri: StrictStr = Field(description="diskURI is the URI of data disk in the blob storage", alias="diskURI") + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", alias="fsType") + kind: Optional[StrictStr] = Field(default=None, description="kind expected values are Shared: multiple blob disks per storage account Dedicated: single blob disk per storage account Managed: azure managed data disk (only in managed availability set). defaults to shared") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + __properties: ClassVar[List[str]] = ["cachingMode", "diskName", "diskURI", "fsType", "kind", "readOnly"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AzureDiskVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AzureDiskVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "cachingMode": obj.get("cachingMode"), + "diskName": obj.get("diskName"), + "diskURI": obj.get("diskURI"), + "fsType": obj.get("fsType"), + "kind": obj.get("kind"), + "readOnly": obj.get("readOnly") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_azure_file_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_azure_file_volume_source.py new file mode 100644 index 0000000000..aa57439ecc --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_azure_file_volume_source.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1AzureFileVolumeSource(BaseModel): + """ + AzureFile represents an Azure File Service mount on the host and bind mount to the pod. + """ # noqa: E501 + read_only: Optional[StrictBool] = Field(default=None, description="readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + secret_name: StrictStr = Field(description="secretName is the name of secret that contains Azure Storage Account Name and Key", alias="secretName") + share_name: StrictStr = Field(description="shareName is the azure share Name", alias="shareName") + __properties: ClassVar[List[str]] = ["readOnly", "secretName", "shareName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AzureFileVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1AzureFileVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "readOnly": obj.get("readOnly"), + "secretName": obj.get("secretName"), + "shareName": obj.get("shareName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_capabilities.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_capabilities.py new file mode 100644 index 0000000000..e95dc059f2 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_capabilities.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Capabilities(BaseModel): + """ + Adds and removes POSIX capabilities from running containers. + """ # noqa: E501 + add: Optional[List[StrictStr]] = Field(default=None, description="Added capabilities") + drop: Optional[List[StrictStr]] = Field(default=None, description="Removed capabilities") + __properties: ClassVar[List[str]] = ["add", "drop"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Capabilities from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Capabilities from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "add": obj.get("add"), + "drop": obj.get("drop") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ceph_fs_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ceph_fs_volume_source.py new file mode 100644 index 0000000000..6aab9a4da9 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ceph_fs_volume_source.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1CephFSVolumeSource(BaseModel): + """ + Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling. + """ # noqa: E501 + monitors: List[StrictStr] = Field(description="monitors is Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it") + path: Optional[StrictStr] = Field(default=None, description="path is Optional: Used as the mounted root, rather than the full Ceph tree, default is /") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", alias="readOnly") + secret_file: Optional[StrictStr] = Field(default=None, description="secretFile is Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it", alias="secretFile") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + user: Optional[StrictStr] = Field(default=None, description="user is optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-it") + __properties: ClassVar[List[str]] = ["monitors", "path", "readOnly", "secretFile", "secretRef", "user"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1CephFSVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1CephFSVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "monitors": obj.get("monitors"), + "path": obj.get("path"), + "readOnly": obj.get("readOnly"), + "secretFile": obj.get("secretFile"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "user": obj.get("user") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_cinder_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_cinder_volume_source.py new file mode 100644 index 0000000000..f20017194f --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_cinder_volume_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1CinderVolumeSource(BaseModel): + """ + Represents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", alias="fsType") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", alias="readOnly") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + volume_id: StrictStr = Field(description="volumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.md", alias="volumeID") + __properties: ClassVar[List[str]] = ["fsType", "readOnly", "secretRef", "volumeID"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1CinderVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1CinderVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "readOnly": obj.get("readOnly"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "volumeID": obj.get("volumeID") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_cluster_trust_bundle_projection.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_cluster_trust_bundle_projection.py new file mode 100644 index 0000000000..b287857390 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_cluster_trust_bundle_projection.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ClusterTrustBundleProjection(BaseModel): + """ + ClusterTrustBundleProjection describes how to select a set of ClusterTrustBundle objects and project their contents into the pod filesystem. + """ # noqa: E501 + label_selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = Field(default=None, alias="labelSelector") + name: Optional[StrictStr] = Field(default=None, description="Select a single ClusterTrustBundle by object name. Mutually-exclusive with signerName and labelSelector.") + optional: Optional[StrictBool] = Field(default=None, description="If true, don't block pod startup if the referenced ClusterTrustBundle(s) aren't available. If using name, then the named ClusterTrustBundle is allowed not to exist. If using signerName, then the combination of signerName and labelSelector is allowed to match zero ClusterTrustBundles.") + path: StrictStr = Field(description="Relative path from the volume root to write the bundle.") + signer_name: Optional[StrictStr] = Field(default=None, description="Select all ClusterTrustBundles that match this signer name. Mutually-exclusive with name. The contents of all selected ClusterTrustBundles will be unified and deduplicated.", alias="signerName") + __properties: ClassVar[List[str]] = ["labelSelector", "name", "optional", "path", "signerName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ClusterTrustBundleProjection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 label_selector + if self.label_selector: + _dict['labelSelector'] = self.label_selector.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ClusterTrustBundleProjection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "labelSelector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["labelSelector"]) if obj.get("labelSelector") is not None else None, + "name": obj.get("name"), + "optional": obj.get("optional"), + "path": obj.get("path"), + "signerName": obj.get("signerName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_env_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_env_source.py new file mode 100644 index 0000000000..ae5c1de9b5 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_env_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ConfigMapEnvSource(BaseModel): + """ + ConfigMapEnvSource selects a ConfigMap to populate the environment variables with. The contents of the target ConfigMap's Data field will represent the key-value pairs as environment variables. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="Specify whether the ConfigMap must be defined") + __properties: ClassVar[List[str]] = ["name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapEnvSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapEnvSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_key_selector.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_key_selector.py new file mode 100644 index 0000000000..873d37b232 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_key_selector.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ConfigMapKeySelector(BaseModel): + """ + Selects a key from a ConfigMap. + """ # noqa: E501 + key: StrictStr = Field(description="The key to select.") + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="Specify whether the ConfigMap or its key must be defined") + __properties: ClassVar[List[str]] = ["key", "name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapKeySelector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapKeySelector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_projection.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_projection.py new file mode 100644 index 0000000000..70b126429b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_projection.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_key_to_path import IoK8sApiCoreV1KeyToPath +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ConfigMapProjection(BaseModel): + """ + Adapts a ConfigMap into a projected volume. The contents of the target ConfigMap's Data field will be presented in a projected volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. Note that this is identical to a configmap volume source without the default mode. + """ # noqa: E501 + items: Optional[List[IoK8sApiCoreV1KeyToPath]] = Field(default=None, description="items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.") + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="optional specify whether the ConfigMap or its keys must be defined") + __properties: ClassVar[List[str]] = ["items", "name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapProjection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapProjection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "items": [IoK8sApiCoreV1KeyToPath.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_volume_source.py new file mode 100644 index 0000000000..50b20d86d0 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_config_map_volume_source.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_key_to_path import IoK8sApiCoreV1KeyToPath +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ConfigMapVolumeSource(BaseModel): + """ + Adapts a ConfigMap into a volume. The contents of the target ConfigMap's Data field will be presented in a volume as files using the keys in the Data field as the file names, unless the items element is populated with specific mappings of keys to paths. ConfigMap volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + default_mode: Optional[StrictInt] = Field(default=None, description="defaultMode is optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", alias="defaultMode") + items: Optional[List[IoK8sApiCoreV1KeyToPath]] = Field(default=None, description="items if unspecified, each key-value pair in the Data field of the referenced ConfigMap will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the ConfigMap, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.") + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="optional specify whether the ConfigMap or its keys must be defined") + __properties: ClassVar[List[str]] = ["defaultMode", "items", "name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ConfigMapVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "defaultMode": obj.get("defaultMode"), + "items": [IoK8sApiCoreV1KeyToPath.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container.py new file mode 100644 index 0000000000..e85d92cdc8 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container.py @@ -0,0 +1,203 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_container_port import IoK8sApiCoreV1ContainerPort +from kubeflow.trainer.models.io_k8s_api_core_v1_container_resize_policy import IoK8sApiCoreV1ContainerResizePolicy +from kubeflow.trainer.models.io_k8s_api_core_v1_env_from_source import IoK8sApiCoreV1EnvFromSource +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_lifecycle import IoK8sApiCoreV1Lifecycle +from kubeflow.trainer.models.io_k8s_api_core_v1_probe import IoK8sApiCoreV1Probe +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_requirements import IoK8sApiCoreV1ResourceRequirements +from kubeflow.trainer.models.io_k8s_api_core_v1_security_context import IoK8sApiCoreV1SecurityContext +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_device import IoK8sApiCoreV1VolumeDevice +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_mount import IoK8sApiCoreV1VolumeMount +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Container(BaseModel): + """ + A single application container that you want to run within a pod. + """ # noqa: E501 + args: Optional[List[StrictStr]] = Field(default=None, description="Arguments to the entrypoint. The container image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell") + command: Optional[List[StrictStr]] = Field(default=None, description="Entrypoint array. Not executed within a shell. The container image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell") + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the container. Cannot be updated.") + env_from: Optional[List[IoK8sApiCoreV1EnvFromSource]] = Field(default=None, description="List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", alias="envFrom") + image: Optional[StrictStr] = Field(default=None, description="Container image name. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.") + image_pull_policy: Optional[StrictStr] = Field(default=None, description="Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images", alias="imagePullPolicy") + lifecycle: Optional[IoK8sApiCoreV1Lifecycle] = None + liveness_probe: Optional[IoK8sApiCoreV1Probe] = Field(default=None, alias="livenessProbe") + name: StrictStr = Field(description="Name of the container specified as a DNS_LABEL. Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated.") + ports: Optional[List[IoK8sApiCoreV1ContainerPort]] = Field(default=None, description="List of ports to expose from the container. Not specifying a port here DOES NOT prevent that port from being exposed. Any port which is listening on the default \"0.0.0.0\" address inside a container will be accessible from the network. Modifying this array with strategic merge patch may corrupt the data. For more information See https://github.com/kubernetes/kubernetes/issues/108255. Cannot be updated.") + readiness_probe: Optional[IoK8sApiCoreV1Probe] = Field(default=None, alias="readinessProbe") + resize_policy: Optional[List[IoK8sApiCoreV1ContainerResizePolicy]] = Field(default=None, description="Resources resize policy for the container.", alias="resizePolicy") + resources: Optional[IoK8sApiCoreV1ResourceRequirements] = None + restart_policy: Optional[StrictStr] = Field(default=None, description="RestartPolicy defines the restart behavior of individual containers in a pod. This field may only be set for init containers, and the only allowed value is \"Always\". For non-init containers or when this field is not specified, the restart behavior is defined by the Pod's restart policy and the container type. Setting the RestartPolicy as \"Always\" for the init container will have the following effect: this init container will be continually restarted on exit until all regular containers have terminated. Once all regular containers have completed, all init containers with restartPolicy \"Always\" will be shut down. This lifecycle differs from normal init containers and is often referred to as a \"sidecar\" container. Although this init container still starts in the init container sequence, it does not wait for the container to complete before proceeding to the next init container. Instead, the next init container starts immediately after this init container is started, or after any startupProbe has successfully completed.", alias="restartPolicy") + security_context: Optional[IoK8sApiCoreV1SecurityContext] = Field(default=None, alias="securityContext") + startup_probe: Optional[IoK8sApiCoreV1Probe] = Field(default=None, alias="startupProbe") + stdin: Optional[StrictBool] = Field(default=None, description="Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.") + stdin_once: Optional[StrictBool] = Field(default=None, description="Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", alias="stdinOnce") + termination_message_path: Optional[StrictStr] = Field(default=None, description="Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", alias="terminationMessagePath") + termination_message_policy: Optional[StrictStr] = Field(default=None, description="Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.", alias="terminationMessagePolicy") + tty: Optional[StrictBool] = Field(default=None, description="Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.") + volume_devices: Optional[List[IoK8sApiCoreV1VolumeDevice]] = Field(default=None, description="volumeDevices is the list of block devices to be used by the container.", alias="volumeDevices") + volume_mounts: Optional[List[IoK8sApiCoreV1VolumeMount]] = Field(default=None, description="Pod volumes to mount into the container's filesystem. Cannot be updated.", alias="volumeMounts") + working_dir: Optional[StrictStr] = Field(default=None, description="Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", alias="workingDir") + __properties: ClassVar[List[str]] = ["args", "command", "env", "envFrom", "image", "imagePullPolicy", "lifecycle", "livenessProbe", "name", "ports", "readinessProbe", "resizePolicy", "resources", "restartPolicy", "securityContext", "startupProbe", "stdin", "stdinOnce", "terminationMessagePath", "terminationMessagePolicy", "tty", "volumeDevices", "volumeMounts", "workingDir"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Container from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in env_from (list) + _items = [] + if self.env_from: + for _item_env_from in self.env_from: + if _item_env_from: + _items.append(_item_env_from.to_dict()) + _dict['envFrom'] = _items + # override the default output from pydantic by calling `to_dict()` of lifecycle + if self.lifecycle: + _dict['lifecycle'] = self.lifecycle.to_dict() + # override the default output from pydantic by calling `to_dict()` of liveness_probe + if self.liveness_probe: + _dict['livenessProbe'] = self.liveness_probe.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in ports (list) + _items = [] + if self.ports: + for _item_ports in self.ports: + if _item_ports: + _items.append(_item_ports.to_dict()) + _dict['ports'] = _items + # override the default output from pydantic by calling `to_dict()` of readiness_probe + if self.readiness_probe: + _dict['readinessProbe'] = self.readiness_probe.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in resize_policy (list) + _items = [] + if self.resize_policy: + for _item_resize_policy in self.resize_policy: + if _item_resize_policy: + _items.append(_item_resize_policy.to_dict()) + _dict['resizePolicy'] = _items + # override the default output from pydantic by calling `to_dict()` of resources + if self.resources: + _dict['resources'] = self.resources.to_dict() + # override the default output from pydantic by calling `to_dict()` of security_context + if self.security_context: + _dict['securityContext'] = self.security_context.to_dict() + # override the default output from pydantic by calling `to_dict()` of startup_probe + if self.startup_probe: + _dict['startupProbe'] = self.startup_probe.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in volume_devices (list) + _items = [] + if self.volume_devices: + for _item_volume_devices in self.volume_devices: + if _item_volume_devices: + _items.append(_item_volume_devices.to_dict()) + _dict['volumeDevices'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in volume_mounts (list) + _items = [] + if self.volume_mounts: + for _item_volume_mounts in self.volume_mounts: + if _item_volume_mounts: + _items.append(_item_volume_mounts.to_dict()) + _dict['volumeMounts'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Container from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "args": obj.get("args"), + "command": obj.get("command"), + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "envFrom": [IoK8sApiCoreV1EnvFromSource.from_dict(_item) for _item in obj["envFrom"]] if obj.get("envFrom") is not None else None, + "image": obj.get("image"), + "imagePullPolicy": obj.get("imagePullPolicy"), + "lifecycle": IoK8sApiCoreV1Lifecycle.from_dict(obj["lifecycle"]) if obj.get("lifecycle") is not None else None, + "livenessProbe": IoK8sApiCoreV1Probe.from_dict(obj["livenessProbe"]) if obj.get("livenessProbe") is not None else None, + "name": obj.get("name"), + "ports": [IoK8sApiCoreV1ContainerPort.from_dict(_item) for _item in obj["ports"]] if obj.get("ports") is not None else None, + "readinessProbe": IoK8sApiCoreV1Probe.from_dict(obj["readinessProbe"]) if obj.get("readinessProbe") is not None else None, + "resizePolicy": [IoK8sApiCoreV1ContainerResizePolicy.from_dict(_item) for _item in obj["resizePolicy"]] if obj.get("resizePolicy") is not None else None, + "resources": IoK8sApiCoreV1ResourceRequirements.from_dict(obj["resources"]) if obj.get("resources") is not None else None, + "restartPolicy": obj.get("restartPolicy"), + "securityContext": IoK8sApiCoreV1SecurityContext.from_dict(obj["securityContext"]) if obj.get("securityContext") is not None else None, + "startupProbe": IoK8sApiCoreV1Probe.from_dict(obj["startupProbe"]) if obj.get("startupProbe") is not None else None, + "stdin": obj.get("stdin"), + "stdinOnce": obj.get("stdinOnce"), + "terminationMessagePath": obj.get("terminationMessagePath"), + "terminationMessagePolicy": obj.get("terminationMessagePolicy"), + "tty": obj.get("tty"), + "volumeDevices": [IoK8sApiCoreV1VolumeDevice.from_dict(_item) for _item in obj["volumeDevices"]] if obj.get("volumeDevices") is not None else None, + "volumeMounts": [IoK8sApiCoreV1VolumeMount.from_dict(_item) for _item in obj["volumeMounts"]] if obj.get("volumeMounts") is not None else None, + "workingDir": obj.get("workingDir") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container_port.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container_port.py new file mode 100644 index 0000000000..0faba4c9cf --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container_port.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ContainerPort(BaseModel): + """ + ContainerPort represents a network port in a single container. + """ # noqa: E501 + container_port: StrictInt = Field(description="Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.", alias="containerPort") + host_ip: Optional[StrictStr] = Field(default=None, description="What host IP to bind the external port to.", alias="hostIP") + host_port: Optional[StrictInt] = Field(default=None, description="Number of port to expose on the host. If specified, this must be a valid port number, 0 < x < 65536. If HostNetwork is specified, this must match ContainerPort. Most containers do not need this.", alias="hostPort") + name: Optional[StrictStr] = Field(default=None, description="If specified, this must be an IANA_SVC_NAME and unique within the pod. Each named port in a pod must have a unique name. Name for the port that can be referred to by services.") + protocol: Optional[StrictStr] = Field(default=None, description="Protocol for port. Must be UDP, TCP, or SCTP. Defaults to \"TCP\".") + __properties: ClassVar[List[str]] = ["containerPort", "hostIP", "hostPort", "name", "protocol"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ContainerPort from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ContainerPort from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "containerPort": obj.get("containerPort"), + "hostIP": obj.get("hostIP"), + "hostPort": obj.get("hostPort"), + "name": obj.get("name"), + "protocol": obj.get("protocol") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container_resize_policy.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container_resize_policy.py new file mode 100644 index 0000000000..74f126fdad --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_container_resize_policy.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ContainerResizePolicy(BaseModel): + """ + ContainerResizePolicy represents resource resize policy for the container. + """ # noqa: E501 + resource_name: StrictStr = Field(description="Name of the resource to which this resource resize policy applies. Supported values: cpu, memory.", alias="resourceName") + restart_policy: StrictStr = Field(description="Restart policy to apply when specified resource is resized. If not specified, it defaults to NotRequired.", alias="restartPolicy") + __properties: ClassVar[List[str]] = ["resourceName", "restartPolicy"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ContainerResizePolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ContainerResizePolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "resourceName": obj.get("resourceName"), + "restartPolicy": obj.get("restartPolicy") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_csi_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_csi_volume_source.py new file mode 100644 index 0000000000..2eb100bbe6 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_csi_volume_source.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1CSIVolumeSource(BaseModel): + """ + Represents a source location of a volume to mount, managed by an external CSI driver + """ # noqa: E501 + driver: StrictStr = Field(description="driver is the name of the CSI driver that handles this volume. Consult with your admin for the correct name as registered in the cluster.") + fs_type: Optional[StrictStr] = Field(default=None, description="fsType to mount. Ex. \"ext4\", \"xfs\", \"ntfs\". If not provided, the empty value is passed to the associated CSI driver which will determine the default filesystem to apply.", alias="fsType") + node_publish_secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="nodePublishSecretRef") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly specifies a read-only configuration for the volume. Defaults to false (read/write).", alias="readOnly") + volume_attributes: Optional[Dict[str, StrictStr]] = Field(default=None, description="volumeAttributes stores driver-specific properties that are passed to the CSI driver. Consult your driver's documentation for supported values.", alias="volumeAttributes") + __properties: ClassVar[List[str]] = ["driver", "fsType", "nodePublishSecretRef", "readOnly", "volumeAttributes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1CSIVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 node_publish_secret_ref + if self.node_publish_secret_ref: + _dict['nodePublishSecretRef'] = self.node_publish_secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1CSIVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "driver": obj.get("driver"), + "fsType": obj.get("fsType"), + "nodePublishSecretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["nodePublishSecretRef"]) if obj.get("nodePublishSecretRef") is not None else None, + "readOnly": obj.get("readOnly"), + "volumeAttributes": obj.get("volumeAttributes") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_projection.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_projection.py new file mode 100644 index 0000000000..0ba79f41b5 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_projection.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_volume_file import IoK8sApiCoreV1DownwardAPIVolumeFile +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1DownwardAPIProjection(BaseModel): + """ + Represents downward API info for projecting into a projected volume. Note that this is identical to a downwardAPI volume source without the default mode. + """ # noqa: E501 + items: Optional[List[IoK8sApiCoreV1DownwardAPIVolumeFile]] = Field(default=None, description="Items is a list of DownwardAPIVolume file") + __properties: ClassVar[List[str]] = ["items"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1DownwardAPIProjection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1DownwardAPIProjection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "items": [IoK8sApiCoreV1DownwardAPIVolumeFile.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_volume_file.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_volume_file.py new file mode 100644 index 0000000000..1f16876cf7 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_volume_file.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_object_field_selector import IoK8sApiCoreV1ObjectFieldSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_field_selector import IoK8sApiCoreV1ResourceFieldSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1DownwardAPIVolumeFile(BaseModel): + """ + DownwardAPIVolumeFile represents information to create the file containing the pod field + """ # noqa: E501 + field_ref: Optional[IoK8sApiCoreV1ObjectFieldSelector] = Field(default=None, alias="fieldRef") + mode: Optional[StrictInt] = Field(default=None, description="Optional: mode bits used to set permissions on this file, must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.") + path: StrictStr = Field(description="Required: Path is the relative path name of the file to be created. Must not be absolute or contain the '..' path. Must be utf-8 encoded. The first item of the relative path must not start with '..'") + resource_field_ref: Optional[IoK8sApiCoreV1ResourceFieldSelector] = Field(default=None, alias="resourceFieldRef") + __properties: ClassVar[List[str]] = ["fieldRef", "mode", "path", "resourceFieldRef"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1DownwardAPIVolumeFile from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 field_ref + if self.field_ref: + _dict['fieldRef'] = self.field_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of resource_field_ref + if self.resource_field_ref: + _dict['resourceFieldRef'] = self.resource_field_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1DownwardAPIVolumeFile from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fieldRef": IoK8sApiCoreV1ObjectFieldSelector.from_dict(obj["fieldRef"]) if obj.get("fieldRef") is not None else None, + "mode": obj.get("mode"), + "path": obj.get("path"), + "resourceFieldRef": IoK8sApiCoreV1ResourceFieldSelector.from_dict(obj["resourceFieldRef"]) if obj.get("resourceFieldRef") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_volume_source.py new file mode 100644 index 0000000000..2e6b20ef24 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_downward_api_volume_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_volume_file import IoK8sApiCoreV1DownwardAPIVolumeFile +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1DownwardAPIVolumeSource(BaseModel): + """ + DownwardAPIVolumeSource represents a volume containing downward API info. Downward API volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + default_mode: Optional[StrictInt] = Field(default=None, description="Optional: mode bits to use on created files by default. Must be a Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", alias="defaultMode") + items: Optional[List[IoK8sApiCoreV1DownwardAPIVolumeFile]] = Field(default=None, description="Items is a list of downward API volume file") + __properties: ClassVar[List[str]] = ["defaultMode", "items"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1DownwardAPIVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1DownwardAPIVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "defaultMode": obj.get("defaultMode"), + "items": [IoK8sApiCoreV1DownwardAPIVolumeFile.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_empty_dir_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_empty_dir_volume_source.py new file mode 100644 index 0000000000..e4361c1264 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_empty_dir_volume_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1EmptyDirVolumeSource(BaseModel): + """ + Represents an empty directory for a pod. Empty directory volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + medium: Optional[StrictStr] = Field(default=None, description="medium represents what type of storage medium should back this directory. The default is \"\" which means to use the node's default medium. Must be an empty string (default) or Memory. More info: https://kubernetes.io/docs/concepts/storage/volumes#emptydir") + size_limit: Optional[StrictStr] = Field(default=None, description="Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors. The serialization format is: ``` ::= (Note that may be empty, from the \"\" case in .) ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html) ::= m | \"\" | k | M | G | T | P | E (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.) ::= \"e\" | \"E\" ``` No matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities. When a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized. Before serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that: - No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible. The sign will be omitted unless the number is negative. Examples: - 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\" Note that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise. Non-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.) This format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.", alias="sizeLimit") + __properties: ClassVar[List[str]] = ["medium", "sizeLimit"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EmptyDirVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EmptyDirVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "medium": obj.get("medium"), + "sizeLimit": obj.get("sizeLimit") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_from_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_from_source.py new file mode 100644 index 0000000000..55fabef35d --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_from_source.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_env_source import IoK8sApiCoreV1ConfigMapEnvSource +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_env_source import IoK8sApiCoreV1SecretEnvSource +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1EnvFromSource(BaseModel): + """ + EnvFromSource represents the source of a set of ConfigMaps + """ # noqa: E501 + config_map_ref: Optional[IoK8sApiCoreV1ConfigMapEnvSource] = Field(default=None, alias="configMapRef") + prefix: Optional[StrictStr] = Field(default=None, description="An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER.") + secret_ref: Optional[IoK8sApiCoreV1SecretEnvSource] = Field(default=None, alias="secretRef") + __properties: ClassVar[List[str]] = ["configMapRef", "prefix", "secretRef"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EnvFromSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 config_map_ref + if self.config_map_ref: + _dict['configMapRef'] = self.config_map_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EnvFromSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "configMapRef": IoK8sApiCoreV1ConfigMapEnvSource.from_dict(obj["configMapRef"]) if obj.get("configMapRef") is not None else None, + "prefix": obj.get("prefix"), + "secretRef": IoK8sApiCoreV1SecretEnvSource.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_var.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_var.py new file mode 100644 index 0000000000..acfc606bc9 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_var.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var_source import IoK8sApiCoreV1EnvVarSource +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1EnvVar(BaseModel): + """ + EnvVar represents an environment variable present in a Container. + """ # noqa: E501 + name: StrictStr = Field(description="Name of the environment variable. Must be a C_IDENTIFIER.") + value: Optional[StrictStr] = Field(default=None, description="Variable references $(VAR_NAME) are expanded using the previously defined environment variables in the container and any service environment variables. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Defaults to \"\".") + value_from: Optional[IoK8sApiCoreV1EnvVarSource] = Field(default=None, alias="valueFrom") + __properties: ClassVar[List[str]] = ["name", "value", "valueFrom"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EnvVar from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 value_from + if self.value_from: + _dict['valueFrom'] = self.value_from.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EnvVar from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "value": obj.get("value"), + "valueFrom": IoK8sApiCoreV1EnvVarSource.from_dict(obj["valueFrom"]) if obj.get("valueFrom") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_var_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_var_source.py new file mode 100644 index 0000000000..c75065aa97 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_env_var_source.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_key_selector import IoK8sApiCoreV1ConfigMapKeySelector +from kubeflow.trainer.models.io_k8s_api_core_v1_object_field_selector import IoK8sApiCoreV1ObjectFieldSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_field_selector import IoK8sApiCoreV1ResourceFieldSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_key_selector import IoK8sApiCoreV1SecretKeySelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1EnvVarSource(BaseModel): + """ + EnvVarSource represents a source for the value of an EnvVar. + """ # noqa: E501 + config_map_key_ref: Optional[IoK8sApiCoreV1ConfigMapKeySelector] = Field(default=None, alias="configMapKeyRef") + field_ref: Optional[IoK8sApiCoreV1ObjectFieldSelector] = Field(default=None, alias="fieldRef") + resource_field_ref: Optional[IoK8sApiCoreV1ResourceFieldSelector] = Field(default=None, alias="resourceFieldRef") + secret_key_ref: Optional[IoK8sApiCoreV1SecretKeySelector] = Field(default=None, alias="secretKeyRef") + __properties: ClassVar[List[str]] = ["configMapKeyRef", "fieldRef", "resourceFieldRef", "secretKeyRef"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EnvVarSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 config_map_key_ref + if self.config_map_key_ref: + _dict['configMapKeyRef'] = self.config_map_key_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of field_ref + if self.field_ref: + _dict['fieldRef'] = self.field_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of resource_field_ref + if self.resource_field_ref: + _dict['resourceFieldRef'] = self.resource_field_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of secret_key_ref + if self.secret_key_ref: + _dict['secretKeyRef'] = self.secret_key_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EnvVarSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "configMapKeyRef": IoK8sApiCoreV1ConfigMapKeySelector.from_dict(obj["configMapKeyRef"]) if obj.get("configMapKeyRef") is not None else None, + "fieldRef": IoK8sApiCoreV1ObjectFieldSelector.from_dict(obj["fieldRef"]) if obj.get("fieldRef") is not None else None, + "resourceFieldRef": IoK8sApiCoreV1ResourceFieldSelector.from_dict(obj["resourceFieldRef"]) if obj.get("resourceFieldRef") is not None else None, + "secretKeyRef": IoK8sApiCoreV1SecretKeySelector.from_dict(obj["secretKeyRef"]) if obj.get("secretKeyRef") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ephemeral_container.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ephemeral_container.py new file mode 100644 index 0000000000..c20f3c917d --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ephemeral_container.py @@ -0,0 +1,205 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_container_port import IoK8sApiCoreV1ContainerPort +from kubeflow.trainer.models.io_k8s_api_core_v1_container_resize_policy import IoK8sApiCoreV1ContainerResizePolicy +from kubeflow.trainer.models.io_k8s_api_core_v1_env_from_source import IoK8sApiCoreV1EnvFromSource +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_lifecycle import IoK8sApiCoreV1Lifecycle +from kubeflow.trainer.models.io_k8s_api_core_v1_probe import IoK8sApiCoreV1Probe +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_requirements import IoK8sApiCoreV1ResourceRequirements +from kubeflow.trainer.models.io_k8s_api_core_v1_security_context import IoK8sApiCoreV1SecurityContext +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_device import IoK8sApiCoreV1VolumeDevice +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_mount import IoK8sApiCoreV1VolumeMount +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1EphemeralContainer(BaseModel): + """ + An EphemeralContainer is a temporary container that you may add to an existing Pod for user-initiated activities such as debugging. Ephemeral containers have no resource or scheduling guarantees, and they will not be restarted when they exit or when a Pod is removed or restarted. The kubelet may evict a Pod if an ephemeral container causes the Pod to exceed its resource allocation. To add an ephemeral container, use the ephemeralcontainers subresource of an existing Pod. Ephemeral containers may not be removed or restarted. + """ # noqa: E501 + args: Optional[List[StrictStr]] = Field(default=None, description="Arguments to the entrypoint. The image's CMD is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell") + command: Optional[List[StrictStr]] = Field(default=None, description="Entrypoint array. Not executed within a shell. The image's ENTRYPOINT is used if this is not provided. Variable references $(VAR_NAME) are expanded using the container's environment. If a variable cannot be resolved, the reference in the input string will be unchanged. Double $$ are reduced to a single $, which allows for escaping the $(VAR_NAME) syntax: i.e. \"$$(VAR_NAME)\" will produce the string literal \"$(VAR_NAME)\". Escaped references will never be expanded, regardless of whether the variable exists or not. Cannot be updated. More info: https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell") + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the container. Cannot be updated.") + env_from: Optional[List[IoK8sApiCoreV1EnvFromSource]] = Field(default=None, description="List of sources to populate environment variables in the container. The keys defined within a source must be a C_IDENTIFIER. All invalid keys will be reported as an event when the container is starting. When a key exists in multiple sources, the value associated with the last source will take precedence. Values defined by an Env with a duplicate key will take precedence. Cannot be updated.", alias="envFrom") + image: Optional[StrictStr] = Field(default=None, description="Container image name. More info: https://kubernetes.io/docs/concepts/containers/images") + image_pull_policy: Optional[StrictStr] = Field(default=None, description="Image pull policy. One of Always, Never, IfNotPresent. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise. Cannot be updated. More info: https://kubernetes.io/docs/concepts/containers/images#updating-images", alias="imagePullPolicy") + lifecycle: Optional[IoK8sApiCoreV1Lifecycle] = None + liveness_probe: Optional[IoK8sApiCoreV1Probe] = Field(default=None, alias="livenessProbe") + name: StrictStr = Field(description="Name of the ephemeral container specified as a DNS_LABEL. This name must be unique among all containers, init containers and ephemeral containers.") + ports: Optional[List[IoK8sApiCoreV1ContainerPort]] = Field(default=None, description="Ports are not allowed for ephemeral containers.") + readiness_probe: Optional[IoK8sApiCoreV1Probe] = Field(default=None, alias="readinessProbe") + resize_policy: Optional[List[IoK8sApiCoreV1ContainerResizePolicy]] = Field(default=None, description="Resources resize policy for the container.", alias="resizePolicy") + resources: Optional[IoK8sApiCoreV1ResourceRequirements] = None + restart_policy: Optional[StrictStr] = Field(default=None, description="Restart policy for the container to manage the restart behavior of each container within a pod. This may only be set for init containers. You cannot set this field on ephemeral containers.", alias="restartPolicy") + security_context: Optional[IoK8sApiCoreV1SecurityContext] = Field(default=None, alias="securityContext") + startup_probe: Optional[IoK8sApiCoreV1Probe] = Field(default=None, alias="startupProbe") + stdin: Optional[StrictBool] = Field(default=None, description="Whether this container should allocate a buffer for stdin in the container runtime. If this is not set, reads from stdin in the container will always result in EOF. Default is false.") + stdin_once: Optional[StrictBool] = Field(default=None, description="Whether the container runtime should close the stdin channel after it has been opened by a single attach. When stdin is true the stdin stream will remain open across multiple attach sessions. If stdinOnce is set to true, stdin is opened on container start, is empty until the first client attaches to stdin, and then remains open and accepts data until the client disconnects, at which time stdin is closed and remains closed until the container is restarted. If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false", alias="stdinOnce") + target_container_name: Optional[StrictStr] = Field(default=None, description="If set, the name of the container from PodSpec that this ephemeral container targets. The ephemeral container will be run in the namespaces (IPC, PID, etc) of this container. If not set then the ephemeral container uses the namespaces configured in the Pod spec. The container runtime must implement support for this feature. If the runtime does not support namespace targeting then the result of setting this field is undefined.", alias="targetContainerName") + termination_message_path: Optional[StrictStr] = Field(default=None, description="Optional: Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. Message written is intended to be brief final status, such as an assertion failure message. Will be truncated by the node if greater than 4096 bytes. The total message length across all containers will be limited to 12kb. Defaults to /dev/termination-log. Cannot be updated.", alias="terminationMessagePath") + termination_message_policy: Optional[StrictStr] = Field(default=None, description="Indicate how the termination message should be populated. File will use the contents of terminationMessagePath to populate the container status message on both success and failure. FallbackToLogsOnError will use the last chunk of container log output if the termination message file is empty and the container exited with an error. The log output is limited to 2048 bytes or 80 lines, whichever is smaller. Defaults to File. Cannot be updated.", alias="terminationMessagePolicy") + tty: Optional[StrictBool] = Field(default=None, description="Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. Default is false.") + volume_devices: Optional[List[IoK8sApiCoreV1VolumeDevice]] = Field(default=None, description="volumeDevices is the list of block devices to be used by the container.", alias="volumeDevices") + volume_mounts: Optional[List[IoK8sApiCoreV1VolumeMount]] = Field(default=None, description="Pod volumes to mount into the container's filesystem. Subpath mounts are not allowed for ephemeral containers. Cannot be updated.", alias="volumeMounts") + working_dir: Optional[StrictStr] = Field(default=None, description="Container's working directory. If not specified, the container runtime's default will be used, which might be configured in the container image. Cannot be updated.", alias="workingDir") + __properties: ClassVar[List[str]] = ["args", "command", "env", "envFrom", "image", "imagePullPolicy", "lifecycle", "livenessProbe", "name", "ports", "readinessProbe", "resizePolicy", "resources", "restartPolicy", "securityContext", "startupProbe", "stdin", "stdinOnce", "targetContainerName", "terminationMessagePath", "terminationMessagePolicy", "tty", "volumeDevices", "volumeMounts", "workingDir"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EphemeralContainer from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in env_from (list) + _items = [] + if self.env_from: + for _item_env_from in self.env_from: + if _item_env_from: + _items.append(_item_env_from.to_dict()) + _dict['envFrom'] = _items + # override the default output from pydantic by calling `to_dict()` of lifecycle + if self.lifecycle: + _dict['lifecycle'] = self.lifecycle.to_dict() + # override the default output from pydantic by calling `to_dict()` of liveness_probe + if self.liveness_probe: + _dict['livenessProbe'] = self.liveness_probe.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in ports (list) + _items = [] + if self.ports: + for _item_ports in self.ports: + if _item_ports: + _items.append(_item_ports.to_dict()) + _dict['ports'] = _items + # override the default output from pydantic by calling `to_dict()` of readiness_probe + if self.readiness_probe: + _dict['readinessProbe'] = self.readiness_probe.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in resize_policy (list) + _items = [] + if self.resize_policy: + for _item_resize_policy in self.resize_policy: + if _item_resize_policy: + _items.append(_item_resize_policy.to_dict()) + _dict['resizePolicy'] = _items + # override the default output from pydantic by calling `to_dict()` of resources + if self.resources: + _dict['resources'] = self.resources.to_dict() + # override the default output from pydantic by calling `to_dict()` of security_context + if self.security_context: + _dict['securityContext'] = self.security_context.to_dict() + # override the default output from pydantic by calling `to_dict()` of startup_probe + if self.startup_probe: + _dict['startupProbe'] = self.startup_probe.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in volume_devices (list) + _items = [] + if self.volume_devices: + for _item_volume_devices in self.volume_devices: + if _item_volume_devices: + _items.append(_item_volume_devices.to_dict()) + _dict['volumeDevices'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in volume_mounts (list) + _items = [] + if self.volume_mounts: + for _item_volume_mounts in self.volume_mounts: + if _item_volume_mounts: + _items.append(_item_volume_mounts.to_dict()) + _dict['volumeMounts'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EphemeralContainer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "args": obj.get("args"), + "command": obj.get("command"), + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "envFrom": [IoK8sApiCoreV1EnvFromSource.from_dict(_item) for _item in obj["envFrom"]] if obj.get("envFrom") is not None else None, + "image": obj.get("image"), + "imagePullPolicy": obj.get("imagePullPolicy"), + "lifecycle": IoK8sApiCoreV1Lifecycle.from_dict(obj["lifecycle"]) if obj.get("lifecycle") is not None else None, + "livenessProbe": IoK8sApiCoreV1Probe.from_dict(obj["livenessProbe"]) if obj.get("livenessProbe") is not None else None, + "name": obj.get("name"), + "ports": [IoK8sApiCoreV1ContainerPort.from_dict(_item) for _item in obj["ports"]] if obj.get("ports") is not None else None, + "readinessProbe": IoK8sApiCoreV1Probe.from_dict(obj["readinessProbe"]) if obj.get("readinessProbe") is not None else None, + "resizePolicy": [IoK8sApiCoreV1ContainerResizePolicy.from_dict(_item) for _item in obj["resizePolicy"]] if obj.get("resizePolicy") is not None else None, + "resources": IoK8sApiCoreV1ResourceRequirements.from_dict(obj["resources"]) if obj.get("resources") is not None else None, + "restartPolicy": obj.get("restartPolicy"), + "securityContext": IoK8sApiCoreV1SecurityContext.from_dict(obj["securityContext"]) if obj.get("securityContext") is not None else None, + "startupProbe": IoK8sApiCoreV1Probe.from_dict(obj["startupProbe"]) if obj.get("startupProbe") is not None else None, + "stdin": obj.get("stdin"), + "stdinOnce": obj.get("stdinOnce"), + "targetContainerName": obj.get("targetContainerName"), + "terminationMessagePath": obj.get("terminationMessagePath"), + "terminationMessagePolicy": obj.get("terminationMessagePolicy"), + "tty": obj.get("tty"), + "volumeDevices": [IoK8sApiCoreV1VolumeDevice.from_dict(_item) for _item in obj["volumeDevices"]] if obj.get("volumeDevices") is not None else None, + "volumeMounts": [IoK8sApiCoreV1VolumeMount.from_dict(_item) for _item in obj["volumeMounts"]] if obj.get("volumeMounts") is not None else None, + "workingDir": obj.get("workingDir") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ephemeral_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ephemeral_volume_source.py new file mode 100644 index 0000000000..07ab9ac564 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_ephemeral_volume_source.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_persistent_volume_claim_template import IoK8sApiCoreV1PersistentVolumeClaimTemplate +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1EphemeralVolumeSource(BaseModel): + """ + Represents an ephemeral volume that is handled by a normal storage driver. + """ # noqa: E501 + volume_claim_template: Optional[IoK8sApiCoreV1PersistentVolumeClaimTemplate] = Field(default=None, alias="volumeClaimTemplate") + __properties: ClassVar[List[str]] = ["volumeClaimTemplate"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EphemeralVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 volume_claim_template + if self.volume_claim_template: + _dict['volumeClaimTemplate'] = self.volume_claim_template.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1EphemeralVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "volumeClaimTemplate": IoK8sApiCoreV1PersistentVolumeClaimTemplate.from_dict(obj["volumeClaimTemplate"]) if obj.get("volumeClaimTemplate") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_exec_action.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_exec_action.py new file mode 100644 index 0000000000..5a2c50fa0b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_exec_action.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ExecAction(BaseModel): + """ + ExecAction describes a \"run in container\" action. + """ # noqa: E501 + command: Optional[List[StrictStr]] = Field(default=None, description="Command is the command line to execute inside the container, the working directory for the command is root ('/') in the container's filesystem. The command is simply exec'd, it is not run inside a shell, so traditional shell instructions ('|', etc) won't work. To use a shell, you need to explicitly call out to that shell. Exit status of 0 is treated as live/healthy and non-zero is unhealthy.") + __properties: ClassVar[List[str]] = ["command"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ExecAction from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ExecAction from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "command": obj.get("command") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_fc_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_fc_volume_source.py new file mode 100644 index 0000000000..8d2003999e --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_fc_volume_source.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1FCVolumeSource(BaseModel): + """ + Represents a Fibre Channel volume. Fibre Channel volumes can only be mounted as read/write once. Fibre Channel volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", alias="fsType") + lun: Optional[StrictInt] = Field(default=None, description="lun is Optional: FC target lun number") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + target_wwns: Optional[List[StrictStr]] = Field(default=None, description="targetWWNs is Optional: FC target worldwide names (WWNs)", alias="targetWWNs") + wwids: Optional[List[StrictStr]] = Field(default=None, description="wwids Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.") + __properties: ClassVar[List[str]] = ["fsType", "lun", "readOnly", "targetWWNs", "wwids"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1FCVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1FCVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "lun": obj.get("lun"), + "readOnly": obj.get("readOnly"), + "targetWWNs": obj.get("targetWWNs"), + "wwids": obj.get("wwids") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_flex_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_flex_volume_source.py new file mode 100644 index 0000000000..377841e40d --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_flex_volume_source.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1FlexVolumeSource(BaseModel): + """ + FlexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. + """ # noqa: E501 + driver: StrictStr = Field(description="driver is the name of the driver to use for this volume.") + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". The default filesystem depends on FlexVolume script.", alias="fsType") + options: Optional[Dict[str, StrictStr]] = Field(default=None, description="options is Optional: this field holds extra command options if any.") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly is Optional: defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + __properties: ClassVar[List[str]] = ["driver", "fsType", "options", "readOnly", "secretRef"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1FlexVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1FlexVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "driver": obj.get("driver"), + "fsType": obj.get("fsType"), + "options": obj.get("options"), + "readOnly": obj.get("readOnly"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_flocker_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_flocker_volume_source.py new file mode 100644 index 0000000000..7d29944ca8 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_flocker_volume_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1FlockerVolumeSource(BaseModel): + """ + Represents a Flocker volume mounted by the Flocker agent. One and only one of datasetName and datasetUUID should be set. Flocker volumes do not support ownership management or SELinux relabeling. + """ # noqa: E501 + dataset_name: Optional[StrictStr] = Field(default=None, description="datasetName is Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecated", alias="datasetName") + dataset_uuid: Optional[StrictStr] = Field(default=None, description="datasetUUID is the UUID of the dataset. This is unique identifier of a Flocker dataset", alias="datasetUUID") + __properties: ClassVar[List[str]] = ["datasetName", "datasetUUID"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1FlockerVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1FlockerVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "datasetName": obj.get("datasetName"), + "datasetUUID": obj.get("datasetUUID") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_gce_persistent_disk_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_gce_persistent_disk_volume_source.py new file mode 100644 index 0000000000..285140c403 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_gce_persistent_disk_volume_source.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1GCEPersistentDiskVolumeSource(BaseModel): + """ + Represents a Persistent Disk resource in Google Compute Engine. A GCE PD must exist before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once or read-only many times. GCE PDs support ownership management and SELinux relabeling. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", alias="fsType") + partition: Optional[StrictInt] = Field(default=None, description="partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as \"1\". Similarly, the volume partition for /dev/sda is \"0\" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk") + pd_name: StrictStr = Field(description="pdName is unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", alias="pdName") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk", alias="readOnly") + __properties: ClassVar[List[str]] = ["fsType", "partition", "pdName", "readOnly"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GCEPersistentDiskVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GCEPersistentDiskVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "partition": obj.get("partition"), + "pdName": obj.get("pdName"), + "readOnly": obj.get("readOnly") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_git_repo_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_git_repo_volume_source.py new file mode 100644 index 0000000000..4757e76296 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_git_repo_volume_source.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1GitRepoVolumeSource(BaseModel): + """ + Represents a volume that is populated with the contents of a git repository. Git repo volumes do not support ownership management. Git repo volumes support SELinux relabeling. DEPRECATED: GitRepo is deprecated. To provision a container with a git repo, mount an EmptyDir into an InitContainer that clones the repo using git, then mount the EmptyDir into the Pod's container. + """ # noqa: E501 + directory: Optional[StrictStr] = Field(default=None, description="directory is the target directory name. Must not contain or start with '..'. If '.' is supplied, the volume directory will be the git repository. Otherwise, if specified, the volume will contain the git repository in the subdirectory with the given name.") + repository: StrictStr = Field(description="repository is the URL") + revision: Optional[StrictStr] = Field(default=None, description="revision is the commit hash for the specified revision.") + __properties: ClassVar[List[str]] = ["directory", "repository", "revision"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GitRepoVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GitRepoVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "directory": obj.get("directory"), + "repository": obj.get("repository"), + "revision": obj.get("revision") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_glusterfs_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_glusterfs_volume_source.py new file mode 100644 index 0000000000..bdedbc5375 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_glusterfs_volume_source.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1GlusterfsVolumeSource(BaseModel): + """ + Represents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling. + """ # noqa: E501 + endpoints: StrictStr = Field(description="endpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod") + path: StrictStr = Field(description="path is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-pod", alias="readOnly") + __properties: ClassVar[List[str]] = ["endpoints", "path", "readOnly"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GlusterfsVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GlusterfsVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "endpoints": obj.get("endpoints"), + "path": obj.get("path"), + "readOnly": obj.get("readOnly") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_grpc_action.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_grpc_action.py new file mode 100644 index 0000000000..05227d7f41 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_grpc_action.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1GRPCAction(BaseModel): + """ + GRPCAction specifies an action involving a GRPC service. + """ # noqa: E501 + port: StrictInt = Field(description="Port number of the gRPC service. Number must be in the range 1 to 65535.") + service: Optional[StrictStr] = Field(default=None, description="Service is the name of the service to place in the gRPC HealthCheckRequest (see https://github.com/grpc/grpc/blob/master/doc/health-checking.md). If this is not specified, the default behavior is defined by gRPC.") + __properties: ClassVar[List[str]] = ["port", "service"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GRPCAction from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1GRPCAction from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "port": obj.get("port"), + "service": obj.get("service") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_host_alias.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_host_alias.py new file mode 100644 index 0000000000..df7071cffd --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_host_alias.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1HostAlias(BaseModel): + """ + HostAlias holds the mapping between IP and hostnames that will be injected as an entry in the pod's hosts file. + """ # noqa: E501 + hostnames: Optional[List[StrictStr]] = Field(default=None, description="Hostnames for the above IP address.") + ip: StrictStr = Field(description="IP address of the host file entry.") + __properties: ClassVar[List[str]] = ["hostnames", "ip"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HostAlias from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HostAlias from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "hostnames": obj.get("hostnames"), + "ip": obj.get("ip") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_host_path_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_host_path_volume_source.py new file mode 100644 index 0000000000..c2df5de0e5 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_host_path_volume_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1HostPathVolumeSource(BaseModel): + """ + Represents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling. + """ # noqa: E501 + path: StrictStr = Field(description="path of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath") + type: Optional[StrictStr] = Field(default=None, description="type for HostPath Volume Defaults to \"\" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpath") + __properties: ClassVar[List[str]] = ["path", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HostPathVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HostPathVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "path": obj.get("path"), + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_http_get_action.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_http_get_action.py new file mode 100644 index 0000000000..af2e45e435 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_http_get_action.py @@ -0,0 +1,103 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_http_header import IoK8sApiCoreV1HTTPHeader +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1HTTPGetAction(BaseModel): + """ + HTTPGetAction describes an action based on HTTP Get requests. + """ # noqa: E501 + host: Optional[StrictStr] = Field(default=None, description="Host name to connect to, defaults to the pod IP. You probably want to set \"Host\" in httpHeaders instead.") + http_headers: Optional[List[IoK8sApiCoreV1HTTPHeader]] = Field(default=None, description="Custom headers to set in the request. HTTP allows repeated headers.", alias="httpHeaders") + path: Optional[StrictStr] = Field(default=None, description="Path to access on the HTTP server.") + port: StrictStr = Field(description="IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.") + scheme: Optional[StrictStr] = Field(default=None, description="Scheme to use for connecting to the host. Defaults to HTTP.") + __properties: ClassVar[List[str]] = ["host", "httpHeaders", "path", "port", "scheme"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HTTPGetAction from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 http_headers (list) + _items = [] + if self.http_headers: + for _item_http_headers in self.http_headers: + if _item_http_headers: + _items.append(_item_http_headers.to_dict()) + _dict['httpHeaders'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HTTPGetAction from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "host": obj.get("host"), + "httpHeaders": [IoK8sApiCoreV1HTTPHeader.from_dict(_item) for _item in obj["httpHeaders"]] if obj.get("httpHeaders") is not None else None, + "path": obj.get("path"), + "port": obj.get("port"), + "scheme": obj.get("scheme") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_http_header.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_http_header.py new file mode 100644 index 0000000000..65927f959d --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_http_header.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1HTTPHeader(BaseModel): + """ + HTTPHeader describes a custom header to be used in HTTP probes + """ # noqa: E501 + name: StrictStr = Field(description="The header field name. This will be canonicalized upon output, so case-variant names will be understood as the same header.") + value: StrictStr = Field(description="The header field value") + __properties: ClassVar[List[str]] = ["name", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HTTPHeader from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1HTTPHeader from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "value": obj.get("value") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_image_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_image_volume_source.py new file mode 100644 index 0000000000..4a151d72e9 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_image_volume_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ImageVolumeSource(BaseModel): + """ + ImageVolumeSource represents a image volume resource. + """ # noqa: E501 + pull_policy: Optional[StrictStr] = Field(default=None, description="Policy for pulling OCI objects. Possible values are: Always: the kubelet always attempts to pull the reference. Container creation will fail If the pull fails. Never: the kubelet never pulls the reference and only uses a local image or artifact. Container creation will fail if the reference isn't present. IfNotPresent: the kubelet pulls if the reference isn't already present on disk. Container creation will fail if the reference isn't present and the pull fails. Defaults to Always if :latest tag is specified, or IfNotPresent otherwise.", alias="pullPolicy") + reference: Optional[StrictStr] = Field(default=None, description="Required: Image or artifact reference to be used. Behaves in the same way as pod.spec.containers[*].image. Pull secrets will be assembled in the same way as for the container image by looking up node credentials, SA image pull secrets, and pod spec image pull secrets. More info: https://kubernetes.io/docs/concepts/containers/images This field is optional to allow higher level config management to default or override container images in workload controllers like Deployments and StatefulSets.") + __properties: ClassVar[List[str]] = ["pullPolicy", "reference"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ImageVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ImageVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "pullPolicy": obj.get("pullPolicy"), + "reference": obj.get("reference") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_iscsi_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_iscsi_volume_source.py new file mode 100644 index 0000000000..2d025ea5df --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_iscsi_volume_source.py @@ -0,0 +1,111 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ISCSIVolumeSource(BaseModel): + """ + Represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + chap_auth_discovery: Optional[StrictBool] = Field(default=None, description="chapAuthDiscovery defines whether support iSCSI Discovery CHAP authentication", alias="chapAuthDiscovery") + chap_auth_session: Optional[StrictBool] = Field(default=None, description="chapAuthSession defines whether support iSCSI Session CHAP authentication", alias="chapAuthSession") + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsi", alias="fsType") + initiator_name: Optional[StrictStr] = Field(default=None, description="initiatorName is the custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface : will be created for the connection.", alias="initiatorName") + iqn: StrictStr = Field(description="iqn is the target iSCSI Qualified Name.") + iscsi_interface: Optional[StrictStr] = Field(default=None, description="iscsiInterface is the interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).", alias="iscsiInterface") + lun: StrictInt = Field(description="lun represents iSCSI Target Lun number.") + portals: Optional[List[StrictStr]] = Field(default=None, description="portals is the iSCSI Target Portal List. The portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.", alias="readOnly") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + target_portal: StrictStr = Field(description="targetPortal is iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).", alias="targetPortal") + __properties: ClassVar[List[str]] = ["chapAuthDiscovery", "chapAuthSession", "fsType", "initiatorName", "iqn", "iscsiInterface", "lun", "portals", "readOnly", "secretRef", "targetPortal"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ISCSIVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ISCSIVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "chapAuthDiscovery": obj.get("chapAuthDiscovery"), + "chapAuthSession": obj.get("chapAuthSession"), + "fsType": obj.get("fsType"), + "initiatorName": obj.get("initiatorName"), + "iqn": obj.get("iqn"), + "iscsiInterface": obj.get("iscsiInterface"), + "lun": obj.get("lun"), + "portals": obj.get("portals"), + "readOnly": obj.get("readOnly"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "targetPortal": obj.get("targetPortal") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_key_to_path.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_key_to_path.py new file mode 100644 index 0000000000..d3ab1b6948 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_key_to_path.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1KeyToPath(BaseModel): + """ + Maps a string key to a path within a volume. + """ # noqa: E501 + key: StrictStr = Field(description="key is the key to project.") + mode: Optional[StrictInt] = Field(default=None, description="mode is Optional: mode bits used to set permissions on this file. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. If not specified, the volume defaultMode will be used. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.") + path: StrictStr = Field(description="path is the relative path of the file to map the key to. May not be an absolute path. May not contain the path element '..'. May not start with the string '..'.") + __properties: ClassVar[List[str]] = ["key", "mode", "path"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1KeyToPath from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1KeyToPath from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "mode": obj.get("mode"), + "path": obj.get("path") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_lifecycle.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_lifecycle.py new file mode 100644 index 0000000000..5ff2e79876 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_lifecycle.py @@ -0,0 +1,96 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_lifecycle_handler import IoK8sApiCoreV1LifecycleHandler +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Lifecycle(BaseModel): + """ + Lifecycle describes actions that the management system should take in response to container lifecycle events. For the PostStart and PreStop lifecycle handlers, management of the container blocks until the action is complete, unless the container process fails, in which case the handler is aborted. + """ # noqa: E501 + post_start: Optional[IoK8sApiCoreV1LifecycleHandler] = Field(default=None, alias="postStart") + pre_stop: Optional[IoK8sApiCoreV1LifecycleHandler] = Field(default=None, alias="preStop") + __properties: ClassVar[List[str]] = ["postStart", "preStop"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Lifecycle from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 post_start + if self.post_start: + _dict['postStart'] = self.post_start.to_dict() + # override the default output from pydantic by calling `to_dict()` of pre_stop + if self.pre_stop: + _dict['preStop'] = self.pre_stop.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Lifecycle from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "postStart": IoK8sApiCoreV1LifecycleHandler.from_dict(obj["postStart"]) if obj.get("postStart") is not None else None, + "preStop": IoK8sApiCoreV1LifecycleHandler.from_dict(obj["preStop"]) if obj.get("preStop") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_lifecycle_handler.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_lifecycle_handler.py new file mode 100644 index 0000000000..ed7bc0ad7b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_lifecycle_handler.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_exec_action import IoK8sApiCoreV1ExecAction +from kubeflow.trainer.models.io_k8s_api_core_v1_http_get_action import IoK8sApiCoreV1HTTPGetAction +from kubeflow.trainer.models.io_k8s_api_core_v1_sleep_action import IoK8sApiCoreV1SleepAction +from kubeflow.trainer.models.io_k8s_api_core_v1_tcp_socket_action import IoK8sApiCoreV1TCPSocketAction +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1LifecycleHandler(BaseModel): + """ + LifecycleHandler defines a specific action that should be taken in a lifecycle hook. One and only one of the fields, except TCPSocket must be specified. + """ # noqa: E501 + var_exec: Optional[IoK8sApiCoreV1ExecAction] = Field(default=None, alias="exec") + http_get: Optional[IoK8sApiCoreV1HTTPGetAction] = Field(default=None, alias="httpGet") + sleep: Optional[IoK8sApiCoreV1SleepAction] = None + tcp_socket: Optional[IoK8sApiCoreV1TCPSocketAction] = Field(default=None, alias="tcpSocket") + __properties: ClassVar[List[str]] = ["exec", "httpGet", "sleep", "tcpSocket"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1LifecycleHandler from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 var_exec + if self.var_exec: + _dict['exec'] = self.var_exec.to_dict() + # override the default output from pydantic by calling `to_dict()` of http_get + if self.http_get: + _dict['httpGet'] = self.http_get.to_dict() + # override the default output from pydantic by calling `to_dict()` of sleep + if self.sleep: + _dict['sleep'] = self.sleep.to_dict() + # override the default output from pydantic by calling `to_dict()` of tcp_socket + if self.tcp_socket: + _dict['tcpSocket'] = self.tcp_socket.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1LifecycleHandler from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "exec": IoK8sApiCoreV1ExecAction.from_dict(obj["exec"]) if obj.get("exec") is not None else None, + "httpGet": IoK8sApiCoreV1HTTPGetAction.from_dict(obj["httpGet"]) if obj.get("httpGet") is not None else None, + "sleep": IoK8sApiCoreV1SleepAction.from_dict(obj["sleep"]) if obj.get("sleep") is not None else None, + "tcpSocket": IoK8sApiCoreV1TCPSocketAction.from_dict(obj["tcpSocket"]) if obj.get("tcpSocket") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_local_object_reference.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_local_object_reference.py new file mode 100644 index 0000000000..0a7add86cb --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_local_object_reference.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1LocalObjectReference(BaseModel): + """ + LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1LocalObjectReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1LocalObjectReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_nfs_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_nfs_volume_source.py new file mode 100644 index 0000000000..11fbdf0aa0 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_nfs_volume_source.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1NFSVolumeSource(BaseModel): + """ + Represents an NFS mount that lasts the lifetime of a pod. NFS volumes do not support ownership management or SELinux relabeling. + """ # noqa: E501 + path: StrictStr = Field(description="path that is exported by the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs", alias="readOnly") + server: StrictStr = Field(description="server is the hostname or IP address of the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfs") + __properties: ClassVar[List[str]] = ["path", "readOnly", "server"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NFSVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NFSVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "path": obj.get("path"), + "readOnly": obj.get("readOnly"), + "server": obj.get("server") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_affinity.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_affinity.py new file mode 100644 index 0000000000..683c2b3e02 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_affinity.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector import IoK8sApiCoreV1NodeSelector +from kubeflow.trainer.models.io_k8s_api_core_v1_preferred_scheduling_term import IoK8sApiCoreV1PreferredSchedulingTerm +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1NodeAffinity(BaseModel): + """ + Node affinity is a group of node affinity scheduling rules. + """ # noqa: E501 + preferred_during_scheduling_ignored_during_execution: Optional[List[IoK8sApiCoreV1PreferredSchedulingTerm]] = Field(default=None, description="The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node matches the corresponding matchExpressions; the node(s) with the highest sum are the most preferred.", alias="preferredDuringSchedulingIgnoredDuringExecution") + required_during_scheduling_ignored_during_execution: Optional[IoK8sApiCoreV1NodeSelector] = Field(default=None, alias="requiredDuringSchedulingIgnoredDuringExecution") + __properties: ClassVar[List[str]] = ["preferredDuringSchedulingIgnoredDuringExecution", "requiredDuringSchedulingIgnoredDuringExecution"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeAffinity from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 preferred_during_scheduling_ignored_during_execution (list) + _items = [] + if self.preferred_during_scheduling_ignored_during_execution: + for _item_preferred_during_scheduling_ignored_during_execution in self.preferred_during_scheduling_ignored_during_execution: + if _item_preferred_during_scheduling_ignored_during_execution: + _items.append(_item_preferred_during_scheduling_ignored_during_execution.to_dict()) + _dict['preferredDuringSchedulingIgnoredDuringExecution'] = _items + # override the default output from pydantic by calling `to_dict()` of required_during_scheduling_ignored_during_execution + if self.required_during_scheduling_ignored_during_execution: + _dict['requiredDuringSchedulingIgnoredDuringExecution'] = self.required_during_scheduling_ignored_during_execution.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeAffinity from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "preferredDuringSchedulingIgnoredDuringExecution": [IoK8sApiCoreV1PreferredSchedulingTerm.from_dict(_item) for _item in obj["preferredDuringSchedulingIgnoredDuringExecution"]] if obj.get("preferredDuringSchedulingIgnoredDuringExecution") is not None else None, + "requiredDuringSchedulingIgnoredDuringExecution": IoK8sApiCoreV1NodeSelector.from_dict(obj["requiredDuringSchedulingIgnoredDuringExecution"]) if obj.get("requiredDuringSchedulingIgnoredDuringExecution") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector.py new file mode 100644 index 0000000000..d2a1be5210 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector_term import IoK8sApiCoreV1NodeSelectorTerm +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1NodeSelector(BaseModel): + """ + A node selector represents the union of the results of one or more label queries over a set of nodes; that is, it represents the OR of the selectors represented by the node selector terms. + """ # noqa: E501 + node_selector_terms: List[IoK8sApiCoreV1NodeSelectorTerm] = Field(description="Required. A list of node selector terms. The terms are ORed.", alias="nodeSelectorTerms") + __properties: ClassVar[List[str]] = ["nodeSelectorTerms"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeSelector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 node_selector_terms (list) + _items = [] + if self.node_selector_terms: + for _item_node_selector_terms in self.node_selector_terms: + if _item_node_selector_terms: + _items.append(_item_node_selector_terms.to_dict()) + _dict['nodeSelectorTerms'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeSelector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nodeSelectorTerms": [IoK8sApiCoreV1NodeSelectorTerm.from_dict(_item) for _item in obj["nodeSelectorTerms"]] if obj.get("nodeSelectorTerms") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector_requirement.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector_requirement.py new file mode 100644 index 0000000000..0bed4bb3be --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector_requirement.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1NodeSelectorRequirement(BaseModel): + """ + A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + """ # noqa: E501 + key: StrictStr = Field(description="The label key that the selector applies to.") + operator: StrictStr = Field(description="Represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt.") + values: Optional[List[StrictStr]] = Field(default=None, description="An array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. This array is replaced during a strategic merge patch.") + __properties: ClassVar[List[str]] = ["key", "operator", "values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeSelectorRequirement from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeSelectorRequirement from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "operator": obj.get("operator"), + "values": obj.get("values") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector_term.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector_term.py new file mode 100644 index 0000000000..743edc16bd --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_node_selector_term.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector_requirement import IoK8sApiCoreV1NodeSelectorRequirement +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1NodeSelectorTerm(BaseModel): + """ + A null or empty node selector term matches no objects. The requirements of them are ANDed. The TopologySelectorTerm type implements a subset of the NodeSelectorTerm. + """ # noqa: E501 + match_expressions: Optional[List[IoK8sApiCoreV1NodeSelectorRequirement]] = Field(default=None, description="A list of node selector requirements by node's labels.", alias="matchExpressions") + match_fields: Optional[List[IoK8sApiCoreV1NodeSelectorRequirement]] = Field(default=None, description="A list of node selector requirements by node's fields.", alias="matchFields") + __properties: ClassVar[List[str]] = ["matchExpressions", "matchFields"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeSelectorTerm from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 match_expressions (list) + _items = [] + if self.match_expressions: + for _item_match_expressions in self.match_expressions: + if _item_match_expressions: + _items.append(_item_match_expressions.to_dict()) + _dict['matchExpressions'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in match_fields (list) + _items = [] + if self.match_fields: + for _item_match_fields in self.match_fields: + if _item_match_fields: + _items.append(_item_match_fields.to_dict()) + _dict['matchFields'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1NodeSelectorTerm from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "matchExpressions": [IoK8sApiCoreV1NodeSelectorRequirement.from_dict(_item) for _item in obj["matchExpressions"]] if obj.get("matchExpressions") is not None else None, + "matchFields": [IoK8sApiCoreV1NodeSelectorRequirement.from_dict(_item) for _item in obj["matchFields"]] if obj.get("matchFields") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_object_field_selector.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_object_field_selector.py new file mode 100644 index 0000000000..5ea4d95b83 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_object_field_selector.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ObjectFieldSelector(BaseModel): + """ + ObjectFieldSelector selects an APIVersioned field of an object. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="Version of the schema the FieldPath is written in terms of, defaults to \"v1\".", alias="apiVersion") + field_path: StrictStr = Field(description="Path of the field to select in the specified API version.", alias="fieldPath") + __properties: ClassVar[List[str]] = ["apiVersion", "fieldPath"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ObjectFieldSelector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ObjectFieldSelector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "fieldPath": obj.get("fieldPath") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_spec.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_spec.py new file mode 100644 index 0000000000..bc35b70c66 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_spec.py @@ -0,0 +1,119 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_typed_local_object_reference import IoK8sApiCoreV1TypedLocalObjectReference +from kubeflow.trainer.models.io_k8s_api_core_v1_typed_object_reference import IoK8sApiCoreV1TypedObjectReference +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_resource_requirements import IoK8sApiCoreV1VolumeResourceRequirements +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PersistentVolumeClaimSpec(BaseModel): + """ + PersistentVolumeClaimSpec describes the common attributes of storage devices and allows a Source for provider-specific attributes + """ # noqa: E501 + access_modes: Optional[List[StrictStr]] = Field(default=None, description="accessModes contains the desired access modes the volume should have. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modes-1", alias="accessModes") + data_source: Optional[IoK8sApiCoreV1TypedLocalObjectReference] = Field(default=None, alias="dataSource") + data_source_ref: Optional[IoK8sApiCoreV1TypedObjectReference] = Field(default=None, alias="dataSourceRef") + resources: Optional[IoK8sApiCoreV1VolumeResourceRequirements] = None + selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = None + storage_class_name: Optional[StrictStr] = Field(default=None, description="storageClassName is the name of the StorageClass required by the claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#class-1", alias="storageClassName") + volume_attributes_class_name: Optional[StrictStr] = Field(default=None, description="volumeAttributesClassName may be used to set the VolumeAttributesClass used by this claim. If specified, the CSI driver will create or update the volume with the attributes defined in the corresponding VolumeAttributesClass. This has a different purpose than storageClassName, it can be changed after the claim is created. An empty string value means that no VolumeAttributesClass will be applied to the claim but it's not allowed to reset this field to empty string once it is set. If unspecified and the PersistentVolumeClaim is unbound, the default VolumeAttributesClass will be set by the persistentvolume controller if it exists. If the resource referred to by volumeAttributesClass does not exist, this PersistentVolumeClaim will be set to a Pending state, as reflected by the modifyVolumeStatus field, until such as a resource exists. More info: https://kubernetes.io/docs/concepts/storage/volume-attributes-classes/ (Beta) Using this field requires the VolumeAttributesClass feature gate to be enabled (off by default).", alias="volumeAttributesClassName") + volume_mode: Optional[StrictStr] = Field(default=None, description="volumeMode defines what type of volume is required by the claim. Value of Filesystem is implied when not included in claim spec.", alias="volumeMode") + volume_name: Optional[StrictStr] = Field(default=None, description="volumeName is the binding reference to the PersistentVolume backing this claim.", alias="volumeName") + __properties: ClassVar[List[str]] = ["accessModes", "dataSource", "dataSourceRef", "resources", "selector", "storageClassName", "volumeAttributesClassName", "volumeMode", "volumeName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PersistentVolumeClaimSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 data_source + if self.data_source: + _dict['dataSource'] = self.data_source.to_dict() + # override the default output from pydantic by calling `to_dict()` of data_source_ref + if self.data_source_ref: + _dict['dataSourceRef'] = self.data_source_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of resources + if self.resources: + _dict['resources'] = self.resources.to_dict() + # override the default output from pydantic by calling `to_dict()` of selector + if self.selector: + _dict['selector'] = self.selector.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PersistentVolumeClaimSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "accessModes": obj.get("accessModes"), + "dataSource": IoK8sApiCoreV1TypedLocalObjectReference.from_dict(obj["dataSource"]) if obj.get("dataSource") is not None else None, + "dataSourceRef": IoK8sApiCoreV1TypedObjectReference.from_dict(obj["dataSourceRef"]) if obj.get("dataSourceRef") is not None else None, + "resources": IoK8sApiCoreV1VolumeResourceRequirements.from_dict(obj["resources"]) if obj.get("resources") is not None else None, + "selector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["selector"]) if obj.get("selector") is not None else None, + "storageClassName": obj.get("storageClassName"), + "volumeAttributesClassName": obj.get("volumeAttributesClassName"), + "volumeMode": obj.get("volumeMode"), + "volumeName": obj.get("volumeName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_template.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_template.py new file mode 100644 index 0000000000..831a06b136 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_template.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_persistent_volume_claim_spec import IoK8sApiCoreV1PersistentVolumeClaimSpec +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PersistentVolumeClaimTemplate(BaseModel): + """ + PersistentVolumeClaimTemplate is used to produce PersistentVolumeClaim objects as part of an EphemeralVolumeSource. + """ # noqa: E501 + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: IoK8sApiCoreV1PersistentVolumeClaimSpec + __properties: ClassVar[List[str]] = ["metadata", "spec"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PersistentVolumeClaimTemplate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PersistentVolumeClaimTemplate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": IoK8sApiCoreV1PersistentVolumeClaimSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_volume_source.py new file mode 100644 index 0000000000..3f307afaff --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_persistent_volume_claim_volume_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PersistentVolumeClaimVolumeSource(BaseModel): + """ + PersistentVolumeClaimVolumeSource references the user's PVC in the same namespace. This volume finds the bound PV and mounts that volume for the pod. A PersistentVolumeClaimVolumeSource is, essentially, a wrapper around another type of volume that is owned by someone else (the system). + """ # noqa: E501 + claim_name: StrictStr = Field(description="claimName is the name of a PersistentVolumeClaim in the same namespace as the pod using this volume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistentvolumeclaims", alias="claimName") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly Will force the ReadOnly setting in VolumeMounts. Default false.", alias="readOnly") + __properties: ClassVar[List[str]] = ["claimName", "readOnly"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PersistentVolumeClaimVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PersistentVolumeClaimVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "claimName": obj.get("claimName"), + "readOnly": obj.get("readOnly") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_photon_persistent_disk_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_photon_persistent_disk_volume_source.py new file mode 100644 index 0000000000..9ec2aa386b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_photon_persistent_disk_volume_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PhotonPersistentDiskVolumeSource(BaseModel): + """ + Represents a Photon Controller persistent disk resource. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", alias="fsType") + pd_id: StrictStr = Field(description="pdID is the ID that identifies Photon Controller persistent disk", alias="pdID") + __properties: ClassVar[List[str]] = ["fsType", "pdID"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PhotonPersistentDiskVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PhotonPersistentDiskVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "pdID": obj.get("pdID") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_affinity.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_affinity.py new file mode 100644 index 0000000000..f8eeb3cc35 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_affinity.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_affinity_term import IoK8sApiCoreV1PodAffinityTerm +from kubeflow.trainer.models.io_k8s_api_core_v1_weighted_pod_affinity_term import IoK8sApiCoreV1WeightedPodAffinityTerm +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodAffinity(BaseModel): + """ + Pod affinity is a group of inter pod affinity scheduling rules. + """ # noqa: E501 + preferred_during_scheduling_ignored_during_execution: Optional[List[IoK8sApiCoreV1WeightedPodAffinityTerm]] = Field(default=None, description="The scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", alias="preferredDuringSchedulingIgnoredDuringExecution") + required_during_scheduling_ignored_during_execution: Optional[List[IoK8sApiCoreV1PodAffinityTerm]] = Field(default=None, description="If the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", alias="requiredDuringSchedulingIgnoredDuringExecution") + __properties: ClassVar[List[str]] = ["preferredDuringSchedulingIgnoredDuringExecution", "requiredDuringSchedulingIgnoredDuringExecution"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodAffinity from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 preferred_during_scheduling_ignored_during_execution (list) + _items = [] + if self.preferred_during_scheduling_ignored_during_execution: + for _item_preferred_during_scheduling_ignored_during_execution in self.preferred_during_scheduling_ignored_during_execution: + if _item_preferred_during_scheduling_ignored_during_execution: + _items.append(_item_preferred_during_scheduling_ignored_during_execution.to_dict()) + _dict['preferredDuringSchedulingIgnoredDuringExecution'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in required_during_scheduling_ignored_during_execution (list) + _items = [] + if self.required_during_scheduling_ignored_during_execution: + for _item_required_during_scheduling_ignored_during_execution in self.required_during_scheduling_ignored_during_execution: + if _item_required_during_scheduling_ignored_during_execution: + _items.append(_item_required_during_scheduling_ignored_during_execution.to_dict()) + _dict['requiredDuringSchedulingIgnoredDuringExecution'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodAffinity from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "preferredDuringSchedulingIgnoredDuringExecution": [IoK8sApiCoreV1WeightedPodAffinityTerm.from_dict(_item) for _item in obj["preferredDuringSchedulingIgnoredDuringExecution"]] if obj.get("preferredDuringSchedulingIgnoredDuringExecution") is not None else None, + "requiredDuringSchedulingIgnoredDuringExecution": [IoK8sApiCoreV1PodAffinityTerm.from_dict(_item) for _item in obj["requiredDuringSchedulingIgnoredDuringExecution"]] if obj.get("requiredDuringSchedulingIgnoredDuringExecution") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_affinity_term.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_affinity_term.py new file mode 100644 index 0000000000..d1e524fd71 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_affinity_term.py @@ -0,0 +1,104 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodAffinityTerm(BaseModel): + """ + Defines a set of pods (namely those matching the labelSelector relative to the given namespace(s)) that this pod should be co-located (affinity) or not co-located (anti-affinity) with, where co-located is defined as running on a node whose value of the label with key matches that of any node on which a pod of the set of pods is running + """ # noqa: E501 + label_selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = Field(default=None, alias="labelSelector") + match_label_keys: Optional[List[StrictStr]] = Field(default=None, description="MatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key in (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both matchLabelKeys and labelSelector. Also, matchLabelKeys cannot be set when labelSelector isn't set. This is a beta field and requires enabling MatchLabelKeysInPodAffinity feature gate (enabled by default).", alias="matchLabelKeys") + mismatch_label_keys: Optional[List[StrictStr]] = Field(default=None, description="MismatchLabelKeys is a set of pod label keys to select which pods will be taken into consideration. The keys are used to lookup values from the incoming pod labels, those key-value labels are merged with `labelSelector` as `key notin (value)` to select the group of existing pods which pods will be taken into consideration for the incoming pod's pod (anti) affinity. Keys that don't exist in the incoming pod labels will be ignored. The default value is empty. The same key is forbidden to exist in both mismatchLabelKeys and labelSelector. Also, mismatchLabelKeys cannot be set when labelSelector isn't set. This is a beta field and requires enabling MatchLabelKeysInPodAffinity feature gate (enabled by default).", alias="mismatchLabelKeys") + namespace_selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = Field(default=None, alias="namespaceSelector") + namespaces: Optional[List[StrictStr]] = Field(default=None, description="namespaces specifies a static list of namespace names that the term applies to. The term is applied to the union of the namespaces listed in this field and the ones selected by namespaceSelector. null or empty namespaces list and null namespaceSelector means \"this pod's namespace\".") + topology_key: StrictStr = Field(description="This pod should be co-located (affinity) or not co-located (anti-affinity) with the pods matching the labelSelector in the specified namespaces, where co-located is defined as running on a node whose value of the label with key topologyKey matches that of any node on which any of the selected pods is running. Empty topologyKey is not allowed.", alias="topologyKey") + __properties: ClassVar[List[str]] = ["labelSelector", "matchLabelKeys", "mismatchLabelKeys", "namespaceSelector", "namespaces", "topologyKey"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodAffinityTerm from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 label_selector + if self.label_selector: + _dict['labelSelector'] = self.label_selector.to_dict() + # override the default output from pydantic by calling `to_dict()` of namespace_selector + if self.namespace_selector: + _dict['namespaceSelector'] = self.namespace_selector.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodAffinityTerm from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "labelSelector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["labelSelector"]) if obj.get("labelSelector") is not None else None, + "matchLabelKeys": obj.get("matchLabelKeys"), + "mismatchLabelKeys": obj.get("mismatchLabelKeys"), + "namespaceSelector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["namespaceSelector"]) if obj.get("namespaceSelector") is not None else None, + "namespaces": obj.get("namespaces"), + "topologyKey": obj.get("topologyKey") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_anti_affinity.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_anti_affinity.py new file mode 100644 index 0000000000..fed0d65f0a --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_anti_affinity.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_affinity_term import IoK8sApiCoreV1PodAffinityTerm +from kubeflow.trainer.models.io_k8s_api_core_v1_weighted_pod_affinity_term import IoK8sApiCoreV1WeightedPodAffinityTerm +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodAntiAffinity(BaseModel): + """ + Pod anti affinity is a group of inter pod anti affinity scheduling rules. + """ # noqa: E501 + preferred_during_scheduling_ignored_during_execution: Optional[List[IoK8sApiCoreV1WeightedPodAffinityTerm]] = Field(default=None, description="The scheduler will prefer to schedule pods to nodes that satisfy the anti-affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. for each node that meets all of the scheduling requirements (resource request, requiredDuringScheduling anti-affinity expressions, etc.), compute a sum by iterating through the elements of this field and adding \"weight\" to the sum if the node has pods which matches the corresponding podAffinityTerm; the node(s) with the highest sum are the most preferred.", alias="preferredDuringSchedulingIgnoredDuringExecution") + required_during_scheduling_ignored_during_execution: Optional[List[IoK8sApiCoreV1PodAffinityTerm]] = Field(default=None, description="If the anti-affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the anti-affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to a pod label update), the system may or may not try to eventually evict the pod from its node. When there are multiple elements, the lists of nodes corresponding to each podAffinityTerm are intersected, i.e. all terms must be satisfied.", alias="requiredDuringSchedulingIgnoredDuringExecution") + __properties: ClassVar[List[str]] = ["preferredDuringSchedulingIgnoredDuringExecution", "requiredDuringSchedulingIgnoredDuringExecution"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodAntiAffinity from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 preferred_during_scheduling_ignored_during_execution (list) + _items = [] + if self.preferred_during_scheduling_ignored_during_execution: + for _item_preferred_during_scheduling_ignored_during_execution in self.preferred_during_scheduling_ignored_during_execution: + if _item_preferred_during_scheduling_ignored_during_execution: + _items.append(_item_preferred_during_scheduling_ignored_during_execution.to_dict()) + _dict['preferredDuringSchedulingIgnoredDuringExecution'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in required_during_scheduling_ignored_during_execution (list) + _items = [] + if self.required_during_scheduling_ignored_during_execution: + for _item_required_during_scheduling_ignored_during_execution in self.required_during_scheduling_ignored_during_execution: + if _item_required_during_scheduling_ignored_during_execution: + _items.append(_item_required_during_scheduling_ignored_during_execution.to_dict()) + _dict['requiredDuringSchedulingIgnoredDuringExecution'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodAntiAffinity from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "preferredDuringSchedulingIgnoredDuringExecution": [IoK8sApiCoreV1WeightedPodAffinityTerm.from_dict(_item) for _item in obj["preferredDuringSchedulingIgnoredDuringExecution"]] if obj.get("preferredDuringSchedulingIgnoredDuringExecution") is not None else None, + "requiredDuringSchedulingIgnoredDuringExecution": [IoK8sApiCoreV1PodAffinityTerm.from_dict(_item) for _item in obj["requiredDuringSchedulingIgnoredDuringExecution"]] if obj.get("requiredDuringSchedulingIgnoredDuringExecution") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_dns_config.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_dns_config.py new file mode 100644 index 0000000000..6db4b3a285 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_dns_config.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_dns_config_option import IoK8sApiCoreV1PodDNSConfigOption +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodDNSConfig(BaseModel): + """ + PodDNSConfig defines the DNS parameters of a pod in addition to those generated from DNSPolicy. + """ # noqa: E501 + nameservers: Optional[List[StrictStr]] = Field(default=None, description="A list of DNS name server IP addresses. This will be appended to the base nameservers generated from DNSPolicy. Duplicated nameservers will be removed.") + options: Optional[List[IoK8sApiCoreV1PodDNSConfigOption]] = Field(default=None, description="A list of DNS resolver options. This will be merged with the base options generated from DNSPolicy. Duplicated entries will be removed. Resolution options given in Options will override those that appear in the base DNSPolicy.") + searches: Optional[List[StrictStr]] = Field(default=None, description="A list of DNS search domains for host-name lookup. This will be appended to the base search paths generated from DNSPolicy. Duplicated search paths will be removed.") + __properties: ClassVar[List[str]] = ["nameservers", "options", "searches"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodDNSConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 options (list) + _items = [] + if self.options: + for _item_options in self.options: + if _item_options: + _items.append(_item_options.to_dict()) + _dict['options'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodDNSConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "nameservers": obj.get("nameservers"), + "options": [IoK8sApiCoreV1PodDNSConfigOption.from_dict(_item) for _item in obj["options"]] if obj.get("options") is not None else None, + "searches": obj.get("searches") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_dns_config_option.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_dns_config_option.py new file mode 100644 index 0000000000..4536154b2b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_dns_config_option.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodDNSConfigOption(BaseModel): + """ + PodDNSConfigOption defines DNS resolver options of a pod. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="Name is this DNS resolver option's name. Required.") + value: Optional[StrictStr] = Field(default=None, description="Value is this DNS resolver option's value.") + __properties: ClassVar[List[str]] = ["name", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodDNSConfigOption from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodDNSConfigOption from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "value": obj.get("value") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_os.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_os.py new file mode 100644 index 0000000000..02c9ebe214 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_os.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodOS(BaseModel): + """ + PodOS defines the OS parameters of a pod. + """ # noqa: E501 + name: StrictStr = Field(description="Name is the name of the operating system. The currently supported values are linux and windows. Additional value may be defined in future and can be one of: https://github.com/opencontainers/runtime-spec/blob/master/config.md#platform-specific-configuration Clients should expect to handle additional values and treat unrecognized values in this field as os: null") + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodOS from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodOS from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_readiness_gate.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_readiness_gate.py new file mode 100644 index 0000000000..4206ad1407 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_readiness_gate.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodReadinessGate(BaseModel): + """ + PodReadinessGate contains the reference to a pod condition + """ # noqa: E501 + condition_type: StrictStr = Field(description="ConditionType refers to a condition in the pod's condition list with matching type.", alias="conditionType") + __properties: ClassVar[List[str]] = ["conditionType"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodReadinessGate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodReadinessGate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "conditionType": obj.get("conditionType") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_resource_claim.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_resource_claim.py new file mode 100644 index 0000000000..f343e7721d --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_resource_claim.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodResourceClaim(BaseModel): + """ + PodResourceClaim references exactly one ResourceClaim, either directly or by naming a ResourceClaimTemplate which is then turned into a ResourceClaim for the pod. It adds a name to it that uniquely identifies the ResourceClaim inside the Pod. Containers that need access to the ResourceClaim reference it with this name. + """ # noqa: E501 + name: StrictStr = Field(description="Name uniquely identifies this resource claim inside the pod. This must be a DNS_LABEL.") + resource_claim_name: Optional[StrictStr] = Field(default=None, description="ResourceClaimName is the name of a ResourceClaim object in the same namespace as this pod. Exactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", alias="resourceClaimName") + resource_claim_template_name: Optional[StrictStr] = Field(default=None, description="ResourceClaimTemplateName is the name of a ResourceClaimTemplate object in the same namespace as this pod. The template will be used to create a new ResourceClaim, which will be bound to this pod. When this pod is deleted, the ResourceClaim will also be deleted. The pod name and resource name, along with a generated component, will be used to form a unique name for the ResourceClaim, which will be recorded in pod.status.resourceClaimStatuses. This field is immutable and no changes will be made to the corresponding ResourceClaim by the control plane after creating the ResourceClaim. Exactly one of ResourceClaimName and ResourceClaimTemplateName must be set.", alias="resourceClaimTemplateName") + __properties: ClassVar[List[str]] = ["name", "resourceClaimName", "resourceClaimTemplateName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodResourceClaim from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodResourceClaim from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "resourceClaimName": obj.get("resourceClaimName"), + "resourceClaimTemplateName": obj.get("resourceClaimTemplateName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_scheduling_gate.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_scheduling_gate.py new file mode 100644 index 0000000000..1445c65c05 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_scheduling_gate.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodSchedulingGate(BaseModel): + """ + PodSchedulingGate is associated to a Pod to guard its scheduling. + """ # noqa: E501 + name: StrictStr = Field(description="Name of the scheduling gate. Each scheduling gate must have a unique name field.") + __properties: ClassVar[List[str]] = ["name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodSchedulingGate from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodSchedulingGate from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_security_context.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_security_context.py new file mode 100644 index 0000000000..e70089a479 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_security_context.py @@ -0,0 +1,135 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_app_armor_profile import IoK8sApiCoreV1AppArmorProfile +from kubeflow.trainer.models.io_k8s_api_core_v1_se_linux_options import IoK8sApiCoreV1SELinuxOptions +from kubeflow.trainer.models.io_k8s_api_core_v1_seccomp_profile import IoK8sApiCoreV1SeccompProfile +from kubeflow.trainer.models.io_k8s_api_core_v1_sysctl import IoK8sApiCoreV1Sysctl +from kubeflow.trainer.models.io_k8s_api_core_v1_windows_security_context_options import IoK8sApiCoreV1WindowsSecurityContextOptions +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodSecurityContext(BaseModel): + """ + PodSecurityContext holds pod-level security attributes and common container settings. Some fields are also present in container.securityContext. Field values of container.securityContext take precedence over field values of PodSecurityContext. + """ # noqa: E501 + app_armor_profile: Optional[IoK8sApiCoreV1AppArmorProfile] = Field(default=None, alias="appArmorProfile") + fs_group: Optional[StrictInt] = Field(default=None, description="A special supplemental group that applies to all containers in a pod. Some volume types allow the Kubelet to change the ownership of that volume to be owned by the pod: 1. The owning GID will be the FSGroup 2. The setgid bit is set (new files created in the volume will be owned by FSGroup) 3. The permission bits are OR'd with rw-rw---- If unset, the Kubelet will not modify the ownership and permissions of any volume. Note that this field cannot be set when spec.os.name is windows.", alias="fsGroup") + fs_group_change_policy: Optional[StrictStr] = Field(default=None, description="fsGroupChangePolicy defines behavior of changing ownership and permission of the volume before being exposed inside Pod. This field will only apply to volume types which support fsGroup based ownership(and permissions). It will have no effect on ephemeral volume types such as: secret, configmaps and emptydir. Valid values are \"OnRootMismatch\" and \"Always\". If not specified, \"Always\" is used. Note that this field cannot be set when spec.os.name is windows.", alias="fsGroupChangePolicy") + run_as_group: Optional[StrictInt] = Field(default=None, description="The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", alias="runAsGroup") + run_as_non_root: Optional[StrictBool] = Field(default=None, description="Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", alias="runAsNonRoot") + run_as_user: Optional[StrictInt] = Field(default=None, description="The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in SecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence for that container. Note that this field cannot be set when spec.os.name is windows.", alias="runAsUser") + se_linux_change_policy: Optional[StrictStr] = Field(default=None, description="seLinuxChangePolicy defines how the container's SELinux label is applied to all volumes used by the Pod. It has no effect on nodes that do not support SELinux or to volumes does not support SELinux. Valid values are \"MountOption\" and \"Recursive\". \"Recursive\" means relabeling of all files on all Pod volumes by the container runtime. This may be slow for large volumes, but allows mixing privileged and unprivileged Pods sharing the same volume on the same node. \"MountOption\" mounts all eligible Pod volumes with `-o context` mount option. This requires all Pods that share the same volume to use the same SELinux label. It is not possible to share the same volume among privileged and unprivileged Pods. Eligible volumes are in-tree FibreChannel and iSCSI volumes, and all CSI volumes whose CSI driver announces SELinux support by setting spec.seLinuxMount: true in their CSIDriver instance. Other volumes are always re-labelled recursively. \"MountOption\" value is allowed only when SELinuxMount feature gate is enabled. If not specified and SELinuxMount feature gate is enabled, \"MountOption\" is used. If not specified and SELinuxMount feature gate is disabled, \"MountOption\" is used for ReadWriteOncePod volumes and \"Recursive\" for all other volumes. This field affects only Pods that have SELinux label set, either in PodSecurityContext or in SecurityContext of all containers. All Pods that use the same volume should use the same seLinuxChangePolicy, otherwise some pods can get stuck in ContainerCreating state. Note that this field cannot be set when spec.os.name is windows.", alias="seLinuxChangePolicy") + se_linux_options: Optional[IoK8sApiCoreV1SELinuxOptions] = Field(default=None, alias="seLinuxOptions") + seccomp_profile: Optional[IoK8sApiCoreV1SeccompProfile] = Field(default=None, alias="seccompProfile") + supplemental_groups: Optional[List[StrictInt]] = Field(default=None, description="A list of groups applied to the first process run in each container, in addition to the container's primary GID and fsGroup (if specified). If the SupplementalGroupsPolicy feature is enabled, the supplementalGroupsPolicy field determines whether these are in addition to or instead of any group memberships defined in the container image. If unspecified, no additional groups are added, though group memberships defined in the container image may still be used, depending on the supplementalGroupsPolicy field. Note that this field cannot be set when spec.os.name is windows.", alias="supplementalGroups") + supplemental_groups_policy: Optional[StrictStr] = Field(default=None, description="Defines how supplemental groups of the first container processes are calculated. Valid values are \"Merge\" and \"Strict\". If not specified, \"Merge\" is used. (Alpha) Using the field requires the SupplementalGroupsPolicy feature gate to be enabled and the container runtime must implement support for this feature. Note that this field cannot be set when spec.os.name is windows.", alias="supplementalGroupsPolicy") + sysctls: Optional[List[IoK8sApiCoreV1Sysctl]] = Field(default=None, description="Sysctls hold a list of namespaced sysctls used for the pod. Pods with unsupported sysctls (by the container runtime) might fail to launch. Note that this field cannot be set when spec.os.name is windows.") + windows_options: Optional[IoK8sApiCoreV1WindowsSecurityContextOptions] = Field(default=None, alias="windowsOptions") + __properties: ClassVar[List[str]] = ["appArmorProfile", "fsGroup", "fsGroupChangePolicy", "runAsGroup", "runAsNonRoot", "runAsUser", "seLinuxChangePolicy", "seLinuxOptions", "seccompProfile", "supplementalGroups", "supplementalGroupsPolicy", "sysctls", "windowsOptions"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodSecurityContext from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 app_armor_profile + if self.app_armor_profile: + _dict['appArmorProfile'] = self.app_armor_profile.to_dict() + # override the default output from pydantic by calling `to_dict()` of se_linux_options + if self.se_linux_options: + _dict['seLinuxOptions'] = self.se_linux_options.to_dict() + # override the default output from pydantic by calling `to_dict()` of seccomp_profile + if self.seccomp_profile: + _dict['seccompProfile'] = self.seccomp_profile.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in sysctls (list) + _items = [] + if self.sysctls: + for _item_sysctls in self.sysctls: + if _item_sysctls: + _items.append(_item_sysctls.to_dict()) + _dict['sysctls'] = _items + # override the default output from pydantic by calling `to_dict()` of windows_options + if self.windows_options: + _dict['windowsOptions'] = self.windows_options.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodSecurityContext from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "appArmorProfile": IoK8sApiCoreV1AppArmorProfile.from_dict(obj["appArmorProfile"]) if obj.get("appArmorProfile") is not None else None, + "fsGroup": obj.get("fsGroup"), + "fsGroupChangePolicy": obj.get("fsGroupChangePolicy"), + "runAsGroup": obj.get("runAsGroup"), + "runAsNonRoot": obj.get("runAsNonRoot"), + "runAsUser": obj.get("runAsUser"), + "seLinuxChangePolicy": obj.get("seLinuxChangePolicy"), + "seLinuxOptions": IoK8sApiCoreV1SELinuxOptions.from_dict(obj["seLinuxOptions"]) if obj.get("seLinuxOptions") is not None else None, + "seccompProfile": IoK8sApiCoreV1SeccompProfile.from_dict(obj["seccompProfile"]) if obj.get("seccompProfile") is not None else None, + "supplementalGroups": obj.get("supplementalGroups"), + "supplementalGroupsPolicy": obj.get("supplementalGroupsPolicy"), + "sysctls": [IoK8sApiCoreV1Sysctl.from_dict(_item) for _item in obj["sysctls"]] if obj.get("sysctls") is not None else None, + "windowsOptions": IoK8sApiCoreV1WindowsSecurityContextOptions.from_dict(obj["windowsOptions"]) if obj.get("windowsOptions") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_spec.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_spec.py new file mode 100644 index 0000000000..63ab75cf00 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_spec.py @@ -0,0 +1,272 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_affinity import IoK8sApiCoreV1Affinity +from kubeflow.trainer.models.io_k8s_api_core_v1_container import IoK8sApiCoreV1Container +from kubeflow.trainer.models.io_k8s_api_core_v1_ephemeral_container import IoK8sApiCoreV1EphemeralContainer +from kubeflow.trainer.models.io_k8s_api_core_v1_host_alias import IoK8sApiCoreV1HostAlias +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_dns_config import IoK8sApiCoreV1PodDNSConfig +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_os import IoK8sApiCoreV1PodOS +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_readiness_gate import IoK8sApiCoreV1PodReadinessGate +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_resource_claim import IoK8sApiCoreV1PodResourceClaim +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_scheduling_gate import IoK8sApiCoreV1PodSchedulingGate +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_security_context import IoK8sApiCoreV1PodSecurityContext +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_requirements import IoK8sApiCoreV1ResourceRequirements +from kubeflow.trainer.models.io_k8s_api_core_v1_toleration import IoK8sApiCoreV1Toleration +from kubeflow.trainer.models.io_k8s_api_core_v1_topology_spread_constraint import IoK8sApiCoreV1TopologySpreadConstraint +from kubeflow.trainer.models.io_k8s_api_core_v1_volume import IoK8sApiCoreV1Volume +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodSpec(BaseModel): + """ + PodSpec is a description of a pod. + """ # noqa: E501 + active_deadline_seconds: Optional[StrictInt] = Field(default=None, description="Optional duration in seconds the pod may be active on the node relative to StartTime before the system will actively try to mark it failed and kill associated containers. Value must be a positive integer.", alias="activeDeadlineSeconds") + affinity: Optional[IoK8sApiCoreV1Affinity] = None + automount_service_account_token: Optional[StrictBool] = Field(default=None, description="AutomountServiceAccountToken indicates whether a service account token should be automatically mounted.", alias="automountServiceAccountToken") + containers: List[IoK8sApiCoreV1Container] = Field(description="List of containers belonging to the pod. Containers cannot currently be added or removed. There must be at least one container in a Pod. Cannot be updated.") + dns_config: Optional[IoK8sApiCoreV1PodDNSConfig] = Field(default=None, alias="dnsConfig") + dns_policy: Optional[StrictStr] = Field(default=None, description="Set DNS policy for the pod. Defaults to \"ClusterFirst\". Valid values are 'ClusterFirstWithHostNet', 'ClusterFirst', 'Default' or 'None'. DNS parameters given in DNSConfig will be merged with the policy selected with DNSPolicy. To have DNS options set along with hostNetwork, you have to specify DNS policy explicitly to 'ClusterFirstWithHostNet'.", alias="dnsPolicy") + enable_service_links: Optional[StrictBool] = Field(default=None, description="EnableServiceLinks indicates whether information about services should be injected into pod's environment variables, matching the syntax of Docker links. Optional: Defaults to true.", alias="enableServiceLinks") + ephemeral_containers: Optional[List[IoK8sApiCoreV1EphemeralContainer]] = Field(default=None, description="List of ephemeral containers run in this pod. Ephemeral containers may be run in an existing pod to perform user-initiated actions such as debugging. This list cannot be specified when creating a pod, and it cannot be modified by updating the pod spec. In order to add an ephemeral container to an existing pod, use the pod's ephemeralcontainers subresource.", alias="ephemeralContainers") + host_aliases: Optional[List[IoK8sApiCoreV1HostAlias]] = Field(default=None, description="HostAliases is an optional list of hosts and IPs that will be injected into the pod's hosts file if specified.", alias="hostAliases") + host_ipc: Optional[StrictBool] = Field(default=None, description="Use the host's ipc namespace. Optional: Default to false.", alias="hostIPC") + host_network: Optional[StrictBool] = Field(default=None, description="Host networking requested for this pod. Use the host's network namespace. If this option is set, the ports that will be used must be specified. Default to false.", alias="hostNetwork") + host_pid: Optional[StrictBool] = Field(default=None, description="Use the host's pid namespace. Optional: Default to false.", alias="hostPID") + host_users: Optional[StrictBool] = Field(default=None, description="Use the host's user namespace. Optional: Default to true. If set to true or not present, the pod will be run in the host user namespace, useful for when the pod needs a feature only available to the host user namespace, such as loading a kernel module with CAP_SYS_MODULE. When set to false, a new userns is created for the pod. Setting false is useful for mitigating container breakout vulnerabilities even allowing users to run their containers as root without actually having root privileges on the host. This field is alpha-level and is only honored by servers that enable the UserNamespacesSupport feature.", alias="hostUsers") + hostname: Optional[StrictStr] = Field(default=None, description="Specifies the hostname of the Pod If not specified, the pod's hostname will be set to a system-defined value.") + image_pull_secrets: Optional[List[IoK8sApiCoreV1LocalObjectReference]] = Field(default=None, description="ImagePullSecrets is an optional list of references to secrets in the same namespace to use for pulling any of the images used by this PodSpec. If specified, these secrets will be passed to individual puller implementations for them to use. More info: https://kubernetes.io/docs/concepts/containers/images#specifying-imagepullsecrets-on-a-pod", alias="imagePullSecrets") + init_containers: Optional[List[IoK8sApiCoreV1Container]] = Field(default=None, description="List of initialization containers belonging to the pod. Init containers are executed in order prior to containers being started. If any init container fails, the pod is considered to have failed and is handled according to its restartPolicy. The name for an init container or normal container must be unique among all containers. Init containers may not have Lifecycle actions, Readiness probes, Liveness probes, or Startup probes. The resourceRequirements of an init container are taken into account during scheduling by finding the highest request/limit for each resource type, and then using the max of of that value or the sum of the normal containers. Limits are applied to init containers in a similar fashion. Init containers cannot currently be added or removed. Cannot be updated. More info: https://kubernetes.io/docs/concepts/workloads/pods/init-containers/", alias="initContainers") + node_name: Optional[StrictStr] = Field(default=None, description="NodeName indicates in which node this pod is scheduled. If empty, this pod is a candidate for scheduling by the scheduler defined in schedulerName. Once this field is set, the kubelet for this node becomes responsible for the lifecycle of this pod. This field should not be used to express a desire for the pod to be scheduled on a specific node. https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#nodename", alias="nodeName") + node_selector: Optional[Dict[str, StrictStr]] = Field(default=None, description="NodeSelector is a selector which must be true for the pod to fit on a node. Selector which must match a node's labels for the pod to be scheduled on that node. More info: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/", alias="nodeSelector") + os: Optional[IoK8sApiCoreV1PodOS] = None + overhead: Optional[Dict[str, StrictStr]] = Field(default=None, description="Overhead represents the resource overhead associated with running a pod for a given RuntimeClass. This field will be autopopulated at admission time by the RuntimeClass admission controller. If the RuntimeClass admission controller is enabled, overhead must not be set in Pod create requests. The RuntimeClass admission controller will reject Pod create requests which have the overhead already set. If RuntimeClass is configured and selected in the PodSpec, Overhead will be set to the value defined in the corresponding RuntimeClass, otherwise it will remain unset and treated as zero. More info: https://git.k8s.io/enhancements/keps/sig-node/688-pod-overhead/README.md") + preemption_policy: Optional[StrictStr] = Field(default=None, description="PreemptionPolicy is the Policy for preempting pods with lower priority. One of Never, PreemptLowerPriority. Defaults to PreemptLowerPriority if unset.", alias="preemptionPolicy") + priority: Optional[StrictInt] = Field(default=None, description="The priority value. Various system components use this field to find the priority of the pod. When Priority Admission Controller is enabled, it prevents users from setting this field. The admission controller populates this field from PriorityClassName. The higher the value, the higher the priority.") + priority_class_name: Optional[StrictStr] = Field(default=None, description="If specified, indicates the pod's priority. \"system-node-critical\" and \"system-cluster-critical\" are two special keywords which indicate the highest priorities with the former being the highest priority. Any other name must be defined by creating a PriorityClass object with that name. If not specified, the pod priority will be default or zero if there is no default.", alias="priorityClassName") + readiness_gates: Optional[List[IoK8sApiCoreV1PodReadinessGate]] = Field(default=None, description="If specified, all readiness gates will be evaluated for pod readiness. A pod is ready when all its containers are ready AND all conditions specified in the readiness gates have status equal to \"True\" More info: https://git.k8s.io/enhancements/keps/sig-network/580-pod-readiness-gates", alias="readinessGates") + resource_claims: Optional[List[IoK8sApiCoreV1PodResourceClaim]] = Field(default=None, description="ResourceClaims defines which ResourceClaims must be allocated and reserved before the Pod is allowed to start. The resources will be made available to those containers which consume them by name. This is an alpha field and requires enabling the DynamicResourceAllocation feature gate. This field is immutable.", alias="resourceClaims") + resources: Optional[IoK8sApiCoreV1ResourceRequirements] = None + restart_policy: Optional[StrictStr] = Field(default=None, description="Restart policy for all containers within the pod. One of Always, OnFailure, Never. In some contexts, only a subset of those values may be permitted. Default to Always. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy", alias="restartPolicy") + runtime_class_name: Optional[StrictStr] = Field(default=None, description="RuntimeClassName refers to a RuntimeClass object in the node.k8s.io group, which should be used to run this pod. If no RuntimeClass resource matches the named class, the pod will not be run. If unset or empty, the \"legacy\" RuntimeClass will be used, which is an implicit class with an empty definition that uses the default runtime handler. More info: https://git.k8s.io/enhancements/keps/sig-node/585-runtime-class", alias="runtimeClassName") + scheduler_name: Optional[StrictStr] = Field(default=None, description="If specified, the pod will be dispatched by specified scheduler. If not specified, the pod will be dispatched by default scheduler.", alias="schedulerName") + scheduling_gates: Optional[List[IoK8sApiCoreV1PodSchedulingGate]] = Field(default=None, description="SchedulingGates is an opaque list of values that if specified will block scheduling the pod. If schedulingGates is not empty, the pod will stay in the SchedulingGated state and the scheduler will not attempt to schedule the pod. SchedulingGates can only be set at pod creation time, and be removed only afterwards.", alias="schedulingGates") + security_context: Optional[IoK8sApiCoreV1PodSecurityContext] = Field(default=None, alias="securityContext") + service_account: Optional[StrictStr] = Field(default=None, description="DeprecatedServiceAccount is a deprecated alias for ServiceAccountName. Deprecated: Use serviceAccountName instead.", alias="serviceAccount") + service_account_name: Optional[StrictStr] = Field(default=None, description="ServiceAccountName is the name of the ServiceAccount to use to run this pod. More info: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/", alias="serviceAccountName") + set_hostname_as_fqdn: Optional[StrictBool] = Field(default=None, description="If true the pod's hostname will be configured as the pod's FQDN, rather than the leaf name (the default). In Linux containers, this means setting the FQDN in the hostname field of the kernel (the nodename field of struct utsname). In Windows containers, this means setting the registry value of hostname for the registry key HKEY_LOCAL_MACHINE\\\\SYSTEM\\\\CurrentControlSet\\\\Services\\\\Tcpip\\\\Parameters to FQDN. If a pod does not have FQDN, this has no effect. Default to false.", alias="setHostnameAsFQDN") + share_process_namespace: Optional[StrictBool] = Field(default=None, description="Share a single process namespace between all of the containers in a pod. When this is set containers will be able to view and signal processes from other containers in the same pod, and the first process in each container will not be assigned PID 1. HostPID and ShareProcessNamespace cannot both be set. Optional: Default to false.", alias="shareProcessNamespace") + subdomain: Optional[StrictStr] = Field(default=None, description="If specified, the fully qualified Pod hostname will be \"...svc.\". If not specified, the pod will not have a domainname at all.") + termination_grace_period_seconds: Optional[StrictInt] = Field(default=None, description="Optional duration in seconds the pod needs to terminate gracefully. May be decreased in delete request. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). If this value is nil, the default grace period will be used instead. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. Defaults to 30 seconds.", alias="terminationGracePeriodSeconds") + tolerations: Optional[List[IoK8sApiCoreV1Toleration]] = Field(default=None, description="If specified, the pod's tolerations.") + topology_spread_constraints: Optional[List[IoK8sApiCoreV1TopologySpreadConstraint]] = Field(default=None, description="TopologySpreadConstraints describes how a group of pods ought to spread across topology domains. Scheduler will schedule pods in a way which abides by the constraints. All topologySpreadConstraints are ANDed.", alias="topologySpreadConstraints") + volumes: Optional[List[IoK8sApiCoreV1Volume]] = Field(default=None, description="List of volumes that can be mounted by containers belonging to the pod. More info: https://kubernetes.io/docs/concepts/storage/volumes") + __properties: ClassVar[List[str]] = ["activeDeadlineSeconds", "affinity", "automountServiceAccountToken", "containers", "dnsConfig", "dnsPolicy", "enableServiceLinks", "ephemeralContainers", "hostAliases", "hostIPC", "hostNetwork", "hostPID", "hostUsers", "hostname", "imagePullSecrets", "initContainers", "nodeName", "nodeSelector", "os", "overhead", "preemptionPolicy", "priority", "priorityClassName", "readinessGates", "resourceClaims", "resources", "restartPolicy", "runtimeClassName", "schedulerName", "schedulingGates", "securityContext", "serviceAccount", "serviceAccountName", "setHostnameAsFQDN", "shareProcessNamespace", "subdomain", "terminationGracePeriodSeconds", "tolerations", "topologySpreadConstraints", "volumes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 affinity + if self.affinity: + _dict['affinity'] = self.affinity.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in containers (list) + _items = [] + if self.containers: + for _item_containers in self.containers: + if _item_containers: + _items.append(_item_containers.to_dict()) + _dict['containers'] = _items + # override the default output from pydantic by calling `to_dict()` of dns_config + if self.dns_config: + _dict['dnsConfig'] = self.dns_config.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in ephemeral_containers (list) + _items = [] + if self.ephemeral_containers: + for _item_ephemeral_containers in self.ephemeral_containers: + if _item_ephemeral_containers: + _items.append(_item_ephemeral_containers.to_dict()) + _dict['ephemeralContainers'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in host_aliases (list) + _items = [] + if self.host_aliases: + for _item_host_aliases in self.host_aliases: + if _item_host_aliases: + _items.append(_item_host_aliases.to_dict()) + _dict['hostAliases'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in image_pull_secrets (list) + _items = [] + if self.image_pull_secrets: + for _item_image_pull_secrets in self.image_pull_secrets: + if _item_image_pull_secrets: + _items.append(_item_image_pull_secrets.to_dict()) + _dict['imagePullSecrets'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in init_containers (list) + _items = [] + if self.init_containers: + for _item_init_containers in self.init_containers: + if _item_init_containers: + _items.append(_item_init_containers.to_dict()) + _dict['initContainers'] = _items + # override the default output from pydantic by calling `to_dict()` of os + if self.os: + _dict['os'] = self.os.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in readiness_gates (list) + _items = [] + if self.readiness_gates: + for _item_readiness_gates in self.readiness_gates: + if _item_readiness_gates: + _items.append(_item_readiness_gates.to_dict()) + _dict['readinessGates'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in resource_claims (list) + _items = [] + if self.resource_claims: + for _item_resource_claims in self.resource_claims: + if _item_resource_claims: + _items.append(_item_resource_claims.to_dict()) + _dict['resourceClaims'] = _items + # override the default output from pydantic by calling `to_dict()` of resources + if self.resources: + _dict['resources'] = self.resources.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in scheduling_gates (list) + _items = [] + if self.scheduling_gates: + for _item_scheduling_gates in self.scheduling_gates: + if _item_scheduling_gates: + _items.append(_item_scheduling_gates.to_dict()) + _dict['schedulingGates'] = _items + # override the default output from pydantic by calling `to_dict()` of security_context + if self.security_context: + _dict['securityContext'] = self.security_context.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in tolerations (list) + _items = [] + if self.tolerations: + for _item_tolerations in self.tolerations: + if _item_tolerations: + _items.append(_item_tolerations.to_dict()) + _dict['tolerations'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in topology_spread_constraints (list) + _items = [] + if self.topology_spread_constraints: + for _item_topology_spread_constraints in self.topology_spread_constraints: + if _item_topology_spread_constraints: + _items.append(_item_topology_spread_constraints.to_dict()) + _dict['topologySpreadConstraints'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in volumes (list) + _items = [] + if self.volumes: + for _item_volumes in self.volumes: + if _item_volumes: + _items.append(_item_volumes.to_dict()) + _dict['volumes'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "activeDeadlineSeconds": obj.get("activeDeadlineSeconds"), + "affinity": IoK8sApiCoreV1Affinity.from_dict(obj["affinity"]) if obj.get("affinity") is not None else None, + "automountServiceAccountToken": obj.get("automountServiceAccountToken"), + "containers": [IoK8sApiCoreV1Container.from_dict(_item) for _item in obj["containers"]] if obj.get("containers") is not None else None, + "dnsConfig": IoK8sApiCoreV1PodDNSConfig.from_dict(obj["dnsConfig"]) if obj.get("dnsConfig") is not None else None, + "dnsPolicy": obj.get("dnsPolicy"), + "enableServiceLinks": obj.get("enableServiceLinks"), + "ephemeralContainers": [IoK8sApiCoreV1EphemeralContainer.from_dict(_item) for _item in obj["ephemeralContainers"]] if obj.get("ephemeralContainers") is not None else None, + "hostAliases": [IoK8sApiCoreV1HostAlias.from_dict(_item) for _item in obj["hostAliases"]] if obj.get("hostAliases") is not None else None, + "hostIPC": obj.get("hostIPC"), + "hostNetwork": obj.get("hostNetwork"), + "hostPID": obj.get("hostPID"), + "hostUsers": obj.get("hostUsers"), + "hostname": obj.get("hostname"), + "imagePullSecrets": [IoK8sApiCoreV1LocalObjectReference.from_dict(_item) for _item in obj["imagePullSecrets"]] if obj.get("imagePullSecrets") is not None else None, + "initContainers": [IoK8sApiCoreV1Container.from_dict(_item) for _item in obj["initContainers"]] if obj.get("initContainers") is not None else None, + "nodeName": obj.get("nodeName"), + "nodeSelector": obj.get("nodeSelector"), + "os": IoK8sApiCoreV1PodOS.from_dict(obj["os"]) if obj.get("os") is not None else None, + "overhead": obj.get("overhead"), + "preemptionPolicy": obj.get("preemptionPolicy"), + "priority": obj.get("priority"), + "priorityClassName": obj.get("priorityClassName"), + "readinessGates": [IoK8sApiCoreV1PodReadinessGate.from_dict(_item) for _item in obj["readinessGates"]] if obj.get("readinessGates") is not None else None, + "resourceClaims": [IoK8sApiCoreV1PodResourceClaim.from_dict(_item) for _item in obj["resourceClaims"]] if obj.get("resourceClaims") is not None else None, + "resources": IoK8sApiCoreV1ResourceRequirements.from_dict(obj["resources"]) if obj.get("resources") is not None else None, + "restartPolicy": obj.get("restartPolicy"), + "runtimeClassName": obj.get("runtimeClassName"), + "schedulerName": obj.get("schedulerName"), + "schedulingGates": [IoK8sApiCoreV1PodSchedulingGate.from_dict(_item) for _item in obj["schedulingGates"]] if obj.get("schedulingGates") is not None else None, + "securityContext": IoK8sApiCoreV1PodSecurityContext.from_dict(obj["securityContext"]) if obj.get("securityContext") is not None else None, + "serviceAccount": obj.get("serviceAccount"), + "serviceAccountName": obj.get("serviceAccountName"), + "setHostnameAsFQDN": obj.get("setHostnameAsFQDN"), + "shareProcessNamespace": obj.get("shareProcessNamespace"), + "subdomain": obj.get("subdomain"), + "terminationGracePeriodSeconds": obj.get("terminationGracePeriodSeconds"), + "tolerations": [IoK8sApiCoreV1Toleration.from_dict(_item) for _item in obj["tolerations"]] if obj.get("tolerations") is not None else None, + "topologySpreadConstraints": [IoK8sApiCoreV1TopologySpreadConstraint.from_dict(_item) for _item in obj["topologySpreadConstraints"]] if obj.get("topologySpreadConstraints") is not None else None, + "volumes": [IoK8sApiCoreV1Volume.from_dict(_item) for _item in obj["volumes"]] if obj.get("volumes") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_template_spec.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_template_spec.py new file mode 100644 index 0000000000..2c92f4f3ab --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_pod_template_spec.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_spec import IoK8sApiCoreV1PodSpec +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PodTemplateSpec(BaseModel): + """ + PodTemplateSpec describes the data a pod should have when created from a template + """ # noqa: E501 + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: Optional[IoK8sApiCoreV1PodSpec] = None + __properties: ClassVar[List[str]] = ["metadata", "spec"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodTemplateSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PodTemplateSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": IoK8sApiCoreV1PodSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_portworx_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_portworx_volume_source.py new file mode 100644 index 0000000000..10be79290b --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_portworx_volume_source.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PortworxVolumeSource(BaseModel): + """ + PortworxVolumeSource represents a Portworx volume resource. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fSType represents the filesystem type to mount Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\". Implicitly inferred to be \"ext4\" if unspecified.", alias="fsType") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + volume_id: StrictStr = Field(description="volumeID uniquely identifies a Portworx volume", alias="volumeID") + __properties: ClassVar[List[str]] = ["fsType", "readOnly", "volumeID"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PortworxVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PortworxVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "readOnly": obj.get("readOnly"), + "volumeID": obj.get("volumeID") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_preferred_scheduling_term.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_preferred_scheduling_term.py new file mode 100644 index 0000000000..6e30d91c05 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_preferred_scheduling_term.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_core_v1_node_selector_term import IoK8sApiCoreV1NodeSelectorTerm +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1PreferredSchedulingTerm(BaseModel): + """ + An empty preferred scheduling term matches all objects with implicit weight 0 (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op). + """ # noqa: E501 + preference: IoK8sApiCoreV1NodeSelectorTerm + weight: StrictInt = Field(description="Weight associated with matching the corresponding nodeSelectorTerm, in the range 1-100.") + __properties: ClassVar[List[str]] = ["preference", "weight"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PreferredSchedulingTerm from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 preference + if self.preference: + _dict['preference'] = self.preference.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1PreferredSchedulingTerm from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "preference": IoK8sApiCoreV1NodeSelectorTerm.from_dict(obj["preference"]) if obj.get("preference") is not None else None, + "weight": obj.get("weight") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_probe.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_probe.py new file mode 100644 index 0000000000..7e2ee1af24 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_probe.py @@ -0,0 +1,121 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_exec_action import IoK8sApiCoreV1ExecAction +from kubeflow.trainer.models.io_k8s_api_core_v1_grpc_action import IoK8sApiCoreV1GRPCAction +from kubeflow.trainer.models.io_k8s_api_core_v1_http_get_action import IoK8sApiCoreV1HTTPGetAction +from kubeflow.trainer.models.io_k8s_api_core_v1_tcp_socket_action import IoK8sApiCoreV1TCPSocketAction +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Probe(BaseModel): + """ + Probe describes a health check to be performed against a container to determine whether it is alive or ready to receive traffic. + """ # noqa: E501 + var_exec: Optional[IoK8sApiCoreV1ExecAction] = Field(default=None, alias="exec") + failure_threshold: Optional[StrictInt] = Field(default=None, description="Minimum consecutive failures for the probe to be considered failed after having succeeded. Defaults to 3. Minimum value is 1.", alias="failureThreshold") + grpc: Optional[IoK8sApiCoreV1GRPCAction] = None + http_get: Optional[IoK8sApiCoreV1HTTPGetAction] = Field(default=None, alias="httpGet") + initial_delay_seconds: Optional[StrictInt] = Field(default=None, description="Number of seconds after the container has started before liveness probes are initiated. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", alias="initialDelaySeconds") + period_seconds: Optional[StrictInt] = Field(default=None, description="How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1.", alias="periodSeconds") + success_threshold: Optional[StrictInt] = Field(default=None, description="Minimum consecutive successes for the probe to be considered successful after having failed. Defaults to 1. Must be 1 for liveness and startup. Minimum value is 1.", alias="successThreshold") + tcp_socket: Optional[IoK8sApiCoreV1TCPSocketAction] = Field(default=None, alias="tcpSocket") + termination_grace_period_seconds: Optional[StrictInt] = Field(default=None, description="Optional duration in seconds the pod needs to terminate gracefully upon probe failure. The grace period is the duration in seconds after the processes running in the pod are sent a termination signal and the time when the processes are forcibly halted with a kill signal. Set this value longer than the expected cleanup time for your process. If this value is nil, the pod's terminationGracePeriodSeconds will be used. Otherwise, this value overrides the value provided by the pod spec. Value must be non-negative integer. The value zero indicates stop immediately via the kill signal (no opportunity to shut down). This is a beta field and requires enabling ProbeTerminationGracePeriod feature gate. Minimum value is 1. spec.terminationGracePeriodSeconds is used if unset.", alias="terminationGracePeriodSeconds") + timeout_seconds: Optional[StrictInt] = Field(default=None, description="Number of seconds after which the probe times out. Defaults to 1 second. Minimum value is 1. More info: https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes", alias="timeoutSeconds") + __properties: ClassVar[List[str]] = ["exec", "failureThreshold", "grpc", "httpGet", "initialDelaySeconds", "periodSeconds", "successThreshold", "tcpSocket", "terminationGracePeriodSeconds", "timeoutSeconds"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Probe from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 var_exec + if self.var_exec: + _dict['exec'] = self.var_exec.to_dict() + # override the default output from pydantic by calling `to_dict()` of grpc + if self.grpc: + _dict['grpc'] = self.grpc.to_dict() + # override the default output from pydantic by calling `to_dict()` of http_get + if self.http_get: + _dict['httpGet'] = self.http_get.to_dict() + # override the default output from pydantic by calling `to_dict()` of tcp_socket + if self.tcp_socket: + _dict['tcpSocket'] = self.tcp_socket.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Probe from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "exec": IoK8sApiCoreV1ExecAction.from_dict(obj["exec"]) if obj.get("exec") is not None else None, + "failureThreshold": obj.get("failureThreshold"), + "grpc": IoK8sApiCoreV1GRPCAction.from_dict(obj["grpc"]) if obj.get("grpc") is not None else None, + "httpGet": IoK8sApiCoreV1HTTPGetAction.from_dict(obj["httpGet"]) if obj.get("httpGet") is not None else None, + "initialDelaySeconds": obj.get("initialDelaySeconds"), + "periodSeconds": obj.get("periodSeconds"), + "successThreshold": obj.get("successThreshold"), + "tcpSocket": IoK8sApiCoreV1TCPSocketAction.from_dict(obj["tcpSocket"]) if obj.get("tcpSocket") is not None else None, + "terminationGracePeriodSeconds": obj.get("terminationGracePeriodSeconds"), + "timeoutSeconds": obj.get("timeoutSeconds") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_projected_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_projected_volume_source.py new file mode 100644 index 0000000000..96ac3e529a --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_projected_volume_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_projection import IoK8sApiCoreV1VolumeProjection +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ProjectedVolumeSource(BaseModel): + """ + Represents a projected volume source + """ # noqa: E501 + default_mode: Optional[StrictInt] = Field(default=None, description="defaultMode are the mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", alias="defaultMode") + sources: Optional[List[IoK8sApiCoreV1VolumeProjection]] = Field(default=None, description="sources is the list of volume projections. Each entry in this list handles one source.") + __properties: ClassVar[List[str]] = ["defaultMode", "sources"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ProjectedVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 sources (list) + _items = [] + if self.sources: + for _item_sources in self.sources: + if _item_sources: + _items.append(_item_sources.to_dict()) + _dict['sources'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ProjectedVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "defaultMode": obj.get("defaultMode"), + "sources": [IoK8sApiCoreV1VolumeProjection.from_dict(_item) for _item in obj["sources"]] if obj.get("sources") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_quobyte_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_quobyte_volume_source.py new file mode 100644 index 0000000000..7c90a358cf --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_quobyte_volume_source.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1QuobyteVolumeSource(BaseModel): + """ + Represents a Quobyte mount that lasts the lifetime of a pod. Quobyte volumes do not support ownership management or SELinux relabeling. + """ # noqa: E501 + group: Optional[StrictStr] = Field(default=None, description="group to map volume access to Default is no group") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly here will force the Quobyte volume to be mounted with read-only permissions. Defaults to false.", alias="readOnly") + registry: StrictStr = Field(description="registry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumes") + tenant: Optional[StrictStr] = Field(default=None, description="tenant owning the given Quobyte volume in the Backend Used with dynamically provisioned Quobyte volumes, value is set by the plugin") + user: Optional[StrictStr] = Field(default=None, description="user to map volume access to Defaults to serivceaccount user") + volume: StrictStr = Field(description="volume is a string that references an already created Quobyte volume by name.") + __properties: ClassVar[List[str]] = ["group", "readOnly", "registry", "tenant", "user", "volume"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1QuobyteVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1QuobyteVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "group": obj.get("group"), + "readOnly": obj.get("readOnly"), + "registry": obj.get("registry"), + "tenant": obj.get("tenant"), + "user": obj.get("user"), + "volume": obj.get("volume") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_rbd_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_rbd_volume_source.py new file mode 100644 index 0000000000..5fca373ffe --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_rbd_volume_source.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1RBDVolumeSource(BaseModel): + """ + Represents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd", alias="fsType") + image: StrictStr = Field(description="image is the rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it") + keyring: Optional[StrictStr] = Field(default=None, description="keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it") + monitors: List[StrictStr] = Field(description="monitors is a collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it") + pool: Optional[StrictStr] = Field(default=None, description="pool is the rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it", alias="readOnly") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + user: Optional[StrictStr] = Field(default=None, description="user is the rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it") + __properties: ClassVar[List[str]] = ["fsType", "image", "keyring", "monitors", "pool", "readOnly", "secretRef", "user"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1RBDVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1RBDVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "image": obj.get("image"), + "keyring": obj.get("keyring"), + "monitors": obj.get("monitors"), + "pool": obj.get("pool"), + "readOnly": obj.get("readOnly"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "user": obj.get("user") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_claim.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_claim.py new file mode 100644 index 0000000000..948258c77d --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_claim.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ResourceClaim(BaseModel): + """ + ResourceClaim references one entry in PodSpec.ResourceClaims. + """ # noqa: E501 + name: StrictStr = Field(description="Name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container.") + request: Optional[StrictStr] = Field(default=None, description="Request is the name chosen for a request in the referenced claim. If empty, everything from the claim is made available, otherwise only the result of this request.") + __properties: ClassVar[List[str]] = ["name", "request"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ResourceClaim from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ResourceClaim from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "request": obj.get("request") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_field_selector.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_field_selector.py new file mode 100644 index 0000000000..d16337cf18 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_field_selector.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ResourceFieldSelector(BaseModel): + """ + ResourceFieldSelector represents container resources (cpu, memory) and their output format + """ # noqa: E501 + container_name: Optional[StrictStr] = Field(default=None, description="Container name: required for volumes, optional for env vars", alias="containerName") + divisor: Optional[StrictStr] = Field(default=None, description="Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors. The serialization format is: ``` ::= (Note that may be empty, from the \"\" case in .) ::= 0 | 1 | ... | 9 ::= | ::= | . | . | . ::= \"+\" | \"-\" ::= | ::= | | ::= Ki | Mi | Gi | Ti | Pi | Ei (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html) ::= m | \"\" | k | M | G | T | P | E (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.) ::= \"e\" | \"E\" ``` No matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities. When a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized. Before serializing, Quantity will be put in \"canonical form\". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that: - No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible. The sign will be omitted unless the number is negative. Examples: - 1.5 will be serialized as \"1500m\" - 1.5Gi will be serialized as \"1536Mi\" Note that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise. Non-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.) This format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.") + resource: StrictStr = Field(description="Required: resource to select") + __properties: ClassVar[List[str]] = ["containerName", "divisor", "resource"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ResourceFieldSelector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ResourceFieldSelector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "containerName": obj.get("containerName"), + "divisor": obj.get("divisor"), + "resource": obj.get("resource") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_requirements.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_requirements.py new file mode 100644 index 0000000000..c0c5e468da --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_resource_requirements.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_claim import IoK8sApiCoreV1ResourceClaim +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ResourceRequirements(BaseModel): + """ + ResourceRequirements describes the compute resource requirements. + """ # noqa: E501 + claims: Optional[List[IoK8sApiCoreV1ResourceClaim]] = Field(default=None, description="Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container. This is an alpha field and requires enabling the DynamicResourceAllocation feature gate. This field is immutable. It can only be set for containers.") + limits: Optional[Dict[str, StrictStr]] = Field(default=None, description="Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/") + requests: Optional[Dict[str, StrictStr]] = Field(default=None, description="Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/") + __properties: ClassVar[List[str]] = ["claims", "limits", "requests"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ResourceRequirements from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 claims (list) + _items = [] + if self.claims: + for _item_claims in self.claims: + if _item_claims: + _items.append(_item_claims.to_dict()) + _dict['claims'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ResourceRequirements from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "claims": [IoK8sApiCoreV1ResourceClaim.from_dict(_item) for _item in obj["claims"]] if obj.get("claims") is not None else None, + "limits": obj.get("limits"), + "requests": obj.get("requests") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_scale_io_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_scale_io_volume_source.py new file mode 100644 index 0000000000..8d9974c694 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_scale_io_volume_source.py @@ -0,0 +1,109 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ScaleIOVolumeSource(BaseModel): + """ + ScaleIOVolumeSource represents a persistent ScaleIO volume + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Default is \"xfs\".", alias="fsType") + gateway: StrictStr = Field(description="gateway is the host address of the ScaleIO API Gateway.") + protection_domain: Optional[StrictStr] = Field(default=None, description="protectionDomain is the name of the ScaleIO Protection Domain for the configured storage.", alias="protectionDomain") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + secret_ref: IoK8sApiCoreV1LocalObjectReference = Field(alias="secretRef") + ssl_enabled: Optional[StrictBool] = Field(default=None, description="sslEnabled Flag enable/disable SSL communication with Gateway, default false", alias="sslEnabled") + storage_mode: Optional[StrictStr] = Field(default=None, description="storageMode indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.", alias="storageMode") + storage_pool: Optional[StrictStr] = Field(default=None, description="storagePool is the ScaleIO Storage Pool associated with the protection domain.", alias="storagePool") + system: StrictStr = Field(description="system is the name of the storage system as configured in ScaleIO.") + volume_name: Optional[StrictStr] = Field(default=None, description="volumeName is the name of a volume already created in the ScaleIO system that is associated with this volume source.", alias="volumeName") + __properties: ClassVar[List[str]] = ["fsType", "gateway", "protectionDomain", "readOnly", "secretRef", "sslEnabled", "storageMode", "storagePool", "system", "volumeName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ScaleIOVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ScaleIOVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "gateway": obj.get("gateway"), + "protectionDomain": obj.get("protectionDomain"), + "readOnly": obj.get("readOnly"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "sslEnabled": obj.get("sslEnabled"), + "storageMode": obj.get("storageMode"), + "storagePool": obj.get("storagePool"), + "system": obj.get("system"), + "volumeName": obj.get("volumeName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_se_linux_options.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_se_linux_options.py new file mode 100644 index 0000000000..656613ebb7 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_se_linux_options.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SELinuxOptions(BaseModel): + """ + SELinuxOptions are the labels to be applied to the container + """ # noqa: E501 + level: Optional[StrictStr] = Field(default=None, description="Level is SELinux level label that applies to the container.") + role: Optional[StrictStr] = Field(default=None, description="Role is a SELinux role label that applies to the container.") + type: Optional[StrictStr] = Field(default=None, description="Type is a SELinux type label that applies to the container.") + user: Optional[StrictStr] = Field(default=None, description="User is a SELinux user label that applies to the container.") + __properties: ClassVar[List[str]] = ["level", "role", "type", "user"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SELinuxOptions from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SELinuxOptions from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "level": obj.get("level"), + "role": obj.get("role"), + "type": obj.get("type"), + "user": obj.get("user") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_seccomp_profile.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_seccomp_profile.py new file mode 100644 index 0000000000..134d0ada63 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_seccomp_profile.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SeccompProfile(BaseModel): + """ + SeccompProfile defines a pod/container's seccomp profile settings. Only one profile source may be set. + """ # noqa: E501 + localhost_profile: Optional[StrictStr] = Field(default=None, description="localhostProfile indicates a profile defined in a file on the node should be used. The profile must be preconfigured on the node to work. Must be a descending path, relative to the kubelet's configured seccomp profile location. Must be set if type is \"Localhost\". Must NOT be set for any other type.", alias="localhostProfile") + type: StrictStr = Field(description="type indicates which kind of seccomp profile will be applied. Valid options are: Localhost - a profile defined in a file on the node should be used. RuntimeDefault - the container runtime default profile should be used. Unconfined - no profile should be applied.") + __properties: ClassVar[List[str]] = ["localhostProfile", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SeccompProfile from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SeccompProfile from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "localhostProfile": obj.get("localhostProfile"), + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_env_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_env_source.py new file mode 100644 index 0000000000..1ac0c7547c --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_env_source.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SecretEnvSource(BaseModel): + """ + SecretEnvSource selects a Secret to populate the environment variables with. The contents of the target Secret's Data field will represent the key-value pairs as environment variables. + """ # noqa: E501 + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="Specify whether the Secret must be defined") + __properties: ClassVar[List[str]] = ["name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretEnvSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretEnvSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_key_selector.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_key_selector.py new file mode 100644 index 0000000000..e8848c1b82 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_key_selector.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SecretKeySelector(BaseModel): + """ + SecretKeySelector selects a key of a Secret. + """ # noqa: E501 + key: StrictStr = Field(description="The key of the secret to select from. Must be a valid secret key.") + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="Specify whether the Secret or its key must be defined") + __properties: ClassVar[List[str]] = ["key", "name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretKeySelector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretKeySelector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_projection.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_projection.py new file mode 100644 index 0000000000..d2302b6704 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_projection.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_key_to_path import IoK8sApiCoreV1KeyToPath +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SecretProjection(BaseModel): + """ + Adapts a secret into a projected volume. The contents of the target Secret's Data field will be presented in a projected volume as files using the keys in the Data field as the file names. Note that this is identical to a secret volume source without the default mode. + """ # noqa: E501 + items: Optional[List[IoK8sApiCoreV1KeyToPath]] = Field(default=None, description="items if unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.") + name: Optional[StrictStr] = Field(default=None, description="Name of the referent. This field is effectively required, but due to backwards compatibility is allowed to be empty. Instances of this type with an empty value here are almost certainly wrong. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + optional: Optional[StrictBool] = Field(default=None, description="optional field specify whether the Secret or its key must be defined") + __properties: ClassVar[List[str]] = ["items", "name", "optional"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretProjection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretProjection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "items": [IoK8sApiCoreV1KeyToPath.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "name": obj.get("name"), + "optional": obj.get("optional") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_volume_source.py new file mode 100644 index 0000000000..295a0630a6 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_secret_volume_source.py @@ -0,0 +1,101 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_key_to_path import IoK8sApiCoreV1KeyToPath +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SecretVolumeSource(BaseModel): + """ + Adapts a Secret into a volume. The contents of the target Secret's Data field will be presented in a volume as files using the keys in the Data field as the file names. Secret volumes support ownership management and SELinux relabeling. + """ # noqa: E501 + default_mode: Optional[StrictInt] = Field(default=None, description="defaultMode is Optional: mode bits used to set permissions on created files by default. Must be an octal value between 0000 and 0777 or a decimal value between 0 and 511. YAML accepts both octal and decimal values, JSON requires decimal values for mode bits. Defaults to 0644. Directories within the path are not affected by this setting. This might be in conflict with other options that affect the file mode, like fsGroup, and the result can be other mode bits set.", alias="defaultMode") + items: Optional[List[IoK8sApiCoreV1KeyToPath]] = Field(default=None, description="items If unspecified, each key-value pair in the Data field of the referenced Secret will be projected into the volume as a file whose name is the key and content is the value. If specified, the listed keys will be projected into the specified paths, and unlisted keys will not be present. If a key is specified which is not present in the Secret, the volume setup will error unless it is marked optional. Paths must be relative and may not contain the '..' path or start with '..'.") + optional: Optional[StrictBool] = Field(default=None, description="optional field specify whether the Secret or its keys must be defined") + secret_name: Optional[StrictStr] = Field(default=None, description="secretName is the name of the secret in the pod's namespace to use. More info: https://kubernetes.io/docs/concepts/storage/volumes#secret", alias="secretName") + __properties: ClassVar[List[str]] = ["defaultMode", "items", "optional", "secretName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecretVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "defaultMode": obj.get("defaultMode"), + "items": [IoK8sApiCoreV1KeyToPath.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "optional": obj.get("optional"), + "secretName": obj.get("secretName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_security_context.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_security_context.py new file mode 100644 index 0000000000..7427430e89 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_security_context.py @@ -0,0 +1,129 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_app_armor_profile import IoK8sApiCoreV1AppArmorProfile +from kubeflow.trainer.models.io_k8s_api_core_v1_capabilities import IoK8sApiCoreV1Capabilities +from kubeflow.trainer.models.io_k8s_api_core_v1_se_linux_options import IoK8sApiCoreV1SELinuxOptions +from kubeflow.trainer.models.io_k8s_api_core_v1_seccomp_profile import IoK8sApiCoreV1SeccompProfile +from kubeflow.trainer.models.io_k8s_api_core_v1_windows_security_context_options import IoK8sApiCoreV1WindowsSecurityContextOptions +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SecurityContext(BaseModel): + """ + SecurityContext holds security configuration that will be applied to a container. Some fields are present in both SecurityContext and PodSecurityContext. When both are set, the values in SecurityContext take precedence. + """ # noqa: E501 + allow_privilege_escalation: Optional[StrictBool] = Field(default=None, description="AllowPrivilegeEscalation controls whether a process can gain more privileges than its parent process. This bool directly controls if the no_new_privs flag will be set on the container process. AllowPrivilegeEscalation is true always when the container is: 1) run as Privileged 2) has CAP_SYS_ADMIN Note that this field cannot be set when spec.os.name is windows.", alias="allowPrivilegeEscalation") + app_armor_profile: Optional[IoK8sApiCoreV1AppArmorProfile] = Field(default=None, alias="appArmorProfile") + capabilities: Optional[IoK8sApiCoreV1Capabilities] = None + privileged: Optional[StrictBool] = Field(default=None, description="Run container in privileged mode. Processes in privileged containers are essentially equivalent to root on the host. Defaults to false. Note that this field cannot be set when spec.os.name is windows.") + proc_mount: Optional[StrictStr] = Field(default=None, description="procMount denotes the type of proc mount to use for the containers. The default value is Default which uses the container runtime defaults for readonly paths and masked paths. This requires the ProcMountType feature flag to be enabled. Note that this field cannot be set when spec.os.name is windows.", alias="procMount") + read_only_root_filesystem: Optional[StrictBool] = Field(default=None, description="Whether this container has a read-only root filesystem. Default is false. Note that this field cannot be set when spec.os.name is windows.", alias="readOnlyRootFilesystem") + run_as_group: Optional[StrictInt] = Field(default=None, description="The GID to run the entrypoint of the container process. Uses runtime default if unset. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", alias="runAsGroup") + run_as_non_root: Optional[StrictBool] = Field(default=None, description="Indicates that the container must run as a non-root user. If true, the Kubelet will validate the image at runtime to ensure that it does not run as UID 0 (root) and fail to start the container if it does. If unset or false, no such validation will be performed. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", alias="runAsNonRoot") + run_as_user: Optional[StrictInt] = Field(default=None, description="The UID to run the entrypoint of the container process. Defaults to user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence. Note that this field cannot be set when spec.os.name is windows.", alias="runAsUser") + se_linux_options: Optional[IoK8sApiCoreV1SELinuxOptions] = Field(default=None, alias="seLinuxOptions") + seccomp_profile: Optional[IoK8sApiCoreV1SeccompProfile] = Field(default=None, alias="seccompProfile") + windows_options: Optional[IoK8sApiCoreV1WindowsSecurityContextOptions] = Field(default=None, alias="windowsOptions") + __properties: ClassVar[List[str]] = ["allowPrivilegeEscalation", "appArmorProfile", "capabilities", "privileged", "procMount", "readOnlyRootFilesystem", "runAsGroup", "runAsNonRoot", "runAsUser", "seLinuxOptions", "seccompProfile", "windowsOptions"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecurityContext from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 app_armor_profile + if self.app_armor_profile: + _dict['appArmorProfile'] = self.app_armor_profile.to_dict() + # override the default output from pydantic by calling `to_dict()` of capabilities + if self.capabilities: + _dict['capabilities'] = self.capabilities.to_dict() + # override the default output from pydantic by calling `to_dict()` of se_linux_options + if self.se_linux_options: + _dict['seLinuxOptions'] = self.se_linux_options.to_dict() + # override the default output from pydantic by calling `to_dict()` of seccomp_profile + if self.seccomp_profile: + _dict['seccompProfile'] = self.seccomp_profile.to_dict() + # override the default output from pydantic by calling `to_dict()` of windows_options + if self.windows_options: + _dict['windowsOptions'] = self.windows_options.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SecurityContext from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "allowPrivilegeEscalation": obj.get("allowPrivilegeEscalation"), + "appArmorProfile": IoK8sApiCoreV1AppArmorProfile.from_dict(obj["appArmorProfile"]) if obj.get("appArmorProfile") is not None else None, + "capabilities": IoK8sApiCoreV1Capabilities.from_dict(obj["capabilities"]) if obj.get("capabilities") is not None else None, + "privileged": obj.get("privileged"), + "procMount": obj.get("procMount"), + "readOnlyRootFilesystem": obj.get("readOnlyRootFilesystem"), + "runAsGroup": obj.get("runAsGroup"), + "runAsNonRoot": obj.get("runAsNonRoot"), + "runAsUser": obj.get("runAsUser"), + "seLinuxOptions": IoK8sApiCoreV1SELinuxOptions.from_dict(obj["seLinuxOptions"]) if obj.get("seLinuxOptions") is not None else None, + "seccompProfile": IoK8sApiCoreV1SeccompProfile.from_dict(obj["seccompProfile"]) if obj.get("seccompProfile") is not None else None, + "windowsOptions": IoK8sApiCoreV1WindowsSecurityContextOptions.from_dict(obj["windowsOptions"]) if obj.get("windowsOptions") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_service_account_token_projection.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_service_account_token_projection.py new file mode 100644 index 0000000000..392a619fb3 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_service_account_token_projection.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1ServiceAccountTokenProjection(BaseModel): + """ + ServiceAccountTokenProjection represents a projected service account token volume. This projection can be used to insert a service account token into the pods runtime filesystem for use against APIs (Kubernetes API Server or otherwise). + """ # noqa: E501 + audience: Optional[StrictStr] = Field(default=None, description="audience is the intended audience of the token. A recipient of a token must identify itself with an identifier specified in the audience of the token, and otherwise should reject the token. The audience defaults to the identifier of the apiserver.") + expiration_seconds: Optional[StrictInt] = Field(default=None, description="expirationSeconds is the requested duration of validity of the service account token. As the token approaches expiration, the kubelet volume plugin will proactively rotate the service account token. The kubelet will start trying to rotate the token if the token is older than 80 percent of its time to live or if the token is older than 24 hours.Defaults to 1 hour and must be at least 10 minutes.", alias="expirationSeconds") + path: StrictStr = Field(description="path is the path relative to the mount point of the file to project the token into.") + __properties: ClassVar[List[str]] = ["audience", "expirationSeconds", "path"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ServiceAccountTokenProjection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1ServiceAccountTokenProjection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "audience": obj.get("audience"), + "expirationSeconds": obj.get("expirationSeconds"), + "path": obj.get("path") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_sleep_action.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_sleep_action.py new file mode 100644 index 0000000000..6f956f130c --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_sleep_action.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1SleepAction(BaseModel): + """ + SleepAction describes a \"sleep\" action. + """ # noqa: E501 + seconds: StrictInt = Field(description="Seconds is the number of seconds to sleep.") + __properties: ClassVar[List[str]] = ["seconds"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SleepAction from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1SleepAction from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "seconds": obj.get("seconds") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_storage_os_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_storage_os_volume_source.py new file mode 100644 index 0000000000..507ba30b96 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_storage_os_volume_source.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1StorageOSVolumeSource(BaseModel): + """ + Represents a StorageOS persistent volume resource. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", alias="fsType") + read_only: Optional[StrictBool] = Field(default=None, description="readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.", alias="readOnly") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + volume_name: Optional[StrictStr] = Field(default=None, description="volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.", alias="volumeName") + volume_namespace: Optional[StrictStr] = Field(default=None, description="volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to \"default\" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.", alias="volumeNamespace") + __properties: ClassVar[List[str]] = ["fsType", "readOnly", "secretRef", "volumeName", "volumeNamespace"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1StorageOSVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1StorageOSVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "readOnly": obj.get("readOnly"), + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "volumeName": obj.get("volumeName"), + "volumeNamespace": obj.get("volumeNamespace") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_sysctl.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_sysctl.py new file mode 100644 index 0000000000..5aa33da77e --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_sysctl.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Sysctl(BaseModel): + """ + Sysctl defines a kernel parameter to be set + """ # noqa: E501 + name: StrictStr = Field(description="Name of a property to set") + value: StrictStr = Field(description="Value of a property to set") + __properties: ClassVar[List[str]] = ["name", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Sysctl from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Sysctl from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "value": obj.get("value") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_tcp_socket_action.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_tcp_socket_action.py new file mode 100644 index 0000000000..6cc250b3a2 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_tcp_socket_action.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1TCPSocketAction(BaseModel): + """ + TCPSocketAction describes an action based on opening a socket + """ # noqa: E501 + host: Optional[StrictStr] = Field(default=None, description="Optional: Host name to connect to, defaults to the pod IP.") + port: StrictStr = Field(description="IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.") + __properties: ClassVar[List[str]] = ["host", "port"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TCPSocketAction from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TCPSocketAction from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "host": obj.get("host"), + "port": obj.get("port") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_toleration.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_toleration.py new file mode 100644 index 0000000000..92e4e27ea7 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_toleration.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Toleration(BaseModel): + """ + The pod this Toleration is attached to tolerates any taint that matches the triple using the matching operator . + """ # noqa: E501 + effect: Optional[StrictStr] = Field(default=None, description="Effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute.") + key: Optional[StrictStr] = Field(default=None, description="Key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys.") + operator: Optional[StrictStr] = Field(default=None, description="Operator represents a key's relationship to the value. Valid operators are Exists and Equal. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category.") + toleration_seconds: Optional[StrictInt] = Field(default=None, description="TolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system.", alias="tolerationSeconds") + value: Optional[StrictStr] = Field(default=None, description="Value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string.") + __properties: ClassVar[List[str]] = ["effect", "key", "operator", "tolerationSeconds", "value"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Toleration from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Toleration from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "effect": obj.get("effect"), + "key": obj.get("key"), + "operator": obj.get("operator"), + "tolerationSeconds": obj.get("tolerationSeconds"), + "value": obj.get("value") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_topology_spread_constraint.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_topology_spread_constraint.py new file mode 100644 index 0000000000..29a57714ab --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_topology_spread_constraint.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector import IoK8sApimachineryPkgApisMetaV1LabelSelector +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1TopologySpreadConstraint(BaseModel): + """ + TopologySpreadConstraint specifies how to spread matching pods among the given topology. + """ # noqa: E501 + label_selector: Optional[IoK8sApimachineryPkgApisMetaV1LabelSelector] = Field(default=None, alias="labelSelector") + match_label_keys: Optional[List[StrictStr]] = Field(default=None, description="MatchLabelKeys is a set of pod label keys to select the pods over which spreading will be calculated. The keys are used to lookup values from the incoming pod labels, those key-value labels are ANDed with labelSelector to select the group of existing pods over which spreading will be calculated for the incoming pod. The same key is forbidden to exist in both MatchLabelKeys and LabelSelector. MatchLabelKeys cannot be set when LabelSelector isn't set. Keys that don't exist in the incoming pod labels will be ignored. A null or empty list means only match against labelSelector. This is a beta field and requires the MatchLabelKeysInPodTopologySpread feature gate to be enabled (enabled by default).", alias="matchLabelKeys") + max_skew: StrictInt = Field(description="MaxSkew describes the degree to which pods may be unevenly distributed. When `whenUnsatisfiable=DoNotSchedule`, it is the maximum permitted difference between the number of matching pods in the target topology and the global minimum. The global minimum is the minimum number of matching pods in an eligible domain or zero if the number of eligible domains is less than MinDomains. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 2/2/1: In this case, the global minimum is 1. | zone1 | zone2 | zone3 | | P P | P P | P | - if MaxSkew is 1, incoming pod can only be scheduled to zone3 to become 2/2/2; scheduling it onto zone1(zone2) would make the ActualSkew(3-1) on zone1(zone2) violate MaxSkew(1). - if MaxSkew is 2, incoming pod can be scheduled onto any zone. When `whenUnsatisfiable=ScheduleAnyway`, it is used to give higher precedence to topologies that satisfy it. It's a required field. Default value is 1 and 0 is not allowed.", alias="maxSkew") + min_domains: Optional[StrictInt] = Field(default=None, description="MinDomains indicates a minimum number of eligible domains. When the number of eligible domains with matching topology keys is less than minDomains, Pod Topology Spread treats \"global minimum\" as 0, and then the calculation of Skew is performed. And when the number of eligible domains with matching topology keys equals or greater than minDomains, this value has no effect on scheduling. As a result, when the number of eligible domains is less than minDomains, scheduler won't schedule more than maxSkew Pods to those domains. If value is nil, the constraint behaves as if MinDomains is equal to 1. Valid values are integers greater than 0. When value is not nil, WhenUnsatisfiable must be DoNotSchedule. For example, in a 3-zone cluster, MaxSkew is set to 2, MinDomains is set to 5 and pods with the same labelSelector spread as 2/2/2: | zone1 | zone2 | zone3 | | P P | P P | P P | The number of domains is less than 5(MinDomains), so \"global minimum\" is treated as 0. In this situation, new pod with the same labelSelector cannot be scheduled, because computed skew will be 3(3 - 0) if new Pod is scheduled to any of the three zones, it will violate MaxSkew.", alias="minDomains") + node_affinity_policy: Optional[StrictStr] = Field(default=None, description="NodeAffinityPolicy indicates how we will treat Pod's nodeAffinity/nodeSelector when calculating pod topology spread skew. Options are: - Honor: only nodes matching nodeAffinity/nodeSelector are included in the calculations. - Ignore: nodeAffinity/nodeSelector are ignored. All nodes are included in the calculations. If this value is nil, the behavior is equivalent to the Honor policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.", alias="nodeAffinityPolicy") + node_taints_policy: Optional[StrictStr] = Field(default=None, description="NodeTaintsPolicy indicates how we will treat node taints when calculating pod topology spread skew. Options are: - Honor: nodes without taints, along with tainted nodes for which the incoming pod has a toleration, are included. - Ignore: node taints are ignored. All nodes are included. If this value is nil, the behavior is equivalent to the Ignore policy. This is a beta-level feature default enabled by the NodeInclusionPolicyInPodTopologySpread feature flag.", alias="nodeTaintsPolicy") + topology_key: StrictStr = Field(description="TopologyKey is the key of node labels. Nodes that have a label with this key and identical values are considered to be in the same topology. We consider each as a \"bucket\", and try to put balanced number of pods into each bucket. We define a domain as a particular instance of a topology. Also, we define an eligible domain as a domain whose nodes meet the requirements of nodeAffinityPolicy and nodeTaintsPolicy. e.g. If TopologyKey is \"kubernetes.io/hostname\", each Node is a domain of that topology. And, if TopologyKey is \"topology.kubernetes.io/zone\", each zone is a domain of that topology. It's a required field.", alias="topologyKey") + when_unsatisfiable: StrictStr = Field(description="WhenUnsatisfiable indicates how to deal with a pod if it doesn't satisfy the spread constraint. - DoNotSchedule (default) tells the scheduler not to schedule it. - ScheduleAnyway tells the scheduler to schedule the pod in any location, but giving higher precedence to topologies that would help reduce the skew. A constraint is considered \"Unsatisfiable\" for an incoming pod if and only if every possible node assignment for that pod would violate \"MaxSkew\" on some topology. For example, in a 3-zone cluster, MaxSkew is set to 1, and pods with the same labelSelector spread as 3/1/1: | zone1 | zone2 | zone3 | | P P P | P | P | If WhenUnsatisfiable is set to DoNotSchedule, incoming pod can only be scheduled to zone2(zone3) to become 3/2/1(3/1/2) as ActualSkew(2-1) on zone2(zone3) satisfies MaxSkew(1). In other words, the cluster can still be imbalanced, but scheduler won't make it *more* imbalanced. It's a required field.", alias="whenUnsatisfiable") + __properties: ClassVar[List[str]] = ["labelSelector", "matchLabelKeys", "maxSkew", "minDomains", "nodeAffinityPolicy", "nodeTaintsPolicy", "topologyKey", "whenUnsatisfiable"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TopologySpreadConstraint from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 label_selector + if self.label_selector: + _dict['labelSelector'] = self.label_selector.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TopologySpreadConstraint from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "labelSelector": IoK8sApimachineryPkgApisMetaV1LabelSelector.from_dict(obj["labelSelector"]) if obj.get("labelSelector") is not None else None, + "matchLabelKeys": obj.get("matchLabelKeys"), + "maxSkew": obj.get("maxSkew"), + "minDomains": obj.get("minDomains"), + "nodeAffinityPolicy": obj.get("nodeAffinityPolicy"), + "nodeTaintsPolicy": obj.get("nodeTaintsPolicy"), + "topologyKey": obj.get("topologyKey"), + "whenUnsatisfiable": obj.get("whenUnsatisfiable") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_typed_local_object_reference.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_typed_local_object_reference.py new file mode 100644 index 0000000000..c4b50cf705 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_typed_local_object_reference.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1TypedLocalObjectReference(BaseModel): + """ + TypedLocalObjectReference contains enough information to let you locate the typed referenced object inside the same namespace. + """ # noqa: E501 + api_group: Optional[StrictStr] = Field(default=None, description="APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", alias="apiGroup") + kind: StrictStr = Field(description="Kind is the type of resource being referenced") + name: StrictStr = Field(description="Name is the name of resource being referenced") + __properties: ClassVar[List[str]] = ["apiGroup", "kind", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TypedLocalObjectReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TypedLocalObjectReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiGroup": obj.get("apiGroup"), + "kind": obj.get("kind"), + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_typed_object_reference.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_typed_object_reference.py new file mode 100644 index 0000000000..07b15b0e3c --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_typed_object_reference.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1TypedObjectReference(BaseModel): + """ + TypedObjectReference contains enough information to let you locate the typed referenced object + """ # noqa: E501 + api_group: Optional[StrictStr] = Field(default=None, description="APIGroup is the group for the resource being referenced. If APIGroup is not specified, the specified Kind must be in the core API group. For any other third-party types, APIGroup is required.", alias="apiGroup") + kind: StrictStr = Field(description="Kind is the type of resource being referenced") + name: StrictStr = Field(description="Name is the name of resource being referenced") + namespace: Optional[StrictStr] = Field(default=None, description="Namespace is the namespace of resource being referenced Note that when a namespace is specified, a gateway.networking.k8s.io/ReferenceGrant object is required in the referent namespace to allow that namespace's owner to accept the reference. See the ReferenceGrant documentation for details. (Alpha) This field requires the CrossNamespaceVolumeDataSource feature gate to be enabled.") + __properties: ClassVar[List[str]] = ["apiGroup", "kind", "name", "namespace"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TypedObjectReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1TypedObjectReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiGroup": obj.get("apiGroup"), + "kind": obj.get("kind"), + "name": obj.get("name"), + "namespace": obj.get("namespace") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume.py new file mode 100644 index 0000000000..178354a599 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume.py @@ -0,0 +1,267 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_aws_elastic_block_store_volume_source import IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_azure_disk_volume_source import IoK8sApiCoreV1AzureDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_azure_file_volume_source import IoK8sApiCoreV1AzureFileVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_ceph_fs_volume_source import IoK8sApiCoreV1CephFSVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_cinder_volume_source import IoK8sApiCoreV1CinderVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_volume_source import IoK8sApiCoreV1ConfigMapVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_csi_volume_source import IoK8sApiCoreV1CSIVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_volume_source import IoK8sApiCoreV1DownwardAPIVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_empty_dir_volume_source import IoK8sApiCoreV1EmptyDirVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_ephemeral_volume_source import IoK8sApiCoreV1EphemeralVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_fc_volume_source import IoK8sApiCoreV1FCVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_flex_volume_source import IoK8sApiCoreV1FlexVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_flocker_volume_source import IoK8sApiCoreV1FlockerVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_gce_persistent_disk_volume_source import IoK8sApiCoreV1GCEPersistentDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_git_repo_volume_source import IoK8sApiCoreV1GitRepoVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_glusterfs_volume_source import IoK8sApiCoreV1GlusterfsVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_host_path_volume_source import IoK8sApiCoreV1HostPathVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_image_volume_source import IoK8sApiCoreV1ImageVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_iscsi_volume_source import IoK8sApiCoreV1ISCSIVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_nfs_volume_source import IoK8sApiCoreV1NFSVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_persistent_volume_claim_volume_source import IoK8sApiCoreV1PersistentVolumeClaimVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_photon_persistent_disk_volume_source import IoK8sApiCoreV1PhotonPersistentDiskVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_portworx_volume_source import IoK8sApiCoreV1PortworxVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_projected_volume_source import IoK8sApiCoreV1ProjectedVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_quobyte_volume_source import IoK8sApiCoreV1QuobyteVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_rbd_volume_source import IoK8sApiCoreV1RBDVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_scale_io_volume_source import IoK8sApiCoreV1ScaleIOVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_volume_source import IoK8sApiCoreV1SecretVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_storage_os_volume_source import IoK8sApiCoreV1StorageOSVolumeSource +from kubeflow.trainer.models.io_k8s_api_core_v1_vsphere_virtual_disk_volume_source import IoK8sApiCoreV1VsphereVirtualDiskVolumeSource +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1Volume(BaseModel): + """ + Volume represents a named volume in a pod that may be accessed by any container in the pod. + """ # noqa: E501 + aws_elastic_block_store: Optional[IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource] = Field(default=None, alias="awsElasticBlockStore") + azure_disk: Optional[IoK8sApiCoreV1AzureDiskVolumeSource] = Field(default=None, alias="azureDisk") + azure_file: Optional[IoK8sApiCoreV1AzureFileVolumeSource] = Field(default=None, alias="azureFile") + cephfs: Optional[IoK8sApiCoreV1CephFSVolumeSource] = None + cinder: Optional[IoK8sApiCoreV1CinderVolumeSource] = None + config_map: Optional[IoK8sApiCoreV1ConfigMapVolumeSource] = Field(default=None, alias="configMap") + csi: Optional[IoK8sApiCoreV1CSIVolumeSource] = None + downward_api: Optional[IoK8sApiCoreV1DownwardAPIVolumeSource] = Field(default=None, alias="downwardAPI") + empty_dir: Optional[IoK8sApiCoreV1EmptyDirVolumeSource] = Field(default=None, alias="emptyDir") + ephemeral: Optional[IoK8sApiCoreV1EphemeralVolumeSource] = None + fc: Optional[IoK8sApiCoreV1FCVolumeSource] = None + flex_volume: Optional[IoK8sApiCoreV1FlexVolumeSource] = Field(default=None, alias="flexVolume") + flocker: Optional[IoK8sApiCoreV1FlockerVolumeSource] = None + gce_persistent_disk: Optional[IoK8sApiCoreV1GCEPersistentDiskVolumeSource] = Field(default=None, alias="gcePersistentDisk") + git_repo: Optional[IoK8sApiCoreV1GitRepoVolumeSource] = Field(default=None, alias="gitRepo") + glusterfs: Optional[IoK8sApiCoreV1GlusterfsVolumeSource] = None + host_path: Optional[IoK8sApiCoreV1HostPathVolumeSource] = Field(default=None, alias="hostPath") + image: Optional[IoK8sApiCoreV1ImageVolumeSource] = None + iscsi: Optional[IoK8sApiCoreV1ISCSIVolumeSource] = None + name: StrictStr = Field(description="name of the volume. Must be a DNS_LABEL and unique within the pod. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names") + nfs: Optional[IoK8sApiCoreV1NFSVolumeSource] = None + persistent_volume_claim: Optional[IoK8sApiCoreV1PersistentVolumeClaimVolumeSource] = Field(default=None, alias="persistentVolumeClaim") + photon_persistent_disk: Optional[IoK8sApiCoreV1PhotonPersistentDiskVolumeSource] = Field(default=None, alias="photonPersistentDisk") + portworx_volume: Optional[IoK8sApiCoreV1PortworxVolumeSource] = Field(default=None, alias="portworxVolume") + projected: Optional[IoK8sApiCoreV1ProjectedVolumeSource] = None + quobyte: Optional[IoK8sApiCoreV1QuobyteVolumeSource] = None + rbd: Optional[IoK8sApiCoreV1RBDVolumeSource] = None + scale_io: Optional[IoK8sApiCoreV1ScaleIOVolumeSource] = Field(default=None, alias="scaleIO") + secret: Optional[IoK8sApiCoreV1SecretVolumeSource] = None + storageos: Optional[IoK8sApiCoreV1StorageOSVolumeSource] = None + vsphere_volume: Optional[IoK8sApiCoreV1VsphereVirtualDiskVolumeSource] = Field(default=None, alias="vsphereVolume") + __properties: ClassVar[List[str]] = ["awsElasticBlockStore", "azureDisk", "azureFile", "cephfs", "cinder", "configMap", "csi", "downwardAPI", "emptyDir", "ephemeral", "fc", "flexVolume", "flocker", "gcePersistentDisk", "gitRepo", "glusterfs", "hostPath", "image", "iscsi", "name", "nfs", "persistentVolumeClaim", "photonPersistentDisk", "portworxVolume", "projected", "quobyte", "rbd", "scaleIO", "secret", "storageos", "vsphereVolume"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Volume from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 aws_elastic_block_store + if self.aws_elastic_block_store: + _dict['awsElasticBlockStore'] = self.aws_elastic_block_store.to_dict() + # override the default output from pydantic by calling `to_dict()` of azure_disk + if self.azure_disk: + _dict['azureDisk'] = self.azure_disk.to_dict() + # override the default output from pydantic by calling `to_dict()` of azure_file + if self.azure_file: + _dict['azureFile'] = self.azure_file.to_dict() + # override the default output from pydantic by calling `to_dict()` of cephfs + if self.cephfs: + _dict['cephfs'] = self.cephfs.to_dict() + # override the default output from pydantic by calling `to_dict()` of cinder + if self.cinder: + _dict['cinder'] = self.cinder.to_dict() + # override the default output from pydantic by calling `to_dict()` of config_map + if self.config_map: + _dict['configMap'] = self.config_map.to_dict() + # override the default output from pydantic by calling `to_dict()` of csi + if self.csi: + _dict['csi'] = self.csi.to_dict() + # override the default output from pydantic by calling `to_dict()` of downward_api + if self.downward_api: + _dict['downwardAPI'] = self.downward_api.to_dict() + # override the default output from pydantic by calling `to_dict()` of empty_dir + if self.empty_dir: + _dict['emptyDir'] = self.empty_dir.to_dict() + # override the default output from pydantic by calling `to_dict()` of ephemeral + if self.ephemeral: + _dict['ephemeral'] = self.ephemeral.to_dict() + # override the default output from pydantic by calling `to_dict()` of fc + if self.fc: + _dict['fc'] = self.fc.to_dict() + # override the default output from pydantic by calling `to_dict()` of flex_volume + if self.flex_volume: + _dict['flexVolume'] = self.flex_volume.to_dict() + # override the default output from pydantic by calling `to_dict()` of flocker + if self.flocker: + _dict['flocker'] = self.flocker.to_dict() + # override the default output from pydantic by calling `to_dict()` of gce_persistent_disk + if self.gce_persistent_disk: + _dict['gcePersistentDisk'] = self.gce_persistent_disk.to_dict() + # override the default output from pydantic by calling `to_dict()` of git_repo + if self.git_repo: + _dict['gitRepo'] = self.git_repo.to_dict() + # override the default output from pydantic by calling `to_dict()` of glusterfs + if self.glusterfs: + _dict['glusterfs'] = self.glusterfs.to_dict() + # override the default output from pydantic by calling `to_dict()` of host_path + if self.host_path: + _dict['hostPath'] = self.host_path.to_dict() + # override the default output from pydantic by calling `to_dict()` of image + if self.image: + _dict['image'] = self.image.to_dict() + # override the default output from pydantic by calling `to_dict()` of iscsi + if self.iscsi: + _dict['iscsi'] = self.iscsi.to_dict() + # override the default output from pydantic by calling `to_dict()` of nfs + if self.nfs: + _dict['nfs'] = self.nfs.to_dict() + # override the default output from pydantic by calling `to_dict()` of persistent_volume_claim + if self.persistent_volume_claim: + _dict['persistentVolumeClaim'] = self.persistent_volume_claim.to_dict() + # override the default output from pydantic by calling `to_dict()` of photon_persistent_disk + if self.photon_persistent_disk: + _dict['photonPersistentDisk'] = self.photon_persistent_disk.to_dict() + # override the default output from pydantic by calling `to_dict()` of portworx_volume + if self.portworx_volume: + _dict['portworxVolume'] = self.portworx_volume.to_dict() + # override the default output from pydantic by calling `to_dict()` of projected + if self.projected: + _dict['projected'] = self.projected.to_dict() + # override the default output from pydantic by calling `to_dict()` of quobyte + if self.quobyte: + _dict['quobyte'] = self.quobyte.to_dict() + # override the default output from pydantic by calling `to_dict()` of rbd + if self.rbd: + _dict['rbd'] = self.rbd.to_dict() + # override the default output from pydantic by calling `to_dict()` of scale_io + if self.scale_io: + _dict['scaleIO'] = self.scale_io.to_dict() + # override the default output from pydantic by calling `to_dict()` of secret + if self.secret: + _dict['secret'] = self.secret.to_dict() + # override the default output from pydantic by calling `to_dict()` of storageos + if self.storageos: + _dict['storageos'] = self.storageos.to_dict() + # override the default output from pydantic by calling `to_dict()` of vsphere_volume + if self.vsphere_volume: + _dict['vsphereVolume'] = self.vsphere_volume.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1Volume from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "awsElasticBlockStore": IoK8sApiCoreV1AWSElasticBlockStoreVolumeSource.from_dict(obj["awsElasticBlockStore"]) if obj.get("awsElasticBlockStore") is not None else None, + "azureDisk": IoK8sApiCoreV1AzureDiskVolumeSource.from_dict(obj["azureDisk"]) if obj.get("azureDisk") is not None else None, + "azureFile": IoK8sApiCoreV1AzureFileVolumeSource.from_dict(obj["azureFile"]) if obj.get("azureFile") is not None else None, + "cephfs": IoK8sApiCoreV1CephFSVolumeSource.from_dict(obj["cephfs"]) if obj.get("cephfs") is not None else None, + "cinder": IoK8sApiCoreV1CinderVolumeSource.from_dict(obj["cinder"]) if obj.get("cinder") is not None else None, + "configMap": IoK8sApiCoreV1ConfigMapVolumeSource.from_dict(obj["configMap"]) if obj.get("configMap") is not None else None, + "csi": IoK8sApiCoreV1CSIVolumeSource.from_dict(obj["csi"]) if obj.get("csi") is not None else None, + "downwardAPI": IoK8sApiCoreV1DownwardAPIVolumeSource.from_dict(obj["downwardAPI"]) if obj.get("downwardAPI") is not None else None, + "emptyDir": IoK8sApiCoreV1EmptyDirVolumeSource.from_dict(obj["emptyDir"]) if obj.get("emptyDir") is not None else None, + "ephemeral": IoK8sApiCoreV1EphemeralVolumeSource.from_dict(obj["ephemeral"]) if obj.get("ephemeral") is not None else None, + "fc": IoK8sApiCoreV1FCVolumeSource.from_dict(obj["fc"]) if obj.get("fc") is not None else None, + "flexVolume": IoK8sApiCoreV1FlexVolumeSource.from_dict(obj["flexVolume"]) if obj.get("flexVolume") is not None else None, + "flocker": IoK8sApiCoreV1FlockerVolumeSource.from_dict(obj["flocker"]) if obj.get("flocker") is not None else None, + "gcePersistentDisk": IoK8sApiCoreV1GCEPersistentDiskVolumeSource.from_dict(obj["gcePersistentDisk"]) if obj.get("gcePersistentDisk") is not None else None, + "gitRepo": IoK8sApiCoreV1GitRepoVolumeSource.from_dict(obj["gitRepo"]) if obj.get("gitRepo") is not None else None, + "glusterfs": IoK8sApiCoreV1GlusterfsVolumeSource.from_dict(obj["glusterfs"]) if obj.get("glusterfs") is not None else None, + "hostPath": IoK8sApiCoreV1HostPathVolumeSource.from_dict(obj["hostPath"]) if obj.get("hostPath") is not None else None, + "image": IoK8sApiCoreV1ImageVolumeSource.from_dict(obj["image"]) if obj.get("image") is not None else None, + "iscsi": IoK8sApiCoreV1ISCSIVolumeSource.from_dict(obj["iscsi"]) if obj.get("iscsi") is not None else None, + "name": obj.get("name"), + "nfs": IoK8sApiCoreV1NFSVolumeSource.from_dict(obj["nfs"]) if obj.get("nfs") is not None else None, + "persistentVolumeClaim": IoK8sApiCoreV1PersistentVolumeClaimVolumeSource.from_dict(obj["persistentVolumeClaim"]) if obj.get("persistentVolumeClaim") is not None else None, + "photonPersistentDisk": IoK8sApiCoreV1PhotonPersistentDiskVolumeSource.from_dict(obj["photonPersistentDisk"]) if obj.get("photonPersistentDisk") is not None else None, + "portworxVolume": IoK8sApiCoreV1PortworxVolumeSource.from_dict(obj["portworxVolume"]) if obj.get("portworxVolume") is not None else None, + "projected": IoK8sApiCoreV1ProjectedVolumeSource.from_dict(obj["projected"]) if obj.get("projected") is not None else None, + "quobyte": IoK8sApiCoreV1QuobyteVolumeSource.from_dict(obj["quobyte"]) if obj.get("quobyte") is not None else None, + "rbd": IoK8sApiCoreV1RBDVolumeSource.from_dict(obj["rbd"]) if obj.get("rbd") is not None else None, + "scaleIO": IoK8sApiCoreV1ScaleIOVolumeSource.from_dict(obj["scaleIO"]) if obj.get("scaleIO") is not None else None, + "secret": IoK8sApiCoreV1SecretVolumeSource.from_dict(obj["secret"]) if obj.get("secret") is not None else None, + "storageos": IoK8sApiCoreV1StorageOSVolumeSource.from_dict(obj["storageos"]) if obj.get("storageos") is not None else None, + "vsphereVolume": IoK8sApiCoreV1VsphereVirtualDiskVolumeSource.from_dict(obj["vsphereVolume"]) if obj.get("vsphereVolume") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_device.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_device.py new file mode 100644 index 0000000000..1b9e4b256a --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_device.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1VolumeDevice(BaseModel): + """ + volumeDevice describes a mapping of a raw block device within a container. + """ # noqa: E501 + device_path: StrictStr = Field(description="devicePath is the path inside of the container that the device will be mapped to.", alias="devicePath") + name: StrictStr = Field(description="name must match the name of a persistentVolumeClaim in the pod") + __properties: ClassVar[List[str]] = ["devicePath", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeDevice from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeDevice from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "devicePath": obj.get("devicePath"), + "name": obj.get("name") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_mount.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_mount.py new file mode 100644 index 0000000000..dc95407a28 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_mount.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1VolumeMount(BaseModel): + """ + VolumeMount describes a mounting of a Volume within a container. + """ # noqa: E501 + mount_path: StrictStr = Field(description="Path within the container at which the volume should be mounted. Must not contain ':'.", alias="mountPath") + mount_propagation: Optional[StrictStr] = Field(default=None, description="mountPropagation determines how mounts are propagated from the host to container and the other way around. When not set, MountPropagationNone is used. This field is beta in 1.10. When RecursiveReadOnly is set to IfPossible or to Enabled, MountPropagation must be None or unspecified (which defaults to None).", alias="mountPropagation") + name: StrictStr = Field(description="This must match the Name of a Volume.") + read_only: Optional[StrictBool] = Field(default=None, description="Mounted read-only if true, read-write otherwise (false or unspecified). Defaults to false.", alias="readOnly") + recursive_read_only: Optional[StrictStr] = Field(default=None, description="RecursiveReadOnly specifies whether read-only mounts should be handled recursively. If ReadOnly is false, this field has no meaning and must be unspecified. If ReadOnly is true, and this field is set to Disabled, the mount is not made recursively read-only. If this field is set to IfPossible, the mount is made recursively read-only, if it is supported by the container runtime. If this field is set to Enabled, the mount is made recursively read-only if it is supported by the container runtime, otherwise the pod will not be started and an error will be generated to indicate the reason. If this field is set to IfPossible or Enabled, MountPropagation must be set to None (or be unspecified, which defaults to None). If this field is not specified, it is treated as an equivalent of Disabled.", alias="recursiveReadOnly") + sub_path: Optional[StrictStr] = Field(default=None, description="Path within the volume from which the container's volume should be mounted. Defaults to \"\" (volume's root).", alias="subPath") + sub_path_expr: Optional[StrictStr] = Field(default=None, description="Expanded path within the volume from which the container's volume should be mounted. Behaves similarly to SubPath but environment variable references $(VAR_NAME) are expanded using the container's environment. Defaults to \"\" (volume's root). SubPathExpr and SubPath are mutually exclusive.", alias="subPathExpr") + __properties: ClassVar[List[str]] = ["mountPath", "mountPropagation", "name", "readOnly", "recursiveReadOnly", "subPath", "subPathExpr"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeMount from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeMount from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mountPath": obj.get("mountPath"), + "mountPropagation": obj.get("mountPropagation"), + "name": obj.get("name"), + "readOnly": obj.get("readOnly"), + "recursiveReadOnly": obj.get("recursiveReadOnly"), + "subPath": obj.get("subPath"), + "subPathExpr": obj.get("subPathExpr") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_projection.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_projection.py new file mode 100644 index 0000000000..6a174078de --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_projection.py @@ -0,0 +1,115 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_cluster_trust_bundle_projection import IoK8sApiCoreV1ClusterTrustBundleProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_config_map_projection import IoK8sApiCoreV1ConfigMapProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_downward_api_projection import IoK8sApiCoreV1DownwardAPIProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_secret_projection import IoK8sApiCoreV1SecretProjection +from kubeflow.trainer.models.io_k8s_api_core_v1_service_account_token_projection import IoK8sApiCoreV1ServiceAccountTokenProjection +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1VolumeProjection(BaseModel): + """ + Projection that may be projected along with other supported volume types. Exactly one of these fields must be set. + """ # noqa: E501 + cluster_trust_bundle: Optional[IoK8sApiCoreV1ClusterTrustBundleProjection] = Field(default=None, alias="clusterTrustBundle") + config_map: Optional[IoK8sApiCoreV1ConfigMapProjection] = Field(default=None, alias="configMap") + downward_api: Optional[IoK8sApiCoreV1DownwardAPIProjection] = Field(default=None, alias="downwardAPI") + secret: Optional[IoK8sApiCoreV1SecretProjection] = None + service_account_token: Optional[IoK8sApiCoreV1ServiceAccountTokenProjection] = Field(default=None, alias="serviceAccountToken") + __properties: ClassVar[List[str]] = ["clusterTrustBundle", "configMap", "downwardAPI", "secret", "serviceAccountToken"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeProjection from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 cluster_trust_bundle + if self.cluster_trust_bundle: + _dict['clusterTrustBundle'] = self.cluster_trust_bundle.to_dict() + # override the default output from pydantic by calling `to_dict()` of config_map + if self.config_map: + _dict['configMap'] = self.config_map.to_dict() + # override the default output from pydantic by calling `to_dict()` of downward_api + if self.downward_api: + _dict['downwardAPI'] = self.downward_api.to_dict() + # override the default output from pydantic by calling `to_dict()` of secret + if self.secret: + _dict['secret'] = self.secret.to_dict() + # override the default output from pydantic by calling `to_dict()` of service_account_token + if self.service_account_token: + _dict['serviceAccountToken'] = self.service_account_token.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeProjection from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "clusterTrustBundle": IoK8sApiCoreV1ClusterTrustBundleProjection.from_dict(obj["clusterTrustBundle"]) if obj.get("clusterTrustBundle") is not None else None, + "configMap": IoK8sApiCoreV1ConfigMapProjection.from_dict(obj["configMap"]) if obj.get("configMap") is not None else None, + "downwardAPI": IoK8sApiCoreV1DownwardAPIProjection.from_dict(obj["downwardAPI"]) if obj.get("downwardAPI") is not None else None, + "secret": IoK8sApiCoreV1SecretProjection.from_dict(obj["secret"]) if obj.get("secret") is not None else None, + "serviceAccountToken": IoK8sApiCoreV1ServiceAccountTokenProjection.from_dict(obj["serviceAccountToken"]) if obj.get("serviceAccountToken") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_resource_requirements.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_resource_requirements.py new file mode 100644 index 0000000000..e5c27443a9 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_volume_resource_requirements.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1VolumeResourceRequirements(BaseModel): + """ + VolumeResourceRequirements describes the storage resource requirements for a volume. + """ # noqa: E501 + limits: Optional[Dict[str, StrictStr]] = Field(default=None, description="Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/") + requests: Optional[Dict[str, StrictStr]] = Field(default=None, description="Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/") + __properties: ClassVar[List[str]] = ["limits", "requests"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeResourceRequirements from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VolumeResourceRequirements from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "limits": obj.get("limits"), + "requests": obj.get("requests") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_vsphere_virtual_disk_volume_source.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_vsphere_virtual_disk_volume_source.py new file mode 100644 index 0000000000..5bedcc8505 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_vsphere_virtual_disk_volume_source.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1VsphereVirtualDiskVolumeSource(BaseModel): + """ + Represents a vSphere volume resource. + """ # noqa: E501 + fs_type: Optional[StrictStr] = Field(default=None, description="fsType is filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. \"ext4\", \"xfs\", \"ntfs\". Implicitly inferred to be \"ext4\" if unspecified.", alias="fsType") + storage_policy_id: Optional[StrictStr] = Field(default=None, description="storagePolicyID is the storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName.", alias="storagePolicyID") + storage_policy_name: Optional[StrictStr] = Field(default=None, description="storagePolicyName is the storage Policy Based Management (SPBM) profile name.", alias="storagePolicyName") + volume_path: StrictStr = Field(description="volumePath is the path that identifies vSphere volume vmdk", alias="volumePath") + __properties: ClassVar[List[str]] = ["fsType", "storagePolicyID", "storagePolicyName", "volumePath"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VsphereVirtualDiskVolumeSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1VsphereVirtualDiskVolumeSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "fsType": obj.get("fsType"), + "storagePolicyID": obj.get("storagePolicyID"), + "storagePolicyName": obj.get("storagePolicyName"), + "volumePath": obj.get("volumePath") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_weighted_pod_affinity_term.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_weighted_pod_affinity_term.py new file mode 100644 index 0000000000..c9dd229021 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_weighted_pod_affinity_term.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List +from kubeflow.trainer.models.io_k8s_api_core_v1_pod_affinity_term import IoK8sApiCoreV1PodAffinityTerm +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1WeightedPodAffinityTerm(BaseModel): + """ + The weights of all of the matched WeightedPodAffinityTerm fields are added per-node to find the most preferred node(s) + """ # noqa: E501 + pod_affinity_term: IoK8sApiCoreV1PodAffinityTerm = Field(alias="podAffinityTerm") + weight: StrictInt = Field(description="weight associated with matching the corresponding podAffinityTerm, in the range 1-100.") + __properties: ClassVar[List[str]] = ["podAffinityTerm", "weight"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1WeightedPodAffinityTerm from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 pod_affinity_term + if self.pod_affinity_term: + _dict['podAffinityTerm'] = self.pod_affinity_term.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1WeightedPodAffinityTerm from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "podAffinityTerm": IoK8sApiCoreV1PodAffinityTerm.from_dict(obj["podAffinityTerm"]) if obj.get("podAffinityTerm") is not None else None, + "weight": obj.get("weight") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_windows_security_context_options.py b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_windows_security_context_options.py new file mode 100644 index 0000000000..84d921eafe --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_api_core_v1_windows_security_context_options.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApiCoreV1WindowsSecurityContextOptions(BaseModel): + """ + WindowsSecurityContextOptions contain Windows-specific options and credentials. + """ # noqa: E501 + gmsa_credential_spec: Optional[StrictStr] = Field(default=None, description="GMSACredentialSpec is where the GMSA admission webhook (https://github.com/kubernetes-sigs/windows-gmsa) inlines the contents of the GMSA credential spec named by the GMSACredentialSpecName field.", alias="gmsaCredentialSpec") + gmsa_credential_spec_name: Optional[StrictStr] = Field(default=None, description="GMSACredentialSpecName is the name of the GMSA credential spec to use.", alias="gmsaCredentialSpecName") + host_process: Optional[StrictBool] = Field(default=None, description="HostProcess determines if a container should be run as a 'Host Process' container. All of a Pod's containers must have the same effective HostProcess value (it is not allowed to have a mix of HostProcess containers and non-HostProcess containers). In addition, if HostProcess is true then HostNetwork must also be set to true.", alias="hostProcess") + run_as_user_name: Optional[StrictStr] = Field(default=None, description="The UserName in Windows to run the entrypoint of the container process. Defaults to the user specified in image metadata if unspecified. May also be set in PodSecurityContext. If set in both SecurityContext and PodSecurityContext, the value specified in SecurityContext takes precedence.", alias="runAsUserName") + __properties: ClassVar[List[str]] = ["gmsaCredentialSpec", "gmsaCredentialSpecName", "hostProcess", "runAsUserName"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1WindowsSecurityContextOptions from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApiCoreV1WindowsSecurityContextOptions from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "gmsaCredentialSpec": obj.get("gmsaCredentialSpec"), + "gmsaCredentialSpecName": obj.get("gmsaCredentialSpecName"), + "hostProcess": obj.get("hostProcess"), + "runAsUserName": obj.get("runAsUserName") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_condition.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_condition.py new file mode 100644 index 0000000000..333eea87f2 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_condition.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1Condition(BaseModel): + """ + Condition contains details for one aspect of the current state of this API Resource. + """ # noqa: E501 + last_transition_time: datetime = Field(description="Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", alias="lastTransitionTime") + message: StrictStr = Field(description="message is a human readable message indicating details about the transition. This may be an empty string.") + observed_generation: Optional[StrictInt] = Field(default=None, description="observedGeneration represents the .metadata.generation that the condition was set based upon. For instance, if .metadata.generation is currently 12, but the .status.conditions[x].observedGeneration is 9, the condition is out of date with respect to the current state of the instance.", alias="observedGeneration") + reason: StrictStr = Field(description="reason contains a programmatic identifier indicating the reason for the condition's last transition. Producers of specific condition types may define expected values and meanings for this field, and whether the values are considered a guaranteed API. The value should be a CamelCase string. This field may not be empty.") + status: StrictStr = Field(description="status of the condition, one of True, False, Unknown.") + type: StrictStr = Field(description="type of condition in CamelCase or in foo.example.com/CamelCase.") + __properties: ClassVar[List[str]] = ["lastTransitionTime", "message", "observedGeneration", "reason", "status", "type"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1Condition from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1Condition from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "lastTransitionTime": obj.get("lastTransitionTime"), + "message": obj.get("message"), + "observedGeneration": obj.get("observedGeneration"), + "reason": obj.get("reason"), + "status": obj.get("status"), + "type": obj.get("type") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_label_selector.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_label_selector.py new file mode 100644 index 0000000000..63c43d64e6 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_label_selector.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement import IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1LabelSelector(BaseModel): + """ + A label selector is a label query over a set of resources. The result of matchLabels and matchExpressions are ANDed. An empty label selector matches all objects. A null label selector matches no objects. + """ # noqa: E501 + match_expressions: Optional[List[IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement]] = Field(default=None, description="matchExpressions is a list of label selector requirements. The requirements are ANDed.", alias="matchExpressions") + match_labels: Optional[Dict[str, StrictStr]] = Field(default=None, description="matchLabels is a map of {key,value} pairs. A single {key,value} in the matchLabels map is equivalent to an element of matchExpressions, whose key field is \"key\", the operator is \"In\", and the values array contains only \"value\". The requirements are ANDed.", alias="matchLabels") + __properties: ClassVar[List[str]] = ["matchExpressions", "matchLabels"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1LabelSelector from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 match_expressions (list) + _items = [] + if self.match_expressions: + for _item_match_expressions in self.match_expressions: + if _item_match_expressions: + _items.append(_item_match_expressions.to_dict()) + _dict['matchExpressions'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1LabelSelector from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "matchExpressions": [IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement.from_dict(_item) for _item in obj["matchExpressions"]] if obj.get("matchExpressions") is not None else None, + "matchLabels": obj.get("matchLabels") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement.py new file mode 100644 index 0000000000..6f759476a3 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_label_selector_requirement.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement(BaseModel): + """ + A label selector requirement is a selector that contains values, a key, and an operator that relates the key and values. + """ # noqa: E501 + key: StrictStr = Field(description="key is the label key that the selector applies to.") + operator: StrictStr = Field(description="operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists and DoesNotExist.") + values: Optional[List[StrictStr]] = Field(default=None, description="values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. This array is replaced during a strategic merge patch.") + __properties: ClassVar[List[str]] = ["key", "operator", "values"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1LabelSelectorRequirement from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "operator": obj.get("operator"), + "values": obj.get("values") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_list_meta.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_list_meta.py new file mode 100644 index 0000000000..d662b9566c --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_list_meta.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1ListMeta(BaseModel): + """ + ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. + """ # noqa: E501 + var_continue: Optional[StrictStr] = Field(default=None, description="continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message.", alias="continue") + remaining_item_count: Optional[StrictInt] = Field(default=None, description="remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact.", alias="remainingItemCount") + resource_version: Optional[StrictStr] = Field(default=None, description="String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", alias="resourceVersion") + self_link: Optional[StrictStr] = Field(default=None, description="Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.", alias="selfLink") + __properties: ClassVar[List[str]] = ["continue", "remainingItemCount", "resourceVersion", "selfLink"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1ListMeta from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1ListMeta from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "continue": obj.get("continue"), + "remainingItemCount": obj.get("remainingItemCount"), + "resourceVersion": obj.get("resourceVersion"), + "selfLink": obj.get("selfLink") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry.py new file mode 100644 index 0000000000..c12b4f0445 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry(BaseModel): + """ + ManagedFieldsEntry is a workflow-id, a FieldSet and the group version of the resource that the fieldset applies to. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the version of this resource that this field set applies to. The format is \"group/version\" just like the top-level APIVersion field. It is necessary to track the version of a field set because it cannot be automatically converted.", alias="apiVersion") + fields_type: Optional[StrictStr] = Field(default=None, description="FieldsType is the discriminator for the different fields format and version. There is currently only one possible value: \"FieldsV1\"", alias="fieldsType") + fields_v1: Optional[Dict[str, Any]] = Field(default=None, description="FieldsV1 stores a set of fields in a data structure like a Trie, in JSON format. Each key is either a '.' representing the field itself, and will always map to an empty set, or a string representing a sub-field or item. The string will follow one of these four formats: 'f:', where is the name of a field in a struct, or key in a map 'v:', where is the exact json formatted value of a list item 'i:', where is position of a item in a list 'k:', where is a map of a list item's key fields to their unique values If a key maps to an empty Fields value, the field that key represents is part of the set. The exact format is defined in sigs.k8s.io/structured-merge-diff", alias="fieldsV1") + manager: Optional[StrictStr] = Field(default=None, description="Manager is an identifier of the workflow managing these fields.") + operation: Optional[StrictStr] = Field(default=None, description="Operation is the type of operation which lead to this ManagedFieldsEntry being created. The only valid values for this field are 'Apply' and 'Update'.") + subresource: Optional[StrictStr] = Field(default=None, description="Subresource is the name of the subresource used to update that object, or empty string if the object was updated through the main resource. The value of this field is used to distinguish between managers, even if they share the same name. For example, a status update will be distinct from a regular update using the same manager name. Note that the APIVersion field is not related to the Subresource field and it always corresponds to the version of the main resource.") + time: Optional[datetime] = Field(default=None, description="Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.") + __properties: ClassVar[List[str]] = ["apiVersion", "fieldsType", "fieldsV1", "manager", "operation", "subresource", "time"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "fieldsType": obj.get("fieldsType"), + "fieldsV1": obj.get("fieldsV1"), + "manager": obj.get("manager"), + "operation": obj.get("operation"), + "subresource": obj.get("subresource"), + "time": obj.get("time") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.py new file mode 100644 index 0000000000..1bce460aa4 --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_object_meta.py @@ -0,0 +1,132 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 datetime import datetime +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_managed_fields_entry import IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference import IoK8sApimachineryPkgApisMetaV1OwnerReference +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1ObjectMeta(BaseModel): + """ + ObjectMeta is metadata that all persisted resources must have, which includes all objects users must create. + """ # noqa: E501 + annotations: Optional[Dict[str, StrictStr]] = Field(default=None, description="Annotations is an unstructured key value map stored with a resource that may be set by external tools to store and retrieve arbitrary metadata. They are not queryable and should be preserved when modifying objects. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/annotations") + creation_timestamp: Optional[datetime] = Field(default=None, description="Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", alias="creationTimestamp") + deletion_grace_period_seconds: Optional[StrictInt] = Field(default=None, description="Number of seconds allowed for this object to gracefully terminate before it will be removed from the system. Only set when deletionTimestamp is also set. May only be shortened. Read-only.", alias="deletionGracePeriodSeconds") + deletion_timestamp: Optional[datetime] = Field(default=None, description="Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.", alias="deletionTimestamp") + finalizers: Optional[List[StrictStr]] = Field(default=None, description="Must be empty before the object is deleted from the registry. Each entry is an identifier for the responsible component that will remove the entry from the list. If the deletionTimestamp of the object is non-nil, entries in this list can only be removed. Finalizers may be processed and removed in any order. Order is NOT enforced because it introduces significant risk of stuck finalizers. finalizers is a shared field, any actor with permission can reorder it. If the finalizer list is processed in order, then this can lead to a situation in which the component responsible for the first finalizer in the list is waiting for a signal (field value, external system, or other) produced by a component responsible for a finalizer later in the list, resulting in a deadlock. Without enforced ordering finalizers are free to order amongst themselves and are not vulnerable to ordering changes in the list.") + generate_name: Optional[StrictStr] = Field(default=None, description="GenerateName is an optional prefix, used by the server, to generate a unique name ONLY IF the Name field has not been provided. If this field is used, the name returned to the client will be different than the name passed. This value will also be combined with a unique suffix. The provided value has the same validation rules as the Name field, and may be truncated by the length of the suffix required to make the value unique on the server. If this field is specified and the generated name exists, the server will return a 409. Applied only if Name is not specified. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency", alias="generateName") + generation: Optional[StrictInt] = Field(default=None, description="A sequence number representing a specific generation of the desired state. Populated by the system. Read-only.") + labels: Optional[Dict[str, StrictStr]] = Field(default=None, description="Map of string keys and values that can be used to organize and categorize (scope and select) objects. May match selectors of replication controllers and services. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/labels") + managed_fields: Optional[List[IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry]] = Field(default=None, description="ManagedFields maps workflow-id and version to the set of fields that are managed by that workflow. This is mostly for internal housekeeping, and users typically shouldn't need to set or understand this field. A workflow can be the user's name, a controller's name, or the name of a specific apply path like \"ci-cd\". The set of fields is always in the version that the workflow used when modifying the object.", alias="managedFields") + name: Optional[StrictStr] = Field(default=None, description="Name must be unique within a namespace. Is required when creating resources, although some resources may allow a client to request the generation of an appropriate name automatically. Name is primarily intended for creation idempotence and configuration definition. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names") + namespace: Optional[StrictStr] = Field(default=None, description="Namespace defines the space within which each name must be unique. An empty namespace is equivalent to the \"default\" namespace, but \"default\" is the canonical representation. Not all objects are required to be scoped to a namespace - the value of this field for those objects will be empty. Must be a DNS_LABEL. Cannot be updated. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces") + owner_references: Optional[List[IoK8sApimachineryPkgApisMetaV1OwnerReference]] = Field(default=None, description="List of objects depended by this object. If ALL objects in the list have been deleted, this object will be garbage collected. If this object is managed by a controller, then an entry in this list will point to this controller, with the controller field set to true. There cannot be more than one managing controller.", alias="ownerReferences") + resource_version: Optional[StrictStr] = Field(default=None, description="An opaque value that represents the internal version of this object that can be used by clients to determine when objects have changed. May be used for optimistic concurrency, change detection, and the watch operation on a resource or set of resources. Clients must treat these values as opaque and passed unmodified back to the server. They may only be valid for a particular resource or set of resources. Populated by the system. Read-only. Value must be treated as opaque by clients and . More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency", alias="resourceVersion") + self_link: Optional[StrictStr] = Field(default=None, description="Deprecated: selfLink is a legacy read-only field that is no longer populated by the system.", alias="selfLink") + uid: Optional[StrictStr] = Field(default=None, description="UID is the unique in time and space value for this object. It is typically generated by the server on successful creation of a resource and is not allowed to change on PUT operations. Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids") + __properties: ClassVar[List[str]] = ["annotations", "creationTimestamp", "deletionGracePeriodSeconds", "deletionTimestamp", "finalizers", "generateName", "generation", "labels", "managedFields", "name", "namespace", "ownerReferences", "resourceVersion", "selfLink", "uid"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1ObjectMeta from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 managed_fields (list) + _items = [] + if self.managed_fields: + for _item_managed_fields in self.managed_fields: + if _item_managed_fields: + _items.append(_item_managed_fields.to_dict()) + _dict['managedFields'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in owner_references (list) + _items = [] + if self.owner_references: + for _item_owner_references in self.owner_references: + if _item_owner_references: + _items.append(_item_owner_references.to_dict()) + _dict['ownerReferences'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1ObjectMeta from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "annotations": obj.get("annotations"), + "creationTimestamp": obj.get("creationTimestamp"), + "deletionGracePeriodSeconds": obj.get("deletionGracePeriodSeconds"), + "deletionTimestamp": obj.get("deletionTimestamp"), + "finalizers": obj.get("finalizers"), + "generateName": obj.get("generateName"), + "generation": obj.get("generation"), + "labels": obj.get("labels"), + "managedFields": [IoK8sApimachineryPkgApisMetaV1ManagedFieldsEntry.from_dict(_item) for _item in obj["managedFields"]] if obj.get("managedFields") is not None else None, + "name": obj.get("name"), + "namespace": obj.get("namespace"), + "ownerReferences": [IoK8sApimachineryPkgApisMetaV1OwnerReference.from_dict(_item) for _item in obj["ownerReferences"]] if obj.get("ownerReferences") is not None else None, + "resourceVersion": obj.get("resourceVersion"), + "selfLink": obj.get("selfLink"), + "uid": obj.get("uid") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference.py b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference.py new file mode 100644 index 0000000000..7adc1deb0c --- /dev/null +++ b/sdk/kubeflow/trainer/models/io_k8s_apimachinery_pkg_apis_meta_v1_owner_reference.py @@ -0,0 +1,97 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class IoK8sApimachineryPkgApisMetaV1OwnerReference(BaseModel): + """ + OwnerReference contains enough information to let you identify an owning object. An owning object must be in the same namespace as the dependent, or be cluster-scoped, so there is no namespace field. + """ # noqa: E501 + api_version: StrictStr = Field(description="API version of the referent.", alias="apiVersion") + block_owner_deletion: Optional[StrictBool] = Field(default=None, description="If true, AND if the owner has the \"foregroundDeletion\" finalizer, then the owner cannot be deleted from the key-value store until this reference is removed. See https://kubernetes.io/docs/concepts/architecture/garbage-collection/#foreground-deletion for how the garbage collector interacts with this field and enforces the foreground deletion. Defaults to false. To set this field, a user needs \"delete\" permission of the owner, otherwise 422 (Unprocessable Entity) will be returned.", alias="blockOwnerDeletion") + controller: Optional[StrictBool] = Field(default=None, description="If true, this reference points to the managing controller.") + kind: StrictStr = Field(description="Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + name: StrictStr = Field(description="Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#names") + uid: StrictStr = Field(description="UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names#uids") + __properties: ClassVar[List[str]] = ["apiVersion", "blockOwnerDeletion", "controller", "kind", "name", "uid"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1OwnerReference from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of IoK8sApimachineryPkgApisMetaV1OwnerReference from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "blockOwnerDeletion": obj.get("blockOwnerDeletion"), + "controller": obj.get("controller"), + "kind": obj.get("kind"), + "name": obj.get("name"), + "uid": obj.get("uid") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_coordinator.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_coordinator.py new file mode 100644 index 0000000000..c474916c51 --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_coordinator.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2Coordinator(BaseModel): + """ + Coordinator defines which pod can be marked as the coordinator for the JobSet workload. + """ # noqa: E501 + job_index: Optional[StrictInt] = Field(default=None, description="JobIndex is the index of Job which contains the coordinator pod (i.e., for a ReplicatedJob with N replicas, there are Job indexes 0 to N-1).", alias="jobIndex") + pod_index: Optional[StrictInt] = Field(default=None, description="PodIndex is the Job completion index of the coordinator pod.", alias="podIndex") + replicated_job: StrictStr = Field(description="ReplicatedJob is the name of the ReplicatedJob which contains the coordinator pod.", alias="replicatedJob") + __properties: ClassVar[List[str]] = ["jobIndex", "podIndex", "replicatedJob"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2Coordinator from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2Coordinator from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "jobIndex": obj.get("jobIndex"), + "podIndex": obj.get("podIndex"), + "replicatedJob": obj.get("replicatedJob") if obj.get("replicatedJob") is not None else '' + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_depends_on.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_depends_on.py new file mode 100644 index 0000000000..5271bfafae --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_depends_on.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2DependsOn(BaseModel): + """ + DependsOn defines the dependency on the previous ReplicatedJob status. + """ # noqa: E501 + name: StrictStr = Field(description="Name of the previous ReplicatedJob.") + status: StrictStr = Field(description="Status defines the condition for the ReplicatedJob. Only Ready or Complete status can be set.") + __properties: ClassVar[List[str]] = ["name", "status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2DependsOn from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2DependsOn from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name") if obj.get("name") is not None else '', + "status": obj.get("status") if obj.get("status") is not None else '' + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_failure_policy.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_failure_policy.py new file mode 100644 index 0000000000..876a7a8f09 --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_failure_policy.py @@ -0,0 +1,99 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.jobset_v1alpha2_failure_policy_rule import JobsetV1alpha2FailurePolicyRule +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2FailurePolicy(BaseModel): + """ + JobsetV1alpha2FailurePolicy + """ # noqa: E501 + max_restarts: Optional[StrictInt] = Field(default=None, description="MaxRestarts defines the limit on the number of JobSet restarts. A restart is achieved by recreating all active child jobs.", alias="maxRestarts") + restart_strategy: Optional[StrictStr] = Field(default=None, description="RestartStrategy defines the strategy to use when restarting the JobSet. Defaults to Recreate.", alias="restartStrategy") + rules: Optional[List[JobsetV1alpha2FailurePolicyRule]] = Field(default=None, description="List of failure policy rules for this JobSet. For a given Job failure, the rules will be evaluated in order, and only the first matching rule will be executed. If no matching rule is found, the RestartJobSet action is applied.") + __properties: ClassVar[List[str]] = ["maxRestarts", "restartStrategy", "rules"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2FailurePolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 rules (list) + _items = [] + if self.rules: + for _item_rules in self.rules: + if _item_rules: + _items.append(_item_rules.to_dict()) + _dict['rules'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2FailurePolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "maxRestarts": obj.get("maxRestarts"), + "restartStrategy": obj.get("restartStrategy"), + "rules": [JobsetV1alpha2FailurePolicyRule.from_dict(_item) for _item in obj["rules"]] if obj.get("rules") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_failure_policy_rule.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_failure_policy_rule.py new file mode 100644 index 0000000000..1dc36d16c6 --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_failure_policy_rule.py @@ -0,0 +1,93 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2FailurePolicyRule(BaseModel): + """ + FailurePolicyRule defines a FailurePolicyAction to be executed if a child job fails due to a reason listed in OnJobFailureReasons. + """ # noqa: E501 + action: StrictStr = Field(description="The action to take if the rule is matched.") + name: StrictStr = Field(description="The name of the failure policy rule. The name is defaulted to 'failurePolicyRuleN' where N is the index of the failure policy rule. The name must match the regular expression \"^[A-Za-z]([A-Za-z0-9_,:]*[A-Za-z0-9_])?$\".") + on_job_failure_reasons: Optional[List[StrictStr]] = Field(default=None, description="The requirement on the job failure reasons. The requirement is satisfied if at least one reason matches the list. The rules are evaluated in order, and the first matching rule is executed. An empty list applies the rule to any job failure reason.", alias="onJobFailureReasons") + target_replicated_jobs: Optional[List[StrictStr]] = Field(default=None, description="TargetReplicatedJobs are the names of the replicated jobs the operator applies to. An empty list will apply to all replicatedJobs.", alias="targetReplicatedJobs") + __properties: ClassVar[List[str]] = ["action", "name", "onJobFailureReasons", "targetReplicatedJobs"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2FailurePolicyRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2FailurePolicyRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "action": obj.get("action") if obj.get("action") is not None else '', + "name": obj.get("name") if obj.get("name") is not None else '', + "onJobFailureReasons": obj.get("onJobFailureReasons"), + "targetReplicatedJobs": obj.get("targetReplicatedJobs") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_job_set_spec.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_job_set_spec.py new file mode 100644 index 0000000000..2f242efc5b --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_job_set_spec.py @@ -0,0 +1,131 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.jobset_v1alpha2_coordinator import JobsetV1alpha2Coordinator +from kubeflow.trainer.models.jobset_v1alpha2_failure_policy import JobsetV1alpha2FailurePolicy +from kubeflow.trainer.models.jobset_v1alpha2_network import JobsetV1alpha2Network +from kubeflow.trainer.models.jobset_v1alpha2_replicated_job import JobsetV1alpha2ReplicatedJob +from kubeflow.trainer.models.jobset_v1alpha2_startup_policy import JobsetV1alpha2StartupPolicy +from kubeflow.trainer.models.jobset_v1alpha2_success_policy import JobsetV1alpha2SuccessPolicy +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2JobSetSpec(BaseModel): + """ + JobSetSpec defines the desired state of JobSet + """ # noqa: E501 + coordinator: Optional[JobsetV1alpha2Coordinator] = None + failure_policy: Optional[JobsetV1alpha2FailurePolicy] = Field(default=None, alias="failurePolicy") + managed_by: Optional[StrictStr] = Field(default=None, description="ManagedBy is used to indicate the controller or entity that manages a JobSet. The built-in JobSet controller reconciles JobSets which don't have this field at all or the field value is the reserved string `jobset.sigs.k8s.io/jobset-controller`, but skips reconciling JobSets with a custom value for this field. The value must be a valid domain-prefixed path (e.g. acme.io/foo) - all characters before the first \"/\" must be a valid subdomain as defined by RFC 1123. All characters trailing the first \"/\" must be valid HTTP Path characters as defined by RFC 3986. The value cannot exceed 63 characters. The field is immutable.", alias="managedBy") + network: Optional[JobsetV1alpha2Network] = None + replicated_jobs: Optional[List[JobsetV1alpha2ReplicatedJob]] = Field(default=None, description="ReplicatedJobs is the group of jobs that will form the set.", alias="replicatedJobs") + startup_policy: Optional[JobsetV1alpha2StartupPolicy] = Field(default=None, alias="startupPolicy") + success_policy: Optional[JobsetV1alpha2SuccessPolicy] = Field(default=None, alias="successPolicy") + suspend: Optional[StrictBool] = Field(default=None, description="Suspend suspends all running child Jobs when set to true.") + ttl_seconds_after_finished: Optional[StrictInt] = Field(default=None, description="TTLSecondsAfterFinished limits the lifetime of a JobSet that has finished execution (either Complete or Failed). If this field is set, TTLSecondsAfterFinished after the JobSet finishes, it is eligible to be automatically deleted. When the JobSet is being deleted, its lifecycle guarantees (e.g. finalizers) will be honored. If this field is unset, the JobSet won't be automatically deleted. If this field is set to zero, the JobSet becomes eligible to be deleted immediately after it finishes.", alias="ttlSecondsAfterFinished") + __properties: ClassVar[List[str]] = ["coordinator", "failurePolicy", "managedBy", "network", "replicatedJobs", "startupPolicy", "successPolicy", "suspend", "ttlSecondsAfterFinished"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2JobSetSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 coordinator + if self.coordinator: + _dict['coordinator'] = self.coordinator.to_dict() + # override the default output from pydantic by calling `to_dict()` of failure_policy + if self.failure_policy: + _dict['failurePolicy'] = self.failure_policy.to_dict() + # override the default output from pydantic by calling `to_dict()` of network + if self.network: + _dict['network'] = self.network.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in replicated_jobs (list) + _items = [] + if self.replicated_jobs: + for _item_replicated_jobs in self.replicated_jobs: + if _item_replicated_jobs: + _items.append(_item_replicated_jobs.to_dict()) + _dict['replicatedJobs'] = _items + # override the default output from pydantic by calling `to_dict()` of startup_policy + if self.startup_policy: + _dict['startupPolicy'] = self.startup_policy.to_dict() + # override the default output from pydantic by calling `to_dict()` of success_policy + if self.success_policy: + _dict['successPolicy'] = self.success_policy.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2JobSetSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "coordinator": JobsetV1alpha2Coordinator.from_dict(obj["coordinator"]) if obj.get("coordinator") is not None else None, + "failurePolicy": JobsetV1alpha2FailurePolicy.from_dict(obj["failurePolicy"]) if obj.get("failurePolicy") is not None else None, + "managedBy": obj.get("managedBy"), + "network": JobsetV1alpha2Network.from_dict(obj["network"]) if obj.get("network") is not None else None, + "replicatedJobs": [JobsetV1alpha2ReplicatedJob.from_dict(_item) for _item in obj["replicatedJobs"]] if obj.get("replicatedJobs") is not None else None, + "startupPolicy": JobsetV1alpha2StartupPolicy.from_dict(obj["startupPolicy"]) if obj.get("startupPolicy") is not None else None, + "successPolicy": JobsetV1alpha2SuccessPolicy.from_dict(obj["successPolicy"]) if obj.get("successPolicy") is not None else None, + "suspend": obj.get("suspend"), + "ttlSecondsAfterFinished": obj.get("ttlSecondsAfterFinished") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_network.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_network.py new file mode 100644 index 0000000000..7ee06e6ce0 --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_network.py @@ -0,0 +1,91 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2Network(BaseModel): + """ + JobsetV1alpha2Network + """ # noqa: E501 + enable_dns_hostnames: Optional[StrictBool] = Field(default=None, description="EnableDNSHostnames allows pods to be reached via their hostnames. Pods will be reachable using the fully qualified pod hostname: ---.", alias="enableDNSHostnames") + publish_not_ready_addresses: Optional[StrictBool] = Field(default=None, description="Indicates if DNS records of pods should be published before the pods are ready. Defaults to True.", alias="publishNotReadyAddresses") + subdomain: Optional[StrictStr] = Field(default=None, description="Subdomain is an explicit choice for a network subdomain name When set, any replicated job in the set is added to this network. Defaults to if not set.") + __properties: ClassVar[List[str]] = ["enableDNSHostnames", "publishNotReadyAddresses", "subdomain"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2Network from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2Network from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "enableDNSHostnames": obj.get("enableDNSHostnames"), + "publishNotReadyAddresses": obj.get("publishNotReadyAddresses"), + "subdomain": obj.get("subdomain") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_replicated_job.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_replicated_job.py new file mode 100644 index 0000000000..7cf559e91a --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_replicated_job.py @@ -0,0 +1,105 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_batch_v1_job_template_spec import IoK8sApiBatchV1JobTemplateSpec +from kubeflow.trainer.models.jobset_v1alpha2_depends_on import JobsetV1alpha2DependsOn +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2ReplicatedJob(BaseModel): + """ + JobsetV1alpha2ReplicatedJob + """ # noqa: E501 + depends_on: Optional[List[JobsetV1alpha2DependsOn]] = Field(default=None, description="DependsOn is an optional list that specifies the preceding ReplicatedJobs upon which the current ReplicatedJob depends. If specified, the ReplicatedJob will be created only after the referenced ReplicatedJobs reach their desired state. The Order of ReplicatedJobs is defined by their enumeration in the slice. Note, that the first ReplicatedJob in the slice cannot use the DependsOn API. Currently, only a single item is supported in the DependsOn list. If JobSet is suspended the all active ReplicatedJobs will be suspended. When JobSet is resumed the Job sequence starts again. This API is mutually exclusive with the StartupPolicy API.", alias="dependsOn") + name: StrictStr = Field(description="Name is the name of the entry and will be used as a suffix for the Job name.") + replicas: Optional[StrictInt] = Field(default=None, description="Replicas is the number of jobs that will be created from this ReplicatedJob's template. Jobs names will be in the format: --") + template: IoK8sApiBatchV1JobTemplateSpec + __properties: ClassVar[List[str]] = ["dependsOn", "name", "replicas", "template"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2ReplicatedJob from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 depends_on (list) + _items = [] + if self.depends_on: + for _item_depends_on in self.depends_on: + if _item_depends_on: + _items.append(_item_depends_on.to_dict()) + _dict['dependsOn'] = _items + # 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: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2ReplicatedJob from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "dependsOn": [JobsetV1alpha2DependsOn.from_dict(_item) for _item in obj["dependsOn"]] if obj.get("dependsOn") is not None else None, + "name": obj.get("name") if obj.get("name") is not None else '', + "replicas": obj.get("replicas"), + "template": IoK8sApiBatchV1JobTemplateSpec.from_dict(obj["template"]) if obj.get("template") is not None else None + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_startup_policy.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_startup_policy.py new file mode 100644 index 0000000000..0eda8534ce --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_startup_policy.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2StartupPolicy(BaseModel): + """ + JobsetV1alpha2StartupPolicy + """ # noqa: E501 + startup_policy_order: StrictStr = Field(description="StartupPolicyOrder determines the startup order of the ReplicatedJobs. AnyOrder means to start replicated jobs in any order. InOrder means to start them as they are listed in the JobSet. A ReplicatedJob is started only when all the jobs of the previous one are ready.", alias="startupPolicyOrder") + __properties: ClassVar[List[str]] = ["startupPolicyOrder"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2StartupPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2StartupPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "startupPolicyOrder": obj.get("startupPolicyOrder") if obj.get("startupPolicyOrder") is not None else '' + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/jobset_v1alpha2_success_policy.py b/sdk/kubeflow/trainer/models/jobset_v1alpha2_success_policy.py new file mode 100644 index 0000000000..92f9b18d88 --- /dev/null +++ b/sdk/kubeflow/trainer/models/jobset_v1alpha2_success_policy.py @@ -0,0 +1,89 @@ +# coding: utf-8 + +""" + Kubeflow Trainer OpenAPI Spec + + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + The version of the OpenAPI document: 1.0.0 + 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 pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class JobsetV1alpha2SuccessPolicy(BaseModel): + """ + JobsetV1alpha2SuccessPolicy + """ # noqa: E501 + operator: StrictStr = Field(description="Operator determines either All or Any of the selected jobs should succeed to consider the JobSet successful") + target_replicated_jobs: Optional[List[StrictStr]] = Field(default=None, description="TargetReplicatedJobs are the names of the replicated jobs the operator will apply to. A null or empty list will apply to all replicatedJobs.", alias="targetReplicatedJobs") + __properties: ClassVar[List[str]] = ["operator", "targetReplicatedJobs"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of JobsetV1alpha2SuccessPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of JobsetV1alpha2SuccessPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "operator": obj.get("operator") if obj.get("operator") is not None else '', + "targetReplicatedJobs": obj.get("targetReplicatedJobs") + }) + return _obj + + diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime.py index aa21241f96..c703d29e1c 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime.py @@ -3,200 +3,99 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from kubeflow.trainer.models.trainer_v1alpha1_training_runtime_spec import TrainerV1alpha1TrainingRuntimeSpec +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1ClusterTrainingRuntime(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1ClusterTrainingRuntime(BaseModel): """ - openapi_types = { - 'api_version': 'str', - 'kind': 'str', - 'metadata': 'V1ObjectMeta', - 'spec': 'TrainerV1alpha1TrainingRuntimeSpec' - } - - attribute_map = { - 'api_version': 'apiVersion', - 'kind': 'kind', - 'metadata': 'metadata', - 'spec': 'spec' - } - - def __init__(self, api_version=None, kind=None, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1ClusterTrainingRuntime - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_version = None - self._kind = None - self._metadata = None - self._spec = None - self.discriminator = None - - if api_version is not None: - self.api_version = api_version - if kind is not None: - self.kind = kind - if metadata is not None: - self.metadata = metadata - if spec is not None: - self.spec = spec - - @property - def api_version(self): - """Gets the api_version of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :return: The api_version of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :rtype: str - """ - return self._api_version - - @api_version.setter - def api_version(self, api_version): - """Sets the api_version of this TrainerV1alpha1ClusterTrainingRuntime. - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :param api_version: The api_version of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :type: str - """ - - self._api_version = api_version - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :return: The kind of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1ClusterTrainingRuntime. - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - - - :return: The metadata of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :rtype: V1ObjectMeta - """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1ClusterTrainingRuntime. - - - :param metadata: The metadata of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :type: V1ObjectMeta - """ - - self._metadata = metadata - - @property - def spec(self): - """Gets the spec of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - - - :return: The spec of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :rtype: TrainerV1alpha1TrainingRuntimeSpec + ClusterTrainingRuntime represents a training runtime which can be referenced as part of `runtimeRef` API in TrainJob. This resource is a cluster-scoped and can be referenced by TrainJob that created in *any* namespace. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", alias="apiVersion") + kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: Optional[TrainerV1alpha1TrainingRuntimeSpec] = None + __properties: ClassVar[List[str]] = ["apiVersion", "kind", "metadata", "spec"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ClusterTrainingRuntime from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._spec - - @spec.setter - def spec(self, spec): - """Sets the spec of this TrainerV1alpha1ClusterTrainingRuntime. + 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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ClusterTrainingRuntime from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "kind": obj.get("kind"), + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": TrainerV1alpha1TrainingRuntimeSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None + }) + return _obj - :param spec: The spec of this TrainerV1alpha1ClusterTrainingRuntime. # noqa: E501 - :type: TrainerV1alpha1TrainingRuntimeSpec - """ - - self._spec = spec - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1ClusterTrainingRuntime): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1ClusterTrainingRuntime): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime_list.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime_list.py index 56702037ae..5896e50e55 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime_list.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_cluster_training_runtime_list.py @@ -3,203 +3,103 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_list_meta import IoK8sApimachineryPkgApisMetaV1ListMeta +from kubeflow.trainer.models.trainer_v1alpha1_cluster_training_runtime import TrainerV1alpha1ClusterTrainingRuntime +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1ClusterTrainingRuntimeList(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1ClusterTrainingRuntimeList(BaseModel): """ - openapi_types = { - 'api_version': 'str', - 'items': 'list[TrainerV1alpha1ClusterTrainingRuntime]', - 'kind': 'str', - 'metadata': 'V1ListMeta' - } - - attribute_map = { - 'api_version': 'apiVersion', - 'items': 'items', - 'kind': 'kind', - 'metadata': 'metadata' - } - - def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1ClusterTrainingRuntimeList - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_version = None - self._items = None - self._kind = None - self._metadata = None - self.discriminator = None - - if api_version is not None: - self.api_version = api_version - self.items = items - if kind is not None: - self.kind = kind - if metadata is not None: - self.metadata = metadata - - @property - def api_version(self): - """Gets the api_version of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :return: The api_version of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :rtype: str - """ - return self._api_version - - @api_version.setter - def api_version(self, api_version): - """Sets the api_version of this TrainerV1alpha1ClusterTrainingRuntimeList. - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :param api_version: The api_version of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :type: str - """ - - self._api_version = api_version - - @property - def items(self): - """Gets the items of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - - List of ClusterTrainingRuntimes. # noqa: E501 - - :return: The items of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :rtype: list[TrainerV1alpha1ClusterTrainingRuntime] - """ - return self._items - - @items.setter - def items(self, items): - """Sets the items of this TrainerV1alpha1ClusterTrainingRuntimeList. - - List of ClusterTrainingRuntimes. # noqa: E501 - - :param items: The items of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :type: list[TrainerV1alpha1ClusterTrainingRuntime] - """ - if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 - raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 - - self._items = items - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :return: The kind of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1ClusterTrainingRuntimeList. - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - - - :return: The metadata of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :rtype: V1ListMeta + ClusterTrainingRuntimeList is a collection of cluster training runtimes. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", alias="apiVersion") + items: List[TrainerV1alpha1ClusterTrainingRuntime] = Field(description="List of ClusterTrainingRuntimes.") + kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ListMeta] = None + __properties: ClassVar[List[str]] = ["apiVersion", "items", "kind", "metadata"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ClusterTrainingRuntimeList from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1ClusterTrainingRuntimeList. + 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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ClusterTrainingRuntimeList from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "items": [TrainerV1alpha1ClusterTrainingRuntime.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "kind": obj.get("kind"), + "metadata": IoK8sApimachineryPkgApisMetaV1ListMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None + }) + return _obj - :param metadata: The metadata of this TrainerV1alpha1ClusterTrainingRuntimeList. # noqa: E501 - :type: V1ListMeta - """ - - self._metadata = metadata - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1ClusterTrainingRuntimeList): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1ClusterTrainingRuntimeList): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_container_override.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_container_override.py index 51e44e45e0..5040f8c944 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_container_override.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_container_override.py @@ -3,261 +3,119 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_env_from_source import IoK8sApiCoreV1EnvFromSource +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_volume_mount import IoK8sApiCoreV1VolumeMount +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1ContainerOverride(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1ContainerOverride(BaseModel): """ - openapi_types = { - 'args': 'list[str]', - 'command': 'list[str]', - 'env': 'list[V1EnvVar]', - 'env_from': 'list[V1EnvFromSource]', - 'name': 'str', - 'volume_mounts': 'list[V1VolumeMount]' - } - - attribute_map = { - 'args': 'args', - 'command': 'command', - 'env': 'env', - 'env_from': 'envFrom', - 'name': 'name', - 'volume_mounts': 'volumeMounts' - } - - def __init__(self, args=None, command=None, env=None, env_from=None, name='', volume_mounts=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1ContainerOverride - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._args = None - self._command = None - self._env = None - self._env_from = None - self._name = None - self._volume_mounts = None - self.discriminator = None - - if args is not None: - self.args = args - if command is not None: - self.command = command - if env is not None: - self.env = env - if env_from is not None: - self.env_from = env_from - self.name = name - if volume_mounts is not None: - self.volume_mounts = volume_mounts - - @property - def args(self): - """Gets the args of this TrainerV1alpha1ContainerOverride. # noqa: E501 - - Arguments to the entrypoint for the training container. # noqa: E501 - - :return: The args of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :rtype: list[str] - """ - return self._args - - @args.setter - def args(self, args): - """Sets the args of this TrainerV1alpha1ContainerOverride. - - Arguments to the entrypoint for the training container. # noqa: E501 - - :param args: The args of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :type: list[str] - """ - - self._args = args - - @property - def command(self): - """Gets the command of this TrainerV1alpha1ContainerOverride. # noqa: E501 - - Entrypoint commands for the training container. # noqa: E501 - - :return: The command of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :rtype: list[str] - """ - return self._command - - @command.setter - def command(self, command): - """Sets the command of this TrainerV1alpha1ContainerOverride. - - Entrypoint commands for the training container. # noqa: E501 - - :param command: The command of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :type: list[str] - """ - - self._command = command - - @property - def env(self): - """Gets the env of this TrainerV1alpha1ContainerOverride. # noqa: E501 - - List of environment variables to set in the container. These values will be merged with the TrainingRuntime's environments. # noqa: E501 - - :return: The env of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :rtype: list[V1EnvVar] - """ - return self._env - - @env.setter - def env(self, env): - """Sets the env of this TrainerV1alpha1ContainerOverride. - - List of environment variables to set in the container. These values will be merged with the TrainingRuntime's environments. # noqa: E501 - - :param env: The env of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :type: list[V1EnvVar] - """ - - self._env = env - - @property - def env_from(self): - """Gets the env_from of this TrainerV1alpha1ContainerOverride. # noqa: E501 - - List of sources to populate environment variables in the container. These values will be merged with the TrainingRuntime's environments. # noqa: E501 - - :return: The env_from of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :rtype: list[V1EnvFromSource] + ContainerOverride represents parameters that can be overridden using PodSpecOverrides. Parameters from the Trainer, DatasetConfig, and ModelConfig will take precedence. + """ # noqa: E501 + args: Optional[List[StrictStr]] = Field(default=None, description="Arguments to the entrypoint for the training container.") + command: Optional[List[StrictStr]] = Field(default=None, description="Entrypoint commands for the training container.") + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the container. These values will be merged with the TrainingRuntime's environments.") + env_from: Optional[List[IoK8sApiCoreV1EnvFromSource]] = Field(default=None, description="List of sources to populate environment variables in the container. These values will be merged with the TrainingRuntime's environments.", alias="envFrom") + name: StrictStr = Field(description="Name for the container. TrainingRuntime must have this container.") + volume_mounts: Optional[List[IoK8sApiCoreV1VolumeMount]] = Field(default=None, description="Pod volumes to mount into the container's filesystem.", alias="volumeMounts") + __properties: ClassVar[List[str]] = ["args", "command", "env", "envFrom", "name", "volumeMounts"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ContainerOverride from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._env_from - - @env_from.setter - def env_from(self, env_from): - """Sets the env_from of this TrainerV1alpha1ContainerOverride. - - List of sources to populate environment variables in the container. These values will be merged with the TrainingRuntime's environments. # noqa: E501 - - :param env_from: The env_from of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :type: list[V1EnvFromSource] - """ - - self._env_from = env_from - - @property - def name(self): - """Gets the name of this TrainerV1alpha1ContainerOverride. # noqa: E501 - - Name for the container. TrainingRuntime must have this container. # noqa: E501 - - :return: The name of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this TrainerV1alpha1ContainerOverride. - - Name for the container. TrainingRuntime must have this container. # noqa: E501 - - :param name: The name of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :type: str - """ - if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - @property - def volume_mounts(self): - """Gets the volume_mounts of this TrainerV1alpha1ContainerOverride. # noqa: E501 - - Pod volumes to mount into the container's filesystem. # noqa: E501 - - :return: The volume_mounts of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :rtype: list[V1VolumeMount] - """ - return self._volume_mounts - - @volume_mounts.setter - def volume_mounts(self, volume_mounts): - """Sets the volume_mounts of this TrainerV1alpha1ContainerOverride. - - Pod volumes to mount into the container's filesystem. # noqa: E501 - - :param volume_mounts: The volume_mounts of this TrainerV1alpha1ContainerOverride. # noqa: E501 - :type: list[V1VolumeMount] - """ - - self._volume_mounts = volume_mounts - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1ContainerOverride): - return False - - return self.to_dict() == other.to_dict() + 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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in env_from (list) + _items = [] + if self.env_from: + for _item_env_from in self.env_from: + if _item_env_from: + _items.append(_item_env_from.to_dict()) + _dict['envFrom'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in volume_mounts (list) + _items = [] + if self.volume_mounts: + for _item_volume_mounts in self.volume_mounts: + if _item_volume_mounts: + _items.append(_item_volume_mounts.to_dict()) + _dict['volumeMounts'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ContainerOverride from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "args": obj.get("args"), + "command": obj.get("command"), + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "envFrom": [IoK8sApiCoreV1EnvFromSource.from_dict(_item) for _item in obj["envFrom"]] if obj.get("envFrom") is not None else None, + "name": obj.get("name") if obj.get("name") is not None else '', + "volumeMounts": [IoK8sApiCoreV1VolumeMount.from_dict(_item) for _item in obj["volumeMounts"]] if obj.get("volumeMounts") is not None else None + }) + return _obj - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1ContainerOverride): - return True - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_coscheduling_pod_group_policy_source.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_coscheduling_pod_group_policy_source.py index 663b703124..5ccf966b23 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_coscheduling_pod_group_policy_source.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_coscheduling_pod_group_policy_source.py @@ -3,120 +3,85 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1CoschedulingPodGroupPolicySource(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self - Do not edit the class manually. +class TrainerV1alpha1CoschedulingPodGroupPolicySource(BaseModel): """ + CoschedulingPodGroupPolicySource represents configuration for coscheduling plugin. The number of min members in the PodGroupSpec is always equal to the number of nodes. + """ # noqa: E501 + schedule_timeout_seconds: Optional[StrictInt] = Field(default=None, description="Time threshold to schedule PodGroup for gang-scheduling. If the scheduling timeout is equal to 0, the default value is used. Defaults to 60 seconds.", alias="scheduleTimeoutSeconds") + __properties: ClassVar[List[str]] = ["scheduleTimeoutSeconds"] - """ - 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. - """ - openapi_types = { - 'schedule_timeout_seconds': 'int' - } + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - attribute_map = { - 'schedule_timeout_seconds': 'scheduleTimeoutSeconds' - } - def __init__(self, schedule_timeout_seconds=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1CoschedulingPodGroupPolicySource - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - self._schedule_timeout_seconds = None - self.discriminator = None + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if schedule_timeout_seconds is not None: - self.schedule_timeout_seconds = schedule_timeout_seconds + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1CoschedulingPodGroupPolicySource from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @property - def schedule_timeout_seconds(self): - """Gets the schedule_timeout_seconds of this TrainerV1alpha1CoschedulingPodGroupPolicySource. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - Time threshold to schedule PodGroup for gang-scheduling. If the scheduling timeout is equal to 0, the default value is used. Defaults to 60 seconds. # noqa: E501 + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The schedule_timeout_seconds of this TrainerV1alpha1CoschedulingPodGroupPolicySource. # noqa: E501 - :rtype: int + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._schedule_timeout_seconds + excluded_fields: Set[str] = set([ + ]) - @schedule_timeout_seconds.setter - def schedule_timeout_seconds(self, schedule_timeout_seconds): - """Sets the schedule_timeout_seconds of this TrainerV1alpha1CoschedulingPodGroupPolicySource. + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - Time threshold to schedule PodGroup for gang-scheduling. If the scheduling timeout is equal to 0, the default value is used. Defaults to 60 seconds. # noqa: E501 + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1CoschedulingPodGroupPolicySource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "scheduleTimeoutSeconds": obj.get("scheduleTimeoutSeconds") + }) + return _obj - :param schedule_timeout_seconds: The schedule_timeout_seconds of this TrainerV1alpha1CoschedulingPodGroupPolicySource. # noqa: E501 - :type: int - """ - self._schedule_timeout_seconds = schedule_timeout_seconds - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1CoschedulingPodGroupPolicySource): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1CoschedulingPodGroupPolicySource): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_dataset_config.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_dataset_config.py index f594e95d37..6156ac9cf8 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_dataset_config.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_dataset_config.py @@ -3,174 +3,101 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1DatasetConfig(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1DatasetConfig(BaseModel): """ - 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. - """ - openapi_types = { - 'env': 'list[V1EnvVar]', - 'secret_ref': 'V1LocalObjectReference', - 'storage_uri': 'str' - } - - attribute_map = { - 'env': 'env', - 'secret_ref': 'secretRef', - 'storage_uri': 'storageUri' - } - - def __init__(self, env=None, secret_ref=None, storage_uri=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1DatasetConfig - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._env = None - self._secret_ref = None - self._storage_uri = None - self.discriminator = None - - if env is not None: - self.env = env - if secret_ref is not None: - self.secret_ref = secret_ref - if storage_uri is not None: - self.storage_uri = storage_uri - - @property - def env(self): - """Gets the env of this TrainerV1alpha1DatasetConfig. # noqa: E501 - - List of environment variables to set in the dataset initializer container. These values will be merged with the TrainingRuntime's dataset initializer environments. # noqa: E501 - - :return: The env of this TrainerV1alpha1DatasetConfig. # noqa: E501 - :rtype: list[V1EnvVar] - """ - return self._env - - @env.setter - def env(self, env): - """Sets the env of this TrainerV1alpha1DatasetConfig. - - List of environment variables to set in the dataset initializer container. These values will be merged with the TrainingRuntime's dataset initializer environments. # noqa: E501 - - :param env: The env of this TrainerV1alpha1DatasetConfig. # noqa: E501 - :type: list[V1EnvVar] + DatasetConfig represents the desired dataset configuration. When this API is used, the training runtime must have the `dataset-initializer` container in the `Initializer` Job. + """ # noqa: E501 + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the dataset initializer container. These values will be merged with the TrainingRuntime's dataset initializer environments.") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + storage_uri: Optional[StrictStr] = Field(default=None, description="Storage uri for the dataset provider.", alias="storageUri") + __properties: ClassVar[List[str]] = ["env", "secretRef", "storageUri"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1DatasetConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1DatasetConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "storageUri": obj.get("storageUri") + }) + return _obj - self._env = env - - @property - def secret_ref(self): - """Gets the secret_ref of this TrainerV1alpha1DatasetConfig. # noqa: E501 - - - :return: The secret_ref of this TrainerV1alpha1DatasetConfig. # noqa: E501 - :rtype: V1LocalObjectReference - """ - return self._secret_ref - - @secret_ref.setter - def secret_ref(self, secret_ref): - """Sets the secret_ref of this TrainerV1alpha1DatasetConfig. - - - :param secret_ref: The secret_ref of this TrainerV1alpha1DatasetConfig. # noqa: E501 - :type: V1LocalObjectReference - """ - - self._secret_ref = secret_ref - - @property - def storage_uri(self): - """Gets the storage_uri of this TrainerV1alpha1DatasetConfig. # noqa: E501 - - Storage uri for the dataset provider. # noqa: E501 - - :return: The storage_uri of this TrainerV1alpha1DatasetConfig. # noqa: E501 - :rtype: str - """ - return self._storage_uri - - @storage_uri.setter - def storage_uri(self, storage_uri): - """Sets the storage_uri of this TrainerV1alpha1DatasetConfig. - - Storage uri for the dataset provider. # noqa: E501 - - :param storage_uri: The storage_uri of this TrainerV1alpha1DatasetConfig. # noqa: E501 - :type: str - """ - self._storage_uri = storage_uri - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1DatasetConfig): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1DatasetConfig): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_input_model.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_input_model.py index 349aeee50c..f6bbf2296f 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_input_model.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_input_model.py @@ -3,174 +3,101 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1InputModel(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1InputModel(BaseModel): """ - 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. - """ - openapi_types = { - 'env': 'list[V1EnvVar]', - 'secret_ref': 'V1LocalObjectReference', - 'storage_uri': 'str' - } - - attribute_map = { - 'env': 'env', - 'secret_ref': 'secretRef', - 'storage_uri': 'storageUri' - } - - def __init__(self, env=None, secret_ref=None, storage_uri=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1InputModel - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._env = None - self._secret_ref = None - self._storage_uri = None - self.discriminator = None - - if env is not None: - self.env = env - if secret_ref is not None: - self.secret_ref = secret_ref - if storage_uri is not None: - self.storage_uri = storage_uri - - @property - def env(self): - """Gets the env of this TrainerV1alpha1InputModel. # noqa: E501 - - List of environment variables to set in the model initializer container. These values will be merged with the TrainingRuntime's model initializer environments. # noqa: E501 - - :return: The env of this TrainerV1alpha1InputModel. # noqa: E501 - :rtype: list[V1EnvVar] - """ - return self._env - - @env.setter - def env(self, env): - """Sets the env of this TrainerV1alpha1InputModel. - - List of environment variables to set in the model initializer container. These values will be merged with the TrainingRuntime's model initializer environments. # noqa: E501 - - :param env: The env of this TrainerV1alpha1InputModel. # noqa: E501 - :type: list[V1EnvVar] + InputModel represents the desired pre-trained model configuration. + """ # noqa: E501 + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the model initializer container. These values will be merged with the TrainingRuntime's model initializer environments.") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + storage_uri: Optional[StrictStr] = Field(default=None, description="Storage uri for the model provider.", alias="storageUri") + __properties: ClassVar[List[str]] = ["env", "secretRef", "storageUri"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1InputModel from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1InputModel from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "storageUri": obj.get("storageUri") + }) + return _obj - self._env = env - - @property - def secret_ref(self): - """Gets the secret_ref of this TrainerV1alpha1InputModel. # noqa: E501 - - - :return: The secret_ref of this TrainerV1alpha1InputModel. # noqa: E501 - :rtype: V1LocalObjectReference - """ - return self._secret_ref - - @secret_ref.setter - def secret_ref(self, secret_ref): - """Sets the secret_ref of this TrainerV1alpha1InputModel. - - - :param secret_ref: The secret_ref of this TrainerV1alpha1InputModel. # noqa: E501 - :type: V1LocalObjectReference - """ - - self._secret_ref = secret_ref - - @property - def storage_uri(self): - """Gets the storage_uri of this TrainerV1alpha1InputModel. # noqa: E501 - - Storage uri for the model provider. # noqa: E501 - - :return: The storage_uri of this TrainerV1alpha1InputModel. # noqa: E501 - :rtype: str - """ - return self._storage_uri - - @storage_uri.setter - def storage_uri(self, storage_uri): - """Sets the storage_uri of this TrainerV1alpha1InputModel. - - Storage uri for the model provider. # noqa: E501 - - :param storage_uri: The storage_uri of this TrainerV1alpha1InputModel. # noqa: E501 - :type: str - """ - self._storage_uri = storage_uri - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1InputModel): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1InputModel): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_set_template_spec.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_set_template_spec.py index 8544b93c82..8ffea219e5 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_set_template_spec.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_set_template_spec.py @@ -3,144 +3,95 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1JobSetTemplateSpec(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from kubeflow.trainer.models.jobset_v1alpha2_job_set_spec import JobsetV1alpha2JobSetSpec +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1JobSetTemplateSpec(BaseModel): """ - 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. - """ - openapi_types = { - 'metadata': 'V1ObjectMeta', - 'spec': 'JobsetV1alpha2JobSetSpec' - } - - attribute_map = { - 'metadata': 'metadata', - 'spec': 'spec' - } - - def __init__(self, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1JobSetTemplateSpec - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._metadata = None - self._spec = None - self.discriminator = None - - if metadata is not None: - self.metadata = metadata - if spec is not None: - self.spec = spec - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1JobSetTemplateSpec. # noqa: E501 - - - :return: The metadata of this TrainerV1alpha1JobSetTemplateSpec. # noqa: E501 - :rtype: V1ObjectMeta - """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1JobSetTemplateSpec. - - - :param metadata: The metadata of this TrainerV1alpha1JobSetTemplateSpec. # noqa: E501 - :type: V1ObjectMeta + JobSetTemplateSpec represents a template of the desired JobSet. + """ # noqa: E501 + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: Optional[JobsetV1alpha2JobSetSpec] = None + __properties: ClassVar[List[str]] = ["metadata", "spec"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1JobSetTemplateSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1JobSetTemplateSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": JobsetV1alpha2JobSetSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None + }) + return _obj - self._metadata = metadata - - @property - def spec(self): - """Gets the spec of this TrainerV1alpha1JobSetTemplateSpec. # noqa: E501 - - - :return: The spec of this TrainerV1alpha1JobSetTemplateSpec. # noqa: E501 - :rtype: JobsetV1alpha2JobSetSpec - """ - return self._spec - - @spec.setter - def spec(self, spec): - """Sets the spec of this TrainerV1alpha1JobSetTemplateSpec. - - - :param spec: The spec of this TrainerV1alpha1JobSetTemplateSpec. # noqa: E501 - :type: JobsetV1alpha2JobSetSpec - """ - self._spec = spec - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1JobSetTemplateSpec): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1JobSetTemplateSpec): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_status.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_status.py index 9d158d8209..368e3341eb 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_status.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_job_status.py @@ -3,266 +3,95 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1JobStatus(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1JobStatus(BaseModel): """ - openapi_types = { - 'active': 'int', - 'failed': 'int', - 'name': 'str', - 'ready': 'int', - 'succeeded': 'int', - 'suspended': 'int' - } - - attribute_map = { - 'active': 'active', - 'failed': 'failed', - 'name': 'name', - 'ready': 'ready', - 'succeeded': 'succeeded', - 'suspended': 'suspended' - } - - def __init__(self, active=0, failed=0, name='', ready=0, succeeded=0, suspended=0, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1JobStatus - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._active = None - self._failed = None - self._name = None - self._ready = None - self._succeeded = None - self._suspended = None - self.discriminator = None - - self.active = active - self.failed = failed - self.name = name - self.ready = ready - self.succeeded = succeeded - self.suspended = suspended - - @property - def active(self): - """Gets the active of this TrainerV1alpha1JobStatus. # noqa: E501 - - Active is the number of child Jobs with at least 1 pod in a running or pending state which are not marked for deletion. # noqa: E501 - - :return: The active of this TrainerV1alpha1JobStatus. # noqa: E501 - :rtype: int - """ - return self._active - - @active.setter - def active(self, active): - """Sets the active of this TrainerV1alpha1JobStatus. - - Active is the number of child Jobs with at least 1 pod in a running or pending state which are not marked for deletion. # noqa: E501 - - :param active: The active of this TrainerV1alpha1JobStatus. # noqa: E501 - :type: int - """ - if self.local_vars_configuration.client_side_validation and active is None: # noqa: E501 - raise ValueError("Invalid value for `active`, must not be `None`") # noqa: E501 - - self._active = active - - @property - def failed(self): - """Gets the failed of this TrainerV1alpha1JobStatus. # noqa: E501 - - Failed is the number of failed child Jobs. # noqa: E501 - - :return: The failed of this TrainerV1alpha1JobStatus. # noqa: E501 - :rtype: int - """ - return self._failed - - @failed.setter - def failed(self, failed): - """Sets the failed of this TrainerV1alpha1JobStatus. - - Failed is the number of failed child Jobs. # noqa: E501 - - :param failed: The failed of this TrainerV1alpha1JobStatus. # noqa: E501 - :type: int - """ - if self.local_vars_configuration.client_side_validation and failed is None: # noqa: E501 - raise ValueError("Invalid value for `failed`, must not be `None`") # noqa: E501 - - self._failed = failed - - @property - def name(self): - """Gets the name of this TrainerV1alpha1JobStatus. # noqa: E501 - - Name of the child Job. # noqa: E501 - - :return: The name of this TrainerV1alpha1JobStatus. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this TrainerV1alpha1JobStatus. - - Name of the child Job. # noqa: E501 - - :param name: The name of this TrainerV1alpha1JobStatus. # noqa: E501 - :type: str - """ - if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - @property - def ready(self): - """Gets the ready of this TrainerV1alpha1JobStatus. # noqa: E501 - - Ready is the number of child Jobs where the number of ready pods and completed pods is greater than or equal to the total expected pod count for the child Job. # noqa: E501 - - :return: The ready of this TrainerV1alpha1JobStatus. # noqa: E501 - :rtype: int + TrainerV1alpha1JobStatus + """ # noqa: E501 + active: StrictInt = Field(description="Active is the number of child Jobs with at least 1 pod in a running or pending state which are not marked for deletion.") + failed: StrictInt = Field(description="Failed is the number of failed child Jobs.") + name: StrictStr = Field(description="Name of the child Job.") + ready: StrictInt = Field(description="Ready is the number of child Jobs where the number of ready pods and completed pods is greater than or equal to the total expected pod count for the child Job.") + succeeded: StrictInt = Field(description="Succeeded is the number of successfully completed child Jobs.") + suspended: StrictInt = Field(description="Suspended is the number of child Jobs which are in a suspended state.") + __properties: ClassVar[List[str]] = ["active", "failed", "name", "ready", "succeeded", "suspended"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1JobStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._ready - - @ready.setter - def ready(self, ready): - """Sets the ready of this TrainerV1alpha1JobStatus. - - Ready is the number of child Jobs where the number of ready pods and completed pods is greater than or equal to the total expected pod count for the child Job. # noqa: E501 - - :param ready: The ready of this TrainerV1alpha1JobStatus. # noqa: E501 - :type: int - """ - if self.local_vars_configuration.client_side_validation and ready is None: # noqa: E501 - raise ValueError("Invalid value for `ready`, must not be `None`") # noqa: E501 - - self._ready = ready - - @property - def succeeded(self): - """Gets the succeeded of this TrainerV1alpha1JobStatus. # noqa: E501 - - Succeeded is the number of successfully completed child Jobs. # noqa: E501 - - :return: The succeeded of this TrainerV1alpha1JobStatus. # noqa: E501 - :rtype: int - """ - return self._succeeded - - @succeeded.setter - def succeeded(self, succeeded): - """Sets the succeeded of this TrainerV1alpha1JobStatus. - - Succeeded is the number of successfully completed child Jobs. # noqa: E501 - - :param succeeded: The succeeded of this TrainerV1alpha1JobStatus. # noqa: E501 - :type: int - """ - if self.local_vars_configuration.client_side_validation and succeeded is None: # noqa: E501 - raise ValueError("Invalid value for `succeeded`, must not be `None`") # noqa: E501 - - self._succeeded = succeeded - - @property - def suspended(self): - """Gets the suspended of this TrainerV1alpha1JobStatus. # noqa: E501 - - Suspended is the number of child Jobs which are in a suspended state. # noqa: E501 - - :return: The suspended of this TrainerV1alpha1JobStatus. # noqa: E501 - :rtype: int - """ - return self._suspended - - @suspended.setter - def suspended(self, suspended): - """Sets the suspended of this TrainerV1alpha1JobStatus. - - Suspended is the number of child Jobs which are in a suspended state. # noqa: E501 - - :param suspended: The suspended of this TrainerV1alpha1JobStatus. # noqa: E501 - :type: int - """ - if self.local_vars_configuration.client_side_validation and suspended is None: # noqa: E501 - raise ValueError("Invalid value for `suspended`, must not be `None`") # noqa: E501 - - self._suspended = suspended - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1JobStatus): - return False - - return self.to_dict() == other.to_dict() + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1JobStatus from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "active": obj.get("active") if obj.get("active") is not None else 0, + "failed": obj.get("failed") if obj.get("failed") is not None else 0, + "name": obj.get("name") if obj.get("name") is not None else '', + "ready": obj.get("ready") if obj.get("ready") is not None else 0, + "succeeded": obj.get("succeeded") if obj.get("succeeded") is not None else 0, + "suspended": obj.get("suspended") if obj.get("suspended") is not None else 0 + }) + return _obj - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1JobStatus): - return True - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy.py index 16f637b692..d461bf5d21 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy.py @@ -3,172 +3,97 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1MLPolicy(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_mpiml_policy_source import TrainerV1alpha1MPIMLPolicySource +from kubeflow.trainer.models.trainer_v1alpha1_torch_ml_policy_source import TrainerV1alpha1TorchMLPolicySource +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1MLPolicy(BaseModel): """ - 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. - """ - openapi_types = { - 'mpi': 'TrainerV1alpha1MPIMLPolicySource', - 'num_nodes': 'int', - 'torch': 'TrainerV1alpha1TorchMLPolicySource' - } - - attribute_map = { - 'mpi': 'mpi', - 'num_nodes': 'numNodes', - 'torch': 'torch' - } - - def __init__(self, mpi=None, num_nodes=None, torch=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1MLPolicy - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._mpi = None - self._num_nodes = None - self._torch = None - self.discriminator = None - - if mpi is not None: - self.mpi = mpi - if num_nodes is not None: - self.num_nodes = num_nodes - if torch is not None: - self.torch = torch - - @property - def mpi(self): - """Gets the mpi of this TrainerV1alpha1MLPolicy. # noqa: E501 - - - :return: The mpi of this TrainerV1alpha1MLPolicy. # noqa: E501 - :rtype: TrainerV1alpha1MPIMLPolicySource - """ - return self._mpi - - @mpi.setter - def mpi(self, mpi): - """Sets the mpi of this TrainerV1alpha1MLPolicy. - - - :param mpi: The mpi of this TrainerV1alpha1MLPolicy. # noqa: E501 - :type: TrainerV1alpha1MPIMLPolicySource + MLPolicy represents configuration for the model trining with ML-specific parameters. + """ # noqa: E501 + mpi: Optional[TrainerV1alpha1MPIMLPolicySource] = None + num_nodes: Optional[StrictInt] = Field(default=None, description="Number of training nodes. Defaults to 1.", alias="numNodes") + torch: Optional[TrainerV1alpha1TorchMLPolicySource] = None + __properties: ClassVar[List[str]] = ["mpi", "numNodes", "torch"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1MLPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 mpi + if self.mpi: + _dict['mpi'] = self.mpi.to_dict() + # override the default output from pydantic by calling `to_dict()` of torch + if self.torch: + _dict['torch'] = self.torch.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1MLPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mpi": TrainerV1alpha1MPIMLPolicySource.from_dict(obj["mpi"]) if obj.get("mpi") is not None else None, + "numNodes": obj.get("numNodes"), + "torch": TrainerV1alpha1TorchMLPolicySource.from_dict(obj["torch"]) if obj.get("torch") is not None else None + }) + return _obj - self._mpi = mpi - - @property - def num_nodes(self): - """Gets the num_nodes of this TrainerV1alpha1MLPolicy. # noqa: E501 - - Number of training nodes. Defaults to 1. # noqa: E501 - - :return: The num_nodes of this TrainerV1alpha1MLPolicy. # noqa: E501 - :rtype: int - """ - return self._num_nodes - - @num_nodes.setter - def num_nodes(self, num_nodes): - """Sets the num_nodes of this TrainerV1alpha1MLPolicy. - - Number of training nodes. Defaults to 1. # noqa: E501 - - :param num_nodes: The num_nodes of this TrainerV1alpha1MLPolicy. # noqa: E501 - :type: int - """ - - self._num_nodes = num_nodes - - @property - def torch(self): - """Gets the torch of this TrainerV1alpha1MLPolicy. # noqa: E501 - - - :return: The torch of this TrainerV1alpha1MLPolicy. # noqa: E501 - :rtype: TrainerV1alpha1TorchMLPolicySource - """ - return self._torch - - @torch.setter - def torch(self, torch): - """Sets the torch of this TrainerV1alpha1MLPolicy. - - - :param torch: The torch of this TrainerV1alpha1MLPolicy. # noqa: E501 - :type: TrainerV1alpha1TorchMLPolicySource - """ - self._torch = torch - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1MLPolicy): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1MLPolicy): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy_source.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy_source.py index 4c273e321b..4c72f53276 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy_source.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_ml_policy_source.py @@ -3,144 +3,95 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1MLPolicySource(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_mpiml_policy_source import TrainerV1alpha1MPIMLPolicySource +from kubeflow.trainer.models.trainer_v1alpha1_torch_ml_policy_source import TrainerV1alpha1TorchMLPolicySource +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1MLPolicySource(BaseModel): """ - 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. - """ - openapi_types = { - 'mpi': 'TrainerV1alpha1MPIMLPolicySource', - 'torch': 'TrainerV1alpha1TorchMLPolicySource' - } - - attribute_map = { - 'mpi': 'mpi', - 'torch': 'torch' - } - - def __init__(self, mpi=None, torch=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1MLPolicySource - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._mpi = None - self._torch = None - self.discriminator = None - - if mpi is not None: - self.mpi = mpi - if torch is not None: - self.torch = torch - - @property - def mpi(self): - """Gets the mpi of this TrainerV1alpha1MLPolicySource. # noqa: E501 - - - :return: The mpi of this TrainerV1alpha1MLPolicySource. # noqa: E501 - :rtype: TrainerV1alpha1MPIMLPolicySource - """ - return self._mpi - - @mpi.setter - def mpi(self, mpi): - """Sets the mpi of this TrainerV1alpha1MLPolicySource. - - - :param mpi: The mpi of this TrainerV1alpha1MLPolicySource. # noqa: E501 - :type: TrainerV1alpha1MPIMLPolicySource + MLPolicySource represents the runtime-specific configuration for various technologies. One of the following specs can be set. + """ # noqa: E501 + mpi: Optional[TrainerV1alpha1MPIMLPolicySource] = None + torch: Optional[TrainerV1alpha1TorchMLPolicySource] = None + __properties: ClassVar[List[str]] = ["mpi", "torch"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1MLPolicySource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 mpi + if self.mpi: + _dict['mpi'] = self.mpi.to_dict() + # override the default output from pydantic by calling `to_dict()` of torch + if self.torch: + _dict['torch'] = self.torch.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1MLPolicySource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mpi": TrainerV1alpha1MPIMLPolicySource.from_dict(obj["mpi"]) if obj.get("mpi") is not None else None, + "torch": TrainerV1alpha1TorchMLPolicySource.from_dict(obj["torch"]) if obj.get("torch") is not None else None + }) + return _obj - self._mpi = mpi - - @property - def torch(self): - """Gets the torch of this TrainerV1alpha1MLPolicySource. # noqa: E501 - - - :return: The torch of this TrainerV1alpha1MLPolicySource. # noqa: E501 - :rtype: TrainerV1alpha1TorchMLPolicySource - """ - return self._torch - - @torch.setter - def torch(self, torch): - """Sets the torch of this TrainerV1alpha1MLPolicySource. - - - :param torch: The torch of this TrainerV1alpha1MLPolicySource. # noqa: E501 - :type: TrainerV1alpha1TorchMLPolicySource - """ - self._torch = torch - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1MLPolicySource): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1MLPolicySource): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_model_config.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_model_config.py index 12e6d42822..093a7fd375 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_model_config.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_model_config.py @@ -3,144 +3,95 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1ModelConfig(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_input_model import TrainerV1alpha1InputModel +from kubeflow.trainer.models.trainer_v1alpha1_output_model import TrainerV1alpha1OutputModel +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1ModelConfig(BaseModel): """ - 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. - """ - openapi_types = { - 'input': 'TrainerV1alpha1InputModel', - 'output': 'TrainerV1alpha1OutputModel' - } - - attribute_map = { - 'input': 'input', - 'output': 'output' - } - - def __init__(self, input=None, output=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1ModelConfig - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._input = None - self._output = None - self.discriminator = None - - if input is not None: - self.input = input - if output is not None: - self.output = output - - @property - def input(self): - """Gets the input of this TrainerV1alpha1ModelConfig. # noqa: E501 - - - :return: The input of this TrainerV1alpha1ModelConfig. # noqa: E501 - :rtype: TrainerV1alpha1InputModel - """ - return self._input - - @input.setter - def input(self, input): - """Sets the input of this TrainerV1alpha1ModelConfig. - - - :param input: The input of this TrainerV1alpha1ModelConfig. # noqa: E501 - :type: TrainerV1alpha1InputModel + ModelConfig represents the desired model configuration. + """ # noqa: E501 + input: Optional[TrainerV1alpha1InputModel] = None + output: Optional[TrainerV1alpha1OutputModel] = None + __properties: ClassVar[List[str]] = ["input", "output"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ModelConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 input + if self.input: + _dict['input'] = self.input.to_dict() + # override the default output from pydantic by calling `to_dict()` of output + if self.output: + _dict['output'] = self.output.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1ModelConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "input": TrainerV1alpha1InputModel.from_dict(obj["input"]) if obj.get("input") is not None else None, + "output": TrainerV1alpha1OutputModel.from_dict(obj["output"]) if obj.get("output") is not None else None + }) + return _obj - self._input = input - - @property - def output(self): - """Gets the output of this TrainerV1alpha1ModelConfig. # noqa: E501 - - - :return: The output of this TrainerV1alpha1ModelConfig. # noqa: E501 - :rtype: TrainerV1alpha1OutputModel - """ - return self._output - - @output.setter - def output(self, output): - """Sets the output of this TrainerV1alpha1ModelConfig. - - - :param output: The output of this TrainerV1alpha1ModelConfig. # noqa: E501 - :type: TrainerV1alpha1OutputModel - """ - self._output = output - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1ModelConfig): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1ModelConfig): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_mpiml_policy_source.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_mpiml_policy_source.py index ce3d1e0f13..053b88dccc 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_mpiml_policy_source.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_mpiml_policy_source.py @@ -3,204 +3,91 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1MPIMLPolicySource(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1MPIMLPolicySource(BaseModel): """ - openapi_types = { - 'mpi_implementation': 'str', - 'num_proc_per_node': 'int', - 'run_launcher_as_node': 'bool', - 'ssh_auth_mount_path': 'str' - } - - attribute_map = { - 'mpi_implementation': 'mpiImplementation', - 'num_proc_per_node': 'numProcPerNode', - 'run_launcher_as_node': 'runLauncherAsNode', - 'ssh_auth_mount_path': 'sshAuthMountPath' - } - - def __init__(self, mpi_implementation=None, num_proc_per_node=None, run_launcher_as_node=None, ssh_auth_mount_path=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1MPIMLPolicySource - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._mpi_implementation = None - self._num_proc_per_node = None - self._run_launcher_as_node = None - self._ssh_auth_mount_path = None - self.discriminator = None - - if mpi_implementation is not None: - self.mpi_implementation = mpi_implementation - if num_proc_per_node is not None: - self.num_proc_per_node = num_proc_per_node - if run_launcher_as_node is not None: - self.run_launcher_as_node = run_launcher_as_node - if ssh_auth_mount_path is not None: - self.ssh_auth_mount_path = ssh_auth_mount_path - - @property - def mpi_implementation(self): - """Gets the mpi_implementation of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - - Implementation name for the MPI to create the appropriate hostfile. Defaults to OpenMPI. # noqa: E501 - - :return: The mpi_implementation of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :rtype: str - """ - return self._mpi_implementation - - @mpi_implementation.setter - def mpi_implementation(self, mpi_implementation): - """Sets the mpi_implementation of this TrainerV1alpha1MPIMLPolicySource. - - Implementation name for the MPI to create the appropriate hostfile. Defaults to OpenMPI. # noqa: E501 - - :param mpi_implementation: The mpi_implementation of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :type: str - """ - - self._mpi_implementation = mpi_implementation - - @property - def num_proc_per_node(self): - """Gets the num_proc_per_node of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - - Number of processes per node. This value is equal to the number of slots for each node in the hostfile. # noqa: E501 - - :return: The num_proc_per_node of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :rtype: int - """ - return self._num_proc_per_node - - @num_proc_per_node.setter - def num_proc_per_node(self, num_proc_per_node): - """Sets the num_proc_per_node of this TrainerV1alpha1MPIMLPolicySource. - - Number of processes per node. This value is equal to the number of slots for each node in the hostfile. # noqa: E501 - - :param num_proc_per_node: The num_proc_per_node of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :type: int - """ - - self._num_proc_per_node = num_proc_per_node - - @property - def run_launcher_as_node(self): - """Gets the run_launcher_as_node of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - - Whether to run training process on the launcher Job. Defaults to false. # noqa: E501 - - :return: The run_launcher_as_node of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :rtype: bool - """ - return self._run_launcher_as_node - - @run_launcher_as_node.setter - def run_launcher_as_node(self, run_launcher_as_node): - """Sets the run_launcher_as_node of this TrainerV1alpha1MPIMLPolicySource. - - Whether to run training process on the launcher Job. Defaults to false. # noqa: E501 - - :param run_launcher_as_node: The run_launcher_as_node of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :type: bool - """ - - self._run_launcher_as_node = run_launcher_as_node - - @property - def ssh_auth_mount_path(self): - """Gets the ssh_auth_mount_path of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - - Directory where SSH keys are mounted. Defaults to /root/.ssh. # noqa: E501 - - :return: The ssh_auth_mount_path of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :rtype: str + MPIMLPolicySource represents a MPI runtime configuration. + """ # noqa: E501 + mpi_implementation: Optional[StrictStr] = Field(default=None, description="Implementation name for the MPI to create the appropriate hostfile. Defaults to OpenMPI.", alias="mpiImplementation") + num_proc_per_node: Optional[StrictInt] = Field(default=None, description="Number of processes per node. This value is equal to the number of slots for each node in the hostfile.", alias="numProcPerNode") + run_launcher_as_node: Optional[StrictBool] = Field(default=None, description="Whether to run training process on the launcher Job. Defaults to false.", alias="runLauncherAsNode") + ssh_auth_mount_path: Optional[StrictStr] = Field(default=None, description="Directory where SSH keys are mounted. Defaults to /root/.ssh.", alias="sshAuthMountPath") + __properties: ClassVar[List[str]] = ["mpiImplementation", "numProcPerNode", "runLauncherAsNode", "sshAuthMountPath"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1MPIMLPolicySource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._ssh_auth_mount_path - - @ssh_auth_mount_path.setter - def ssh_auth_mount_path(self, ssh_auth_mount_path): - """Sets the ssh_auth_mount_path of this TrainerV1alpha1MPIMLPolicySource. + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1MPIMLPolicySource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mpiImplementation": obj.get("mpiImplementation"), + "numProcPerNode": obj.get("numProcPerNode"), + "runLauncherAsNode": obj.get("runLauncherAsNode"), + "sshAuthMountPath": obj.get("sshAuthMountPath") + }) + return _obj - Directory where SSH keys are mounted. Defaults to /root/.ssh. # noqa: E501 - - :param ssh_auth_mount_path: The ssh_auth_mount_path of this TrainerV1alpha1MPIMLPolicySource. # noqa: E501 - :type: str - """ - self._ssh_auth_mount_path = ssh_auth_mount_path - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1MPIMLPolicySource): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1MPIMLPolicySource): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_output_model.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_output_model.py index be32489f67..9a90ddcbc7 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_output_model.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_output_model.py @@ -3,174 +3,101 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1OutputModel(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_local_object_reference import IoK8sApiCoreV1LocalObjectReference +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1OutputModel(BaseModel): """ - 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. - """ - openapi_types = { - 'env': 'list[V1EnvVar]', - 'secret_ref': 'V1LocalObjectReference', - 'storage_uri': 'str' - } - - attribute_map = { - 'env': 'env', - 'secret_ref': 'secretRef', - 'storage_uri': 'storageUri' - } - - def __init__(self, env=None, secret_ref=None, storage_uri=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1OutputModel - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._env = None - self._secret_ref = None - self._storage_uri = None - self.discriminator = None - - if env is not None: - self.env = env - if secret_ref is not None: - self.secret_ref = secret_ref - if storage_uri is not None: - self.storage_uri = storage_uri - - @property - def env(self): - """Gets the env of this TrainerV1alpha1OutputModel. # noqa: E501 - - List of environment variables to set in the model exporter container. These values will be merged with the TrainingRuntime's model exporter environments. # noqa: E501 - - :return: The env of this TrainerV1alpha1OutputModel. # noqa: E501 - :rtype: list[V1EnvVar] - """ - return self._env - - @env.setter - def env(self, env): - """Sets the env of this TrainerV1alpha1OutputModel. - - List of environment variables to set in the model exporter container. These values will be merged with the TrainingRuntime's model exporter environments. # noqa: E501 - - :param env: The env of this TrainerV1alpha1OutputModel. # noqa: E501 - :type: list[V1EnvVar] + OutputModel represents the desired trained model configuration. + """ # noqa: E501 + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the model exporter container. These values will be merged with the TrainingRuntime's model exporter environments.") + secret_ref: Optional[IoK8sApiCoreV1LocalObjectReference] = Field(default=None, alias="secretRef") + storage_uri: Optional[StrictStr] = Field(default=None, description="Storage uri for the model exporter.", alias="storageUri") + __properties: ClassVar[List[str]] = ["env", "secretRef", "storageUri"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1OutputModel from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of secret_ref + if self.secret_ref: + _dict['secretRef'] = self.secret_ref.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1OutputModel from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "secretRef": IoK8sApiCoreV1LocalObjectReference.from_dict(obj["secretRef"]) if obj.get("secretRef") is not None else None, + "storageUri": obj.get("storageUri") + }) + return _obj - self._env = env - - @property - def secret_ref(self): - """Gets the secret_ref of this TrainerV1alpha1OutputModel. # noqa: E501 - - - :return: The secret_ref of this TrainerV1alpha1OutputModel. # noqa: E501 - :rtype: V1LocalObjectReference - """ - return self._secret_ref - - @secret_ref.setter - def secret_ref(self, secret_ref): - """Sets the secret_ref of this TrainerV1alpha1OutputModel. - - - :param secret_ref: The secret_ref of this TrainerV1alpha1OutputModel. # noqa: E501 - :type: V1LocalObjectReference - """ - - self._secret_ref = secret_ref - - @property - def storage_uri(self): - """Gets the storage_uri of this TrainerV1alpha1OutputModel. # noqa: E501 - - Storage uri for the model exporter. # noqa: E501 - - :return: The storage_uri of this TrainerV1alpha1OutputModel. # noqa: E501 - :rtype: str - """ - return self._storage_uri - - @storage_uri.setter - def storage_uri(self, storage_uri): - """Sets the storage_uri of this TrainerV1alpha1OutputModel. - - Storage uri for the model exporter. # noqa: E501 - - :param storage_uri: The storage_uri of this TrainerV1alpha1OutputModel. # noqa: E501 - :type: str - """ - self._storage_uri = storage_uri - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1OutputModel): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1OutputModel): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy.py index 4da79422ea..90cb6e124c 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy.py @@ -3,118 +3,89 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1PodGroupPolicy(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_coscheduling_pod_group_policy_source import TrainerV1alpha1CoschedulingPodGroupPolicySource +from typing import Optional, Set +from typing_extensions import Self - Do not edit the class manually. +class TrainerV1alpha1PodGroupPolicy(BaseModel): """ + PodGroupPolicy represents a PodGroup configuration for gang-scheduling. + """ # noqa: E501 + coscheduling: Optional[TrainerV1alpha1CoschedulingPodGroupPolicySource] = None + __properties: ClassVar[List[str]] = ["coscheduling"] - """ - 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. - """ - openapi_types = { - 'coscheduling': 'TrainerV1alpha1CoschedulingPodGroupPolicySource' - } + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - attribute_map = { - 'coscheduling': 'coscheduling' - } - def __init__(self, coscheduling=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1PodGroupPolicy - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - self._coscheduling = None - self.discriminator = None + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if coscheduling is not None: - self.coscheduling = coscheduling + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodGroupPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @property - def coscheduling(self): - """Gets the coscheduling of this TrainerV1alpha1PodGroupPolicy. # noqa: E501 + def to_dict(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)`: - :return: The coscheduling of this TrainerV1alpha1PodGroupPolicy. # noqa: E501 - :rtype: TrainerV1alpha1CoschedulingPodGroupPolicySource + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._coscheduling + 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 coscheduling + if self.coscheduling: + _dict['coscheduling'] = self.coscheduling.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodGroupPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "coscheduling": TrainerV1alpha1CoschedulingPodGroupPolicySource.from_dict(obj["coscheduling"]) if obj.get("coscheduling") is not None else None + }) + return _obj - @coscheduling.setter - def coscheduling(self, coscheduling): - """Sets the coscheduling of this TrainerV1alpha1PodGroupPolicy. - - - :param coscheduling: The coscheduling of this TrainerV1alpha1PodGroupPolicy. # noqa: E501 - :type: TrainerV1alpha1CoschedulingPodGroupPolicySource - """ - self._coscheduling = coscheduling - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1PodGroupPolicy): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1PodGroupPolicy): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy_source.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy_source.py index 02460e1cfd..6a0988c6d9 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy_source.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_group_policy_source.py @@ -3,118 +3,89 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1PodGroupPolicySource(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech +from pydantic import BaseModel, ConfigDict +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_coscheduling_pod_group_policy_source import TrainerV1alpha1CoschedulingPodGroupPolicySource +from typing import Optional, Set +from typing_extensions import Self - Do not edit the class manually. +class TrainerV1alpha1PodGroupPolicySource(BaseModel): """ + PodGroupPolicySource represents supported plugins for gang-scheduling. Only one of its members may be specified. + """ # noqa: E501 + coscheduling: Optional[TrainerV1alpha1CoschedulingPodGroupPolicySource] = None + __properties: ClassVar[List[str]] = ["coscheduling"] - """ - 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. - """ - openapi_types = { - 'coscheduling': 'TrainerV1alpha1CoschedulingPodGroupPolicySource' - } + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) - attribute_map = { - 'coscheduling': 'coscheduling' - } - def __init__(self, coscheduling=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1PodGroupPolicySource - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - self._coscheduling = None - self.discriminator = None + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - if coscheduling is not None: - self.coscheduling = coscheduling + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodGroupPolicySource from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @property - def coscheduling(self): - """Gets the coscheduling of this TrainerV1alpha1PodGroupPolicySource. # noqa: E501 + def to_dict(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)`: - :return: The coscheduling of this TrainerV1alpha1PodGroupPolicySource. # noqa: E501 - :rtype: TrainerV1alpha1CoschedulingPodGroupPolicySource + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._coscheduling + 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 coscheduling + if self.coscheduling: + _dict['coscheduling'] = self.coscheduling.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodGroupPolicySource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "coscheduling": TrainerV1alpha1CoschedulingPodGroupPolicySource.from_dict(obj["coscheduling"]) if obj.get("coscheduling") is not None else None + }) + return _obj - @coscheduling.setter - def coscheduling(self, coscheduling): - """Sets the coscheduling of this TrainerV1alpha1PodGroupPolicySource. - - - :param coscheduling: The coscheduling of this TrainerV1alpha1PodGroupPolicySource. # noqa: E501 - :type: TrainerV1alpha1CoschedulingPodGroupPolicySource - """ - self._coscheduling = coscheduling - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1PodGroupPolicySource): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1PodGroupPolicySource): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override.py index 14578945b6..e28a351dc2 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override.py @@ -3,289 +3,136 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1PodSpecOverride(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_toleration import IoK8sApiCoreV1Toleration +from kubeflow.trainer.models.io_k8s_api_core_v1_volume import IoK8sApiCoreV1Volume +from kubeflow.trainer.models.trainer_v1alpha1_container_override import TrainerV1alpha1ContainerOverride +from kubeflow.trainer.models.trainer_v1alpha1_pod_spec_override_target_job import TrainerV1alpha1PodSpecOverrideTargetJob +from typing import Optional, Set +from typing_extensions import Self + +class TrainerV1alpha1PodSpecOverride(BaseModel): """ - 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. - """ - openapi_types = { - 'containers': 'list[TrainerV1alpha1ContainerOverride]', - 'init_containers': 'list[TrainerV1alpha1ContainerOverride]', - 'node_selector': 'dict(str, str)', - 'service_account_name': 'str', - 'target_jobs': 'list[TrainerV1alpha1PodSpecOverrideTargetJob]', - 'tolerations': 'list[V1Toleration]', - 'volumes': 'list[V1Volume]' - } - - attribute_map = { - 'containers': 'containers', - 'init_containers': 'initContainers', - 'node_selector': 'nodeSelector', - 'service_account_name': 'serviceAccountName', - 'target_jobs': 'targetJobs', - 'tolerations': 'tolerations', - 'volumes': 'volumes' - } - - def __init__(self, containers=None, init_containers=None, node_selector=None, service_account_name=None, target_jobs=None, tolerations=None, volumes=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1PodSpecOverride - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._containers = None - self._init_containers = None - self._node_selector = None - self._service_account_name = None - self._target_jobs = None - self._tolerations = None - self._volumes = None - self.discriminator = None - - if containers is not None: - self.containers = containers - if init_containers is not None: - self.init_containers = init_containers - if node_selector is not None: - self.node_selector = node_selector - if service_account_name is not None: - self.service_account_name = service_account_name - self.target_jobs = target_jobs - if tolerations is not None: - self.tolerations = tolerations - if volumes is not None: - self.volumes = volumes - - @property - def containers(self): - """Gets the containers of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - Overrides for the containers in the desired job templates. # noqa: E501 - - :return: The containers of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: list[TrainerV1alpha1ContainerOverride] + PodSpecOverride represents the custom overrides that will be applied for the TrainJob's resources. + """ # noqa: E501 + containers: Optional[List[TrainerV1alpha1ContainerOverride]] = Field(default=None, description="Overrides for the containers in the desired job templates.") + init_containers: Optional[List[TrainerV1alpha1ContainerOverride]] = Field(default=None, description="Overrides for the init container in the desired job templates.", alias="initContainers") + node_selector: Optional[Dict[str, StrictStr]] = Field(default=None, description="Override for the node selector to place Pod on the specific mode.", alias="nodeSelector") + service_account_name: Optional[StrictStr] = Field(default=None, description="Override for the service account.", alias="serviceAccountName") + target_jobs: List[TrainerV1alpha1PodSpecOverrideTargetJob] = Field(description="TrainJobs is the training job replicas in the training runtime template to apply the overrides.", alias="targetJobs") + tolerations: Optional[List[IoK8sApiCoreV1Toleration]] = Field(default=None, description="Override for the Pod's tolerations.") + volumes: Optional[List[IoK8sApiCoreV1Volume]] = Field(default=None, description="Overrides for the Pod volume configuration.") + __properties: ClassVar[List[str]] = ["containers", "initContainers", "nodeSelector", "serviceAccountName", "targetJobs", "tolerations", "volumes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodSpecOverride from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._containers - - @containers.setter - def containers(self, containers): - """Sets the containers of this TrainerV1alpha1PodSpecOverride. - - Overrides for the containers in the desired job templates. # noqa: E501 - - :param containers: The containers of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: list[TrainerV1alpha1ContainerOverride] - """ - - self._containers = containers - - @property - def init_containers(self): - """Gets the init_containers of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - Overrides for the init container in the desired job templates. # noqa: E501 - - :return: The init_containers of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: list[TrainerV1alpha1ContainerOverride] - """ - return self._init_containers - - @init_containers.setter - def init_containers(self, init_containers): - """Sets the init_containers of this TrainerV1alpha1PodSpecOverride. - - Overrides for the init container in the desired job templates. # noqa: E501 - - :param init_containers: The init_containers of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: list[TrainerV1alpha1ContainerOverride] - """ - - self._init_containers = init_containers - - @property - def node_selector(self): - """Gets the node_selector of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - Override for the node selector to place Pod on the specific mode. # noqa: E501 - - :return: The node_selector of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: dict(str, str) - """ - return self._node_selector - - @node_selector.setter - def node_selector(self, node_selector): - """Sets the node_selector of this TrainerV1alpha1PodSpecOverride. - - Override for the node selector to place Pod on the specific mode. # noqa: E501 - - :param node_selector: The node_selector of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: dict(str, str) - """ - - self._node_selector = node_selector - - @property - def service_account_name(self): - """Gets the service_account_name of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - Override for the service account. # noqa: E501 - - :return: The service_account_name of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: str - """ - return self._service_account_name - - @service_account_name.setter - def service_account_name(self, service_account_name): - """Sets the service_account_name of this TrainerV1alpha1PodSpecOverride. - - Override for the service account. # noqa: E501 - - :param service_account_name: The service_account_name of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: str - """ - - self._service_account_name = service_account_name - - @property - def target_jobs(self): - """Gets the target_jobs of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - TrainJobs is the training job replicas in the training runtime template to apply the overrides. # noqa: E501 - - :return: The target_jobs of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: list[TrainerV1alpha1PodSpecOverrideTargetJob] - """ - return self._target_jobs - - @target_jobs.setter - def target_jobs(self, target_jobs): - """Sets the target_jobs of this TrainerV1alpha1PodSpecOverride. - - TrainJobs is the training job replicas in the training runtime template to apply the overrides. # noqa: E501 - - :param target_jobs: The target_jobs of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: list[TrainerV1alpha1PodSpecOverrideTargetJob] - """ - if self.local_vars_configuration.client_side_validation and target_jobs is None: # noqa: E501 - raise ValueError("Invalid value for `target_jobs`, must not be `None`") # noqa: E501 - - self._target_jobs = target_jobs - - @property - def tolerations(self): - """Gets the tolerations of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - Override for the Pod's tolerations. # noqa: E501 - - :return: The tolerations of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: list[V1Toleration] - """ - return self._tolerations - - @tolerations.setter - def tolerations(self, tolerations): - """Sets the tolerations of this TrainerV1alpha1PodSpecOverride. - - Override for the Pod's tolerations. # noqa: E501 - - :param tolerations: The tolerations of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: list[V1Toleration] - """ - - self._tolerations = tolerations - - @property - def volumes(self): - """Gets the volumes of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - - Overrides for the Pod volume configuration. # noqa: E501 - - :return: The volumes of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :rtype: list[V1Volume] - """ - return self._volumes - - @volumes.setter - def volumes(self, volumes): - """Sets the volumes of this TrainerV1alpha1PodSpecOverride. - - Overrides for the Pod volume configuration. # noqa: E501 - - :param volumes: The volumes of this TrainerV1alpha1PodSpecOverride. # noqa: E501 - :type: list[V1Volume] - """ - - self._volumes = volumes - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1PodSpecOverride): - return False - - return self.to_dict() == other.to_dict() + 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 containers (list) + _items = [] + if self.containers: + for _item_containers in self.containers: + if _item_containers: + _items.append(_item_containers.to_dict()) + _dict['containers'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in init_containers (list) + _items = [] + if self.init_containers: + for _item_init_containers in self.init_containers: + if _item_init_containers: + _items.append(_item_init_containers.to_dict()) + _dict['initContainers'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in target_jobs (list) + _items = [] + if self.target_jobs: + for _item_target_jobs in self.target_jobs: + if _item_target_jobs: + _items.append(_item_target_jobs.to_dict()) + _dict['targetJobs'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in tolerations (list) + _items = [] + if self.tolerations: + for _item_tolerations in self.tolerations: + if _item_tolerations: + _items.append(_item_tolerations.to_dict()) + _dict['tolerations'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in volumes (list) + _items = [] + if self.volumes: + for _item_volumes in self.volumes: + if _item_volumes: + _items.append(_item_volumes.to_dict()) + _dict['volumes'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodSpecOverride from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "containers": [TrainerV1alpha1ContainerOverride.from_dict(_item) for _item in obj["containers"]] if obj.get("containers") is not None else None, + "initContainers": [TrainerV1alpha1ContainerOverride.from_dict(_item) for _item in obj["initContainers"]] if obj.get("initContainers") is not None else None, + "nodeSelector": obj.get("nodeSelector"), + "serviceAccountName": obj.get("serviceAccountName"), + "targetJobs": [TrainerV1alpha1PodSpecOverrideTargetJob.from_dict(_item) for _item in obj["targetJobs"]] if obj.get("targetJobs") is not None else None, + "tolerations": [IoK8sApiCoreV1Toleration.from_dict(_item) for _item in obj["tolerations"]] if obj.get("tolerations") is not None else None, + "volumes": [IoK8sApiCoreV1Volume.from_dict(_item) for _item in obj["volumes"]] if obj.get("volumes") is not None else None + }) + return _obj - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1PodSpecOverride): - return True - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override_target_job.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override_target_job.py index 10c976699e..0d7429f552 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override_target_job.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_pod_spec_override_target_job.py @@ -3,121 +3,85 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self -from kubeflow.trainer.configuration import Configuration +class TrainerV1alpha1PodSpecOverrideTargetJob(BaseModel): + """ + TrainerV1alpha1PodSpecOverrideTargetJob + """ # noqa: E501 + name: StrictStr = Field(description="Name is the target training job name for which the PodSpec is overridden.") + __properties: ClassVar[List[str]] = ["name"] + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) -class TrainerV1alpha1PodSpecOverrideTargetJob(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - Do not edit the class manually. - """ + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - """ - 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. - """ - openapi_types = { - 'name': 'str' - } + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - attribute_map = { - 'name': 'name' - } + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodSpecOverrideTargetJob from a JSON string""" + return cls.from_dict(json.loads(json_str)) - def __init__(self, name='', local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1PodSpecOverrideTargetJob - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - self._name = None - self.discriminator = None + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - self.name = name + * `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([ + ]) - @property - def name(self): - """Gets the name of this TrainerV1alpha1PodSpecOverrideTargetJob. # noqa: E501 + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - Name is the target training job name for which the PodSpec is overridden. # noqa: E501 + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1PodSpecOverrideTargetJob from a dict""" + if obj is None: + return None - :return: The name of this TrainerV1alpha1PodSpecOverrideTargetJob. # noqa: E501 - :rtype: str - """ - return self._name + if not isinstance(obj, dict): + return cls.model_validate(obj) - @name.setter - def name(self, name): - """Sets the name of this TrainerV1alpha1PodSpecOverrideTargetJob. + _obj = cls.model_validate({ + "name": obj.get("name") if obj.get("name") is not None else '' + }) + return _obj - Name is the target training job name for which the PodSpec is overridden. # noqa: E501 - :param name: The name of this TrainerV1alpha1PodSpecOverrideTargetJob. # noqa: E501 - :type: str - """ - if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1PodSpecOverrideTargetJob): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1PodSpecOverrideTargetJob): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_runtime_ref.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_runtime_ref.py index 58009db38f..b53ea5b55c 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_runtime_ref.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_runtime_ref.py @@ -3,177 +3,89 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self - -class TrainerV1alpha1RuntimeRef(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. +class TrainerV1alpha1RuntimeRef(BaseModel): """ - - """ - 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. - """ - openapi_types = { - 'api_group': 'str', - 'kind': 'str', - 'name': 'str' - } - - attribute_map = { - 'api_group': 'apiGroup', - 'kind': 'kind', - 'name': 'name' - } - - def __init__(self, api_group=None, kind=None, name='', local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1RuntimeRef - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_group = None - self._kind = None - self._name = None - self.discriminator = None - - if api_group is not None: - self.api_group = api_group - if kind is not None: - self.kind = kind - self.name = name - - @property - def api_group(self): - """Gets the api_group of this TrainerV1alpha1RuntimeRef. # noqa: E501 - - APIGroup of the runtime being referenced. Defaults to `trainer.kubeflow.org`. # noqa: E501 - - :return: The api_group of this TrainerV1alpha1RuntimeRef. # noqa: E501 - :rtype: str - """ - return self._api_group - - @api_group.setter - def api_group(self, api_group): - """Sets the api_group of this TrainerV1alpha1RuntimeRef. - - APIGroup of the runtime being referenced. Defaults to `trainer.kubeflow.org`. # noqa: E501 - - :param api_group: The api_group of this TrainerV1alpha1RuntimeRef. # noqa: E501 - :type: str + RuntimeRef represents the reference to the existing training runtime. + """ # noqa: E501 + api_group: Optional[StrictStr] = Field(default=None, description="APIGroup of the runtime being referenced. Defaults to `trainer.kubeflow.org`.", alias="apiGroup") + kind: Optional[StrictStr] = Field(default=None, description="Kind of the runtime being referenced. Defaults to ClusterTrainingRuntime.") + name: StrictStr = Field(description="Name of the runtime being referenced. When namespaced-scoped TrainingRuntime is used, the TrainJob must have the same namespace as the deployed runtime.") + __properties: ClassVar[List[str]] = ["apiGroup", "kind", "name"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1RuntimeRef from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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([ + ]) - self._api_group = api_group - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1RuntimeRef. # noqa: E501 + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict - Kind of the runtime being referenced. Defaults to ClusterTrainingRuntime. # noqa: E501 - - :return: The kind of this TrainerV1alpha1RuntimeRef. # noqa: E501 - :rtype: str - """ - return self._kind + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1RuntimeRef from a dict""" + if obj is None: + return None - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1RuntimeRef. - - Kind of the runtime being referenced. Defaults to ClusterTrainingRuntime. # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1RuntimeRef. # noqa: E501 - :type: str - """ + if not isinstance(obj, dict): + return cls.model_validate(obj) - self._kind = kind + _obj = cls.model_validate({ + "apiGroup": obj.get("apiGroup"), + "kind": obj.get("kind"), + "name": obj.get("name") if obj.get("name") is not None else '' + }) + return _obj - @property - def name(self): - """Gets the name of this TrainerV1alpha1RuntimeRef. # noqa: E501 - Name of the runtime being referenced. When namespaced-scoped TrainingRuntime is used, the TrainJob must have the same namespace as the deployed runtime. # noqa: E501 - - :return: The name of this TrainerV1alpha1RuntimeRef. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this TrainerV1alpha1RuntimeRef. - - Name of the runtime being referenced. When namespaced-scoped TrainingRuntime is used, the TrainJob must have the same namespace as the deployed runtime. # noqa: E501 - - :param name: The name of this TrainerV1alpha1RuntimeRef. # noqa: E501 - :type: str - """ - if self.local_vars_configuration.client_side_validation and name is None: # noqa: E501 - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1RuntimeRef): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1RuntimeRef): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_elastic_policy.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_elastic_policy.py index f6069c5f68..8208d0087d 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_elastic_policy.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_elastic_policy.py @@ -3,204 +3,99 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_autoscaling_v2_metric_spec import IoK8sApiAutoscalingV2MetricSpec +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1TorchElasticPolicy(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1TorchElasticPolicy(BaseModel): """ - openapi_types = { - 'max_nodes': 'int', - 'max_restarts': 'int', - 'metrics': 'list[V2MetricSpec]', - 'min_nodes': 'int' - } - - attribute_map = { - 'max_nodes': 'maxNodes', - 'max_restarts': 'maxRestarts', - 'metrics': 'metrics', - 'min_nodes': 'minNodes' - } - - def __init__(self, max_nodes=None, max_restarts=None, metrics=None, min_nodes=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TorchElasticPolicy - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._max_nodes = None - self._max_restarts = None - self._metrics = None - self._min_nodes = None - self.discriminator = None - - if max_nodes is not None: - self.max_nodes = max_nodes - if max_restarts is not None: - self.max_restarts = max_restarts - if metrics is not None: - self.metrics = metrics - if min_nodes is not None: - self.min_nodes = min_nodes - - @property - def max_nodes(self): - """Gets the max_nodes of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - - Upper limit for the number of nodes to which training job can scale up. # noqa: E501 - - :return: The max_nodes of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :rtype: int - """ - return self._max_nodes - - @max_nodes.setter - def max_nodes(self, max_nodes): - """Sets the max_nodes of this TrainerV1alpha1TorchElasticPolicy. - - Upper limit for the number of nodes to which training job can scale up. # noqa: E501 - - :param max_nodes: The max_nodes of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :type: int - """ - - self._max_nodes = max_nodes - - @property - def max_restarts(self): - """Gets the max_restarts of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - - How many times the training job can be restarted. This value is inserted into the `--max-restarts` argument of the `torchrun` CLI and the `.spec.failurePolicy.maxRestarts` parameter of the training Job. # noqa: E501 - - :return: The max_restarts of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :rtype: int - """ - return self._max_restarts - - @max_restarts.setter - def max_restarts(self, max_restarts): - """Sets the max_restarts of this TrainerV1alpha1TorchElasticPolicy. - - How many times the training job can be restarted. This value is inserted into the `--max-restarts` argument of the `torchrun` CLI and the `.spec.failurePolicy.maxRestarts` parameter of the training Job. # noqa: E501 - - :param max_restarts: The max_restarts of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :type: int - """ - - self._max_restarts = max_restarts - - @property - def metrics(self): - """Gets the metrics of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - - Specification which are used to calculate the desired number of nodes. See the individual metric source types for more information about how each type of metric must respond. The HPA will be created to perform auto-scaling. # noqa: E501 - - :return: The metrics of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :rtype: list[V2MetricSpec] - """ - return self._metrics - - @metrics.setter - def metrics(self, metrics): - """Sets the metrics of this TrainerV1alpha1TorchElasticPolicy. - - Specification which are used to calculate the desired number of nodes. See the individual metric source types for more information about how each type of metric must respond. The HPA will be created to perform auto-scaling. # noqa: E501 - - :param metrics: The metrics of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :type: list[V2MetricSpec] - """ - - self._metrics = metrics - - @property - def min_nodes(self): - """Gets the min_nodes of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - - Lower limit for the number of nodes to which training job can scale down. # noqa: E501 - - :return: The min_nodes of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :rtype: int + TorchElasticPolicy represents a configuration for the PyTorch elastic training. If this policy is set, the `.spec.numNodes` parameter must be omitted, since min and max node is used to configure the `torchrun` CLI argument: `--nnodes=minNodes:maxNodes`. Only `c10d` backend is supported for the Rendezvous communication. + """ # noqa: E501 + max_nodes: Optional[StrictInt] = Field(default=None, description="Upper limit for the number of nodes to which training job can scale up.", alias="maxNodes") + max_restarts: Optional[StrictInt] = Field(default=None, description="How many times the training job can be restarted. This value is inserted into the `--max-restarts` argument of the `torchrun` CLI and the `.spec.failurePolicy.maxRestarts` parameter of the training Job.", alias="maxRestarts") + metrics: Optional[List[IoK8sApiAutoscalingV2MetricSpec]] = Field(default=None, description="Specification which are used to calculate the desired number of nodes. See the individual metric source types for more information about how each type of metric must respond. The HPA will be created to perform auto-scaling.") + min_nodes: Optional[StrictInt] = Field(default=None, description="Lower limit for the number of nodes to which training job can scale down.", alias="minNodes") + __properties: ClassVar[List[str]] = ["maxNodes", "maxRestarts", "metrics", "minNodes"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TorchElasticPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._min_nodes - - @min_nodes.setter - def min_nodes(self, min_nodes): - """Sets the min_nodes of this TrainerV1alpha1TorchElasticPolicy. + 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 metrics (list) + _items = [] + if self.metrics: + for _item_metrics in self.metrics: + if _item_metrics: + _items.append(_item_metrics.to_dict()) + _dict['metrics'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TorchElasticPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "maxNodes": obj.get("maxNodes"), + "maxRestarts": obj.get("maxRestarts"), + "metrics": [IoK8sApiAutoscalingV2MetricSpec.from_dict(_item) for _item in obj["metrics"]] if obj.get("metrics") is not None else None, + "minNodes": obj.get("minNodes") + }) + return _obj - Lower limit for the number of nodes to which training job can scale down. # noqa: E501 - - :param min_nodes: The min_nodes of this TrainerV1alpha1TorchElasticPolicy. # noqa: E501 - :type: int - """ - self._min_nodes = min_nodes - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TorchElasticPolicy): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TorchElasticPolicy): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_ml_policy_source.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_ml_policy_source.py index f0e6dacc2a..fbc587dfbd 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_ml_policy_source.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_torch_ml_policy_source.py @@ -3,144 +3,91 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1TorchMLPolicySource(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_torch_elastic_policy import TrainerV1alpha1TorchElasticPolicy +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1TorchMLPolicySource(BaseModel): """ - 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. - """ - openapi_types = { - 'elastic_policy': 'TrainerV1alpha1TorchElasticPolicy', - 'num_proc_per_node': 'object' - } - - attribute_map = { - 'elastic_policy': 'elasticPolicy', - 'num_proc_per_node': 'numProcPerNode' - } - - def __init__(self, elastic_policy=None, num_proc_per_node=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TorchMLPolicySource - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._elastic_policy = None - self._num_proc_per_node = None - self.discriminator = None - - if elastic_policy is not None: - self.elastic_policy = elastic_policy - if num_proc_per_node is not None: - self.num_proc_per_node = num_proc_per_node - - @property - def elastic_policy(self): - """Gets the elastic_policy of this TrainerV1alpha1TorchMLPolicySource. # noqa: E501 - - - :return: The elastic_policy of this TrainerV1alpha1TorchMLPolicySource. # noqa: E501 - :rtype: TrainerV1alpha1TorchElasticPolicy - """ - return self._elastic_policy - - @elastic_policy.setter - def elastic_policy(self, elastic_policy): - """Sets the elastic_policy of this TrainerV1alpha1TorchMLPolicySource. - - - :param elastic_policy: The elastic_policy of this TrainerV1alpha1TorchMLPolicySource. # noqa: E501 - :type: TrainerV1alpha1TorchElasticPolicy + TorchMLPolicySource represents a PyTorch runtime configuration. + """ # noqa: E501 + elastic_policy: Optional[TrainerV1alpha1TorchElasticPolicy] = Field(default=None, alias="elasticPolicy") + num_proc_per_node: Optional[StrictStr] = Field(default=None, description="IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", alias="numProcPerNode") + __properties: ClassVar[List[str]] = ["elasticPolicy", "numProcPerNode"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TorchMLPolicySource from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 elastic_policy + if self.elastic_policy: + _dict['elasticPolicy'] = self.elastic_policy.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TorchMLPolicySource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "elasticPolicy": TrainerV1alpha1TorchElasticPolicy.from_dict(obj["elasticPolicy"]) if obj.get("elasticPolicy") is not None else None, + "numProcPerNode": obj.get("numProcPerNode") + }) + return _obj - self._elastic_policy = elastic_policy - - @property - def num_proc_per_node(self): - """Gets the num_proc_per_node of this TrainerV1alpha1TorchMLPolicySource. # noqa: E501 - - - :return: The num_proc_per_node of this TrainerV1alpha1TorchMLPolicySource. # noqa: E501 - :rtype: object - """ - return self._num_proc_per_node - - @num_proc_per_node.setter - def num_proc_per_node(self, num_proc_per_node): - """Sets the num_proc_per_node of this TrainerV1alpha1TorchMLPolicySource. - - - :param num_proc_per_node: The num_proc_per_node of this TrainerV1alpha1TorchMLPolicySource. # noqa: E501 - :type: object - """ - self._num_proc_per_node = num_proc_per_node - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TorchMLPolicySource): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TorchMLPolicySource): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job.py index 9557adcb1c..a9b33ad6ee 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job.py @@ -3,226 +3,105 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from kubeflow.trainer.models.trainer_v1alpha1_train_job_spec import TrainerV1alpha1TrainJobSpec +from kubeflow.trainer.models.trainer_v1alpha1_train_job_status import TrainerV1alpha1TrainJobStatus +from typing import Optional, Set +from typing_extensions import Self - -class TrainerV1alpha1TrainJob(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. +class TrainerV1alpha1TrainJob(BaseModel): """ - - """ - 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. - """ - openapi_types = { - 'api_version': 'str', - 'kind': 'str', - 'metadata': 'V1ObjectMeta', - 'spec': 'TrainerV1alpha1TrainJobSpec', - 'status': 'TrainerV1alpha1TrainJobStatus' - } - - attribute_map = { - 'api_version': 'apiVersion', - 'kind': 'kind', - 'metadata': 'metadata', - 'spec': 'spec', - 'status': 'status' - } - - def __init__(self, api_version=None, kind=None, metadata=None, spec=None, status=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainJob - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_version = None - self._kind = None - self._metadata = None - self._spec = None - self._status = None - self.discriminator = None - - if api_version is not None: - self.api_version = api_version - if kind is not None: - self.kind = kind - if metadata is not None: - self.metadata = metadata - if spec is not None: - self.spec = spec - if status is not None: - self.status = status - - @property - def api_version(self): - """Gets the api_version of this TrainerV1alpha1TrainJob. # noqa: E501 - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :return: The api_version of this TrainerV1alpha1TrainJob. # noqa: E501 - :rtype: str + TrainJob represents configuration of a training job. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", alias="apiVersion") + kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: Optional[TrainerV1alpha1TrainJobSpec] = None + status: Optional[TrainerV1alpha1TrainJobStatus] = None + __properties: ClassVar[List[str]] = ["apiVersion", "kind", "metadata", "spec", "status"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJob from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._api_version - - @api_version.setter - def api_version(self, api_version): - """Sets the api_version of this TrainerV1alpha1TrainJob. - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :param api_version: The api_version of this TrainerV1alpha1TrainJob. # noqa: E501 - :type: str - """ - - self._api_version = api_version - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1TrainJob. # noqa: E501 - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :return: The kind of this TrainerV1alpha1TrainJob. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1TrainJob. - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1TrainJob. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1TrainJob. # noqa: E501 + 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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + # override the default output from pydantic by calling `to_dict()` of status + if self.status: + _dict['status'] = self.status.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJob from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "kind": obj.get("kind"), + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": TrainerV1alpha1TrainJobSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None, + "status": TrainerV1alpha1TrainJobStatus.from_dict(obj["status"]) if obj.get("status") is not None else None + }) + return _obj - :return: The metadata of this TrainerV1alpha1TrainJob. # noqa: E501 - :rtype: V1ObjectMeta - """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1TrainJob. - - - :param metadata: The metadata of this TrainerV1alpha1TrainJob. # noqa: E501 - :type: V1ObjectMeta - """ - - self._metadata = metadata - - @property - def spec(self): - """Gets the spec of this TrainerV1alpha1TrainJob. # noqa: E501 - - - :return: The spec of this TrainerV1alpha1TrainJob. # noqa: E501 - :rtype: TrainerV1alpha1TrainJobSpec - """ - return self._spec - - @spec.setter - def spec(self, spec): - """Sets the spec of this TrainerV1alpha1TrainJob. - - - :param spec: The spec of this TrainerV1alpha1TrainJob. # noqa: E501 - :type: TrainerV1alpha1TrainJobSpec - """ - - self._spec = spec - - @property - def status(self): - """Gets the status of this TrainerV1alpha1TrainJob. # noqa: E501 - - - :return: The status of this TrainerV1alpha1TrainJob. # noqa: E501 - :rtype: TrainerV1alpha1TrainJobStatus - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this TrainerV1alpha1TrainJob. - - - :param status: The status of this TrainerV1alpha1TrainJob. # noqa: E501 - :type: TrainerV1alpha1TrainJobStatus - """ - - self._status = status - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainJob): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainJob): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_list.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_list.py index 22f19ab4bb..d24a7cb5c1 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_list.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_list.py @@ -3,203 +3,103 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_list_meta import IoK8sApimachineryPkgApisMetaV1ListMeta +from kubeflow.trainer.models.trainer_v1alpha1_train_job import TrainerV1alpha1TrainJob +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1TrainJobList(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1TrainJobList(BaseModel): """ - openapi_types = { - 'api_version': 'str', - 'items': 'list[TrainerV1alpha1TrainJob]', - 'kind': 'str', - 'metadata': 'V1ListMeta' - } - - attribute_map = { - 'api_version': 'apiVersion', - 'items': 'items', - 'kind': 'kind', - 'metadata': 'metadata' - } - - def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainJobList - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_version = None - self._items = None - self._kind = None - self._metadata = None - self.discriminator = None - - if api_version is not None: - self.api_version = api_version - self.items = items - if kind is not None: - self.kind = kind - if metadata is not None: - self.metadata = metadata - - @property - def api_version(self): - """Gets the api_version of this TrainerV1alpha1TrainJobList. # noqa: E501 - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :return: The api_version of this TrainerV1alpha1TrainJobList. # noqa: E501 - :rtype: str - """ - return self._api_version - - @api_version.setter - def api_version(self, api_version): - """Sets the api_version of this TrainerV1alpha1TrainJobList. - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :param api_version: The api_version of this TrainerV1alpha1TrainJobList. # noqa: E501 - :type: str - """ - - self._api_version = api_version - - @property - def items(self): - """Gets the items of this TrainerV1alpha1TrainJobList. # noqa: E501 - - List of TrainJobs. # noqa: E501 - - :return: The items of this TrainerV1alpha1TrainJobList. # noqa: E501 - :rtype: list[TrainerV1alpha1TrainJob] - """ - return self._items - - @items.setter - def items(self, items): - """Sets the items of this TrainerV1alpha1TrainJobList. - - List of TrainJobs. # noqa: E501 - - :param items: The items of this TrainerV1alpha1TrainJobList. # noqa: E501 - :type: list[TrainerV1alpha1TrainJob] - """ - if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 - raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 - - self._items = items - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1TrainJobList. # noqa: E501 - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :return: The kind of this TrainerV1alpha1TrainJobList. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1TrainJobList. - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1TrainJobList. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1TrainJobList. # noqa: E501 - - - :return: The metadata of this TrainerV1alpha1TrainJobList. # noqa: E501 - :rtype: V1ListMeta + TrainJobList is a collection of training jobs. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", alias="apiVersion") + items: List[TrainerV1alpha1TrainJob] = Field(description="List of TrainJobs.") + kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ListMeta] = None + __properties: ClassVar[List[str]] = ["apiVersion", "items", "kind", "metadata"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJobList from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1TrainJobList. + 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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJobList from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "items": [TrainerV1alpha1TrainJob.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "kind": obj.get("kind"), + "metadata": IoK8sApimachineryPkgApisMetaV1ListMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None + }) + return _obj - :param metadata: The metadata of this TrainerV1alpha1TrainJobList. # noqa: E501 - :type: V1ListMeta - """ - - self._metadata = metadata - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainJobList): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainJobList): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_spec.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_spec.py index 9b1d5e3f20..bff7dc4405 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_spec.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_spec.py @@ -3,337 +3,125 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1TrainJobSpec(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +import json + +from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_dataset_config import TrainerV1alpha1DatasetConfig +from kubeflow.trainer.models.trainer_v1alpha1_model_config import TrainerV1alpha1ModelConfig +from kubeflow.trainer.models.trainer_v1alpha1_pod_spec_override import TrainerV1alpha1PodSpecOverride +from kubeflow.trainer.models.trainer_v1alpha1_runtime_ref import TrainerV1alpha1RuntimeRef +from kubeflow.trainer.models.trainer_v1alpha1_trainer import TrainerV1alpha1Trainer +from typing import Optional, Set +from typing_extensions import Self + +class TrainerV1alpha1TrainJobSpec(BaseModel): """ - openapi_types = { - 'annotations': 'dict(str, str)', - 'dataset_config': 'TrainerV1alpha1DatasetConfig', - 'labels': 'dict(str, str)', - 'managed_by': 'str', - 'model_config': 'TrainerV1alpha1ModelConfig', - 'pod_spec_overrides': 'list[TrainerV1alpha1PodSpecOverride]', - 'runtime_ref': 'TrainerV1alpha1RuntimeRef', - 'suspend': 'bool', - 'trainer': 'TrainerV1alpha1Trainer' - } - - attribute_map = { - 'annotations': 'annotations', - 'dataset_config': 'datasetConfig', - 'labels': 'labels', - 'managed_by': 'managedBy', - 'model_config': 'modelConfig', - 'pod_spec_overrides': 'podSpecOverrides', - 'runtime_ref': 'runtimeRef', - 'suspend': 'suspend', - 'trainer': 'trainer' - } - - def __init__(self, annotations=None, dataset_config=None, labels=None, managed_by=None, model_config=None, pod_spec_overrides=None, runtime_ref=None, suspend=None, trainer=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainJobSpec - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._annotations = None - self._dataset_config = None - self._labels = None - self._managed_by = None - self._model_config = None - self._pod_spec_overrides = None - self._runtime_ref = None - self._suspend = None - self._trainer = None - self.discriminator = None - - if annotations is not None: - self.annotations = annotations - if dataset_config is not None: - self.dataset_config = dataset_config - if labels is not None: - self.labels = labels - if managed_by is not None: - self.managed_by = managed_by - if model_config is not None: - self.model_config = model_config - if pod_spec_overrides is not None: - self.pod_spec_overrides = pod_spec_overrides - self.runtime_ref = runtime_ref - if suspend is not None: - self.suspend = suspend - if trainer is not None: - self.trainer = trainer - - @property - def annotations(self): - """Gets the annotations of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - Annotations to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values. # noqa: E501 - - :return: The annotations of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: dict(str, str) - """ - return self._annotations - - @annotations.setter - def annotations(self, annotations): - """Sets the annotations of this TrainerV1alpha1TrainJobSpec. - - Annotations to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values. # noqa: E501 - - :param annotations: The annotations of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: dict(str, str) - """ - - self._annotations = annotations - - @property - def dataset_config(self): - """Gets the dataset_config of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - - :return: The dataset_config of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: TrainerV1alpha1DatasetConfig - """ - return self._dataset_config - - @dataset_config.setter - def dataset_config(self, dataset_config): - """Sets the dataset_config of this TrainerV1alpha1TrainJobSpec. - - - :param dataset_config: The dataset_config of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: TrainerV1alpha1DatasetConfig - """ - - self._dataset_config = dataset_config - - @property - def labels(self): - """Gets the labels of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - Labels to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values. # noqa: E501 - - :return: The labels of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: dict(str, str) - """ - return self._labels - - @labels.setter - def labels(self, labels): - """Sets the labels of this TrainerV1alpha1TrainJobSpec. - - Labels to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values. # noqa: E501 - - :param labels: The labels of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: dict(str, str) - """ - - self._labels = labels - - @property - def managed_by(self): - """Gets the managed_by of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - ManagedBy is used to indicate the controller or entity that manages a TrainJob. The value must be either an empty, `trainer.kubeflow.org/trainjob-controller` or `kueue.x-k8s.io/multikueue`. The built-in TrainJob controller reconciles TrainJob which don't have this field at all or the field value is the reserved string `trainer.kubeflow.org/trainjob-controller`, but delegates reconciling TrainJobs with a 'kueue.x-k8s.io/multikueue' to the Kueue. The field is immutable. Defaults to `trainer.kubeflow.org/trainjob-controller` # noqa: E501 - - :return: The managed_by of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: str - """ - return self._managed_by - - @managed_by.setter - def managed_by(self, managed_by): - """Sets the managed_by of this TrainerV1alpha1TrainJobSpec. - - ManagedBy is used to indicate the controller or entity that manages a TrainJob. The value must be either an empty, `trainer.kubeflow.org/trainjob-controller` or `kueue.x-k8s.io/multikueue`. The built-in TrainJob controller reconciles TrainJob which don't have this field at all or the field value is the reserved string `trainer.kubeflow.org/trainjob-controller`, but delegates reconciling TrainJobs with a 'kueue.x-k8s.io/multikueue' to the Kueue. The field is immutable. Defaults to `trainer.kubeflow.org/trainjob-controller` # noqa: E501 - - :param managed_by: The managed_by of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: str - """ - - self._managed_by = managed_by - - @property - def model_config(self): - """Gets the model_config of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - - :return: The model_config of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: TrainerV1alpha1ModelConfig - """ - return self._model_config - - @model_config.setter - def model_config(self, model_config): - """Sets the model_config of this TrainerV1alpha1TrainJobSpec. - - - :param model_config: The model_config of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: TrainerV1alpha1ModelConfig - """ - - self._model_config = model_config - - @property - def pod_spec_overrides(self): - """Gets the pod_spec_overrides of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - Custom overrides for the training runtime. # noqa: E501 - - :return: The pod_spec_overrides of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: list[TrainerV1alpha1PodSpecOverride] - """ - return self._pod_spec_overrides - - @pod_spec_overrides.setter - def pod_spec_overrides(self, pod_spec_overrides): - """Sets the pod_spec_overrides of this TrainerV1alpha1TrainJobSpec. - - Custom overrides for the training runtime. # noqa: E501 - - :param pod_spec_overrides: The pod_spec_overrides of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: list[TrainerV1alpha1PodSpecOverride] - """ - - self._pod_spec_overrides = pod_spec_overrides - - @property - def runtime_ref(self): - """Gets the runtime_ref of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - - :return: The runtime_ref of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: TrainerV1alpha1RuntimeRef - """ - return self._runtime_ref - - @runtime_ref.setter - def runtime_ref(self, runtime_ref): - """Sets the runtime_ref of this TrainerV1alpha1TrainJobSpec. - - - :param runtime_ref: The runtime_ref of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: TrainerV1alpha1RuntimeRef - """ - if self.local_vars_configuration.client_side_validation and runtime_ref is None: # noqa: E501 - raise ValueError("Invalid value for `runtime_ref`, must not be `None`") # noqa: E501 - - self._runtime_ref = runtime_ref - - @property - def suspend(self): - """Gets the suspend of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - Whether the controller should suspend the running TrainJob. Defaults to false. # noqa: E501 - - :return: The suspend of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: bool - """ - return self._suspend - - @suspend.setter - def suspend(self, suspend): - """Sets the suspend of this TrainerV1alpha1TrainJobSpec. - - Whether the controller should suspend the running TrainJob. Defaults to false. # noqa: E501 - - :param suspend: The suspend of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: bool - """ - - self._suspend = suspend - - @property - def trainer(self): - """Gets the trainer of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - - - :return: The trainer of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :rtype: TrainerV1alpha1Trainer - """ - return self._trainer - - @trainer.setter - def trainer(self, trainer): - """Sets the trainer of this TrainerV1alpha1TrainJobSpec. - - - :param trainer: The trainer of this TrainerV1alpha1TrainJobSpec. # noqa: E501 - :type: TrainerV1alpha1Trainer - """ - - self._trainer = trainer - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainJobSpec): - return False - - return self.to_dict() == other.to_dict() + TrainJobSpec represents specification of the desired TrainJob. + """ # noqa: E501 + annotations: Optional[Dict[str, StrictStr]] = Field(default=None, description="Annotations to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values.") + dataset_config: Optional[TrainerV1alpha1DatasetConfig] = Field(default=None, alias="datasetConfig") + labels: Optional[Dict[str, StrictStr]] = Field(default=None, description="Labels to apply for the derivative JobSet and Jobs. They will be merged with the TrainingRuntime values.") + managed_by: Optional[StrictStr] = Field(default=None, description="ManagedBy is used to indicate the controller or entity that manages a TrainJob. The value must be either an empty, `trainer.kubeflow.org/trainjob-controller` or `kueue.x-k8s.io/multikueue`. The built-in TrainJob controller reconciles TrainJob which don't have this field at all or the field value is the reserved string `trainer.kubeflow.org/trainjob-controller`, but delegates reconciling TrainJobs with a 'kueue.x-k8s.io/multikueue' to the Kueue. The field is immutable. Defaults to `trainer.kubeflow.org/trainjob-controller`", alias="managedBy") + model_config_crd: Optional[TrainerV1alpha1ModelConfig] = Field(default=None, alias="modelConfig") + pod_spec_overrides: Optional[List[TrainerV1alpha1PodSpecOverride]] = Field(default=None, description="Custom overrides for the training runtime.", alias="podSpecOverrides") + runtime_ref: TrainerV1alpha1RuntimeRef = Field(alias="runtimeRef") + suspend: Optional[StrictBool] = Field(default=None, description="Whether the controller should suspend the running TrainJob. Defaults to false.") + trainer: Optional[TrainerV1alpha1Trainer] = None + __properties: ClassVar[List[str]] = ["annotations", "datasetConfig", "labels", "managedBy", "modelConfig", "podSpecOverrides", "runtimeRef", "suspend", "trainer"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJobSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 dataset_config + if self.dataset_config: + _dict['datasetConfig'] = self.dataset_config.to_dict() + # override the default output from pydantic by calling `to_dict()` of model_config_crd + if self.model_config_crd: + _dict['modelConfig'] = self.model_config_crd.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in pod_spec_overrides (list) + _items = [] + if self.pod_spec_overrides: + for _item_pod_spec_overrides in self.pod_spec_overrides: + if _item_pod_spec_overrides: + _items.append(_item_pod_spec_overrides.to_dict()) + _dict['podSpecOverrides'] = _items + # override the default output from pydantic by calling `to_dict()` of runtime_ref + if self.runtime_ref: + _dict['runtimeRef'] = self.runtime_ref.to_dict() + # override the default output from pydantic by calling `to_dict()` of trainer + if self.trainer: + _dict['trainer'] = self.trainer.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJobSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "annotations": obj.get("annotations"), + "datasetConfig": TrainerV1alpha1DatasetConfig.from_dict(obj["datasetConfig"]) if obj.get("datasetConfig") is not None else None, + "labels": obj.get("labels"), + "managedBy": obj.get("managedBy"), + "modelConfig": TrainerV1alpha1ModelConfig.from_dict(obj["modelConfig"]) if obj.get("modelConfig") is not None else None, + "podSpecOverrides": [TrainerV1alpha1PodSpecOverride.from_dict(_item) for _item in obj["podSpecOverrides"]] if obj.get("podSpecOverrides") is not None else None, + "runtimeRef": TrainerV1alpha1RuntimeRef.from_dict(obj["runtimeRef"]) if obj.get("runtimeRef") is not None else None, + "suspend": obj.get("suspend"), + "trainer": TrainerV1alpha1Trainer.from_dict(obj["trainer"]) if obj.get("trainer") is not None else None + }) + return _obj - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainJobSpec): - return True - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_status.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_status.py index a90a3296c3..a3bce412e8 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_status.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_train_job_status.py @@ -3,148 +3,103 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1TrainJobStatus(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_condition import IoK8sApimachineryPkgApisMetaV1Condition +from kubeflow.trainer.models.trainer_v1alpha1_job_status import TrainerV1alpha1JobStatus +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1TrainJobStatus(BaseModel): """ - 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. - """ - openapi_types = { - 'conditions': 'list[V1Condition]', - 'jobs_status': 'list[TrainerV1alpha1JobStatus]' - } - - attribute_map = { - 'conditions': 'conditions', - 'jobs_status': 'jobsStatus' - } - - def __init__(self, conditions=None, jobs_status=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainJobStatus - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._conditions = None - self._jobs_status = None - self.discriminator = None - - if conditions is not None: - self.conditions = conditions - if jobs_status is not None: - self.jobs_status = jobs_status - - @property - def conditions(self): - """Gets the conditions of this TrainerV1alpha1TrainJobStatus. # noqa: E501 - - Conditions for the TrainJob. # noqa: E501 - - :return: The conditions of this TrainerV1alpha1TrainJobStatus. # noqa: E501 - :rtype: list[V1Condition] - """ - return self._conditions - - @conditions.setter - def conditions(self, conditions): - """Sets the conditions of this TrainerV1alpha1TrainJobStatus. - - Conditions for the TrainJob. # noqa: E501 - - :param conditions: The conditions of this TrainerV1alpha1TrainJobStatus. # noqa: E501 - :type: list[V1Condition] + TrainJobStatus represents the current status of TrainJob. + """ # noqa: E501 + conditions: Optional[List[IoK8sApimachineryPkgApisMetaV1Condition]] = Field(default=None, description="Conditions for the TrainJob.") + jobs_status: Optional[List[TrainerV1alpha1JobStatus]] = Field(default=None, description="JobsStatus tracks the child Jobs in TrainJob.", alias="jobsStatus") + __properties: ClassVar[List[str]] = ["conditions", "jobsStatus"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJobStatus from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 conditions (list) + _items = [] + if self.conditions: + for _item_conditions in self.conditions: + if _item_conditions: + _items.append(_item_conditions.to_dict()) + _dict['conditions'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in jobs_status (list) + _items = [] + if self.jobs_status: + for _item_jobs_status in self.jobs_status: + if _item_jobs_status: + _items.append(_item_jobs_status.to_dict()) + _dict['jobsStatus'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainJobStatus from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "conditions": [IoK8sApimachineryPkgApisMetaV1Condition.from_dict(_item) for _item in obj["conditions"]] if obj.get("conditions") is not None else None, + "jobsStatus": [TrainerV1alpha1JobStatus.from_dict(_item) for _item in obj["jobsStatus"]] if obj.get("jobsStatus") is not None else None + }) + return _obj - self._conditions = conditions - - @property - def jobs_status(self): - """Gets the jobs_status of this TrainerV1alpha1TrainJobStatus. # noqa: E501 - - JobsStatus tracks the child Jobs in TrainJob. # noqa: E501 - - :return: The jobs_status of this TrainerV1alpha1TrainJobStatus. # noqa: E501 - :rtype: list[TrainerV1alpha1JobStatus] - """ - return self._jobs_status - - @jobs_status.setter - def jobs_status(self, jobs_status): - """Sets the jobs_status of this TrainerV1alpha1TrainJobStatus. - - JobsStatus tracks the child Jobs in TrainJob. # noqa: E501 - - :param jobs_status: The jobs_status of this TrainerV1alpha1TrainJobStatus. # noqa: E501 - :type: list[TrainerV1alpha1JobStatus] - """ - self._jobs_status = jobs_status - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainJobStatus): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainJobStatus): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_trainer.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_trainer.py index e57cbc5b1d..37cae74962 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_trainer.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_trainer.py @@ -3,284 +3,109 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - - -class TrainerV1alpha1Trainer(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ +from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_api_core_v1_env_var import IoK8sApiCoreV1EnvVar +from kubeflow.trainer.models.io_k8s_api_core_v1_resource_requirements import IoK8sApiCoreV1ResourceRequirements +from typing import Optional, Set +from typing_extensions import Self +class TrainerV1alpha1Trainer(BaseModel): """ - 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. - """ - openapi_types = { - 'args': 'list[str]', - 'command': 'list[str]', - 'env': 'list[V1EnvVar]', - 'image': 'str', - 'num_nodes': 'int', - 'num_proc_per_node': 'object', - 'resources_per_node': 'V1ResourceRequirements' - } - - attribute_map = { - 'args': 'args', - 'command': 'command', - 'env': 'env', - 'image': 'image', - 'num_nodes': 'numNodes', - 'num_proc_per_node': 'numProcPerNode', - 'resources_per_node': 'resourcesPerNode' - } - - def __init__(self, args=None, command=None, env=None, image=None, num_nodes=None, num_proc_per_node=None, resources_per_node=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1Trainer - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._args = None - self._command = None - self._env = None - self._image = None - self._num_nodes = None - self._num_proc_per_node = None - self._resources_per_node = None - self.discriminator = None - - if args is not None: - self.args = args - if command is not None: - self.command = command - if env is not None: - self.env = env - if image is not None: - self.image = image - if num_nodes is not None: - self.num_nodes = num_nodes - if num_proc_per_node is not None: - self.num_proc_per_node = num_proc_per_node - if resources_per_node is not None: - self.resources_per_node = resources_per_node - - @property - def args(self): - """Gets the args of this TrainerV1alpha1Trainer. # noqa: E501 - - Arguments to the entrypoint for the training container. # noqa: E501 - - :return: The args of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: list[str] - """ - return self._args - - @args.setter - def args(self, args): - """Sets the args of this TrainerV1alpha1Trainer. - - Arguments to the entrypoint for the training container. # noqa: E501 - - :param args: The args of this TrainerV1alpha1Trainer. # noqa: E501 - :type: list[str] + Trainer represents the desired trainer configuration. Every training runtime contains `trainer` container which represents Trainer. + """ # noqa: E501 + args: Optional[List[StrictStr]] = Field(default=None, description="Arguments to the entrypoint for the training container.") + command: Optional[List[StrictStr]] = Field(default=None, description="Entrypoint commands for the training container.") + env: Optional[List[IoK8sApiCoreV1EnvVar]] = Field(default=None, description="List of environment variables to set in the training container. These values will be merged with the TrainingRuntime's trainer environments.") + image: Optional[StrictStr] = Field(default=None, description="Docker image for the training container.") + num_nodes: Optional[StrictInt] = Field(default=None, description="Number of training nodes.", alias="numNodes") + num_proc_per_node: Optional[StrictStr] = Field(default=None, description="IntOrString is a type that can hold an int32 or a string. When used in JSON or YAML marshalling and unmarshalling, it produces or consumes the inner type. This allows you to have, for example, a JSON field that can accept a name or number.", alias="numProcPerNode") + resources_per_node: Optional[IoK8sApiCoreV1ResourceRequirements] = Field(default=None, alias="resourcesPerNode") + __properties: ClassVar[List[str]] = ["args", "command", "env", "image", "numNodes", "numProcPerNode", "resourcesPerNode"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1Trainer from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 env (list) + _items = [] + if self.env: + for _item_env in self.env: + if _item_env: + _items.append(_item_env.to_dict()) + _dict['env'] = _items + # override the default output from pydantic by calling `to_dict()` of resources_per_node + if self.resources_per_node: + _dict['resourcesPerNode'] = self.resources_per_node.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1Trainer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "args": obj.get("args"), + "command": obj.get("command"), + "env": [IoK8sApiCoreV1EnvVar.from_dict(_item) for _item in obj["env"]] if obj.get("env") is not None else None, + "image": obj.get("image"), + "numNodes": obj.get("numNodes"), + "numProcPerNode": obj.get("numProcPerNode"), + "resourcesPerNode": IoK8sApiCoreV1ResourceRequirements.from_dict(obj["resourcesPerNode"]) if obj.get("resourcesPerNode") is not None else None + }) + return _obj - self._args = args - - @property - def command(self): - """Gets the command of this TrainerV1alpha1Trainer. # noqa: E501 - - Entrypoint commands for the training container. # noqa: E501 - - :return: The command of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: list[str] - """ - return self._command - - @command.setter - def command(self, command): - """Sets the command of this TrainerV1alpha1Trainer. - - Entrypoint commands for the training container. # noqa: E501 - - :param command: The command of this TrainerV1alpha1Trainer. # noqa: E501 - :type: list[str] - """ - - self._command = command - - @property - def env(self): - """Gets the env of this TrainerV1alpha1Trainer. # noqa: E501 - - List of environment variables to set in the training container. These values will be merged with the TrainingRuntime's trainer environments. # noqa: E501 - - :return: The env of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: list[V1EnvVar] - """ - return self._env - - @env.setter - def env(self, env): - """Sets the env of this TrainerV1alpha1Trainer. - - List of environment variables to set in the training container. These values will be merged with the TrainingRuntime's trainer environments. # noqa: E501 - - :param env: The env of this TrainerV1alpha1Trainer. # noqa: E501 - :type: list[V1EnvVar] - """ - - self._env = env - - @property - def image(self): - """Gets the image of this TrainerV1alpha1Trainer. # noqa: E501 - - Docker image for the training container. # noqa: E501 - - :return: The image of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: str - """ - return self._image - - @image.setter - def image(self, image): - """Sets the image of this TrainerV1alpha1Trainer. - - Docker image for the training container. # noqa: E501 - - :param image: The image of this TrainerV1alpha1Trainer. # noqa: E501 - :type: str - """ - - self._image = image - - @property - def num_nodes(self): - """Gets the num_nodes of this TrainerV1alpha1Trainer. # noqa: E501 - - Number of training nodes. # noqa: E501 - - :return: The num_nodes of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: int - """ - return self._num_nodes - - @num_nodes.setter - def num_nodes(self, num_nodes): - """Sets the num_nodes of this TrainerV1alpha1Trainer. - - Number of training nodes. # noqa: E501 - - :param num_nodes: The num_nodes of this TrainerV1alpha1Trainer. # noqa: E501 - :type: int - """ - - self._num_nodes = num_nodes - - @property - def num_proc_per_node(self): - """Gets the num_proc_per_node of this TrainerV1alpha1Trainer. # noqa: E501 - - - :return: The num_proc_per_node of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: object - """ - return self._num_proc_per_node - - @num_proc_per_node.setter - def num_proc_per_node(self, num_proc_per_node): - """Sets the num_proc_per_node of this TrainerV1alpha1Trainer. - - - :param num_proc_per_node: The num_proc_per_node of this TrainerV1alpha1Trainer. # noqa: E501 - :type: object - """ - - self._num_proc_per_node = num_proc_per_node - - @property - def resources_per_node(self): - """Gets the resources_per_node of this TrainerV1alpha1Trainer. # noqa: E501 - - - :return: The resources_per_node of this TrainerV1alpha1Trainer. # noqa: E501 - :rtype: V1ResourceRequirements - """ - return self._resources_per_node - - @resources_per_node.setter - def resources_per_node(self, resources_per_node): - """Sets the resources_per_node of this TrainerV1alpha1Trainer. - - - :param resources_per_node: The resources_per_node of this TrainerV1alpha1Trainer. # noqa: E501 - :type: V1ResourceRequirements - """ - - self._resources_per_node = resources_per_node - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1Trainer): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1Trainer): - return True - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime.py index bb626d43cf..5bd464f66c 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime.py @@ -3,200 +3,99 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_object_meta import IoK8sApimachineryPkgApisMetaV1ObjectMeta +from kubeflow.trainer.models.trainer_v1alpha1_training_runtime_spec import TrainerV1alpha1TrainingRuntimeSpec +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1TrainingRuntime(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1TrainingRuntime(BaseModel): """ - openapi_types = { - 'api_version': 'str', - 'kind': 'str', - 'metadata': 'V1ObjectMeta', - 'spec': 'TrainerV1alpha1TrainingRuntimeSpec' - } - - attribute_map = { - 'api_version': 'apiVersion', - 'kind': 'kind', - 'metadata': 'metadata', - 'spec': 'spec' - } - - def __init__(self, api_version=None, kind=None, metadata=None, spec=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainingRuntime - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_version = None - self._kind = None - self._metadata = None - self._spec = None - self.discriminator = None - - if api_version is not None: - self.api_version = api_version - if kind is not None: - self.kind = kind - if metadata is not None: - self.metadata = metadata - if spec is not None: - self.spec = spec - - @property - def api_version(self): - """Gets the api_version of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :return: The api_version of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :rtype: str - """ - return self._api_version - - @api_version.setter - def api_version(self, api_version): - """Sets the api_version of this TrainerV1alpha1TrainingRuntime. - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :param api_version: The api_version of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :type: str - """ - - self._api_version = api_version - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :return: The kind of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1TrainingRuntime. - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - - - :return: The metadata of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :rtype: V1ObjectMeta - """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1TrainingRuntime. - - - :param metadata: The metadata of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :type: V1ObjectMeta - """ - - self._metadata = metadata - - @property - def spec(self): - """Gets the spec of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - - - :return: The spec of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :rtype: TrainerV1alpha1TrainingRuntimeSpec + TrainingRuntime represents a training runtime which can be referenced as part of `runtimeRef` API in TrainJob. This resource is a namespaced-scoped and can be referenced by TrainJob that created in the *same* namespace as the TrainingRuntime. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", alias="apiVersion") + kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ObjectMeta] = None + spec: Optional[TrainerV1alpha1TrainingRuntimeSpec] = None + __properties: ClassVar[List[str]] = ["apiVersion", "kind", "metadata", "spec"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainingRuntime from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._spec - - @spec.setter - def spec(self, spec): - """Sets the spec of this TrainerV1alpha1TrainingRuntime. + 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 metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainingRuntime from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "kind": obj.get("kind"), + "metadata": IoK8sApimachineryPkgApisMetaV1ObjectMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None, + "spec": TrainerV1alpha1TrainingRuntimeSpec.from_dict(obj["spec"]) if obj.get("spec") is not None else None + }) + return _obj - :param spec: The spec of this TrainerV1alpha1TrainingRuntime. # noqa: E501 - :type: TrainerV1alpha1TrainingRuntimeSpec - """ - - self._spec = spec - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainingRuntime): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainingRuntime): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_list.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_list.py index 7a34a53869..6d2e5ff845 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_list.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_list.py @@ -3,203 +3,103 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration - +from pydantic import BaseModel, ConfigDict, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.io_k8s_apimachinery_pkg_apis_meta_v1_list_meta import IoK8sApimachineryPkgApisMetaV1ListMeta +from kubeflow.trainer.models.trainer_v1alpha1_training_runtime import TrainerV1alpha1TrainingRuntime +from typing import Optional, Set +from typing_extensions import Self -class TrainerV1alpha1TrainingRuntimeList(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - """ - 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. +class TrainerV1alpha1TrainingRuntimeList(BaseModel): """ - openapi_types = { - 'api_version': 'str', - 'items': 'list[TrainerV1alpha1TrainingRuntime]', - 'kind': 'str', - 'metadata': 'V1ListMeta' - } - - attribute_map = { - 'api_version': 'apiVersion', - 'items': 'items', - 'kind': 'kind', - 'metadata': 'metadata' - } - - def __init__(self, api_version=None, items=None, kind=None, metadata=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainingRuntimeList - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._api_version = None - self._items = None - self._kind = None - self._metadata = None - self.discriminator = None - - if api_version is not None: - self.api_version = api_version - self.items = items - if kind is not None: - self.kind = kind - if metadata is not None: - self.metadata = metadata - - @property - def api_version(self): - """Gets the api_version of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :return: The api_version of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :rtype: str - """ - return self._api_version - - @api_version.setter - def api_version(self, api_version): - """Sets the api_version of this TrainerV1alpha1TrainingRuntimeList. - - APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources # noqa: E501 - - :param api_version: The api_version of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :type: str - """ - - self._api_version = api_version - - @property - def items(self): - """Gets the items of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - - List of TrainingRuntimes. # noqa: E501 - - :return: The items of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :rtype: list[TrainerV1alpha1TrainingRuntime] - """ - return self._items - - @items.setter - def items(self, items): - """Sets the items of this TrainerV1alpha1TrainingRuntimeList. - - List of TrainingRuntimes. # noqa: E501 - - :param items: The items of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :type: list[TrainerV1alpha1TrainingRuntime] - """ - if self.local_vars_configuration.client_side_validation and items is None: # noqa: E501 - raise ValueError("Invalid value for `items`, must not be `None`") # noqa: E501 - - self._items = items - - @property - def kind(self): - """Gets the kind of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :return: The kind of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this TrainerV1alpha1TrainingRuntimeList. - - Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds # noqa: E501 - - :param kind: The kind of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def metadata(self): - """Gets the metadata of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - - - :return: The metadata of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :rtype: V1ListMeta + TrainingRuntimeList is a collection of training runtimes. + """ # noqa: E501 + api_version: Optional[StrictStr] = Field(default=None, description="APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources", alias="apiVersion") + items: List[TrainerV1alpha1TrainingRuntime] = Field(description="List of TrainingRuntimes.") + kind: Optional[StrictStr] = Field(default=None, description="Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds") + metadata: Optional[IoK8sApimachineryPkgApisMetaV1ListMeta] = None + __properties: ClassVar[List[str]] = ["apiVersion", "items", "kind", "metadata"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainingRuntimeList from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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. """ - return self._metadata - - @metadata.setter - def metadata(self, metadata): - """Sets the metadata of this TrainerV1alpha1TrainingRuntimeList. + 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 items (list) + _items = [] + if self.items: + for _item_items in self.items: + if _item_items: + _items.append(_item_items.to_dict()) + _dict['items'] = _items + # override the default output from pydantic by calling `to_dict()` of metadata + if self.metadata: + _dict['metadata'] = self.metadata.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainingRuntimeList from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "apiVersion": obj.get("apiVersion"), + "items": [TrainerV1alpha1TrainingRuntime.from_dict(_item) for _item in obj["items"]] if obj.get("items") is not None else None, + "kind": obj.get("kind"), + "metadata": IoK8sApimachineryPkgApisMetaV1ListMeta.from_dict(obj["metadata"]) if obj.get("metadata") is not None else None + }) + return _obj - :param metadata: The metadata of this TrainerV1alpha1TrainingRuntimeList. # noqa: E501 - :type: V1ListMeta - """ - - self._metadata = metadata - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainingRuntimeList): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainingRuntimeList): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_spec.py b/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_spec.py index 1722d9fb54..9c8edcf44c 100644 --- a/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_spec.py +++ b/sdk/kubeflow/trainer/models/trainer_v1alpha1_training_runtime_spec.py @@ -3,171 +3,101 @@ """ Kubeflow Trainer OpenAPI Spec - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + 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 -import six - -from kubeflow.trainer.configuration import Configuration +from pydantic import BaseModel, ConfigDict, Field +from typing import Any, ClassVar, Dict, List, Optional +from kubeflow.trainer.models.trainer_v1alpha1_job_set_template_spec import TrainerV1alpha1JobSetTemplateSpec +from kubeflow.trainer.models.trainer_v1alpha1_ml_policy import TrainerV1alpha1MLPolicy +from kubeflow.trainer.models.trainer_v1alpha1_pod_group_policy import TrainerV1alpha1PodGroupPolicy +from typing import Optional, Set +from typing_extensions import Self - -class TrainerV1alpha1TrainingRuntimeSpec(object): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. +class TrainerV1alpha1TrainingRuntimeSpec(BaseModel): """ - - """ - 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. - """ - openapi_types = { - 'ml_policy': 'TrainerV1alpha1MLPolicy', - 'pod_group_policy': 'TrainerV1alpha1PodGroupPolicy', - 'template': 'TrainerV1alpha1JobSetTemplateSpec' - } - - attribute_map = { - 'ml_policy': 'mlPolicy', - 'pod_group_policy': 'podGroupPolicy', - 'template': 'template' - } - - def __init__(self, ml_policy=None, pod_group_policy=None, template=None, local_vars_configuration=None): # noqa: E501 - """TrainerV1alpha1TrainingRuntimeSpec - a model defined in OpenAPI""" # noqa: E501 - if local_vars_configuration is None: - local_vars_configuration = Configuration() - self.local_vars_configuration = local_vars_configuration - - self._ml_policy = None - self._pod_group_policy = None - self._template = None - self.discriminator = None - - if ml_policy is not None: - self.ml_policy = ml_policy - if pod_group_policy is not None: - self.pod_group_policy = pod_group_policy - self.template = template - - @property - def ml_policy(self): - """Gets the ml_policy of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - - - :return: The ml_policy of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - :rtype: TrainerV1alpha1MLPolicy - """ - return self._ml_policy - - @ml_policy.setter - def ml_policy(self, ml_policy): - """Sets the ml_policy of this TrainerV1alpha1TrainingRuntimeSpec. - - - :param ml_policy: The ml_policy of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - :type: TrainerV1alpha1MLPolicy - """ - - self._ml_policy = ml_policy - - @property - def pod_group_policy(self): - """Gets the pod_group_policy of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - - - :return: The pod_group_policy of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - :rtype: TrainerV1alpha1PodGroupPolicy - """ - return self._pod_group_policy - - @pod_group_policy.setter - def pod_group_policy(self, pod_group_policy): - """Sets the pod_group_policy of this TrainerV1alpha1TrainingRuntimeSpec. - - - :param pod_group_policy: The pod_group_policy of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - :type: TrainerV1alpha1PodGroupPolicy + TrainingRuntimeSpec represents a specification of the desired training runtime. + """ # noqa: E501 + ml_policy: Optional[TrainerV1alpha1MLPolicy] = Field(default=None, alias="mlPolicy") + pod_group_policy: Optional[TrainerV1alpha1PodGroupPolicy] = Field(default=None, alias="podGroupPolicy") + template: TrainerV1alpha1JobSetTemplateSpec + __properties: ClassVar[List[str]] = ["mlPolicy", "podGroupPolicy", "template"] + + model_config = ConfigDict( + populate_by_name=True, + validate_assignment=True, + protected_namespaces=(), + ) + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainingRuntimeSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(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 ml_policy + if self.ml_policy: + _dict['mlPolicy'] = self.ml_policy.to_dict() + # override the default output from pydantic by calling `to_dict()` of pod_group_policy + if self.pod_group_policy: + _dict['podGroupPolicy'] = self.pod_group_policy.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: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TrainerV1alpha1TrainingRuntimeSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mlPolicy": TrainerV1alpha1MLPolicy.from_dict(obj["mlPolicy"]) if obj.get("mlPolicy") is not None else None, + "podGroupPolicy": TrainerV1alpha1PodGroupPolicy.from_dict(obj["podGroupPolicy"]) if obj.get("podGroupPolicy") is not None else None, + "template": TrainerV1alpha1JobSetTemplateSpec.from_dict(obj["template"]) if obj.get("template") is not None else None + }) + return _obj - self._pod_group_policy = pod_group_policy - @property - def template(self): - """Gets the template of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - - - :return: The template of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - :rtype: TrainerV1alpha1JobSetTemplateSpec - """ - return self._template - - @template.setter - def template(self, template): - """Sets the template of this TrainerV1alpha1TrainingRuntimeSpec. - - - :param template: The template of this TrainerV1alpha1TrainingRuntimeSpec. # noqa: E501 - :type: TrainerV1alpha1JobSetTemplateSpec - """ - if self.local_vars_configuration.client_side_validation and template is None: # noqa: E501 - raise ValueError("Invalid value for `template`, must not be `None`") # noqa: E501 - - self._template = template - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.openapi_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, TrainerV1alpha1TrainingRuntimeSpec): - return False - - return self.to_dict() == other.to_dict() - - def __ne__(self, other): - """Returns true if both objects are not equal""" - if not isinstance(other, TrainerV1alpha1TrainingRuntimeSpec): - return True - - return self.to_dict() != other.to_dict() diff --git a/sdk/kubeflow/trainer/rest.py b/sdk/kubeflow/trainer/rest.py deleted file mode 100644 index e510046c09..0000000000 --- a/sdk/kubeflow/trainer/rest.py +++ /dev/null @@ -1,291 +0,0 @@ -# coding: utf-8 - -""" - Kubeflow Trainer OpenAPI Spec - - No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import io -import json -import logging -import re -import ssl - -import certifi -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode -import urllib3 - -from kubeflow.trainer.exceptions import ApiException, ApiValueError - - -logger = logging.getLogger(__name__) - - -class RESTResponse(io.IOBase): - - def __init__(self, resp): - self.urllib3_response = resp - self.status = resp.status - self.reason = resp.reason - self.data = resp.data - - def getheaders(self): - """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() - - def getheader(self, name, default=None): - """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) - - -class RESTClientObject(object): - - def __init__(self, configuration, pools_size=4, maxsize=None): - # urllib3.PoolManager will pass all kw parameters to connectionpool - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 - # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 - # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 - - # cert_reqs - if configuration.verify_ssl: - cert_reqs = ssl.CERT_REQUIRED - else: - cert_reqs = ssl.CERT_NONE - - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - - addition_pool_args = {} - if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 - - if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries - - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 - - # https pool manager - if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) - else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=ca_certs, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): - """Perform requests. - - :param method: http request method - :param url: http request url - :param query_params: query parameters in the url - :param headers: http request headers - :param body: request json body, for `application/json` - :param post_params: request post parameters, - `application/x-www-form-urlencoded` - and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - """ - method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] - - if post_params and body: - raise ApiValueError( - "body parameter cannot be used with post_params parameter." - ) - - post_params = post_params or {} - headers = headers or {} - - timeout = None - if _request_timeout: - if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 - timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): - timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) - - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - - try: - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` - if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if query_params: - url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = None - if body is not None: - request_body = json.dumps(body) - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=False, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': - # must del headers['Content-Type'], or the correct - # Content-Type which generated by urllib3 will be - # overwritten. - del headers['Content-Type'] - r = self.pool_manager.request( - method, url, - fields=post_params, - encode_multipart=True, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form - elif isinstance(body, str) or isinstance(body, bytes): - request_body = body - r = self.pool_manager.request( - method, url, - body=request_body, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - else: - # Cannot generate the request from given parameters - msg = """Cannot prepare a request message for provided - arguments. Please check that your arguments match - declared content type.""" - raise ApiException(status=0, reason=msg) - # For `GET`, `HEAD` - else: - r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers) - except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) - raise ApiException(status=0, reason=msg) - - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) diff --git a/sdk/kubeflow/trainer/utils/utils.py b/sdk/kubeflow/trainer/utils/utils.py index f24860bbb7..44a8b00ced 100644 --- a/sdk/kubeflow/trainer/utils/utils.py +++ b/sdk/kubeflow/trainer/utils/utils.py @@ -21,10 +21,10 @@ import threading from typing import Any, Callable, Dict, List, Optional, Tuple -from kubeflow.trainer import models +import kubeflow.trainer.models as models from kubeflow.trainer.constants import constants from kubeflow.trainer.types import types -from kubernetes import client, config +from kubernetes import config def is_running_in_k8s() -> bool: @@ -42,18 +42,9 @@ def get_default_target_namespace() -> str: return f.readline() -class FakeResponse: - """Fake object of RESTResponse to deserialize - Ref) https://github.com/kubeflow/katib/pull/1630#discussion_r697877815 - Ref) https://github.com/kubernetes-client/python/issues/977#issuecomment-592030030 - """ - - def __init__(self, obj): - self.data = json.dumps(obj) - - def get_container_devices( - resources: Optional[client.V1ResourceRequirements], num_procs: Optional[str] = None + resources: Optional[models.IoK8sApiCoreV1ResourceRequirements], + num_procs: Optional[str] = None, ) -> Tuple[str, str]: """ Get the device type and device count for the given container. @@ -106,17 +97,19 @@ def validate_trainer(trainer: types.Trainer): # TODO (andreyvelich): Discuss if we want to support V1ResourceRequirements resources as input. -def get_resources_per_node(resources_per_node: dict) -> client.V1ResourceRequirements: +def get_resources_per_node( + resources_per_node: dict, +) -> models.IoK8sApiCoreV1ResourceRequirements: """ Get the Trainer resources for the training node from the given dict. """ # Convert all keys in resources to lowercase. - resources = {k.lower(): v for k, v in resources_per_node.items()} + resources = {k.lower(): str(v) for k, v in resources_per_node.items()} if "gpu" in resources: resources["nvidia.com/gpu"] = resources.pop("gpu") - resources = client.V1ResourceRequirements( + resources = models.IoK8sApiCoreV1ResourceRequirements( requests=resources, limits=resources, ) @@ -125,7 +118,7 @@ def get_resources_per_node(resources_per_node: dict) -> client.V1ResourceRequire # TODO (andreyvelich): Move this part to the Kubeflow Trainer torch plugins. # Ref issue: https://github.com/kubeflow/trainer/issues/2407 -def get_num_proc_per_node(resources_per_node: dict) -> object: +def get_num_proc_per_node(resources_per_node: dict) -> str: """ Get the Trainer numProcPerNode from the given resources. """ @@ -134,14 +127,14 @@ def get_num_proc_per_node(resources_per_node: dict) -> object: # NumProcPerNode is equal to number of GPUs or CPUs, otherwise set it to `auto` for key, value in resources.items(): if "gpu" in key: - return value + return str(value) for key, value in resources.items(): if "cpu" in key: # For now, we can't convert milliCPUs to the numProcPerNode. try: value = math.ceil(int(value)) - return value + return str(value) except Exception: pass @@ -237,12 +230,12 @@ def get_script_for_python_packages( return script_for_python_packages -def get_lora_config(lora_config: types.LoraConfig) -> List[client.V1EnvVar]: +def get_lora_config(lora_config: types.LoraConfig) -> List[models.IoK8sApiCoreV1EnvVar]: """ Get the TrainJob env from the given Lora config. """ - env = client.V1EnvVar( + env = models.IoK8sApiCoreV1EnvVar( name=constants.ENV_LORA_CONFIG, value=json.dumps(lora_config.__dict__) ) return [env] @@ -259,7 +252,7 @@ def get_dataset_config( # TODO (andreyvelich): Support more parameters. ds_config = models.TrainerV1alpha1DatasetConfig( - storage_uri=( + storageUri=( dataset_config.storage_uri if dataset_config.storage_uri.startswith("hf://") else "hf://" + dataset_config.storage_uri @@ -280,7 +273,7 @@ def get_model_config( # TODO (andreyvelich): Support more parameters. m_config = models.TrainerV1alpha1ModelConfig( - input=models.TrainerV1alpha1InputModel(storage_uri=model_config.storage_uri) + input=models.TrainerV1alpha1InputModel(storageUri=model_config.storage_uri) ) return m_config diff --git a/sdk/pyproject.toml b/sdk/pyproject.toml index 0cd2e66344..8f701d981d 100644 --- a/sdk/pyproject.toml +++ b/sdk/pyproject.toml @@ -6,35 +6,30 @@ build-backend = "hatchling.build" name = "kubeflow" dynamic = ["version"] authors = [ - { name = "The Kubeflow Authors", email = "kubeflow-discuss@googlegroups.com" }, + { name = "The Kubeflow Authors", email = "kubeflow-discuss@googlegroups.com" }, ] license = { file = "../LICENSE" } description = "Kubeflow Python SDK to manage ML workloads and to interact with Kubeflow APIs." readme = "../README.md" keywords = ["kubeflow", "trainer", "model training", "llm", "ai"] classifiers = [ - "Intended Audience :: Developers", - "Intended Audience :: Education", - "Intended Audience :: Science/Research", - # TODO (andreyvelich): Check Python version for Kubeflow Trainer. - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "License :: OSI Approved :: Apache Software License", - "Operating System :: OS Independent", - "Topic :: Scientific/Engineering", - "Topic :: Scientific/Engineering :: Artificial Intelligence", - "Topic :: Software Development", - "Topic :: Software Development :: Libraries", - "Topic :: Software Development :: Libraries :: Python Modules", -] -dependencies = [ - "kubernetes>=27.2.0", - # TODO (andreyvelich): Update JobSet to v0.8.0 once this PR is merged: https://github.com/kubeflow/trainer/pull/2466 - # "pydantic>=2.10.0", - "jobset @ git+https://github.com/kubernetes-sigs/jobset.git@v0.7.2#subdirectory=sdk/python", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + # TODO (andreyvelich): Check Python version for Kubeflow Trainer. + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Topic :: Scientific/Engineering", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "Topic :: Software Development", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Libraries :: Python Modules", ] +dependencies = ["kubernetes>=27.2.0", "pydantic>=2.10.0"] [project.urls] Homepage = "https://github.com/kubeflow/trainer"