diff --git a/sdk/batch/azure-batch/CHANGELOG.md b/sdk/batch/azure-batch/CHANGELOG.md index c39c95213585..a5da72489d56 100644 --- a/sdk/batch/azure-batch/CHANGELOG.md +++ b/sdk/batch/azure-batch/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 15.2.0 (2026-11-06) + +skip changelog generation for data-plane package and please add changelog manually. + ## 15.1.0 (2026-03-06) ### Other Changes diff --git a/sdk/batch/azure-batch/_metadata.json b/sdk/batch/azure-batch/_metadata.json index 05e6b511e7bd..e18cb64dc85b 100644 --- a/sdk/batch/azure-batch/_metadata.json +++ b/sdk/batch/azure-batch/_metadata.json @@ -1,6 +1,11 @@ { - "apiVersion": "2025-06-01", + "apiVersion": "2026-10-01", "apiVersions": { - "Azure.Batch": "2025-06-01" - } + "Azure.Batch": "2026-10-01" + }, + "commit": "0b01059c3d95a84bc84ff16a4bb0fd10f66f3abd", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/batch/data-plane/Batch", + "emitterVersion": "0.63.10", + "httpClientPythonVersion": "0.39.0" } \ No newline at end of file diff --git a/sdk/batch/azure-batch/api.md b/sdk/batch/azure-batch/api.md new file mode 100644 index 000000000000..de70d8c07b59 --- /dev/null +++ b/sdk/batch/azure-batch/api.md @@ -0,0 +1,5160 @@ +```py +namespace azure.batch + + class azure.batch.BatchClient(_BatchClientOperationsMixin): implements ContextManager + + def __init__( + self, + endpoint: str, + credential: TokenCredential, + *, + api_version: str = ..., + **kwargs: Any + ) -> None: ... + + def close(self) -> None: ... + + @distributed_trace + def create_job( + self, + job: BatchJobCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def create_job_schedule( + self, + job_schedule: BatchJobScheduleCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def create_node_user( + self, + pool_id: str, + node_id: str, + user: BatchNodeUserCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def create_pool( + self, + pool: BatchPoolCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def create_task( + self, + job_id: str, + task: BatchTaskCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def create_task_collection( + self, + job_id: str, + task_collection: BatchTaskGroup, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchCreateTaskCollectionResult: ... + + @distributed_trace + def delete_node_file( + self, + pool_id: str, + node_id: str, + file_path: str, + *, + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def delete_node_user( + self, + pool_id: str, + node_id: str, + user_name: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def delete_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def delete_task_file( + self, + job_id: str, + task_id: str, + file_path: str, + *, + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def disable_job_schedule( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def disable_node_scheduling( + self, + pool_id: str, + node_id: str, + options: Optional[BatchNodeDisableSchedulingOptions] = None, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def disable_pool_auto_scale( + self, + pool_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def download_node_file( + self, + pool_id: str, + node_id: str, + file_path: str, + *, + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + ocp_date: Optional[datetime] = ..., + ocp_range: Optional[str] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> Iterator[bytes]: ... + + @distributed_trace + def download_task_file( + self, + job_id: str, + task_id: str, + file_path: str, + *, + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + ocp_date: Optional[datetime] = ..., + ocp_range: Optional[str] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> Iterator[bytes]: ... + + @distributed_trace + def enable_job_schedule( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def enable_node_scheduling( + self, + pool_id: str, + node_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def enable_pool_auto_scale( + self, + pool_id: str, + enable_auto_scale_options: BatchPoolEnableAutoScaleOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def evaluate_pool_auto_scale( + self, + pool_id: str, + evaluate_auto_scale_options: BatchPoolEvaluateAutoScaleOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AutoScaleRun: ... + + @distributed_trace + def get_application( + self, + application_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchApplication: ... + + @distributed_trace + def get_job( + self, + job_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchJob: ... + + @distributed_trace + def get_job_schedule( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchJobSchedule: ... + + @distributed_trace + def get_job_task_counts( + self, + job_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchTaskCountsResult: ... + + @distributed_trace + def get_node( + self, + pool_id: str, + node_id: str, + *, + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchNode: ... + + @distributed_trace + def get_node_extension( + self, + pool_id: str, + node_id: str, + extension_name: str, + *, + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchNodeVMExtension: ... + + @distributed_trace + def get_node_remote_login_settings( + self, + pool_id: str, + node_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchNodeRemoteLoginSettings: ... + + @distributed_trace + def get_pool( + self, + pool_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchPool: ... + + @distributed_trace + def get_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchTask: ... + + @distributed_trace + def job_schedule_exists( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> bool: ... + + @distributed_trace + def list_applications( + self, + *, + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchApplication]: ... + + @distributed_trace + def list_job_preparation_and_release_task_status( + self, + job_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchJobPreparationAndReleaseTaskStatus]: ... + + @distributed_trace + def list_job_schedules( + self, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchJobSchedule]: ... + + @distributed_trace + def list_jobs( + self, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchJob]: ... + + @distributed_trace + def list_jobs_from_schedule( + self, + job_schedule_id: str, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchJob]: ... + + @distributed_trace + def list_node_extensions( + self, + pool_id: str, + node_id: str, + *, + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchNodeVMExtension]: ... + + @distributed_trace + def list_node_files( + self, + pool_id: str, + node_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchNodeFile]: ... + + @distributed_trace + def list_nodes( + self, + pool_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchNode]: ... + + @distributed_trace + def list_pool_node_counts( + self, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchPoolNodeCounts]: ... + + @distributed_trace + def list_pools( + self, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchPool]: ... + + @distributed_trace + def list_subtasks( + self, + job_id: str, + task_id: str, + *, + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchSubtask]: ... + + @distributed_trace + def list_supported_images( + self, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchSupportedImage]: ... + + @distributed_trace + def list_task_files( + self, + job_id: str, + task_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchNodeFile]: ... + + @distributed_trace + def list_tasks( + self, + job_id: str, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> ItemPaged[BatchTask]: ... + + @distributed_trace + def pool_exists( + self, + pool_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> bool: ... + + @distributed_trace + def reactivate_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def replace_job( + self, + job_id: str, + job: BatchJob, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def replace_job_schedule( + self, + job_schedule_id: str, + job_schedule: BatchJobSchedule, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def replace_node_user( + self, + pool_id: str, + node_id: str, + user_name: str, + update_options: BatchNodeUserReplaceOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def replace_pool_properties( + self, + pool_id: str, + pool: BatchPoolReplaceOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def replace_task( + self, + job_id: str, + task_id: str, + task: BatchTask, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + def send_request( + self, + request: HttpRequest, + *, + stream: bool = False, + **kwargs: Any + ) -> HttpResponse: ... + + @distributed_trace + def terminate_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def update_job( + self, + job_id: str, + job: BatchJobUpdateOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def update_job_schedule( + self, + job_schedule_id: str, + job_schedule: BatchJobScheduleUpdateOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def update_pool( + self, + pool_id: str, + pool: BatchPoolUpdateOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace + def upload_node_logs( + self, + pool_id: str, + node_id: str, + upload_options: UploadBatchServiceLogsOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> UploadBatchServiceLogsResult: ... + + +namespace azure.batch.aio + + class azure.batch.aio.BatchClient(_BatchClientOperationsMixin): implements AsyncContextManager + + def __init__( + self, + endpoint: str, + credential: AsyncTokenCredential, + *, + api_version: str = ..., + **kwargs: Any + ) -> None: ... + + async def close(self) -> None: ... + + @distributed_trace_async + async def create_job( + self, + job: BatchJobCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def create_job_schedule( + self, + job_schedule: BatchJobScheduleCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def create_node_user( + self, + pool_id: str, + node_id: str, + user: BatchNodeUserCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def create_pool( + self, + pool: BatchPoolCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def create_task( + self, + job_id: str, + task: BatchTaskCreateOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def create_task_collection( + self, + job_id: str, + task_collection: BatchTaskGroup, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchCreateTaskCollectionResult: ... + + @distributed_trace_async + async def delete_node_file( + self, + pool_id: str, + node_id: str, + file_path: str, + *, + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def delete_node_user( + self, + pool_id: str, + node_id: str, + user_name: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def delete_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def delete_task_file( + self, + job_id: str, + task_id: str, + file_path: str, + *, + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def disable_job_schedule( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def disable_node_scheduling( + self, + pool_id: str, + node_id: str, + options: Optional[BatchNodeDisableSchedulingOptions] = None, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def disable_pool_auto_scale( + self, + pool_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def download_node_file( + self, + pool_id: str, + node_id: str, + file_path: str, + *, + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + ocp_date: Optional[datetime] = ..., + ocp_range: Optional[str] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncIterator[bytes]: ... + + @distributed_trace_async + async def download_task_file( + self, + job_id: str, + task_id: str, + file_path: str, + *, + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + ocp_date: Optional[datetime] = ..., + ocp_range: Optional[str] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncIterator[bytes]: ... + + @distributed_trace_async + async def enable_job_schedule( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def enable_node_scheduling( + self, + pool_id: str, + node_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def enable_pool_auto_scale( + self, + pool_id: str, + enable_auto_scale_options: BatchPoolEnableAutoScaleOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def evaluate_pool_auto_scale( + self, + pool_id: str, + evaluate_auto_scale_options: BatchPoolEvaluateAutoScaleOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AutoScaleRun: ... + + @distributed_trace_async + async def get_application( + self, + application_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchApplication: ... + + @distributed_trace_async + async def get_job( + self, + job_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchJob: ... + + @distributed_trace_async + async def get_job_schedule( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchJobSchedule: ... + + @distributed_trace_async + async def get_job_task_counts( + self, + job_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchTaskCountsResult: ... + + @distributed_trace_async + async def get_node( + self, + pool_id: str, + node_id: str, + *, + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchNode: ... + + @distributed_trace_async + async def get_node_extension( + self, + pool_id: str, + node_id: str, + extension_name: str, + *, + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchNodeVMExtension: ... + + @distributed_trace_async + async def get_node_remote_login_settings( + self, + pool_id: str, + node_id: str, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchNodeRemoteLoginSettings: ... + + @distributed_trace_async + async def get_pool( + self, + pool_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchPool: ... + + @distributed_trace_async + async def get_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + expand: Optional[list[str]] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> BatchTask: ... + + @distributed_trace_async + async def job_schedule_exists( + self, + job_schedule_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> bool: ... + + @distributed_trace + def list_applications( + self, + *, + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchApplication]: ... + + @distributed_trace + def list_job_preparation_and_release_task_status( + self, + job_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchJobPreparationAndReleaseTaskStatus]: ... + + @distributed_trace + def list_job_schedules( + self, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchJobSchedule]: ... + + @distributed_trace + def list_jobs( + self, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchJob]: ... + + @distributed_trace + def list_jobs_from_schedule( + self, + job_schedule_id: str, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchJob]: ... + + @distributed_trace + def list_node_extensions( + self, + pool_id: str, + node_id: str, + *, + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchNodeVMExtension]: ... + + @distributed_trace + def list_node_files( + self, + pool_id: str, + node_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchNodeFile]: ... + + @distributed_trace + def list_nodes( + self, + pool_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchNode]: ... + + @distributed_trace + def list_pool_node_counts( + self, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchPoolNodeCounts]: ... + + @distributed_trace + def list_pools( + self, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchPool]: ... + + @distributed_trace + def list_subtasks( + self, + job_id: str, + task_id: str, + *, + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchSubtask]: ... + + @distributed_trace + def list_supported_images( + self, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchSupportedImage]: ... + + @distributed_trace + def list_task_files( + self, + job_id: str, + task_id: str, + *, + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + recursive: Optional[bool] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchNodeFile]: ... + + @distributed_trace + def list_tasks( + self, + job_id: str, + *, + expand: Optional[list[str]] = ..., + filter: Optional[str] = ..., + max_results: Optional[int] = ..., + ocp_date: Optional[datetime] = ..., + select: Optional[list[str]] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> AsyncItemPaged[BatchTask]: ... + + @distributed_trace_async + async def pool_exists( + self, + pool_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> bool: ... + + @distributed_trace_async + async def reactivate_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def replace_job( + self, + job_id: str, + job: BatchJob, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def replace_job_schedule( + self, + job_schedule_id: str, + job_schedule: BatchJobSchedule, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def replace_node_user( + self, + pool_id: str, + node_id: str, + user_name: str, + update_options: BatchNodeUserReplaceOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def replace_pool_properties( + self, + pool_id: str, + pool: BatchPoolReplaceOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def replace_task( + self, + job_id: str, + task_id: str, + task: BatchTask, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + def send_request( + self, + request: HttpRequest, + *, + stream: bool = False, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: ... + + @distributed_trace_async + async def terminate_task( + self, + job_id: str, + task_id: str, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def update_job( + self, + job_id: str, + job: BatchJobUpdateOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def update_job_schedule( + self, + job_schedule_id: str, + job_schedule: BatchJobScheduleUpdateOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def update_pool( + self, + pool_id: str, + pool: BatchPoolUpdateOptions, + *, + etag: Optional[str] = ..., + if_modified_since: Optional[datetime] = ..., + if_unmodified_since: Optional[datetime] = ..., + match_condition: Optional[MatchConditions] = ..., + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def upload_node_logs( + self, + pool_id: str, + node_id: str, + upload_options: UploadBatchServiceLogsOptions, + *, + ocp_date: Optional[datetime] = ..., + service_timeout: Optional[timedelta] = ..., + **kwargs: Any + ) -> UploadBatchServiceLogsResult: ... + + +namespace azure.batch.models + + class azure.batch.models.AllocationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + RESIZING = "resizing" + STEADY = "steady" + STOPPING = "stopping" + + + class azure.batch.models.AutoScaleRun(_Model): + error: Optional[AutoScaleRunError] + results: Optional[str] + timestamp: datetime + + @overload + def __init__( + self, + *, + error: Optional[AutoScaleRunError] = ..., + results: Optional[str] = ..., + timestamp: datetime + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.AutoScaleRunError(_Model): + code: Optional[str] + error_values: Optional[list[NameValuePair]] + message: Optional[str] + + @overload + def __init__( + self, + *, + code: Optional[str] = ..., + error_values: Optional[list[NameValuePair]] = ..., + message: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.AutoUserScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + POOL = "pool" + TASK = "task" + + + class azure.batch.models.AutoUserSpecification(_Model): + elevation_level: Optional[Union[str, ElevationLevel]] + scope: Optional[Union[str, AutoUserScope]] + + @overload + def __init__( + self, + *, + elevation_level: Optional[Union[str, ElevationLevel]] = ..., + scope: Optional[Union[str, AutoUserScope]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.AutomaticOsUpgradePolicy(_Model): + disable_automatic_rollback: Optional[bool] + enable_automatic_os_upgrade: Optional[bool] + os_rolling_upgrade_deferral: Optional[bool] + use_rolling_upgrade_policy: Optional[bool] + + @overload + def __init__( + self, + *, + disable_automatic_rollback: Optional[bool] = ..., + enable_automatic_os_upgrade: Optional[bool] = ..., + os_rolling_upgrade_deferral: Optional[bool] = ..., + use_rolling_upgrade_policy: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.AzureBlobFileSystemConfiguration(_Model): + account_key: Optional[str] + account_name: str + blobfuse_options: Optional[str] + container_name: str + identity_reference: Optional[BatchNodeIdentityReference] + relative_mount_path: str + sas_key: Optional[str] + + @overload + def __init__( + self, + *, + account_key: Optional[str] = ..., + account_name: str, + blobfuse_options: Optional[str] = ..., + container_name: str, + identity_reference: Optional[BatchNodeIdentityReference] = ..., + relative_mount_path: str, + sas_key: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.AzureFileShareConfiguration(_Model): + account_key: str + account_name: str + azure_file_url: str + mount_options: Optional[str] + relative_mount_path: str + + @overload + def __init__( + self, + *, + account_key: str, + account_name: str, + azure_file_url: str, + mount_options: Optional[str] = ..., + relative_mount_path: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchAffinityInfo(_Model): + affinity_id: str + + @overload + def __init__( + self, + *, + affinity_id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchAllTasksCompleteMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + NO_ACTION = "noaction" + TERMINATE_JOB = "terminatejob" + + + class azure.batch.models.BatchApplication(_Model): + display_name: str + id: str + versions: list[str] + + @overload + def __init__( + self, + *, + display_name: str, + id: str, + versions: list[str] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchApplicationPackageReference(_Model): + application_id: str + version: Optional[str] + + @overload + def __init__( + self, + *, + application_id: str, + version: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchAutoPoolSpecification(_Model): + auto_pool_id_prefix: Optional[str] + keep_alive: Optional[bool] + pool: Optional[BatchPoolSpecification] + pool_lifetime_option: Union[str, BatchPoolLifetimeOption] + + @overload + def __init__( + self, + *, + auto_pool_id_prefix: Optional[str] = ..., + keep_alive: Optional[bool] = ..., + pool: Optional[BatchPoolSpecification] = ..., + pool_lifetime_option: Union[str, BatchPoolLifetimeOption] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchContainerConfiguration(_Model): + container_image_names: Optional[list[str]] + container_registries: Optional[list[ContainerRegistryReference]] + type: Union[str, ContainerType] + + @overload + def __init__( + self, + *, + container_image_names: Optional[list[str]] = ..., + container_registries: Optional[list[ContainerRegistryReference]] = ..., + type: Union[str, ContainerType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchCreateTaskCollectionResult(_Model): + result_values: Optional[list[BatchTaskCreateResult]] + + @overload + def __init__( + self, + *, + result_values: Optional[list[BatchTaskCreateResult]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchDiffDiskSettings(_Model): + placement: Optional[Union[str, DiffDiskPlacement]] + + @overload + def __init__( + self, + *, + placement: Optional[Union[str, DiffDiskPlacement]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchError(_Model): + code: Optional[str] + error_values: Optional[list[BatchErrorDetail]] + message: Optional[BatchErrorMessage] + + @overload + def __init__( + self, + *, + code: Optional[str] = ..., + error_values: Optional[list[BatchErrorDetail]] = ..., + message: Optional[BatchErrorMessage] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchErrorDetail(_Model): + key: Optional[str] + value: Optional[str] + + @overload + def __init__( + self, + *, + key: Optional[str] = ..., + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchErrorMessage(_Model): + lang: Optional[str] + value: Optional[str] + + @overload + def __init__( + self, + *, + lang: Optional[str] = ..., + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchErrorSourceCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + SERVER_ERROR = "servererror" + USER_ERROR = "usererror" + + + class azure.batch.models.BatchInboundNatPool(_Model): + backend_port: int + frontend_port_range_end: int + frontend_port_range_start: int + name: str + network_security_group_rules: Optional[list[NetworkSecurityGroupRule]] + protocol: Union[str, InboundEndpointProtocol] + + @overload + def __init__( + self, + *, + backend_port: int, + frontend_port_range_end: int, + frontend_port_range_start: int, + name: str, + network_security_group_rules: Optional[list[NetworkSecurityGroupRule]] = ..., + protocol: Union[str, InboundEndpointProtocol] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJob(_Model): + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] + allow_task_preemption: Optional[bool] + common_environment_settings: Optional[list[EnvironmentSetting]] + constraints: Optional[BatchJobConstraints] + creation_time: datetime + display_name: Optional[str] + etag: str + execution_info: Optional[BatchJobExecutionInfo] + id: str + job_manager_task: Optional[BatchJobManagerTask] + job_preparation_task: Optional[BatchJobPreparationTask] + job_release_task: Optional[BatchJobReleaseTask] + job_statistics: Optional[BatchJobStatistics] + last_modified: datetime + max_parallel_tasks: Optional[int] + metadata: Optional[list[BatchMetadataItem]] + network_configuration: Optional[BatchJobNetworkConfiguration] + pool_info: BatchPoolInfo + previous_state: Optional[Union[str, BatchJobState]] + previous_state_transition_time: Optional[datetime] + priority: Optional[int] + state: Union[str, BatchJobState] + state_transition_time: datetime + task_failure_mode: Optional[Union[str, BatchTaskFailureMode]] + url: str + uses_task_dependencies: Optional[bool] + + @overload + def __init__( + self, + *, + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] = ..., + allow_task_preemption: Optional[bool] = ..., + constraints: Optional[BatchJobConstraints] = ..., + max_parallel_tasks: Optional[int] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + pool_info: BatchPoolInfo, + priority: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + DISABLE = "disable" + NONE = "none" + TERMINATE = "terminate" + + + class azure.batch.models.BatchJobConstraints(_Model): + max_task_retry_count: Optional[int] + max_wall_clock_time: Optional[timedelta] + + @overload + def __init__( + self, + *, + max_task_retry_count: Optional[int] = ..., + max_wall_clock_time: Optional[timedelta] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobCreateOptions(_Model): + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] + allow_task_preemption: Optional[bool] + common_environment_settings: Optional[list[EnvironmentSetting]] + constraints: Optional[BatchJobConstraints] + display_name: Optional[str] + id: str + job_manager_task: Optional[BatchJobManagerTask] + job_preparation_task: Optional[BatchJobPreparationTask] + job_release_task: Optional[BatchJobReleaseTask] + max_parallel_tasks: Optional[int] + metadata: Optional[list[BatchMetadataItem]] + network_configuration: Optional[BatchJobNetworkConfiguration] + pool_info: BatchPoolInfo + priority: Optional[int] + task_failure_mode: Optional[Union[str, BatchTaskFailureMode]] + uses_task_dependencies: Optional[bool] + + @overload + def __init__( + self, + *, + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] = ..., + allow_task_preemption: Optional[bool] = ..., + common_environment_settings: Optional[list[EnvironmentSetting]] = ..., + constraints: Optional[BatchJobConstraints] = ..., + display_name: Optional[str] = ..., + id: str, + job_manager_task: Optional[BatchJobManagerTask] = ..., + job_preparation_task: Optional[BatchJobPreparationTask] = ..., + job_release_task: Optional[BatchJobReleaseTask] = ..., + max_parallel_tasks: Optional[int] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + network_configuration: Optional[BatchJobNetworkConfiguration] = ..., + pool_info: BatchPoolInfo, + priority: Optional[int] = ..., + task_failure_mode: Optional[Union[str, BatchTaskFailureMode]] = ..., + uses_task_dependencies: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobDefaultOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CREATION_TIME = "creationtime" + NONE = "none" + + + class azure.batch.models.BatchJobDisableOptions(_Model): + disable_tasks: Union[str, DisableBatchJobOption] + + @overload + def __init__( + self, + *, + disable_tasks: Union[str, DisableBatchJobOption] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobExecutionInfo(_Model): + end_time: Optional[datetime] + pool_id: Optional[str] + scheduling_error: Optional[BatchJobSchedulingError] + start_time: datetime + termination_reason: Optional[str] + + @overload + def __init__( + self, + *, + end_time: Optional[datetime] = ..., + pool_id: Optional[str] = ..., + scheduling_error: Optional[BatchJobSchedulingError] = ..., + start_time: datetime, + termination_reason: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobManagerTask(_Model): + allow_low_priority_node: Optional[bool] + application_package_references: Optional[list[BatchApplicationPackageReference]] + command_line: str + constraints: Optional[BatchTaskConstraints] + container_settings: Optional[BatchTaskContainerSettings] + display_name: Optional[str] + environment_settings: Optional[list[EnvironmentSetting]] + id: str + kill_job_on_completion: Optional[bool] + output_files: Optional[list[OutputFile]] + required_slots: Optional[int] + resource_files: Optional[list[ResourceFile]] + run_exclusive: Optional[bool] + user_identity: Optional[UserIdentity] + + @overload + def __init__( + self, + *, + allow_low_priority_node: Optional[bool] = ..., + application_package_references: Optional[list[BatchApplicationPackageReference]] = ..., + command_line: str, + constraints: Optional[BatchTaskConstraints] = ..., + container_settings: Optional[BatchTaskContainerSettings] = ..., + display_name: Optional[str] = ..., + environment_settings: Optional[list[EnvironmentSetting]] = ..., + id: str, + kill_job_on_completion: Optional[bool] = ..., + output_files: Optional[list[OutputFile]] = ..., + required_slots: Optional[int] = ..., + resource_files: Optional[list[ResourceFile]] = ..., + run_exclusive: Optional[bool] = ..., + user_identity: Optional[UserIdentity] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobNetworkConfiguration(_Model): + skip_withdraw_from_vnet: Optional[bool] + subnet_id: str + + @overload + def __init__( + self, + *, + skip_withdraw_from_vnet: Optional[bool] = ..., + subnet_id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobPreparationAndReleaseTaskStatus(_Model): + job_preparation_task_execution_info: Optional[BatchJobPreparationTaskExecutionInfo] + job_release_task_execution_info: Optional[BatchJobReleaseTaskExecutionInfo] + node_id: Optional[str] + node_url: Optional[str] + pool_id: Optional[str] + + @overload + def __init__( + self, + *, + job_preparation_task_execution_info: Optional[BatchJobPreparationTaskExecutionInfo] = ..., + job_release_task_execution_info: Optional[BatchJobReleaseTaskExecutionInfo] = ..., + node_id: Optional[str] = ..., + node_url: Optional[str] = ..., + pool_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobPreparationTask(_Model): + command_line: str + constraints: Optional[BatchTaskConstraints] + container_settings: Optional[BatchTaskContainerSettings] + environment_settings: Optional[list[EnvironmentSetting]] + id: Optional[str] + rerun_on_node_reboot_after_success: Optional[bool] + resource_files: Optional[list[ResourceFile]] + user_identity: Optional[UserIdentity] + wait_for_success: Optional[bool] + + @overload + def __init__( + self, + *, + command_line: str, + constraints: Optional[BatchTaskConstraints] = ..., + container_settings: Optional[BatchTaskContainerSettings] = ..., + environment_settings: Optional[list[EnvironmentSetting]] = ..., + id: Optional[str] = ..., + rerun_on_node_reboot_after_success: Optional[bool] = ..., + resource_files: Optional[list[ResourceFile]] = ..., + user_identity: Optional[UserIdentity] = ..., + wait_for_success: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobPreparationTaskExecutionInfo(_Model): + container_info: Optional[BatchTaskContainerExecutionInfo] + end_time: Optional[datetime] + exit_code: Optional[int] + failure_info: Optional[BatchTaskFailureInfo] + last_retry_time: Optional[datetime] + result: Optional[Union[str, BatchTaskExecutionResult]] + retry_count: int + start_time: datetime + state: Union[str, BatchJobPreparationTaskState] + task_root_directory: Optional[str] + task_root_directory_url: Optional[str] + + @overload + def __init__( + self, + *, + container_info: Optional[BatchTaskContainerExecutionInfo] = ..., + end_time: Optional[datetime] = ..., + exit_code: Optional[int] = ..., + failure_info: Optional[BatchTaskFailureInfo] = ..., + last_retry_time: Optional[datetime] = ..., + result: Optional[Union[str, BatchTaskExecutionResult]] = ..., + retry_count: int, + start_time: datetime, + state: Union[str, BatchJobPreparationTaskState], + task_root_directory: Optional[str] = ..., + task_root_directory_url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobPreparationTaskState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + COMPLETED = "completed" + RUNNING = "running" + + + class azure.batch.models.BatchJobReleaseTask(_Model): + command_line: str + container_settings: Optional[BatchTaskContainerSettings] + environment_settings: Optional[list[EnvironmentSetting]] + id: Optional[str] + max_wall_clock_time: Optional[timedelta] + resource_files: Optional[list[ResourceFile]] + retention_time: Optional[timedelta] + user_identity: Optional[UserIdentity] + + @overload + def __init__( + self, + *, + command_line: str, + container_settings: Optional[BatchTaskContainerSettings] = ..., + environment_settings: Optional[list[EnvironmentSetting]] = ..., + id: Optional[str] = ..., + max_wall_clock_time: Optional[timedelta] = ..., + resource_files: Optional[list[ResourceFile]] = ..., + retention_time: Optional[timedelta] = ..., + user_identity: Optional[UserIdentity] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobReleaseTaskExecutionInfo(_Model): + container_info: Optional[BatchTaskContainerExecutionInfo] + end_time: Optional[datetime] + exit_code: Optional[int] + failure_info: Optional[BatchTaskFailureInfo] + result: Optional[Union[str, BatchTaskExecutionResult]] + start_time: datetime + state: Union[str, BatchJobReleaseTaskState] + task_root_directory: Optional[str] + task_root_directory_url: Optional[str] + + @overload + def __init__( + self, + *, + container_info: Optional[BatchTaskContainerExecutionInfo] = ..., + end_time: Optional[datetime] = ..., + exit_code: Optional[int] = ..., + failure_info: Optional[BatchTaskFailureInfo] = ..., + result: Optional[Union[str, BatchTaskExecutionResult]] = ..., + start_time: datetime, + state: Union[str, BatchJobReleaseTaskState], + task_root_directory: Optional[str] = ..., + task_root_directory_url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobReleaseTaskState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + COMPLETED = "completed" + RUNNING = "running" + + + class azure.batch.models.BatchJobSchedule(_Model): + creation_time: datetime + display_name: Optional[str] + etag: str + execution_info: BatchJobScheduleExecutionInfo + id: str + job_schedule_statistics: Optional[BatchJobScheduleStatistics] + job_specification: BatchJobSpecification + last_modified: datetime + metadata: Optional[list[BatchMetadataItem]] + previous_state: Optional[Union[str, BatchJobScheduleState]] + previous_state_transition_time: Optional[datetime] + schedule: Optional[BatchJobScheduleConfiguration] + state: Union[str, BatchJobScheduleState] + state_transition_time: datetime + url: str + + @overload + def __init__( + self, + *, + job_specification: BatchJobSpecification, + metadata: Optional[list[BatchMetadataItem]] = ..., + schedule: Optional[BatchJobScheduleConfiguration] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobScheduleConfiguration(_Model): + do_not_run_after: Optional[datetime] + do_not_run_until: Optional[datetime] + recurrence_interval: Optional[timedelta] + start_window: Optional[timedelta] + + @overload + def __init__( + self, + *, + do_not_run_after: Optional[datetime] = ..., + do_not_run_until: Optional[datetime] = ..., + recurrence_interval: Optional[timedelta] = ..., + start_window: Optional[timedelta] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobScheduleCreateOptions(_Model): + display_name: Optional[str] + id: str + job_specification: BatchJobSpecification + metadata: Optional[list[BatchMetadataItem]] + schedule: BatchJobScheduleConfiguration + + @overload + def __init__( + self, + *, + display_name: Optional[str] = ..., + id: str, + job_specification: BatchJobSpecification, + metadata: Optional[list[BatchMetadataItem]] = ..., + schedule: BatchJobScheduleConfiguration + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobScheduleExecutionInfo(_Model): + end_time: Optional[datetime] + next_run_time: Optional[datetime] + recent_job: Optional[RecentBatchJob] + + @overload + def __init__( + self, + *, + end_time: Optional[datetime] = ..., + next_run_time: Optional[datetime] = ..., + recent_job: Optional[RecentBatchJob] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobScheduleState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACTIVE = "active" + COMPLETED = "completed" + DELETING = "deleting" + DISABLED = "disabled" + TERMINATING = "terminating" + + + class azure.batch.models.BatchJobScheduleStatistics(_Model): + failed_tasks_count: int + kernel_cpu_time: timedelta + last_update_time: datetime + read_io_gib: float + read_iops: int + start_time: datetime + succeeded_tasks_count: int + task_retries_count: int + url: str + user_cpu_time: timedelta + wait_time: timedelta + wall_clock_time: timedelta + write_io_gib: float + write_iops: int + + @overload + def __init__( + self, + *, + failed_tasks_count: int, + kernel_cpu_time: timedelta, + last_update_time: datetime, + read_io_gib: float, + read_iops: int, + start_time: datetime, + succeeded_tasks_count: int, + task_retries_count: int, + url: str, + user_cpu_time: timedelta, + wait_time: timedelta, + wall_clock_time: timedelta, + write_io_gib: float, + write_iops: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobScheduleUpdateOptions(_Model): + job_specification: Optional[BatchJobSpecification] + metadata: Optional[list[BatchMetadataItem]] + schedule: Optional[BatchJobScheduleConfiguration] + + @overload + def __init__( + self, + *, + job_specification: Optional[BatchJobSpecification] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + schedule: Optional[BatchJobScheduleConfiguration] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobSchedulingError(_Model): + category: Union[str, BatchErrorSourceCategory] + code: Optional[str] + details: Optional[list[NameValuePair]] + message: Optional[str] + + @overload + def __init__( + self, + *, + category: Union[str, BatchErrorSourceCategory], + code: Optional[str] = ..., + details: Optional[list[NameValuePair]] = ..., + message: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobSpecification(_Model): + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] + allow_task_preemption: Optional[bool] + common_environment_settings: Optional[list[EnvironmentSetting]] + constraints: Optional[BatchJobConstraints] + display_name: Optional[str] + job_manager_task: Optional[BatchJobManagerTask] + job_preparation_task: Optional[BatchJobPreparationTask] + job_release_task: Optional[BatchJobReleaseTask] + max_parallel_tasks: Optional[int] + metadata: Optional[list[BatchMetadataItem]] + network_configuration: Optional[BatchJobNetworkConfiguration] + pool_info: BatchPoolInfo + priority: Optional[int] + task_failure_mode: Optional[Union[str, BatchTaskFailureMode]] + uses_task_dependencies: Optional[bool] + + @overload + def __init__( + self, + *, + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] = ..., + allow_task_preemption: Optional[bool] = ..., + common_environment_settings: Optional[list[EnvironmentSetting]] = ..., + constraints: Optional[BatchJobConstraints] = ..., + display_name: Optional[str] = ..., + job_manager_task: Optional[BatchJobManagerTask] = ..., + job_preparation_task: Optional[BatchJobPreparationTask] = ..., + job_release_task: Optional[BatchJobReleaseTask] = ..., + max_parallel_tasks: Optional[int] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + network_configuration: Optional[BatchJobNetworkConfiguration] = ..., + pool_info: BatchPoolInfo, + priority: Optional[int] = ..., + task_failure_mode: Optional[Union[str, BatchTaskFailureMode]] = ..., + uses_task_dependencies: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACTIVE = "active" + COMPLETED = "completed" + DELETING = "deleting" + DISABLED = "disabled" + DISABLING = "disabling" + ENABLING = "enabling" + TERMINATING = "terminating" + + + class azure.batch.models.BatchJobStatistics(_Model): + failed_tasks_count: int + kernel_cpu_time: timedelta + last_update_time: datetime + read_io_gib: float + read_iops: int + start_time: datetime + succeeded_tasks_count: int + task_retries_count: int + url: str + user_cpu_time: timedelta + wait_time: timedelta + wall_clock_time: timedelta + write_io_gib: float + write_iops: int + + @overload + def __init__( + self, + *, + failed_tasks_count: int, + kernel_cpu_time: timedelta, + last_update_time: datetime, + read_io_gib: float, + read_iops: int, + start_time: datetime, + succeeded_tasks_count: int, + task_retries_count: int, + url: str, + user_cpu_time: timedelta, + wait_time: timedelta, + wall_clock_time: timedelta, + write_io_gib: float, + write_iops: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobTerminateOptions(_Model): + termination_reason: Optional[str] + + @overload + def __init__( + self, + *, + termination_reason: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchJobUpdateOptions(_Model): + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] + allow_task_preemption: Optional[bool] + constraints: Optional[BatchJobConstraints] + max_parallel_tasks: Optional[int] + metadata: Optional[list[BatchMetadataItem]] + network_configuration: Optional[BatchJobNetworkConfiguration] + pool_info: Optional[BatchPoolInfo] + priority: Optional[int] + + @overload + def __init__( + self, + *, + all_tasks_complete_mode: Optional[Union[str, BatchAllTasksCompleteMode]] = ..., + allow_task_preemption: Optional[bool] = ..., + constraints: Optional[BatchJobConstraints] = ..., + max_parallel_tasks: Optional[int] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + network_configuration: Optional[BatchJobNetworkConfiguration] = ..., + pool_info: Optional[BatchPoolInfo] = ..., + priority: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchMetadataItem(_Model): + name: str + value: str + + @overload + def __init__( + self, + *, + name: str, + value: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNode(_Model): + affinity_id: str + allocation_time: datetime + endpoint_configuration: Optional[BatchNodeEndpointConfiguration] + errors: Optional[list[BatchNodeError]] + id: str + ip_address: str + ipv6_address: str + is_dedicated: Optional[bool] + last_boot_time: datetime + node_agent_info: Optional[BatchNodeAgentInfo] + public_ip_address: Optional[str] + public_ipv6_address: Optional[str] + recent_tasks: Optional[list[BatchTaskInfo]] + running_task_slots_count: Optional[int] + running_tasks_count: Optional[int] + scheduling_state: Optional[Union[str, SchedulingState]] + start_task: Optional[BatchStartTask] + start_task_info: Optional[BatchStartTaskInfo] + state: Union[str, BatchNodeState] + state_transition_time: datetime + total_tasks_run: int + total_tasks_succeeded: Optional[int] + url: str + virtual_machine_info: VirtualMachineInfo + vm_size: str + + + class azure.batch.models.BatchNodeAgentInfo(_Model): + last_update_time: datetime + version: str + + @overload + def __init__( + self, + *, + last_update_time: datetime, + version: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeCounts(_Model): + creating: int + deallocated: int + deallocating: int + idle: int + leaving_pool: int + offline: int + preempted: int + rebooting: int + reimaging: int + running: int + start_task_failed: int + starting: int + total: int + unknown: int + unusable: int + upgrading_os: int + waiting_for_start_task: int + + @overload + def __init__( + self, + *, + creating: int, + deallocated: int, + deallocating: int, + idle: int, + leaving_pool: int, + offline: int, + preempted: int, + rebooting: int, + reimaging: int, + running: int, + start_task_failed: int, + starting: int, + total: int, + unknown: int, + unusable: int, + upgrading_os: int, + waiting_for_start_task: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeDeallocateOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REQUEUE = "requeue" + TASK_COMPLETION = "taskcompletion" + TERMINATE = "terminate" + + + class azure.batch.models.BatchNodeDeallocateOptions(_Model): + node_deallocate_option: Optional[Union[str, BatchNodeDeallocateOption]] + + @overload + def __init__( + self, + *, + node_deallocate_option: Optional[Union[str, BatchNodeDeallocateOption]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeDeallocationOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REQUEUE = "requeue" + TASK_COMPLETION = "taskcompletion" + TERMINATE = "terminate" + + + class azure.batch.models.BatchNodeDisableSchedulingOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REQUEUE = "requeue" + TASK_COMPLETION = "taskcompletion" + TERMINATE = "terminate" + + + class azure.batch.models.BatchNodeDisableSchedulingOptions(_Model): + node_disable_scheduling_option: Optional[Union[str, BatchNodeDisableSchedulingOption]] + + @overload + def __init__( + self, + *, + node_disable_scheduling_option: Optional[Union[str, BatchNodeDisableSchedulingOption]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeEndpointConfiguration(_Model): + inbound_endpoints: list[InboundEndpoint] + + @overload + def __init__( + self, + *, + inbound_endpoints: list[InboundEndpoint] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeError(_Model): + code: Optional[str] + error_details: Optional[list[NameValuePair]] + message: Optional[str] + + @overload + def __init__( + self, + *, + code: Optional[str] = ..., + error_details: Optional[list[NameValuePair]] = ..., + message: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeFile(_Model): + is_directory: Optional[bool] + name: Optional[str] + properties: Optional[FileProperties] + url: Optional[str] + + @overload + def __init__( + self, + *, + is_directory: Optional[bool] = ..., + name: Optional[str] = ..., + properties: Optional[FileProperties] = ..., + url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeFillType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + PACK = "pack" + SPREAD = "spread" + + + class azure.batch.models.BatchNodeIdentityReference(_Model): + resource_id: Optional[str] + + @overload + def __init__( + self, + *, + resource_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeInfo(_Model): + affinity_id: Optional[str] + node_id: Optional[str] + node_url: Optional[str] + pool_id: Optional[str] + task_root_directory: Optional[str] + task_root_directory_url: Optional[str] + + @overload + def __init__( + self, + *, + affinity_id: Optional[str] = ..., + node_id: Optional[str] = ..., + node_url: Optional[str] = ..., + pool_id: Optional[str] = ..., + task_root_directory: Optional[str] = ..., + task_root_directory_url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodePlacementConfiguration(_Model): + policy: Optional[Union[str, BatchNodePlacementPolicyType]] + + @overload + def __init__( + self, + *, + policy: Optional[Union[str, BatchNodePlacementPolicyType]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REGIONAL = "regional" + ZONAL = "zonal" + + + class azure.batch.models.BatchNodeRebootKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REQUEUE = "requeue" + TASK_COMPLETION = "taskcompletion" + TERMINATE = "terminate" + + + class azure.batch.models.BatchNodeRebootOptions(_Model): + node_reboot_kind: Optional[Union[str, BatchNodeRebootKind]] + + @overload + def __init__( + self, + *, + node_reboot_kind: Optional[Union[str, BatchNodeRebootKind]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeReimageOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REQUEUE = "requeue" + TASK_COMPLETION = "taskcompletion" + TERMINATE = "terminate" + + + class azure.batch.models.BatchNodeReimageOptions(_Model): + node_reimage_option: Optional[Union[str, BatchNodeReimageOption]] + + @overload + def __init__( + self, + *, + node_reimage_option: Optional[Union[str, BatchNodeReimageOption]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeRemoteLoginSettings(_Model): + ipv6_remote_login_ip_address: Optional[str] + ipv6_remote_login_port: Optional[int] + remote_login_ip_address: str + remote_login_port: int + + @overload + def __init__( + self, + *, + ipv6_remote_login_ip_address: Optional[str] = ..., + ipv6_remote_login_port: Optional[int] = ..., + remote_login_ip_address: str, + remote_login_port: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeRemoveOptions(_Model): + node_deallocation_option: Optional[Union[str, BatchNodeDeallocationOption]] + node_ids: list[str] + resize_timeout: Optional[timedelta] + + @overload + def __init__( + self, + *, + node_deallocation_option: Optional[Union[str, BatchNodeDeallocationOption]] = ..., + node_ids: list[str], + resize_timeout: Optional[timedelta] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CREATING = "creating" + DEALLOCATED = "deallocated" + DEALLOCATING = "deallocating" + IDLE = "idle" + LEAVING_POOL = "leavingpool" + OFFLINE = "offline" + PREEMPTED = "preempted" + REBOOTING = "rebooting" + REIMAGING = "reimaging" + RUNNING = "running" + STARTING = "starting" + START_TASK_FAILED = "starttaskfailed" + UNKNOWN = "unknown" + UNUSABLE = "unusable" + UPGRADING_OS = "upgradingos" + WAITING_FOR_START_TASK = "waitingforstarttask" + + + class azure.batch.models.BatchNodeUserCreateOptions(_Model): + expiry_time: Optional[datetime] + is_admin: Optional[bool] + name: str + password: Optional[str] + ssh_public_key: Optional[str] + + @overload + def __init__( + self, + *, + expiry_time: Optional[datetime] = ..., + is_admin: Optional[bool] = ..., + name: str, + password: Optional[str] = ..., + ssh_public_key: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeUserReplaceOptions(_Model): + expiry_time: Optional[datetime] + password: Optional[str] + ssh_public_key: Optional[str] + + @overload + def __init__( + self, + *, + expiry_time: Optional[datetime] = ..., + password: Optional[str] = ..., + ssh_public_key: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchNodeVMExtension(_Model): + instance_view: Optional[VMExtensionInstanceView] + provisioning_state: Optional[str] + vm_extension: Optional[VMExtension] + + @overload + def __init__( + self, + *, + instance_view: Optional[VMExtensionInstanceView] = ..., + provisioning_state: Optional[str] = ..., + vm_extension: Optional[VMExtension] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchOsDisk(_Model): + caching: Optional[Union[str, CachingType]] + disk_size_gb: Optional[int] + ephemeral_os_disk_settings: Optional[BatchDiffDiskSettings] + managed_disk: Optional[ManagedDisk] + write_accelerator_enabled: Optional[bool] + + @overload + def __init__( + self, + *, + caching: Optional[Union[str, CachingType]] = ..., + disk_size_gb: Optional[int] = ..., + ephemeral_os_disk_settings: Optional[BatchDiffDiskSettings] = ..., + managed_disk: Optional[ManagedDisk] = ..., + write_accelerator_enabled: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPool(_Model): + allocation_state: Optional[Union[str, AllocationState]] + allocation_state_transition_time: Optional[datetime] + application_package_references: Optional[list[BatchApplicationPackageReference]] + auto_scale_evaluation_interval: Optional[timedelta] + auto_scale_formula: Optional[str] + auto_scale_run: Optional[AutoScaleRun] + creation_time: datetime + current_dedicated_nodes: int + current_low_priority_nodes: int + display_name: Optional[str] + enable_auto_scale: Optional[bool] + enable_inter_node_communication: Optional[bool] + etag: str + id: str + identity: Optional[BatchPoolIdentity] + last_modified: datetime + metadata: Optional[list[BatchMetadataItem]] + mount_configuration: Optional[list[MountConfiguration]] + network_configuration: Optional[NetworkConfiguration] + pool_statistics: Optional[BatchPoolStatistics] + resize_errors: Optional[list[ResizeError]] + resize_timeout: Optional[timedelta] + start_task: Optional[BatchStartTask] + state: Union[str, BatchPoolState] + state_transition_time: datetime + target_dedicated_nodes: Optional[int] + target_low_priority_nodes: Optional[int] + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] + task_slots_per_node: Optional[int] + upgrade_policy: Optional[UpgradePolicy] + url: str + user_accounts: Optional[list[UserAccount]] + virtual_machine_configuration: Optional[VirtualMachineConfiguration] + vm_size: str + vm_sku_profile: Optional[VirtualMachineSkuProfile] + + @overload + def __init__( + self, + *, + start_task: Optional[BatchStartTask] = ..., + upgrade_policy: Optional[UpgradePolicy] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolCreateOptions(_Model): + application_package_references: Optional[list[BatchApplicationPackageReference]] + auto_scale_evaluation_interval: Optional[timedelta] + auto_scale_formula: Optional[str] + display_name: Optional[str] + enable_auto_scale: Optional[bool] + enable_inter_node_communication: Optional[bool] + id: str + metadata: Optional[list[BatchMetadataItem]] + mount_configuration: Optional[list[MountConfiguration]] + network_configuration: Optional[NetworkConfiguration] + resize_timeout: Optional[timedelta] + start_task: Optional[BatchStartTask] + target_dedicated_nodes: Optional[int] + target_low_priority_nodes: Optional[int] + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] + task_slots_per_node: Optional[int] + upgrade_policy: Optional[UpgradePolicy] + user_accounts: Optional[list[UserAccount]] + virtual_machine_configuration: Optional[VirtualMachineConfiguration] + vm_size: str + vm_sku_profile: Optional[VirtualMachineSkuProfile] + + @overload + def __init__( + self, + *, + application_package_references: Optional[list[BatchApplicationPackageReference]] = ..., + auto_scale_evaluation_interval: Optional[timedelta] = ..., + auto_scale_formula: Optional[str] = ..., + display_name: Optional[str] = ..., + enable_auto_scale: Optional[bool] = ..., + enable_inter_node_communication: Optional[bool] = ..., + id: str, + metadata: Optional[list[BatchMetadataItem]] = ..., + mount_configuration: Optional[list[MountConfiguration]] = ..., + network_configuration: Optional[NetworkConfiguration] = ..., + resize_timeout: Optional[timedelta] = ..., + start_task: Optional[BatchStartTask] = ..., + target_dedicated_nodes: Optional[int] = ..., + target_low_priority_nodes: Optional[int] = ..., + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] = ..., + task_slots_per_node: Optional[int] = ..., + upgrade_policy: Optional[UpgradePolicy] = ..., + user_accounts: Optional[list[UserAccount]] = ..., + virtual_machine_configuration: Optional[VirtualMachineConfiguration] = ..., + vm_size: str, + vm_sku_profile: Optional[VirtualMachineSkuProfile] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolEnableAutoScaleOptions(_Model): + auto_scale_evaluation_interval: Optional[timedelta] + auto_scale_formula: Optional[str] + + @overload + def __init__( + self, + *, + auto_scale_evaluation_interval: Optional[timedelta] = ..., + auto_scale_formula: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolEndpointConfiguration(_Model): + inbound_nat_pools: list[BatchInboundNatPool] + + @overload + def __init__( + self, + *, + inbound_nat_pools: list[BatchInboundNatPool] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolEvaluateAutoScaleOptions(_Model): + auto_scale_formula: str + + @overload + def __init__( + self, + *, + auto_scale_formula: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolIdentity(_Model): + type: Union[str, BatchPoolIdentityType] + user_assigned_identities: Optional[list[BatchUserAssignedIdentity]] + + @overload + def __init__( + self, + *, + type: Union[str, BatchPoolIdentityType], + user_assigned_identities: Optional[list[BatchUserAssignedIdentity]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolIdentityReference(_Model): + resource_id: Optional[str] + + @overload + def __init__( + self, + *, + resource_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + NONE = "None" + USER_ASSIGNED = "UserAssigned" + + + class azure.batch.models.BatchPoolInfo(_Model): + auto_pool_specification: Optional[BatchAutoPoolSpecification] + pool_id: Optional[str] + + @overload + def __init__( + self, + *, + auto_pool_specification: Optional[BatchAutoPoolSpecification] = ..., + pool_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolLifetimeOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + JOB = "job" + JOB_SCHEDULE = "jobschedule" + + + class azure.batch.models.BatchPoolNodeCounts(_Model): + dedicated: Optional[BatchNodeCounts] + low_priority: Optional[BatchNodeCounts] + pool_id: str + + @overload + def __init__( + self, + *, + dedicated: Optional[BatchNodeCounts] = ..., + low_priority: Optional[BatchNodeCounts] = ..., + pool_id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolReplaceOptions(_Model): + application_package_references: list[BatchApplicationPackageReference] + metadata: list[BatchMetadataItem] + start_task: Optional[BatchStartTask] + + @overload + def __init__( + self, + *, + application_package_references: list[BatchApplicationPackageReference], + metadata: list[BatchMetadataItem], + start_task: Optional[BatchStartTask] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolResizeOptions(_Model): + node_deallocation_option: Optional[Union[str, BatchNodeDeallocationOption]] + resize_timeout: Optional[timedelta] + target_dedicated_nodes: Optional[int] + target_low_priority_nodes: Optional[int] + + @overload + def __init__( + self, + *, + node_deallocation_option: Optional[Union[str, BatchNodeDeallocationOption]] = ..., + resize_timeout: Optional[timedelta] = ..., + target_dedicated_nodes: Optional[int] = ..., + target_low_priority_nodes: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolResourceStatistics(_Model): + avg_cpu_percentage: float + avg_disk_gib: float + avg_memory_gib: float + disk_read_gib: float + disk_read_iops: int + disk_write_gib: float + disk_write_iops: int + last_update_time: datetime + network_read_gib: float + network_write_gib: float + peak_disk_gib: float + peak_memory_gib: float + start_time: datetime + + @overload + def __init__( + self, + *, + avg_cpu_percentage: float, + avg_disk_gib: float, + avg_memory_gib: float, + disk_read_gib: float, + disk_read_iops: int, + disk_write_gib: float, + disk_write_iops: int, + last_update_time: datetime, + network_read_gib: float, + network_write_gib: float, + peak_disk_gib: float, + peak_memory_gib: float, + start_time: datetime + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolSpecification(_Model): + application_package_references: Optional[list[BatchApplicationPackageReference]] + auto_scale_evaluation_interval: Optional[timedelta] + auto_scale_formula: Optional[str] + display_name: Optional[str] + enable_auto_scale: Optional[bool] + enable_inter_node_communication: Optional[bool] + metadata: Optional[list[BatchMetadataItem]] + mount_configuration: Optional[list[MountConfiguration]] + network_configuration: Optional[NetworkConfiguration] + resize_timeout: Optional[timedelta] + start_task: Optional[BatchStartTask] + target_dedicated_nodes: Optional[int] + target_low_priority_nodes: Optional[int] + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] + task_slots_per_node: Optional[int] + upgrade_policy: Optional[UpgradePolicy] + user_accounts: Optional[list[UserAccount]] + virtual_machine_configuration: Optional[VirtualMachineConfiguration] + vm_size: str + + @overload + def __init__( + self, + *, + application_package_references: Optional[list[BatchApplicationPackageReference]] = ..., + auto_scale_evaluation_interval: Optional[timedelta] = ..., + auto_scale_formula: Optional[str] = ..., + display_name: Optional[str] = ..., + enable_auto_scale: Optional[bool] = ..., + enable_inter_node_communication: Optional[bool] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + mount_configuration: Optional[list[MountConfiguration]] = ..., + network_configuration: Optional[NetworkConfiguration] = ..., + resize_timeout: Optional[timedelta] = ..., + start_task: Optional[BatchStartTask] = ..., + target_dedicated_nodes: Optional[int] = ..., + target_low_priority_nodes: Optional[int] = ..., + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] = ..., + task_slots_per_node: Optional[int] = ..., + upgrade_policy: Optional[UpgradePolicy] = ..., + user_accounts: Optional[list[UserAccount]] = ..., + virtual_machine_configuration: Optional[VirtualMachineConfiguration] = ..., + vm_size: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACTIVE = "active" + DELETING = "deleting" + + + class azure.batch.models.BatchPoolStatistics(_Model): + last_update_time: datetime + resource_statistics: Optional[BatchPoolResourceStatistics] + start_time: datetime + url: str + + @overload + def __init__( + self, + *, + last_update_time: datetime, + resource_statistics: Optional[BatchPoolResourceStatistics] = ..., + start_time: datetime, + url: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPoolUpdateOptions(_Model): + application_package_references: Optional[list[BatchApplicationPackageReference]] + display_name: Optional[str] + enable_inter_node_communication: Optional[bool] + metadata: Optional[list[BatchMetadataItem]] + mount_configuration: Optional[list[MountConfiguration]] + network_configuration: Optional[NetworkConfiguration] + start_task: Optional[BatchStartTask] + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] + task_slots_per_node: Optional[int] + upgrade_policy: Optional[UpgradePolicy] + user_accounts: Optional[list[UserAccount]] + virtual_machine_configuration: Optional[VirtualMachineConfiguration] + vm_size: Optional[str] + vm_sku_profile: Optional[VirtualMachineSkuProfile] + + @overload + def __init__( + self, + *, + application_package_references: Optional[list[BatchApplicationPackageReference]] = ..., + display_name: Optional[str] = ..., + enable_inter_node_communication: Optional[bool] = ..., + metadata: Optional[list[BatchMetadataItem]] = ..., + mount_configuration: Optional[list[MountConfiguration]] = ..., + network_configuration: Optional[NetworkConfiguration] = ..., + start_task: Optional[BatchStartTask] = ..., + task_scheduling_policy: Optional[BatchTaskSchedulingPolicy] = ..., + task_slots_per_node: Optional[int] = ..., + upgrade_policy: Optional[UpgradePolicy] = ..., + user_accounts: Optional[list[UserAccount]] = ..., + virtual_machine_configuration: Optional[VirtualMachineConfiguration] = ..., + vm_size: Optional[str] = ..., + vm_sku_profile: Optional[VirtualMachineSkuProfile] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchPublicIpAddressConfiguration(_Model): + ip_address_ids: Optional[list[str]] + ip_address_provisioning_type: Optional[Union[str, IpAddressProvisioningType]] + ip_families: Optional[list[Union[str, IPFamily]]] + ip_tags: Optional[list[IPTag]] + + @overload + def __init__( + self, + *, + ip_address_ids: Optional[list[str]] = ..., + ip_address_provisioning_type: Optional[Union[str, IpAddressProvisioningType]] = ..., + ip_families: Optional[list[Union[str, IPFamily]]] = ..., + ip_tags: Optional[list[IPTag]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchStartTask(_Model): + command_line: str + container_settings: Optional[BatchTaskContainerSettings] + environment_settings: Optional[list[EnvironmentSetting]] + max_task_retry_count: Optional[int] + resource_files: Optional[list[ResourceFile]] + user_identity: Optional[UserIdentity] + wait_for_success: Optional[bool] + + @overload + def __init__( + self, + *, + command_line: str, + container_settings: Optional[BatchTaskContainerSettings] = ..., + environment_settings: Optional[list[EnvironmentSetting]] = ..., + max_task_retry_count: Optional[int] = ..., + resource_files: Optional[list[ResourceFile]] = ..., + user_identity: Optional[UserIdentity] = ..., + wait_for_success: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchStartTaskInfo(_Model): + container_info: Optional[BatchTaskContainerExecutionInfo] + end_time: Optional[datetime] + exit_code: Optional[int] + failure_info: Optional[BatchTaskFailureInfo] + last_retry_time: Optional[datetime] + result: Optional[Union[str, BatchTaskExecutionResult]] + retry_count: int + start_time: datetime + state: Union[str, BatchStartTaskState] + + @overload + def __init__( + self, + *, + container_info: Optional[BatchTaskContainerExecutionInfo] = ..., + end_time: Optional[datetime] = ..., + exit_code: Optional[int] = ..., + failure_info: Optional[BatchTaskFailureInfo] = ..., + last_retry_time: Optional[datetime] = ..., + result: Optional[Union[str, BatchTaskExecutionResult]] = ..., + retry_count: int, + start_time: datetime, + state: Union[str, BatchStartTaskState] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchStartTaskState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + COMPLETED = "completed" + RUNNING = "running" + + + class azure.batch.models.BatchSubtask(_Model): + container_info: Optional[BatchTaskContainerExecutionInfo] + end_time: Optional[datetime] + exit_code: Optional[int] + failure_info: Optional[BatchTaskFailureInfo] + id: Optional[int] + node_info: Optional[BatchNodeInfo] + previous_state: Optional[Union[str, BatchSubtaskState]] + previous_state_transition_time: Optional[datetime] + result: Optional[Union[str, BatchTaskExecutionResult]] + start_time: Optional[datetime] + state: Optional[Union[str, BatchSubtaskState]] + state_transition_time: Optional[datetime] + + @overload + def __init__( + self, + *, + container_info: Optional[BatchTaskContainerExecutionInfo] = ..., + end_time: Optional[datetime] = ..., + exit_code: Optional[int] = ..., + failure_info: Optional[BatchTaskFailureInfo] = ..., + id: Optional[int] = ..., + node_info: Optional[BatchNodeInfo] = ..., + previous_state: Optional[Union[str, BatchSubtaskState]] = ..., + previous_state_transition_time: Optional[datetime] = ..., + result: Optional[Union[str, BatchTaskExecutionResult]] = ..., + start_time: Optional[datetime] = ..., + state: Optional[Union[str, BatchSubtaskState]] = ..., + state_transition_time: Optional[datetime] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchSubtaskState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + COMPLETED = "completed" + PREPARING = "preparing" + RUNNING = "running" + + + class azure.batch.models.BatchSupportedImage(_Model): + batch_support_end_of_life: Optional[datetime] + capabilities: Optional[list[str]] + image_reference: BatchVmImageReference + node_agent_sku_id: str + os_type: Union[str, OSType] + verification_type: Union[str, ImageVerificationType] + + @overload + def __init__( + self, + *, + batch_support_end_of_life: Optional[datetime] = ..., + capabilities: Optional[list[str]] = ..., + image_reference: BatchVmImageReference, + node_agent_sku_id: str, + os_type: Union[str, OSType], + verification_type: Union[str, ImageVerificationType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTask(_Model): + affinity_info: Optional[BatchAffinityInfo] + application_package_references: Optional[list[BatchApplicationPackageReference]] + command_line: str + constraints: Optional[BatchTaskConstraints] + container_settings: Optional[BatchTaskContainerSettings] + creation_time: datetime + depends_on: Optional[BatchTaskDependencies] + display_name: Optional[str] + environment_settings: Optional[list[EnvironmentSetting]] + etag: str + execution_info: Optional[BatchTaskExecutionInfo] + exit_conditions: Optional[ExitConditions] + id: str + last_modified: datetime + multi_instance_settings: Optional[MultiInstanceSettings] + node_info: Optional[BatchNodeInfo] + output_files: Optional[list[OutputFile]] + previous_state: Optional[Union[str, BatchTaskState]] + previous_state_transition_time: Optional[datetime] + required_slots: Optional[int] + resource_files: Optional[list[ResourceFile]] + state: Union[str, BatchTaskState] + state_transition_time: datetime + task_statistics: Optional[BatchTaskStatistics] + url: str + user_identity: Optional[UserIdentity] + + @overload + def __init__( + self, + *, + constraints: Optional[BatchTaskConstraints] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskAddStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CLIENT_ERROR = "clienterror" + SERVER_ERROR = "servererror" + SUCCESS = "success" + + + class azure.batch.models.BatchTaskConstraints(_Model): + max_task_retry_count: Optional[int] + max_wall_clock_time: Optional[timedelta] + retention_time: Optional[timedelta] + + @overload + def __init__( + self, + *, + max_task_retry_count: Optional[int] = ..., + max_wall_clock_time: Optional[timedelta] = ..., + retention_time: Optional[timedelta] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskContainerExecutionInfo(_Model): + container_id: Optional[str] + error: Optional[str] + state: Optional[str] + + @overload + def __init__( + self, + *, + container_id: Optional[str] = ..., + error: Optional[str] = ..., + state: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskContainerSettings(_Model): + container_host_batch_bind_mounts: Optional[list[ContainerHostBatchBindMountEntry]] + container_run_options: Optional[str] + image_name: str + registry: Optional[ContainerRegistryReference] + working_directory: Optional[Union[str, ContainerWorkingDirectory]] + + @overload + def __init__( + self, + *, + container_host_batch_bind_mounts: Optional[list[ContainerHostBatchBindMountEntry]] = ..., + container_run_options: Optional[str] = ..., + image_name: str, + registry: Optional[ContainerRegistryReference] = ..., + working_directory: Optional[Union[str, ContainerWorkingDirectory]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskCounts(_Model): + active: int + completed: int + failed: int + running: int + succeeded: int + + @overload + def __init__( + self, + *, + active: int, + completed: int, + failed: int, + running: int, + succeeded: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskCountsResult(_Model): + task_counts: BatchTaskCounts + task_slot_counts: BatchTaskSlotCounts + + @overload + def __init__( + self, + *, + task_counts: BatchTaskCounts, + task_slot_counts: BatchTaskSlotCounts + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskCreateOptions(_Model): + affinity_info: Optional[BatchAffinityInfo] + application_package_references: Optional[list[BatchApplicationPackageReference]] + command_line: str + constraints: Optional[BatchTaskConstraints] + container_settings: Optional[BatchTaskContainerSettings] + depends_on: Optional[BatchTaskDependencies] + display_name: Optional[str] + environment_settings: Optional[list[EnvironmentSetting]] + exit_conditions: Optional[ExitConditions] + id: str + multi_instance_settings: Optional[MultiInstanceSettings] + output_files: Optional[list[OutputFile]] + required_slots: Optional[int] + resource_files: Optional[list[ResourceFile]] + user_identity: Optional[UserIdentity] + + @overload + def __init__( + self, + *, + affinity_info: Optional[BatchAffinityInfo] = ..., + application_package_references: Optional[list[BatchApplicationPackageReference]] = ..., + command_line: str, + constraints: Optional[BatchTaskConstraints] = ..., + container_settings: Optional[BatchTaskContainerSettings] = ..., + depends_on: Optional[BatchTaskDependencies] = ..., + display_name: Optional[str] = ..., + environment_settings: Optional[list[EnvironmentSetting]] = ..., + exit_conditions: Optional[ExitConditions] = ..., + id: str, + multi_instance_settings: Optional[MultiInstanceSettings] = ..., + output_files: Optional[list[OutputFile]] = ..., + required_slots: Optional[int] = ..., + resource_files: Optional[list[ResourceFile]] = ..., + user_identity: Optional[UserIdentity] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskCreateResult(_Model): + error: Optional[BatchError] + etag: Optional[str] + last_modified: Optional[datetime] + location: Optional[str] + status: Union[str, BatchTaskAddStatus] + task_id: str + + @overload + def __init__( + self, + *, + error: Optional[BatchError] = ..., + etag: Optional[str] = ..., + last_modified: Optional[datetime] = ..., + location: Optional[str] = ..., + status: Union[str, BatchTaskAddStatus], + task_id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskDependencies(_Model): + task_id_ranges: Optional[list[BatchTaskIdRange]] + task_ids: Optional[list[str]] + + @overload + def __init__( + self, + *, + task_id_ranges: Optional[list[BatchTaskIdRange]] = ..., + task_ids: Optional[list[str]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskExecutionInfo(_Model): + container_info: Optional[BatchTaskContainerExecutionInfo] + end_time: Optional[datetime] + exit_code: Optional[int] + failure_info: Optional[BatchTaskFailureInfo] + last_requeue_time: Optional[datetime] + last_retry_time: Optional[datetime] + requeue_count: int + result: Optional[Union[str, BatchTaskExecutionResult]] + retry_count: int + start_time: Optional[datetime] + + @overload + def __init__( + self, + *, + container_info: Optional[BatchTaskContainerExecutionInfo] = ..., + end_time: Optional[datetime] = ..., + exit_code: Optional[int] = ..., + failure_info: Optional[BatchTaskFailureInfo] = ..., + last_requeue_time: Optional[datetime] = ..., + last_retry_time: Optional[datetime] = ..., + requeue_count: int, + result: Optional[Union[str, BatchTaskExecutionResult]] = ..., + retry_count: int, + start_time: Optional[datetime] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskExecutionResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + FAILURE = "failure" + SUCCESS = "success" + + + class azure.batch.models.BatchTaskFailureInfo(_Model): + category: Union[str, BatchErrorSourceCategory] + code: Optional[str] + details: Optional[list[NameValuePair]] + message: Optional[str] + + @overload + def __init__( + self, + *, + category: Union[str, BatchErrorSourceCategory], + code: Optional[str] = ..., + details: Optional[list[NameValuePair]] = ..., + message: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskFailureMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + NO_ACTION = "noaction" + PERFORM_EXIT_OPTIONS_JOB_ACTION = "performexitoptionsjobaction" + + + class azure.batch.models.BatchTaskGroup(_Model): + task_values: list[BatchTaskCreateOptions] + + @overload + def __init__( + self, + *, + task_values: list[BatchTaskCreateOptions] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskIdRange(_Model): + end: int + start: int + + @overload + def __init__( + self, + *, + end: int, + start: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskInfo(_Model): + execution_info: Optional[BatchTaskExecutionInfo] + job_id: Optional[str] + subtask_id: Optional[int] + task_id: Optional[str] + task_state: Union[str, BatchTaskState] + task_url: Optional[str] + + @overload + def __init__( + self, + *, + execution_info: Optional[BatchTaskExecutionInfo] = ..., + job_id: Optional[str] = ..., + subtask_id: Optional[int] = ..., + task_id: Optional[str] = ..., + task_state: Union[str, BatchTaskState], + task_url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskSchedulingPolicy(_Model): + job_default_order: Optional[Union[str, BatchJobDefaultOrder]] + node_fill_type: Union[str, BatchNodeFillType] + + @overload + def __init__( + self, + *, + job_default_order: Optional[Union[str, BatchJobDefaultOrder]] = ..., + node_fill_type: Union[str, BatchNodeFillType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskSlotCounts(_Model): + active: int + completed: int + failed: int + running: int + succeeded: int + + @overload + def __init__( + self, + *, + active: int, + completed: int, + failed: int, + running: int, + succeeded: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchTaskState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACTIVE = "active" + COMPLETED = "completed" + PREPARING = "preparing" + RUNNING = "running" + + + class azure.batch.models.BatchTaskStatistics(_Model): + kernel_cpu_time: timedelta + last_update_time: datetime + read_io_gib: float + read_iops: int + start_time: datetime + url: str + user_cpu_time: timedelta + wait_time: timedelta + wall_clock_time: timedelta + write_io_gib: float + write_iops: int + + @overload + def __init__( + self, + *, + kernel_cpu_time: timedelta, + last_update_time: datetime, + read_io_gib: float, + read_iops: int, + start_time: datetime, + url: str, + user_cpu_time: timedelta, + wait_time: timedelta, + wall_clock_time: timedelta, + write_io_gib: float, + write_iops: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchUefiSettings(_Model): + secure_boot_enabled: Optional[bool] + vtpm_enabled: Optional[bool] + + @overload + def __init__( + self, + *, + secure_boot_enabled: Optional[bool] = ..., + vtpm_enabled: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchUserAssignedIdentity(_Model): + client_id: Optional[str] + principal_id: Optional[str] + resource_id: str + + @overload + def __init__( + self, + *, + resource_id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchVmDiskSecurityProfile(_Model): + security_encryption_type: Optional[Union[str, SecurityEncryptionTypes]] + + @overload + def __init__( + self, + *, + security_encryption_type: Optional[Union[str, SecurityEncryptionTypes]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.BatchVmImageReference(_Model): + community_gallery_image_id: Optional[str] + exact_version: Optional[str] + offer: Optional[str] + publisher: Optional[str] + shared_gallery_image_id: Optional[str] + sku: Optional[str] + version: Optional[str] + virtual_machine_image_id: Optional[str] + + @overload + def __init__( + self, + *, + community_gallery_image_id: Optional[str] = ..., + offer: Optional[str] = ..., + publisher: Optional[str] = ..., + shared_gallery_image_id: Optional[str] = ..., + sku: Optional[str] = ..., + version: Optional[str] = ..., + virtual_machine_image_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.CachingType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + NONE = "none" + READ_ONLY = "readonly" + READ_WRITE = "readwrite" + + + class azure.batch.models.CifsMountConfiguration(_Model): + mount_options: Optional[str] + password: str + relative_mount_path: str + source: str + username: str + + @overload + def __init__( + self, + *, + mount_options: Optional[str] = ..., + password: str, + relative_mount_path: str, + source: str, + username: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ContainerHostBatchBindMountEntry(_Model): + is_read_only: Optional[bool] + source: Optional[Union[str, ContainerHostDataPath]] + + @overload + def __init__( + self, + *, + is_read_only: Optional[bool] = ..., + source: Optional[Union[str, ContainerHostDataPath]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ContainerHostDataPath(str, Enum, metaclass=CaseInsensitiveEnumMeta): + APPLICATIONS = "Applications" + JOB_PREP = "JobPrep" + SHARED = "Shared" + STARTUP = "Startup" + TASK = "Task" + VFS_MOUNTS = "VfsMounts" + + + class azure.batch.models.ContainerRegistryReference(_Model): + identity_reference: Optional[BatchNodeIdentityReference] + password: Optional[str] + registry_server: Optional[str] + username: Optional[str] + + @overload + def __init__( + self, + *, + identity_reference: Optional[BatchNodeIdentityReference] = ..., + password: Optional[str] = ..., + registry_server: Optional[str] = ..., + username: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ContainerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CRI_COMPATIBLE = "criCompatible" + DOCKER_COMPATIBLE = "dockerCompatible" + + + class azure.batch.models.ContainerWorkingDirectory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CONTAINER_IMAGE_DEFAULT = "containerImageDefault" + TASK_WORKING_DIRECTORY = "taskWorkingDirectory" + + + class azure.batch.models.DataDisk(_Model): + caching: Optional[Union[str, CachingType]] + disk_size_gb: int + logical_unit_number: int + managed_disk: Optional[ManagedDisk] + + @overload + def __init__( + self, + *, + caching: Optional[Union[str, CachingType]] = ..., + disk_size_gb: int, + logical_unit_number: int, + managed_disk: Optional[ManagedDisk] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.DependencyAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): + BLOCK = "block" + SATISFY = "satisfy" + + + class azure.batch.models.DiffDiskPlacement(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CACHE_DISK = "cachedisk" + + + class azure.batch.models.DisableBatchJobOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): + REQUEUE = "requeue" + TERMINATE = "terminate" + WAIT = "wait" + + + class azure.batch.models.DiskCustomerManagedKey(_Model): + identity_reference: Optional[BatchPoolIdentityReference] + key_url: Optional[str] + rotation_to_latest_key_version_enabled: Optional[bool] + + @overload + def __init__( + self, + *, + identity_reference: Optional[BatchPoolIdentityReference] = ..., + key_url: Optional[str] = ..., + rotation_to_latest_key_version_enabled: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.DiskEncryptionConfiguration(_Model): + customer_managed_key: Optional[DiskCustomerManagedKey] + targets: Optional[list[Union[str, DiskEncryptionTarget]]] + + @overload + def __init__( + self, + *, + customer_managed_key: Optional[DiskCustomerManagedKey] = ..., + targets: Optional[list[Union[str, DiskEncryptionTarget]]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.DiskEncryptionSetParameters(_Model): + id: Optional[str] + + @overload + def __init__( + self, + *, + id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.DiskEncryptionTarget(str, Enum, metaclass=CaseInsensitiveEnumMeta): + OS_DISK = "osdisk" + TEMPORARY_DISK = "temporarydisk" + + + class azure.batch.models.DynamicVNetAssignmentScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + JOB = "job" + NONE = "none" + + + class azure.batch.models.ElevationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ADMIN = "admin" + NON_ADMIN = "nonadmin" + + + class azure.batch.models.EnvironmentSetting(_Model): + name: str + value: Optional[str] + + @overload + def __init__( + self, + *, + name: str, + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ExitCodeMapping(_Model): + code: int + exit_options: ExitOptions + + @overload + def __init__( + self, + *, + code: int, + exit_options: ExitOptions + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ExitCodeRangeMapping(_Model): + end: int + exit_options: ExitOptions + start: int + + @overload + def __init__( + self, + *, + end: int, + exit_options: ExitOptions, + start: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ExitConditions(_Model): + default: Optional[ExitOptions] + exit_code_ranges: Optional[list[ExitCodeRangeMapping]] + exit_codes: Optional[list[ExitCodeMapping]] + file_upload_error: Optional[ExitOptions] + pre_processing_error: Optional[ExitOptions] + + @overload + def __init__( + self, + *, + default: Optional[ExitOptions] = ..., + exit_code_ranges: Optional[list[ExitCodeRangeMapping]] = ..., + exit_codes: Optional[list[ExitCodeMapping]] = ..., + file_upload_error: Optional[ExitOptions] = ..., + pre_processing_error: Optional[ExitOptions] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ExitOptions(_Model): + dependency_action: Optional[Union[str, DependencyAction]] + job_action: Optional[Union[str, BatchJobActionKind]] + + @overload + def __init__( + self, + *, + dependency_action: Optional[Union[str, DependencyAction]] = ..., + job_action: Optional[Union[str, BatchJobActionKind]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.FileProperties(_Model): + content_length: int + content_type: Optional[str] + creation_time: Optional[datetime] + file_mode: Optional[str] + last_modified: datetime + + @overload + def __init__( + self, + *, + content_length: int, + content_type: Optional[str] = ..., + creation_time: Optional[datetime] = ..., + file_mode: Optional[str] = ..., + last_modified: datetime + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.HardwareProfile(_Model): + vm_size_properties: Optional[VMSizeProperties] + + @overload + def __init__( + self, + *, + vm_size_properties: Optional[VMSizeProperties] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.HostEndpointSettings(_Model): + in_vm_access_control_profile_reference_id: Optional[str] + mode: Optional[Union[str, HostEndpointSettingsModeTypes]] + + @overload + def __init__( + self, + *, + in_vm_access_control_profile_reference_id: Optional[str] = ..., + mode: Optional[Union[str, HostEndpointSettingsModeTypes]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.HostEndpointSettingsModeTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + AUDIT = "Audit" + ENFORCE = "Enforce" + + + class azure.batch.models.IPFamily(str, Enum, metaclass=CaseInsensitiveEnumMeta): + IPV4 = "IPv4" + IPV6 = "IPv6" + + + class azure.batch.models.IPTag(_Model): + ip_tag_type: Optional[str] + tag: Optional[str] + + @overload + def __init__( + self, + *, + ip_tag_type: Optional[str] = ..., + tag: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ImageVerificationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + UNVERIFIED = "unverified" + VERIFIED = "verified" + + + class azure.batch.models.InboundEndpoint(_Model): + backend_port: int + frontend_port: int + name: str + protocol: Union[str, InboundEndpointProtocol] + public_fqdn: str + public_ip_address: str + + @overload + def __init__( + self, + *, + backend_port: int, + frontend_port: int, + name: str, + protocol: Union[str, InboundEndpointProtocol], + public_fqdn: str, + public_ip_address: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.InboundEndpointProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + TCP = "tcp" + UDP = "udp" + + + class azure.batch.models.InstanceViewStatus(_Model): + code: Optional[str] + display_status: Optional[str] + level: Optional[Union[str, StatusLevelTypes]] + message: Optional[str] + time: Optional[datetime] + + @overload + def __init__( + self, + *, + code: Optional[str] = ..., + display_status: Optional[str] = ..., + level: Optional[Union[str, StatusLevelTypes]] = ..., + message: Optional[str] = ..., + time: Optional[datetime] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.IpAddressProvisioningType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + BATCH_MANAGED = "batchmanaged" + NO_PUBLIC_IP_ADDRESSES = "nopublicipaddresses" + USER_MANAGED = "usermanaged" + + + class azure.batch.models.LinuxUserConfiguration(_Model): + gid: Optional[int] + ssh_private_key: Optional[str] + uid: Optional[int] + + @overload + def __init__( + self, + *, + gid: Optional[int] = ..., + ssh_private_key: Optional[str] = ..., + uid: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.LoginMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + BATCH = "batch" + INTERACTIVE = "interactive" + + + class azure.batch.models.ManagedDisk(_Model): + disk_encryption_set: Optional[DiskEncryptionSetParameters] + security_profile: Optional[BatchVmDiskSecurityProfile] + storage_account_type: Optional[Union[str, StorageAccountType]] + + @overload + def __init__( + self, + *, + disk_encryption_set: Optional[DiskEncryptionSetParameters] = ..., + security_profile: Optional[BatchVmDiskSecurityProfile] = ..., + storage_account_type: Optional[Union[str, StorageAccountType]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.MaxInstancePercentPerZonePolicy(_Model): + enabled: Optional[bool] + value: int + + @overload + def __init__( + self, + *, + enabled: Optional[bool] = ..., + value: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.MountConfiguration(_Model): + azure_blob_file_system_configuration: Optional[AzureBlobFileSystemConfiguration] + azure_file_share_configuration: Optional[AzureFileShareConfiguration] + cifs_mount_configuration: Optional[CifsMountConfiguration] + nfs_mount_configuration: Optional[NfsMountConfiguration] + + @overload + def __init__( + self, + *, + azure_blob_file_system_configuration: Optional[AzureBlobFileSystemConfiguration] = ..., + azure_file_share_configuration: Optional[AzureFileShareConfiguration] = ..., + cifs_mount_configuration: Optional[CifsMountConfiguration] = ..., + nfs_mount_configuration: Optional[NfsMountConfiguration] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.MultiInstanceSettings(_Model): + common_resource_files: Optional[list[ResourceFile]] + coordination_command_line: str + number_of_instances: Optional[int] + + @overload + def __init__( + self, + *, + common_resource_files: Optional[list[ResourceFile]] = ..., + coordination_command_line: str, + number_of_instances: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.NameValuePair(_Model): + name: Optional[str] + value: Optional[str] + + @overload + def __init__( + self, + *, + name: Optional[str] = ..., + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.NetworkConfiguration(_Model): + dynamic_vnet_assignment_scope: Optional[Union[str, DynamicVNetAssignmentScope]] + enable_accelerated_networking: Optional[bool] + endpoint_configuration: Optional[BatchPoolEndpointConfiguration] + public_ip_address_configuration: Optional[BatchPublicIpAddressConfiguration] + subnet_id: Optional[str] + + @overload + def __init__( + self, + *, + dynamic_vnet_assignment_scope: Optional[Union[str, DynamicVNetAssignmentScope]] = ..., + enable_accelerated_networking: Optional[bool] = ..., + endpoint_configuration: Optional[BatchPoolEndpointConfiguration] = ..., + public_ip_address_configuration: Optional[BatchPublicIpAddressConfiguration] = ..., + subnet_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.NetworkSecurityGroupRule(_Model): + access: Union[str, NetworkSecurityGroupRuleAccess] + priority: int + source_address_prefix: str + source_port_ranges: Optional[list[str]] + + @overload + def __init__( + self, + *, + access: Union[str, NetworkSecurityGroupRuleAccess], + priority: int, + source_address_prefix: str, + source_port_ranges: Optional[list[str]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.NetworkSecurityGroupRuleAccess(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ALLOW = "allow" + DENY = "deny" + + + class azure.batch.models.NfsMountConfiguration(_Model): + mount_options: Optional[str] + relative_mount_path: str + source: str + + @overload + def __init__( + self, + *, + mount_options: Optional[str] = ..., + relative_mount_path: str, + source: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.OSType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + LINUX = "linux" + WINDOWS = "windows" + + + class azure.batch.models.OutputFile(_Model): + destination: OutputFileDestination + file_pattern: str + upload_options: OutputFileUploadConfiguration + + @overload + def __init__( + self, + *, + destination: OutputFileDestination, + file_pattern: str, + upload_options: OutputFileUploadConfiguration + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.OutputFileBlobContainerDestination(_Model): + container_url: str + identity_reference: Optional[BatchNodeIdentityReference] + path: Optional[str] + upload_headers: Optional[list[OutputFileUploadHeader]] + + @overload + def __init__( + self, + *, + container_url: str, + identity_reference: Optional[BatchNodeIdentityReference] = ..., + path: Optional[str] = ..., + upload_headers: Optional[list[OutputFileUploadHeader]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.OutputFileDestination(_Model): + container: Optional[OutputFileBlobContainerDestination] + + @overload + def __init__( + self, + *, + container: Optional[OutputFileBlobContainerDestination] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.OutputFileUploadCondition(str, Enum, metaclass=CaseInsensitiveEnumMeta): + TASK_COMPLETION = "taskcompletion" + TASK_FAILURE = "taskfailure" + TASK_SUCCESS = "tasksuccess" + + + class azure.batch.models.OutputFileUploadConfiguration(_Model): + upload_condition: Union[str, OutputFileUploadCondition] + + @overload + def __init__( + self, + *, + upload_condition: Union[str, OutputFileUploadCondition] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.OutputFileUploadHeader(_Model): + name: str + value: Optional[str] + + @overload + def __init__( + self, + *, + name: str, + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.Placement(_Model): + zone_placement_policy: Union[str, ZonePlacementPolicyType] + + @overload + def __init__( + self, + *, + zone_placement_policy: Union[str, ZonePlacementPolicyType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ProxyAgentSettings(_Model): + enabled: Optional[bool] + imds: Optional[HostEndpointSettings] + wire_server: Optional[HostEndpointSettings] + + @overload + def __init__( + self, + *, + enabled: Optional[bool] = ..., + imds: Optional[HostEndpointSettings] = ..., + wire_server: Optional[HostEndpointSettings] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.RecentBatchJob(_Model): + id: Optional[str] + url: Optional[str] + + @overload + def __init__( + self, + *, + id: Optional[str] = ..., + url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ResiliencyPolicy(_Model): + zone_allocation_policy: ZoneAllocationPolicy + + @overload + def __init__( + self, + *, + zone_allocation_policy: ZoneAllocationPolicy + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ResizeError(_Model): + code: Optional[str] + error_values: Optional[list[NameValuePair]] + message: Optional[str] + + @overload + def __init__( + self, + *, + code: Optional[str] = ..., + error_values: Optional[list[NameValuePair]] = ..., + message: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ResourceFile(_Model): + auto_storage_container_name: Optional[str] + blob_prefix: Optional[str] + file_mode: Optional[str] + file_path: Optional[str] + http_url: Optional[str] + identity_reference: Optional[BatchNodeIdentityReference] + storage_container_url: Optional[str] + + @overload + def __init__( + self, + *, + auto_storage_container_name: Optional[str] = ..., + blob_prefix: Optional[str] = ..., + file_mode: Optional[str] = ..., + file_path: Optional[str] = ..., + http_url: Optional[str] = ..., + identity_reference: Optional[BatchNodeIdentityReference] = ..., + storage_container_url: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.RollingUpgradePolicy(_Model): + enable_cross_zone_upgrade: Optional[bool] + max_batch_instance_percent: Optional[int] + max_unhealthy_instance_percent: Optional[int] + max_unhealthy_upgraded_instance_percent: Optional[int] + pause_time_between_batches: Optional[timedelta] + prioritize_unhealthy_instances: Optional[bool] + rollback_failed_instances_on_policy_breach: Optional[bool] + + @overload + def __init__( + self, + *, + enable_cross_zone_upgrade: Optional[bool] = ..., + max_batch_instance_percent: Optional[int] = ..., + max_unhealthy_instance_percent: Optional[int] = ..., + max_unhealthy_upgraded_instance_percent: Optional[int] = ..., + pause_time_between_batches: Optional[timedelta] = ..., + prioritize_unhealthy_instances: Optional[bool] = ..., + rollback_failed_instances_on_policy_breach: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.SchedulingState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + DISABLED = "disabled" + ENABLED = "enabled" + + + class azure.batch.models.SecurityEncryptionTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + DISK_WITH_VM_GUEST_STATE = "DiskWithVMGuestState" + NON_PERSISTED_TPM = "NonPersistedTPM" + VM_GUEST_STATE_ONLY = "VMGuestStateOnly" + + + class azure.batch.models.SecurityProfile(_Model): + encryption_at_host: Optional[bool] + proxy_agent_settings: Optional[ProxyAgentSettings] + security_type: Optional[Union[str, SecurityTypes]] + uefi_settings: Optional[BatchUefiSettings] + + @overload + def __init__( + self, + *, + encryption_at_host: Optional[bool] = ..., + proxy_agent_settings: Optional[ProxyAgentSettings] = ..., + security_type: Optional[Union[str, SecurityTypes]] = ..., + uefi_settings: Optional[BatchUefiSettings] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.SecurityTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CONFIDENTIAL_VM = "confidentialvm" + TRUSTED_LAUNCH = "trustedLaunch" + + + class azure.batch.models.ServiceArtifactReference(_Model): + id: str + + @overload + def __init__( + self, + *, + id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.StatusLevelTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ERROR = "Error" + INFO = "Info" + WARNING = "Warning" + + + class azure.batch.models.StorageAccountType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + PREMIUM_LRS = "premium_lrs" + STANDARD_LRS = "standard_lrs" + STANDARD_SSDLRS = "standardssd_lrs" + + + class azure.batch.models.UpgradeMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + AUTOMATIC = "automatic" + MANUAL = "manual" + ROLLING = "rolling" + + + class azure.batch.models.UpgradePolicy(_Model): + automatic_os_upgrade_policy: Optional[AutomaticOsUpgradePolicy] + mode: Union[str, UpgradeMode] + rolling_upgrade_policy: Optional[RollingUpgradePolicy] + + @overload + def __init__( + self, + *, + automatic_os_upgrade_policy: Optional[AutomaticOsUpgradePolicy] = ..., + mode: Union[str, UpgradeMode], + rolling_upgrade_policy: Optional[RollingUpgradePolicy] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.UploadBatchServiceLogsOptions(_Model): + container_url: str + end_time: Optional[datetime] + identity_reference: Optional[BatchNodeIdentityReference] + start_time: datetime + + @overload + def __init__( + self, + *, + container_url: str, + end_time: Optional[datetime] = ..., + identity_reference: Optional[BatchNodeIdentityReference] = ..., + start_time: datetime + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.UploadBatchServiceLogsResult(_Model): + number_of_files_uploaded: int + virtual_directory_name: str + + @overload + def __init__( + self, + *, + number_of_files_uploaded: int, + virtual_directory_name: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.UserAccount(_Model): + elevation_level: Optional[Union[str, ElevationLevel]] + linux_user_configuration: Optional[LinuxUserConfiguration] + name: str + password: str + windows_user_configuration: Optional[WindowsUserConfiguration] + + @overload + def __init__( + self, + *, + elevation_level: Optional[Union[str, ElevationLevel]] = ..., + linux_user_configuration: Optional[LinuxUserConfiguration] = ..., + name: str, + password: str, + windows_user_configuration: Optional[WindowsUserConfiguration] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.UserIdentity(_Model): + auto_user: Optional[AutoUserSpecification] + username: Optional[str] + + @overload + def __init__( + self, + *, + auto_user: Optional[AutoUserSpecification] = ..., + username: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VMExtension(_Model): + auto_upgrade_minor_version: Optional[bool] + enable_automatic_upgrade: Optional[bool] + name: str + protected_settings: Optional[dict[str, str]] + provision_after_extensions: Optional[list[str]] + publisher: str + settings: Optional[dict[str, str]] + type: str + type_handler_version: Optional[str] + + @overload + def __init__( + self, + *, + auto_upgrade_minor_version: Optional[bool] = ..., + enable_automatic_upgrade: Optional[bool] = ..., + name: str, + protected_settings: Optional[dict[str, str]] = ..., + provision_after_extensions: Optional[list[str]] = ..., + publisher: str, + settings: Optional[dict[str, str]] = ..., + type: str, + type_handler_version: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VMExtensionInstanceView(_Model): + name: Optional[str] + statuses: Optional[list[InstanceViewStatus]] + sub_statuses: Optional[list[InstanceViewStatus]] + + @overload + def __init__( + self, + *, + name: Optional[str] = ..., + statuses: Optional[list[InstanceViewStatus]] = ..., + sub_statuses: Optional[list[InstanceViewStatus]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VMSizeProperties(_Model): + v_cpus_available: Optional[int] + v_cpus_per_core: Optional[int] + + @overload + def __init__( + self, + *, + v_cpus_available: Optional[int] = ..., + v_cpus_per_core: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VirtualMachineConfiguration(_Model): + container_configuration: Optional[BatchContainerConfiguration] + data_disks: Optional[list[DataDisk]] + disk_encryption_configuration: Optional[DiskEncryptionConfiguration] + extensions: Optional[list[VMExtension]] + hardware_profile: Optional[HardwareProfile] + image_reference: BatchVmImageReference + license_type: Optional[str] + node_agent_sku_id: str + node_placement_configuration: Optional[BatchNodePlacementConfiguration] + os_disk: Optional[BatchOsDisk] + placement: Optional[Placement] + resiliency_policy: Optional[ResiliencyPolicy] + security_profile: Optional[SecurityProfile] + service_artifact_reference: Optional[ServiceArtifactReference] + windows_configuration: Optional[WindowsConfiguration] + + @overload + def __init__( + self, + *, + container_configuration: Optional[BatchContainerConfiguration] = ..., + data_disks: Optional[list[DataDisk]] = ..., + disk_encryption_configuration: Optional[DiskEncryptionConfiguration] = ..., + extensions: Optional[list[VMExtension]] = ..., + hardware_profile: Optional[HardwareProfile] = ..., + image_reference: BatchVmImageReference, + license_type: Optional[str] = ..., + node_agent_sku_id: str, + node_placement_configuration: Optional[BatchNodePlacementConfiguration] = ..., + os_disk: Optional[BatchOsDisk] = ..., + placement: Optional[Placement] = ..., + resiliency_policy: Optional[ResiliencyPolicy] = ..., + security_profile: Optional[SecurityProfile] = ..., + service_artifact_reference: Optional[ServiceArtifactReference] = ..., + windows_configuration: Optional[WindowsConfiguration] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VirtualMachineInfo(_Model): + image_reference: Optional[BatchVmImageReference] + scale_set_vm_resource_id: Optional[str] + + @overload + def __init__( + self, + *, + image_reference: Optional[BatchVmImageReference] = ..., + scale_set_vm_resource_id: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VirtualMachineSkuAllocationStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CAPACITY_OPTIMIZED = "capacityOptimized" + LOWEST_PRICE = "lowestPrice" + PRIORITIZED = "prioritized" + + + class azure.batch.models.VirtualMachineSkuProfile(_Model): + allocation_strategy: Optional[Union[str, VirtualMachineSkuAllocationStrategy]] + vm_sizes: Optional[list[VirtualMachineSkuProfileVmSize]] + + @overload + def __init__( + self, + *, + allocation_strategy: Optional[Union[str, VirtualMachineSkuAllocationStrategy]] = ..., + vm_sizes: Optional[list[VirtualMachineSkuProfileVmSize]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.VirtualMachineSkuProfileVmSize(_Model): + name: str + rank: Optional[int] + + @overload + def __init__( + self, + *, + name: str, + rank: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.WindowsConfiguration(_Model): + enable_automatic_updates: Optional[bool] + + @overload + def __init__( + self, + *, + enable_automatic_updates: Optional[bool] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.WindowsUserConfiguration(_Model): + login_mode: Optional[Union[str, LoginMode]] + + @overload + def __init__( + self, + *, + login_mode: Optional[Union[str, LoginMode]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ZoneAllocationPolicy(_Model): + max_instance_percent_per_zone_policy: Optional[MaxInstancePercentPerZonePolicy] + max_zone_count: Optional[int] + + @overload + def __init__( + self, + *, + max_instance_percent_per_zone_policy: Optional[MaxInstancePercentPerZonePolicy] = ..., + max_zone_count: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.batch.models.ZonePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + AUTO = "Auto" + + +``` \ No newline at end of file diff --git a/sdk/batch/azure-batch/api.metadata.yml b/sdk/batch/azure-batch/api.metadata.yml new file mode 100644 index 000000000000..f3192941409a --- /dev/null +++ b/sdk/batch/azure-batch/api.metadata.yml @@ -0,0 +1,4 @@ +apiHash: c008f06725aece3194b868c99b11c819eb156843d30df3671be87f00939b47e3 +packageVersion: 15.2.0 +parserVersion: 0.3.31 +pythonVersion: 3.13.17 diff --git a/sdk/batch/azure-batch/apiview-properties.json b/sdk/batch/azure-batch/apiview-properties.json index 7a3c4effe06b..9f9f0d39034f 100644 --- a/sdk/batch/azure-batch/apiview-properties.json +++ b/sdk/batch/azure-batch/apiview-properties.json @@ -39,11 +39,13 @@ "azure.batch.models.BatchJobSchedulingError": "Azure.Batch.BatchJobSchedulingError", "azure.batch.models.BatchJobSpecification": "Azure.Batch.BatchJobSpecification", "azure.batch.models.BatchJobStatistics": "Azure.Batch.BatchJobStatistics", + "azure.batch.models.BatchJobTerminateOptions": "Azure.Batch.BatchJobTerminateOptions", "azure.batch.models.BatchJobUpdateOptions": "Azure.Batch.BatchJobUpdateOptions", "azure.batch.models.BatchMetadataItem": "Azure.Batch.BatchMetadataItem", "azure.batch.models.BatchNode": "Azure.Batch.BatchNode", "azure.batch.models.BatchNodeAgentInfo": "Azure.Batch.BatchNodeAgentInfo", "azure.batch.models.BatchNodeCounts": "Azure.Batch.BatchNodeCounts", + "azure.batch.models.BatchNodeDeallocateOptions": "Azure.Batch.BatchNodeDeallocateOptions", "azure.batch.models.BatchNodeDisableSchedulingOptions": "Azure.Batch.BatchNodeDisableSchedulingOptions", "azure.batch.models.BatchNodeEndpointConfiguration": "Azure.Batch.BatchNodeEndpointConfiguration", "azure.batch.models.BatchNodeError": "Azure.Batch.BatchNodeError", @@ -51,6 +53,8 @@ "azure.batch.models.BatchNodeIdentityReference": "Azure.Batch.BatchNodeIdentityReference", "azure.batch.models.BatchNodeInfo": "Azure.Batch.BatchNodeInfo", "azure.batch.models.BatchNodePlacementConfiguration": "Azure.Batch.BatchNodePlacementConfiguration", + "azure.batch.models.BatchNodeRebootOptions": "Azure.Batch.BatchNodeRebootOptions", + "azure.batch.models.BatchNodeReimageOptions": "Azure.Batch.BatchNodeReimageOptions", "azure.batch.models.BatchNodeRemoteLoginSettings": "Azure.Batch.BatchNodeRemoteLoginSettings", "azure.batch.models.BatchNodeRemoveOptions": "Azure.Batch.BatchNodeRemoveOptions", "azure.batch.models.BatchNodeUserCreateOptions": "Azure.Batch.BatchNodeUserCreateOptions", @@ -72,8 +76,6 @@ "azure.batch.models.BatchPoolSpecification": "Azure.Batch.BatchPoolSpecification", "azure.batch.models.BatchPoolStatistics": "Azure.Batch.BatchPoolStatistics", "azure.batch.models.BatchPoolUpdateOptions": "Azure.Batch.BatchPoolUpdateOptions", - "azure.batch.models.BatchPoolUsageMetrics": "Azure.Batch.BatchPoolUsageMetrics", - "azure.batch.models.BatchPoolUsageStatistics": "Azure.Batch.BatchPoolUsageStatistics", "azure.batch.models.BatchPublicIpAddressConfiguration": "Azure.Batch.BatchPublicIpAddressConfiguration", "azure.batch.models.BatchStartTask": "Azure.Batch.BatchStartTask", "azure.batch.models.BatchStartTaskInfo": "Azure.Batch.BatchStartTaskInfo", @@ -113,12 +115,14 @@ "azure.batch.models.ExitConditions": "Azure.Batch.ExitConditions", "azure.batch.models.ExitOptions": "Azure.Batch.ExitOptions", "azure.batch.models.FileProperties": "Azure.Batch.FileProperties", + "azure.batch.models.HardwareProfile": "Azure.Batch.HardwareProfile", "azure.batch.models.HostEndpointSettings": "Azure.Batch.HostEndpointSettings", "azure.batch.models.InboundEndpoint": "Azure.Batch.InboundEndpoint", "azure.batch.models.InstanceViewStatus": "Azure.Batch.InstanceViewStatus", "azure.batch.models.IPTag": "Azure.Batch.IPTag", "azure.batch.models.LinuxUserConfiguration": "Azure.Batch.LinuxUserConfiguration", "azure.batch.models.ManagedDisk": "Azure.Batch.ManagedDisk", + "azure.batch.models.MaxInstancePercentPerZonePolicy": "Azure.Batch.MaxInstancePercentPerZonePolicy", "azure.batch.models.MountConfiguration": "Azure.Batch.MountConfiguration", "azure.batch.models.MultiInstanceSettings": "Azure.Batch.MultiInstanceSettings", "azure.batch.models.NameValuePair": "Azure.Batch.NameValuePair", @@ -130,8 +134,10 @@ "azure.batch.models.OutputFileDestination": "Azure.Batch.OutputFileDestination", "azure.batch.models.OutputFileUploadConfiguration": "Azure.Batch.OutputFileUploadConfig", "azure.batch.models.OutputFileUploadHeader": "Azure.Batch.OutputFileUploadHeader", + "azure.batch.models.Placement": "Azure.Batch.Placement", "azure.batch.models.ProxyAgentSettings": "Azure.Batch.ProxyAgentSettings", "azure.batch.models.RecentBatchJob": "Azure.Batch.RecentBatchJob", + "azure.batch.models.ResiliencyPolicy": "Azure.Batch.ResiliencyPolicy", "azure.batch.models.ResizeError": "Azure.Batch.ResizeError", "azure.batch.models.ResourceFile": "Azure.Batch.ResourceFile", "azure.batch.models.RollingUpgradePolicy": "Azure.Batch.RollingUpgradePolicy", @@ -144,10 +150,14 @@ "azure.batch.models.UserIdentity": "Azure.Batch.UserIdentity", "azure.batch.models.VirtualMachineConfiguration": "Azure.Batch.VirtualMachineConfiguration", "azure.batch.models.VirtualMachineInfo": "Azure.Batch.VirtualMachineInfo", + "azure.batch.models.VirtualMachineSkuProfile": "Azure.Batch.VirtualMachineSkuProfile", + "azure.batch.models.VirtualMachineSkuProfileVmSize": "Azure.Batch.VirtualMachineSkuProfileVmSize", "azure.batch.models.VMExtension": "Azure.Batch.VMExtension", "azure.batch.models.VMExtensionInstanceView": "Azure.Batch.VMExtensionInstanceView", + "azure.batch.models.VMSizeProperties": "Azure.Batch.VMSizeProperties", "azure.batch.models.WindowsConfiguration": "Azure.Batch.WindowsConfiguration", "azure.batch.models.WindowsUserConfiguration": "Azure.Batch.WindowsUserConfiguration", + "azure.batch.models.ZoneAllocationPolicy": "Azure.Batch.ZoneAllocationPolicy", "azure.batch.models.CachingType": "Azure.Batch.CachingType", "azure.batch.models.StorageAccountType": "Azure.Batch.StorageAccountType", "azure.batch.models.SecurityEncryptionTypes": "Azure.Batch.SecurityEncryptionTypes", @@ -157,6 +167,8 @@ "azure.batch.models.DiffDiskPlacement": "Azure.Batch.DiffDiskPlacement", "azure.batch.models.HostEndpointSettingsModeTypes": "Azure.Batch.HostEndpointSettingsModeTypes", "azure.batch.models.SecurityTypes": "Azure.Batch.SecurityTypes", + "azure.batch.models.ZonePlacementPolicyType": "Azure.Batch.ZonePlacementPolicyType", + "azure.batch.models.VirtualMachineSkuAllocationStrategy": "Azure.Batch.VirtualMachineSkuAllocationStrategy", "azure.batch.models.DynamicVNetAssignmentScope": "Azure.Batch.DynamicVNetAssignmentScope", "azure.batch.models.InboundEndpointProtocol": "Azure.Batch.InboundEndpointProtocol", "azure.batch.models.NetworkSecurityGroupRuleAccess": "Azure.Batch.NetworkSecurityGroupRuleAccess", @@ -195,14 +207,15 @@ "azure.batch.models.BatchNodeState": "Azure.Batch.BatchNodeState", "azure.batch.models.SchedulingState": "Azure.Batch.SchedulingState", "azure.batch.models.BatchStartTaskState": "Azure.Batch.BatchStartTaskState", + "azure.batch.models.BatchNodeRebootKind": "Azure.Batch.BatchNodeRebootKind", + "azure.batch.models.BatchNodeReimageOption": "Azure.Batch.BatchNodeReimageOption", + "azure.batch.models.BatchNodeDeallocateOption": "Azure.Batch.BatchNodeDeallocateOption", "azure.batch.models.BatchNodeDisableSchedulingOption": "Azure.Batch.BatchNodeDisableSchedulingOption", "azure.batch.models.StatusLevelTypes": "Azure.Batch.StatusLevelTypes", "azure.batch.BatchClient.list_applications": "Client.BatchClient.listApplications", "azure.batch.aio.BatchClient.list_applications": "Client.BatchClient.listApplications", "azure.batch.BatchClient.get_application": "Client.BatchClient.getApplication", "azure.batch.aio.BatchClient.get_application": "Client.BatchClient.getApplication", - "azure.batch.BatchClient.list_pool_usage_metrics": "Client.BatchClient.listPoolUsageMetrics", - "azure.batch.aio.BatchClient.list_pool_usage_metrics": "Client.BatchClient.listPoolUsageMetrics", "azure.batch.BatchClient.create_pool": "Client.BatchClient.createPool", "azure.batch.aio.BatchClient.create_pool": "Client.BatchClient.createPool", "azure.batch.BatchClient.list_pools": "Client.BatchClient.listPools", @@ -309,5 +322,6 @@ "azure.batch.aio.BatchClient.download_node_file": "Client.BatchClient.getNodeFile", "azure.batch.BatchClient.list_node_files": "Client.BatchClient.listNodeFiles", "azure.batch.aio.BatchClient.list_node_files": "Client.BatchClient.listNodeFiles" - } + }, + "CrossLanguageVersion": "059eefb84093" } \ No newline at end of file diff --git a/sdk/batch/azure-batch/azure/batch/_client.py b/sdk/batch/azure-batch/azure/batch/_client.py index f85f83848c35..92c1d9e4958f 100644 --- a/sdk/batch/azure-batch/azure/batch/_client.py +++ b/sdk/batch/azure-batch/azure/batch/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, TYPE_CHECKING -from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -18,11 +18,16 @@ from ._operations import _BatchClientOperationsMixin from ._utils.serialization import Deserializer, Serializer +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: from azure.core.credentials import TokenCredential -class BatchClient(_BatchClientOperationsMixin): +class BatchClient(_BatchClientOperationsMixin): # pylint: disable=docstring-keyword-should-match-keyword-only """BatchClient. :param endpoint: Batch account endpoint (for example: @@ -31,9 +36,9 @@ class BatchClient(_BatchClientOperationsMixin): :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for this operation. Known values are "2025-06-01". - Default value is "2025-06-01". Note that overriding this default value may result in - unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-10-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ diff --git a/sdk/batch/azure-batch/azure/batch/_configuration.py b/sdk/batch/azure-batch/azure/batch/_configuration.py index aff5edc1bb1d..4d091bada987 100644 --- a/sdk/batch/azure-batch/azure/batch/_configuration.py +++ b/sdk/batch/azure-batch/azure/batch/_configuration.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -16,7 +17,7 @@ from azure.core.credentials import TokenCredential -class BatchClientConfiguration: # pylint: disable=too-many-instance-attributes +class BatchClientConfiguration: # pylint: disable=too-many-instance-attributes,docstring-keyword-should-match-keyword-only """Configuration for BatchClient. Note that all parameters used to create this instance are saved as instance @@ -28,14 +29,14 @@ class BatchClientConfiguration: # pylint: disable=too-many-instance-attributes :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for this operation. Known values are "2025-06-01". - Default value is "2025-06-01". Note that overriding this default value may result in - unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-10-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-06-01") + api_version: str = kwargs.pop("api_version", "2026-10-01") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/batch/azure-batch/azure/batch/_model_base.py b/sdk/batch/azure-batch/azure/batch/_model_base.py deleted file mode 100644 index 22d62109bb8a..000000000000 --- a/sdk/batch/azure-batch/azure/batch/_model_base.py +++ /dev/null @@ -1,1235 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -# pylint: disable=protected-access, broad-except - -import copy -import calendar -import decimal -import functools -import sys -import logging -import base64 -import re -import typing -import enum -import email.utils -from datetime import datetime, date, time, timedelta, timezone -from json import JSONEncoder -import xml.etree.ElementTree as ET -from typing_extensions import Self -import isodate -from azure.core.exceptions import DeserializationError -from azure.core import CaseInsensitiveEnumMeta -from azure.core.pipeline import PipelineResponse -from azure.core.serialization import _Null - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping - -_LOGGER = logging.getLogger(__name__) - -__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] - -TZ_UTC = timezone.utc -_T = typing.TypeVar("_T") - - -def _timedelta_as_isostr(td: timedelta) -> str: - """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' - - Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython - - :param timedelta td: The timedelta to convert - :rtype: str - :return: ISO8601 version of this timedelta - """ - - # Split seconds to larger units - seconds = td.total_seconds() - minutes, seconds = divmod(seconds, 60) - hours, minutes = divmod(minutes, 60) - days, hours = divmod(hours, 24) - - days, hours, minutes = list(map(int, (days, hours, minutes))) - seconds = round(seconds, 6) - - # Build date - date_str = "" - if days: - date_str = "%sD" % days - - if hours or minutes or seconds: - # Build time - time_str = "T" - - # Hours - bigger_exists = date_str or hours - if bigger_exists: - time_str += "{:02}H".format(hours) - - # Minutes - bigger_exists = bigger_exists or minutes - if bigger_exists: - time_str += "{:02}M".format(minutes) - - # Seconds - try: - if seconds.is_integer(): - seconds_string = "{:02}".format(int(seconds)) - else: - # 9 chars long w/ leading 0, 6 digits after decimal - seconds_string = "%09.6f" % seconds - # Remove trailing zeros - seconds_string = seconds_string.rstrip("0") - except AttributeError: # int.is_integer() raises - seconds_string = "{:02}".format(seconds) - - time_str += "{}S".format(seconds_string) - else: - time_str = "" - - return "P" + date_str + time_str - - -def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: - encoded = base64.b64encode(o).decode() - if format == "base64url": - return encoded.strip("=").replace("+", "-").replace("/", "_") - return encoded - - -def _serialize_datetime(o, format: typing.Optional[str] = None): - if hasattr(o, "year") and hasattr(o, "hour"): - if format == "rfc7231": - return email.utils.format_datetime(o, usegmt=True) - if format == "unix-timestamp": - return int(calendar.timegm(o.utctimetuple())) - - # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) - if not o.tzinfo: - iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() - else: - iso_formatted = o.astimezone(TZ_UTC).isoformat() - # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) - return iso_formatted.replace("+00:00", "Z") - # Next try datetime.date or datetime.time - return o.isoformat() - - -def _is_readonly(p): - try: - return p._visibility == ["read"] - except AttributeError: - return False - - -class SdkJSONEncoder(JSONEncoder): - """A JSON encoder that's capable of serializing datetime objects and bytes.""" - - def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): - super().__init__(*args, **kwargs) - self.exclude_readonly = exclude_readonly - self.format = format - - def default(self, o): # pylint: disable=too-many-return-statements - if _is_model(o): - if self.exclude_readonly: - readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] - return {k: v for k, v in o.items() if k not in readonly_props} - return dict(o.items()) - try: - return super(SdkJSONEncoder, self).default(o) - except TypeError: - if isinstance(o, _Null): - return None - if isinstance(o, decimal.Decimal): - return float(o) - if isinstance(o, (bytes, bytearray)): - return _serialize_bytes(o, self.format) - try: - # First try datetime.datetime - return _serialize_datetime(o, self.format) - except AttributeError: - pass - # Last, try datetime.timedelta - try: - return _timedelta_as_isostr(o) - except AttributeError: - # This will be raised when it hits value.total_seconds in the method above - pass - return super(SdkJSONEncoder, self).default(o) - - -_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") -_VALID_RFC7231 = re.compile( - r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" - r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" -) - - -def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: ~datetime.datetime - :returns: The datetime object from that input - """ - if isinstance(attr, datetime): - # i'm already deserialized - return attr - attr = attr.upper() - match = _VALID_DATE.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - return date_obj - - -def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: - """Deserialize RFC7231 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: ~datetime.datetime - :returns: The datetime object from that input - """ - if isinstance(attr, datetime): - # i'm already deserialized - return attr - match = _VALID_RFC7231.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - return email.utils.parsedate_to_datetime(attr) - - -def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: - """Deserialize unix timestamp into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: ~datetime.datetime - :returns: The datetime object from that input - """ - if isinstance(attr, datetime): - # i'm already deserialized - return attr - return datetime.fromtimestamp(attr, TZ_UTC) - - -def _deserialize_date(attr: typing.Union[str, date]) -> date: - """Deserialize ISO-8601 formatted string into Date object. - :param str attr: response string to be deserialized. - :rtype: date - :returns: The date object from that input - """ - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - if isinstance(attr, date): - return attr - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore - - -def _deserialize_time(attr: typing.Union[str, time]) -> time: - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :returns: The time object from that input - """ - if isinstance(attr, time): - return attr - return isodate.parse_time(attr) - - -def _deserialize_bytes(attr): - if isinstance(attr, (bytes, bytearray)): - return attr - return bytes(base64.b64decode(attr)) - - -def _deserialize_bytes_base64(attr): - if isinstance(attr, (bytes, bytearray)): - return attr - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return bytes(base64.b64decode(encoded)) - - -def _deserialize_duration(attr): - if isinstance(attr, timedelta): - return attr - return isodate.parse_duration(attr) - - -def _deserialize_decimal(attr): - if isinstance(attr, decimal.Decimal): - return attr - return decimal.Decimal(str(attr)) - - -def _deserialize_int_as_str(attr): - if isinstance(attr, int): - return attr - return int(attr) - - -_DESERIALIZE_MAPPING = { - datetime: _deserialize_datetime, - date: _deserialize_date, - time: _deserialize_time, - bytes: _deserialize_bytes, - bytearray: _deserialize_bytes, - timedelta: _deserialize_duration, - typing.Any: lambda x: x, - decimal.Decimal: _deserialize_decimal, -} - -_DESERIALIZE_MAPPING_WITHFORMAT = { - "rfc3339": _deserialize_datetime, - "rfc7231": _deserialize_datetime_rfc7231, - "unix-timestamp": _deserialize_datetime_unix_timestamp, - "base64": _deserialize_bytes, - "base64url": _deserialize_bytes_base64, -} - - -def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): - if annotation is int and rf and rf._format == "str": - return _deserialize_int_as_str - if rf and rf._format: - return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) - return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore - - -def _get_type_alias_type(module_name: str, alias_name: str): - types = { - k: v - for k, v in sys.modules[module_name].__dict__.items() - if isinstance(v, typing._GenericAlias) # type: ignore - } - if alias_name not in types: - return alias_name - return types[alias_name] - - -def _get_model(module_name: str, model_name: str): - models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} - module_end = module_name.rsplit(".", 1)[0] - models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) - if isinstance(model_name, str): - model_name = model_name.split(".")[-1] - if model_name not in models: - return model_name - return models[model_name] - - -_UNSET = object() - - -class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object - def __init__(self, data: typing.Dict[str, typing.Any]) -> None: - self._data = data - - def __contains__(self, key: typing.Any) -> bool: - return key in self._data - - def __getitem__(self, key: str) -> typing.Any: - return self._data.__getitem__(key) - - def __setitem__(self, key: str, value: typing.Any) -> None: - self._data.__setitem__(key, value) - - def __delitem__(self, key: str) -> None: - self._data.__delitem__(key) - - def __iter__(self) -> typing.Iterator[typing.Any]: - return self._data.__iter__() - - def __len__(self) -> int: - return self._data.__len__() - - def __ne__(self, other: typing.Any) -> bool: - return not self.__eq__(other) - - def keys(self) -> typing.KeysView[str]: - """ - :returns: a set-like object providing a view on D's keys - :rtype: ~typing.KeysView - """ - return self._data.keys() - - def values(self) -> typing.ValuesView[typing.Any]: - """ - :returns: an object providing a view on D's values - :rtype: ~typing.ValuesView - """ - return self._data.values() - - def items(self) -> typing.ItemsView[str, typing.Any]: - """ - :returns: set-like object providing a view on D's items - :rtype: ~typing.ItemsView - """ - return self._data.items() - - def get(self, key: str, default: typing.Any = None) -> typing.Any: - """ - Get the value for key if key is in the dictionary, else default. - :param str key: The key to look up. - :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. - :rtype: any - """ - try: - return self[key] - except KeyError: - return default - - @typing.overload - def pop(self, key: str) -> typing.Any: ... - - @typing.overload - def pop(self, key: str, default: _T) -> _T: ... - - @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: ... - - def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: - """ - Removes specified key and return the corresponding value. - :param str key: The key to pop. - :param any default: The value to return if key is not in the dictionary - :returns: The value corresponding to the key. - :rtype: any - :raises KeyError: If key is not found and default is not given. - """ - if default is _UNSET: - return self._data.pop(key) - return self._data.pop(key, default) - - def popitem(self) -> typing.Tuple[str, typing.Any]: - """ - Removes and returns some (key, value) pair - :returns: The (key, value) pair. - :rtype: tuple - :raises KeyError: if D is empty. - """ - return self._data.popitem() - - def clear(self) -> None: - """ - Remove all items from D. - """ - self._data.clear() - - def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: - """ - Updates D from mapping/iterable E and F. - :param any args: Either a mapping object or an iterable of key-value pairs. - """ - self._data.update(*args, **kwargs) - - @typing.overload - def setdefault(self, key: str, default: None = None) -> None: ... - - @typing.overload - def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... - - def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: - """ - Same as calling D.get(k, d), and setting D[k]=d if k not found - :param str key: The key to look up. - :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. - :rtype: any - """ - if default is _UNSET: - return self._data.setdefault(key) - return self._data.setdefault(key, default) - - def __eq__(self, other: typing.Any) -> bool: - try: - other_model = self.__class__(other) - except Exception: - return False - return self._data == other_model._data - - def __repr__(self) -> str: - return str(self._data) - - -def _is_model(obj: typing.Any) -> bool: - return getattr(obj, "_is_model", False) - - -def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements - if isinstance(o, list): - return [_serialize(x, format) for x in o] - if isinstance(o, dict): - return {k: _serialize(v, format) for k, v in o.items()} - if isinstance(o, set): - return {_serialize(x, format) for x in o} - if isinstance(o, tuple): - return tuple(_serialize(x, format) for x in o) - if isinstance(o, (bytes, bytearray)): - return _serialize_bytes(o, format) - if isinstance(o, decimal.Decimal): - return float(o) - if isinstance(o, enum.Enum): - return o.value - if isinstance(o, int): - if format == "str": - return str(o) - return o - try: - # First try datetime.datetime - return _serialize_datetime(o, format) - except AttributeError: - pass - # Last, try datetime.timedelta - try: - return _timedelta_as_isostr(o) - except AttributeError: - # This will be raised when it hits value.total_seconds in the method above - pass - return o - - -def _get_rest_field( - attr_to_rest_field: typing.Dict[str, "_RestField"], rest_name: str -) -> typing.Optional["_RestField"]: - try: - return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) - except StopIteration: - return None - - -def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: - if not rf: - return _serialize(value, None) - if rf._is_multipart_file_input: - return value - if rf._is_model: - return _deserialize(rf._type, value) - if isinstance(value, ET.Element): - value = _deserialize(rf._type, value) - return _serialize(value, rf._format) - - -class Model(_MyMutableMapping): - _is_model = True - # label whether current class's _attr_to_rest_field has been calculated - # could not see _attr_to_rest_field directly because subclass inherits it from parent class - _calculated: typing.Set[str] = set() - - def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: - class_name = self.__class__.__name__ - if len(args) > 1: - raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") - dict_to_pass = { - rest_field._rest_name: rest_field._default - for rest_field in self._attr_to_rest_field.values() - if rest_field._default is not _UNSET - } - if args: # pylint: disable=too-many-nested-blocks - if isinstance(args[0], ET.Element): - existed_attr_keys = [] - model_meta = getattr(self, "_xml", {}) - - for rf in self._attr_to_rest_field.values(): - prop_meta = getattr(rf, "_xml", {}) - xml_name = prop_meta.get("name", rf._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - if prop_meta.get("itemsName"): - xml_name = prop_meta.get("itemsName") - xml_ns = prop_meta.get("itemNs") - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = args[0].findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - continue - - # text element is primitive type - if prop_meta.get("text", False): - if args[0].text is not None: - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = args[0].find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in args[0]: - if e.tag not in existed_attr_keys: - dict_to_pass[e.tag] = _convert_element(e) - else: - dict_to_pass.update( - {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} - ) - else: - non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] - if non_attr_kwargs: - # actual type errors only throw the first wrong keyword arg they see, so following that. - raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") - dict_to_pass.update( - { - self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) - for k, v in kwargs.items() - if v is not None - } - ) - super().__init__(dict_to_pass) - - def copy(self) -> "Model": - return Model(self.__dict__) - - def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: - if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: - # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', - # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' - mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order - attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property - k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") - } - annotations = { - k: v - for mro_class in mros - if hasattr(mro_class, "__annotations__") - for k, v in mro_class.__annotations__.items() - } - for attr, rf in attr_to_rest_field.items(): - rf._module = cls.__module__ - if not rf._type: - rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) - if not rf._rest_name_input: - rf._rest_name_input = attr - cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) - cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - - return super().__new__(cls) # pylint: disable=no-value-for-parameter - - def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: - for base in cls.__bases__: - if hasattr(base, "__mapping__"): - base.__mapping__[discriminator or cls.__name__] = cls # type: ignore - - @classmethod - def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: - for v in cls.__dict__.values(): - if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: - return v - return None - - @classmethod - def _deserialize(cls, data, exist_discriminators): - if not hasattr(cls, "__mapping__"): - return cls(data) - discriminator = cls._get_discriminator(exist_discriminators) - if discriminator is None: - return cls(data) - exist_discriminators.append(discriminator._rest_name) - if isinstance(data, ET.Element): - model_meta = getattr(cls, "_xml", {}) - prop_meta = getattr(discriminator, "_xml", {}) - xml_name = prop_meta.get("name", discriminator._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - if data.get(xml_name) is not None: - discriminator_value = data.get(xml_name) - else: - discriminator_value = data.find(xml_name).text # pyright: ignore - else: - discriminator_value = data.get(discriminator._rest_name) - mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member - return mapped_cls._deserialize(data, exist_discriminators) - - def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: - """Return a dict that can be turned into json using json.dump. - - :keyword bool exclude_readonly: Whether to remove the readonly properties. - :returns: A dict JSON compatible object - :rtype: dict - """ - - result = {} - readonly_props = [] - if exclude_readonly: - readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] - for k, v in self.items(): - if exclude_readonly and k in readonly_props: # pyright: ignore - continue - is_multipart_file_input = False - try: - is_multipart_file_input = next( - rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k - )._is_multipart_file_input - except StopIteration: - pass - result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) - return result - - @staticmethod - def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: - if v is None or isinstance(v, _Null): - return None - if isinstance(v, (list, tuple, set)): - return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) - if isinstance(v, dict): - return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} - return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v - - -def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): - if _is_model(obj): - return obj - return _deserialize(model_deserializer, obj) - - -def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): - if obj is None: - return obj - return _deserialize_with_callable(if_obj_deserializer, obj) - - -def _deserialize_with_union(deserializers, obj): - for deserializer in deserializers: - try: - return _deserialize(deserializer, obj) - except DeserializationError: - pass - raise DeserializationError() - - -def _deserialize_dict( - value_deserializer: typing.Optional[typing.Callable], - module: typing.Optional[str], - obj: typing.Dict[typing.Any, typing.Any], -): - if obj is None: - return obj - if isinstance(obj, ET.Element): - obj = {child.tag: child for child in obj} - return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} - - -def _deserialize_multiple_sequence( - entry_deserializers: typing.List[typing.Optional[typing.Callable]], - module: typing.Optional[str], - obj, -): - if obj is None: - return obj - return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) - - -def _deserialize_sequence( - deserializer: typing.Optional[typing.Callable], - module: typing.Optional[str], - obj, -): - if obj is None: - return obj - if isinstance(obj, ET.Element): - obj = list(obj) - return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) - - -def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]: - return sorted( - types, - key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), - ) - - -def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches - annotation: typing.Any, - module: typing.Optional[str], - rf: typing.Optional["_RestField"] = None, -) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - if not annotation: - return None - - # is it a type alias? - if isinstance(annotation, str): - if module is not None: - annotation = _get_type_alias_type(module, annotation) - - # is it a forward ref / in quotes? - if isinstance(annotation, (str, typing.ForwardRef)): - try: - model_name = annotation.__forward_arg__ # type: ignore - except AttributeError: - model_name = annotation - if module is not None: - annotation = _get_model(module, model_name) # type: ignore - - try: - if module and _is_model(annotation): - if rf: - rf._is_model = True - - return functools.partial(_deserialize_model, annotation) # pyright: ignore - except Exception: - pass - - # is it a literal? - try: - if annotation.__origin__ is typing.Literal: # pyright: ignore - return None - except AttributeError: - pass - - # is it optional? - try: - if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore # pylint: disable=unidiomatic-typecheck - if len(annotation.__args__) <= 2: # pyright: ignore - if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore # pylint: disable=unidiomatic-typecheck - ) - - return functools.partial(_deserialize_with_optional, if_obj_deserializer) - # the type is Optional[Union[...]], we need to remove the None type from the Union - annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore # pylint: disable=unidiomatic-typecheck - return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) - except AttributeError: - pass - - # is it union? - if getattr(annotation, "__origin__", None) is typing.Union: - # initial ordering is we make `string` the last deserialization option, because it is often them most generic - deserializers = [ - _get_deserialize_callable_from_annotation(arg, module, rf) - for arg in _sorted_annotations(annotation.__args__) # pyright: ignore - ] - - return functools.partial(_deserialize_with_union, deserializers) - - try: - if annotation._name == "Dict": # pyright: ignore - value_deserializer = _get_deserialize_callable_from_annotation( - annotation.__args__[1], module, rf # pyright: ignore - ) - - return functools.partial( - _deserialize_dict, - value_deserializer, - module, - ) - except (AttributeError, IndexError): - pass - try: - if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore - if len(annotation.__args__) > 1: # pyright: ignore - entry_deserializers = [ - _get_deserialize_callable_from_annotation(dt, module, rf) - for dt in annotation.__args__ # pyright: ignore - ] - return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) - deserializer = _get_deserialize_callable_from_annotation( - annotation.__args__[0], module, rf # pyright: ignore - ) - - return functools.partial(_deserialize_sequence, deserializer, module) - except (TypeError, IndexError, AttributeError, SyntaxError): - pass - - def _deserialize_default( - deserializer, - obj, - ): - if obj is None: - return obj - try: - return _deserialize_with_callable(deserializer, obj) - except Exception: - pass - return obj - - if get_deserializer(annotation, rf): - return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) - - return functools.partial(_deserialize_default, annotation) - - -def _deserialize_with_callable( - deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], - value: typing.Any, -): # pylint: disable=too-many-return-statements - try: - if value is None or isinstance(value, _Null): - return None - if isinstance(value, ET.Element): - if deserializer is str: - return value.text or "" - if deserializer is int: - return int(value.text) if value.text else None - if deserializer is float: - return float(value.text) if value.text else None - if deserializer is bool: - return value.text == "true" if value.text else None - if deserializer is None: - return value - if deserializer in [int, float, bool]: - return deserializer(value) - if isinstance(deserializer, CaseInsensitiveEnumMeta): - try: - return deserializer(value) - except ValueError: - # for unknown value, return raw value - return value - if isinstance(deserializer, type) and issubclass(deserializer, Model): - return deserializer._deserialize(value, []) - return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) - except Exception as e: - raise DeserializationError() from e - - -def _deserialize( - deserializer: typing.Any, - value: typing.Any, - module: typing.Optional[str] = None, - rf: typing.Optional["_RestField"] = None, - format: typing.Optional[str] = None, -) -> typing.Any: - if isinstance(value, PipelineResponse): - value = value.http_response.json() - if rf is None and format: - rf = _RestField(format=format) - if not isinstance(deserializer, functools.partial): - deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) - return _deserialize_with_callable(deserializer, value) - - -def _failsafe_deserialize( - deserializer: typing.Any, - value: typing.Any, - module: typing.Optional[str] = None, - rf: typing.Optional["_RestField"] = None, - format: typing.Optional[str] = None, -) -> typing.Any: - try: - return _deserialize(deserializer, value, module, rf, format) - except DeserializationError: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - -def _failsafe_deserialize_xml( - deserializer: typing.Any, - value: typing.Any, -) -> typing.Any: - try: - return _deserialize_xml(deserializer, value) - except DeserializationError: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - -class _RestField: - def __init__( - self, - *, - name: typing.Optional[str] = None, - type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - is_discriminator: bool = False, - visibility: typing.Optional[typing.List[str]] = None, - default: typing.Any = _UNSET, - format: typing.Optional[str] = None, - is_multipart_file_input: bool = False, - xml: typing.Optional[typing.Dict[str, typing.Any]] = None, - ): - self._type = type - self._rest_name_input = name - self._module: typing.Optional[str] = None - self._is_discriminator = is_discriminator - self._visibility = visibility - self._is_model = False - self._default = default - self._format = format - self._is_multipart_file_input = is_multipart_file_input - self._xml = xml if xml is not None else {} - - @property - def _class_type(self) -> typing.Any: - return getattr(self._type, "args", [None])[0] - - @property - def _rest_name(self) -> str: - if self._rest_name_input is None: - raise ValueError("Rest name was never set") - return self._rest_name_input - - def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin - # by this point, type and rest_name will have a value bc we default - # them in __new__ of the Model class - item = obj.get(self._rest_name) - if item is None: - return item - if self._is_model: - return item - return _deserialize(self._type, _serialize(item, self._format), rf=self) - - def __set__(self, obj: Model, value) -> None: - if value is None: - # we want to wipe out entries if users set attr to None - try: - obj.__delitem__(self._rest_name) - except KeyError: - pass - return - if self._is_model: - if not _is_model(value): - value = _deserialize(self._type, value) - obj.__setitem__(self._rest_name, value) - return - obj.__setitem__(self._rest_name, _serialize(value, self._format)) - - def _get_deserialize_callable_from_annotation( - self, annotation: typing.Any - ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - return _get_deserialize_callable_from_annotation(annotation, self._module, self) - - -def rest_field( - *, - name: typing.Optional[str] = None, - type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - visibility: typing.Optional[typing.List[str]] = None, - default: typing.Any = _UNSET, - format: typing.Optional[str] = None, - is_multipart_file_input: bool = False, - xml: typing.Optional[typing.Dict[str, typing.Any]] = None, -) -> typing.Any: - return _RestField( - name=name, - type=type, - visibility=visibility, - default=default, - format=format, - is_multipart_file_input=is_multipart_file_input, - xml=xml, - ) - - -def rest_discriminator( - *, - name: typing.Optional[str] = None, - type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - visibility: typing.Optional[typing.List[str]] = None, - xml: typing.Optional[typing.Dict[str, typing.Any]] = None, -) -> typing.Any: - return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) - - -def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: - """Serialize a model to XML. - - :param Model model: The model to serialize. - :param bool exclude_readonly: Whether to exclude readonly properties. - :returns: The XML representation of the model. - :rtype: str - """ - return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore - - -def _get_element( - o: typing.Any, - exclude_readonly: bool = False, - parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None, - wrapped_element: typing.Optional[ET.Element] = None, -) -> typing.Union[ET.Element, typing.List[ET.Element]]: - if _is_model(o): - model_meta = getattr(o, "_xml", {}) - - # if prop is a model, then use the prop element directly, else generate a wrapper of model - if wrapped_element is None: - wrapped_element = _create_xml_element( - model_meta.get("name", o.__class__.__name__), - model_meta.get("prefix"), - model_meta.get("ns"), - ) - - readonly_props = [] - if exclude_readonly: - readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] - - for k, v in o.items(): - # do not serialize readonly properties - if exclude_readonly and k in readonly_props: - continue - - prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) - if prop_rest_field: - prop_meta = getattr(prop_rest_field, "_xml").copy() - # use the wire name as xml name if no specific name is set - if prop_meta.get("name") is None: - prop_meta["name"] = k - else: - # additional properties will not have rest field, use the wire name as xml name - prop_meta = {"name": k} - - # if no ns for prop, use model's - if prop_meta.get("ns") is None and model_meta.get("ns"): - prop_meta["ns"] = model_meta.get("ns") - prop_meta["prefix"] = model_meta.get("prefix") - - if prop_meta.get("unwrapped", False): - # unwrapped could only set on array - wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) - elif prop_meta.get("text", False): - # text could only set on primitive type - wrapped_element.text = _get_primitive_type_value(v) - elif prop_meta.get("attribute", False): - xml_name = prop_meta.get("name", k) - if prop_meta.get("ns"): - ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore - xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore - # attribute should be primitive type - wrapped_element.set(xml_name, _get_primitive_type_value(v)) - else: - # other wrapped prop element - wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) - return wrapped_element - if isinstance(o, list): - return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore - if isinstance(o, dict): - result = [] - for k, v in o.items(): - result.append( - _get_wrapped_element( - v, - exclude_readonly, - { - "name": k, - "ns": parent_meta.get("ns") if parent_meta else None, - "prefix": parent_meta.get("prefix") if parent_meta else None, - }, - ) - ) - return result - - # primitive case need to create element based on parent_meta - if parent_meta: - return _get_wrapped_element( - o, - exclude_readonly, - { - "name": parent_meta.get("itemsName", parent_meta.get("name")), - "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), - "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), - }, - ) - - raise ValueError("Could not serialize value into xml: " + o) - - -def _get_wrapped_element( - v: typing.Any, - exclude_readonly: bool, - meta: typing.Optional[typing.Dict[str, typing.Any]], -) -> ET.Element: - wrapped_element = _create_xml_element( - meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None - ) - if isinstance(v, (dict, list)): - wrapped_element.extend(_get_element(v, exclude_readonly, meta)) - elif _is_model(v): - _get_element(v, exclude_readonly, meta, wrapped_element) - else: - wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element - - -def _get_primitive_type_value(v) -> str: - if v is True: - return "true" - if v is False: - return "false" - if isinstance(v, _Null): - return "" - return str(v) - - -def _create_xml_element(tag, prefix=None, ns=None): - if prefix and ns: - ET.register_namespace(prefix, ns) - if ns: - return ET.Element("{" + ns + "}" + tag) - return ET.Element(tag) - - -def _deserialize_xml( - deserializer: typing.Any, - value: str, -) -> typing.Any: - element = ET.fromstring(value) # nosec - return _deserialize(deserializer, element) - - -def _convert_element(e: ET.Element): - # dict case - if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: - dict_result: typing.Dict[str, typing.Any] = {} - for child in e: - if dict_result.get(child.tag) is not None: - if isinstance(dict_result[child.tag], list): - dict_result[child.tag].append(_convert_element(child)) - else: - dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] - else: - dict_result[child.tag] = _convert_element(child) - dict_result.update(e.attrib) - return dict_result - # array case - if len(e) > 0: - array_result: typing.List[typing.Any] = [] - for child in e: - array_result.append(_convert_element(child)) - return array_result - # primitive case - return e.text diff --git a/sdk/batch/azure-batch/azure/batch/_operations/_operations.py b/sdk/batch/azure-batch/azure/batch/_operations/_operations.py index 6790090607eb..d760d8ecbde5 100644 --- a/sdk/batch/azure-batch/azure/batch/_operations/_operations.py +++ b/sdk/batch/azure-batch/azure/batch/_operations/_operations.py @@ -45,7 +45,7 @@ def build_batch_list_applications_request( *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, **kwargs: Any @@ -53,7 +53,7 @@ def build_batch_list_applications_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -62,7 +62,7 @@ def build_batch_list_applications_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") @@ -77,14 +77,14 @@ def build_batch_list_applications_request( def build_batch_get_application_request( application_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -98,47 +98,7 @@ def build_batch_get_application_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") - - # Construct headers - if ocp_date is not None: - _headers["ocp-date"] = _SERIALIZER.header("ocp_date", ocp_date, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_batch_list_pool_usage_metrics_request( # pylint: disable=name-too-long - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - max_results: Optional[int] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - filter: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/poolusagemetrics" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") - if max_results is not None: - _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") - if start_time is not None: - _params["startTime"] = _SERIALIZER.query("start_time", start_time, "iso-8601") - if end_time is not None: - _params["endtime"] = _SERIALIZER.query("end_time", end_time, "iso-8601") - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -149,20 +109,20 @@ def build_batch_list_pool_usage_metrics_request( # pylint: disable=name-too-lon def build_batch_create_pool_request( - *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + *, service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -174,7 +134,7 @@ def build_batch_create_pool_request( def build_batch_list_pools_request( *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -185,7 +145,7 @@ def build_batch_list_pools_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -194,7 +154,7 @@ def build_batch_list_pools_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -215,7 +175,7 @@ def build_batch_list_pools_request( def build_batch_delete_pool_internal_request( pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -226,7 +186,7 @@ def build_batch_delete_pool_internal_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}" path_format_arguments = { @@ -238,7 +198,7 @@ def build_batch_delete_pool_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -260,7 +220,7 @@ def build_batch_delete_pool_internal_request( def build_batch_pool_exists_request( pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -271,7 +231,7 @@ def build_batch_pool_exists_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}" path_format_arguments = { @@ -283,7 +243,7 @@ def build_batch_pool_exists_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -305,7 +265,7 @@ def build_batch_pool_exists_request( def build_batch_get_pool_request( pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -318,7 +278,7 @@ def build_batch_get_pool_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -332,7 +292,7 @@ def build_batch_get_pool_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") if expand is not None: @@ -359,7 +319,7 @@ def build_batch_get_pool_request( def build_batch_update_pool_request( pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -371,7 +331,7 @@ def build_batch_update_pool_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}" path_format_arguments = { @@ -383,7 +343,7 @@ def build_batch_update_pool_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -404,12 +364,16 @@ def build_batch_update_pool_request( def build_batch_disable_pool_auto_scale_request( # pylint: disable=name-too-long - pool_id: str, *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + pool_id: str, + *, + service_timeout: Optional[datetime.timedelta] = None, + ocp_date: Optional[datetime.datetime] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/disableautoscale" path_format_arguments = { @@ -421,7 +385,7 @@ def build_batch_disable_pool_auto_scale_request( # pylint: disable=name-too-lon # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -433,7 +397,7 @@ def build_batch_disable_pool_auto_scale_request( # pylint: disable=name-too-lon def build_batch_enable_pool_auto_scale_request( # pylint: disable=name-too-long pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -445,7 +409,7 @@ def build_batch_enable_pool_auto_scale_request( # pylint: disable=name-too-long _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/enableautoscale" path_format_arguments = { @@ -457,7 +421,7 @@ def build_batch_enable_pool_auto_scale_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -478,13 +442,17 @@ def build_batch_enable_pool_auto_scale_request( # pylint: disable=name-too-long def build_batch_evaluate_pool_auto_scale_request( # pylint: disable=name-too-long - pool_id: str, *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + pool_id: str, + *, + service_timeout: Optional[datetime.timedelta] = None, + ocp_date: Optional[datetime.datetime] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -498,7 +466,7 @@ def build_batch_evaluate_pool_auto_scale_request( # pylint: disable=name-too-lo # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -512,7 +480,7 @@ def build_batch_evaluate_pool_auto_scale_request( # pylint: disable=name-too-lo def build_batch_resize_pool_internal_request( pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -524,7 +492,7 @@ def build_batch_resize_pool_internal_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/resize" path_format_arguments = { @@ -536,7 +504,7 @@ def build_batch_resize_pool_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -559,7 +527,7 @@ def build_batch_resize_pool_internal_request( def build_batch_stop_pool_resize_internal_request( # pylint: disable=name-too-long pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -570,7 +538,7 @@ def build_batch_stop_pool_resize_internal_request( # pylint: disable=name-too-l _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/stopresize" path_format_arguments = { @@ -582,7 +550,7 @@ def build_batch_stop_pool_resize_internal_request( # pylint: disable=name-too-l # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -602,13 +570,17 @@ def build_batch_stop_pool_resize_internal_request( # pylint: disable=name-too-l def build_batch_replace_pool_properties_request( # pylint: disable=name-too-long - pool_id: str, *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + pool_id: str, + *, + service_timeout: Optional[datetime.timedelta] = None, + ocp_date: Optional[datetime.datetime] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/updateproperties" path_format_arguments = { @@ -620,7 +592,7 @@ def build_batch_replace_pool_properties_request( # pylint: disable=name-too-lon # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -633,7 +605,7 @@ def build_batch_replace_pool_properties_request( # pylint: disable=name-too-lon def build_batch_remove_nodes_internal_request( # pylint: disable=name-too-long pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -645,7 +617,7 @@ def build_batch_remove_nodes_internal_request( # pylint: disable=name-too-long _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/removenodes" path_format_arguments = { @@ -657,7 +629,7 @@ def build_batch_remove_nodes_internal_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -679,7 +651,7 @@ def build_batch_remove_nodes_internal_request( # pylint: disable=name-too-long def build_batch_list_supported_images_request( # pylint: disable=name-too-long *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -688,7 +660,7 @@ def build_batch_list_supported_images_request( # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -697,7 +669,7 @@ def build_batch_list_supported_images_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -713,7 +685,7 @@ def build_batch_list_supported_images_request( # pylint: disable=name-too-long def build_batch_list_pool_node_counts_request( # pylint: disable=name-too-long *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -722,7 +694,7 @@ def build_batch_list_pool_node_counts_request( # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -731,7 +703,7 @@ def build_batch_list_pool_node_counts_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -748,7 +720,7 @@ def build_batch_list_pool_node_counts_request( # pylint: disable=name-too-long def build_batch_delete_job_internal_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -760,7 +732,7 @@ def build_batch_delete_job_internal_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}" path_format_arguments = { @@ -772,7 +744,7 @@ def build_batch_delete_job_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if force is not None: _params["force"] = _SERIALIZER.query("force", force, "bool") @@ -796,7 +768,7 @@ def build_batch_delete_job_internal_request( def build_batch_get_job_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -809,7 +781,7 @@ def build_batch_get_job_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -823,7 +795,7 @@ def build_batch_get_job_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") if expand is not None: @@ -850,7 +822,7 @@ def build_batch_get_job_request( def build_batch_update_job_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -862,7 +834,7 @@ def build_batch_update_job_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}" path_format_arguments = { @@ -874,7 +846,7 @@ def build_batch_update_job_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -897,7 +869,7 @@ def build_batch_update_job_request( def build_batch_replace_job_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -909,7 +881,7 @@ def build_batch_replace_job_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}" path_format_arguments = { @@ -921,7 +893,7 @@ def build_batch_replace_job_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -944,7 +916,7 @@ def build_batch_replace_job_request( def build_batch_disable_job_internal_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -956,7 +928,7 @@ def build_batch_disable_job_internal_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/disable" path_format_arguments = { @@ -968,7 +940,7 @@ def build_batch_disable_job_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -991,7 +963,7 @@ def build_batch_disable_job_internal_request( def build_batch_enable_job_internal_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1002,7 +974,7 @@ def build_batch_enable_job_internal_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/enable" path_format_arguments = { @@ -1014,7 +986,7 @@ def build_batch_enable_job_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1036,7 +1008,7 @@ def build_batch_enable_job_internal_request( def build_batch_terminate_job_internal_request( # pylint: disable=name-too-long job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1048,8 +1020,8 @@ def build_batch_terminate_job_internal_request( # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/terminate" path_format_arguments = { @@ -1061,14 +1033,15 @@ def build_batch_terminate_job_internal_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if force is not None: _params["force"] = _SERIALIZER.query("force", force, "bool") # Construct headers if ocp_date is not None: _headers["ocp-date"] = _SERIALIZER.header("ocp_date", ocp_date, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") if if_modified_since is not None: _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: @@ -1084,20 +1057,20 @@ def build_batch_terminate_job_internal_request( # pylint: disable=name-too-long def build_batch_create_job_request( - *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + *, service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1109,7 +1082,7 @@ def build_batch_create_job_request( def build_batch_list_jobs_request( *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -1120,7 +1093,7 @@ def build_batch_list_jobs_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1129,7 +1102,7 @@ def build_batch_list_jobs_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -1150,7 +1123,7 @@ def build_batch_list_jobs_request( def build_batch_list_jobs_from_schedule_request( # pylint: disable=name-too-long job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -1161,7 +1134,7 @@ def build_batch_list_jobs_from_schedule_request( # pylint: disable=name-too-lon _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1175,7 +1148,7 @@ def build_batch_list_jobs_from_schedule_request( # pylint: disable=name-too-lon # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -1196,7 +1169,7 @@ def build_batch_list_jobs_from_schedule_request( # pylint: disable=name-too-lon def build_batch_list_job_preparation_and_release_task_status_request( # pylint: disable=name-too-long job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -1206,7 +1179,7 @@ def build_batch_list_job_preparation_and_release_task_status_request( # pylint: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1220,7 +1193,7 @@ def build_batch_list_job_preparation_and_release_task_status_request( # pylint: # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -1237,12 +1210,16 @@ def build_batch_list_job_preparation_and_release_task_status_request( # pylint: def build_batch_get_job_task_counts_request( - job_id: str, *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + job_id: str, + *, + service_timeout: Optional[datetime.timedelta] = None, + ocp_date: Optional[datetime.datetime] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1256,7 +1233,7 @@ def build_batch_get_job_task_counts_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1269,7 +1246,7 @@ def build_batch_get_job_task_counts_request( def build_batch_job_schedule_exists_request( job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1280,7 +1257,7 @@ def build_batch_job_schedule_exists_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1292,7 +1269,7 @@ def build_batch_job_schedule_exists_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1314,7 +1291,7 @@ def build_batch_job_schedule_exists_request( def build_batch_delete_job_schedule_internal_request( # pylint: disable=name-too-long job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1326,7 +1303,7 @@ def build_batch_delete_job_schedule_internal_request( # pylint: disable=name-to _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1338,7 +1315,7 @@ def build_batch_delete_job_schedule_internal_request( # pylint: disable=name-to # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if force is not None: _params["force"] = _SERIALIZER.query("force", force, "bool") @@ -1362,7 +1339,7 @@ def build_batch_delete_job_schedule_internal_request( # pylint: disable=name-to def build_batch_get_job_schedule_request( job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1375,7 +1352,7 @@ def build_batch_get_job_schedule_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1389,7 +1366,7 @@ def build_batch_get_job_schedule_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") if expand is not None: @@ -1416,7 +1393,7 @@ def build_batch_get_job_schedule_request( def build_batch_update_job_schedule_request( job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1428,7 +1405,7 @@ def build_batch_update_job_schedule_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1440,7 +1417,7 @@ def build_batch_update_job_schedule_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1463,7 +1440,7 @@ def build_batch_update_job_schedule_request( def build_batch_replace_job_schedule_request( job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1475,7 +1452,7 @@ def build_batch_replace_job_schedule_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1487,7 +1464,7 @@ def build_batch_replace_job_schedule_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1510,7 +1487,7 @@ def build_batch_replace_job_schedule_request( def build_batch_disable_job_schedule_request( job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1521,7 +1498,7 @@ def build_batch_disable_job_schedule_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}/disable" path_format_arguments = { @@ -1533,7 +1510,7 @@ def build_batch_disable_job_schedule_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1555,7 +1532,7 @@ def build_batch_disable_job_schedule_request( def build_batch_enable_job_schedule_request( job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1566,7 +1543,7 @@ def build_batch_enable_job_schedule_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}/enable" path_format_arguments = { @@ -1578,7 +1555,7 @@ def build_batch_enable_job_schedule_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1600,7 +1577,7 @@ def build_batch_enable_job_schedule_request( def build_batch_terminate_job_schedule_internal_request( # pylint: disable=name-too-long job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1612,7 +1589,7 @@ def build_batch_terminate_job_schedule_internal_request( # pylint: disable=name _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules/{jobScheduleId}/terminate" path_format_arguments = { @@ -1624,7 +1601,7 @@ def build_batch_terminate_job_schedule_internal_request( # pylint: disable=name # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if force is not None: _params["force"] = _SERIALIZER.query("force", force, "bool") @@ -1646,20 +1623,20 @@ def build_batch_terminate_job_schedule_internal_request( # pylint: disable=name def build_batch_create_job_schedule_request( - *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + *, service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobschedules" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1671,7 +1648,7 @@ def build_batch_create_job_schedule_request( def build_batch_list_job_schedules_request( *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -1682,7 +1659,7 @@ def build_batch_list_job_schedules_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1691,7 +1668,7 @@ def build_batch_list_job_schedules_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -1710,13 +1687,17 @@ def build_batch_list_job_schedules_request( def build_batch_create_task_request( - job_id: str, *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + job_id: str, + *, + service_timeout: Optional[datetime.timedelta] = None, + ocp_date: Optional[datetime.datetime] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks" path_format_arguments = { @@ -1728,7 +1709,7 @@ def build_batch_create_task_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1741,7 +1722,7 @@ def build_batch_create_task_request( def build_batch_list_tasks_request( job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -1752,7 +1733,7 @@ def build_batch_list_tasks_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1766,7 +1747,7 @@ def build_batch_list_tasks_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -1785,13 +1766,17 @@ def build_batch_list_tasks_request( def build_batch_create_task_collection_request( # pylint: disable=name-too-long - job_id: str, *, service_timeout: Optional[int] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any + job_id: str, + *, + service_timeout: Optional[datetime.timedelta] = None, + ocp_date: Optional[datetime.datetime] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1805,7 +1790,7 @@ def build_batch_create_task_collection_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1820,7 +1805,7 @@ def build_batch_delete_task_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1831,7 +1816,7 @@ def build_batch_delete_task_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}" path_format_arguments = { @@ -1844,7 +1829,7 @@ def build_batch_delete_task_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1867,7 +1852,7 @@ def build_batch_get_task_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1880,7 +1865,7 @@ def build_batch_get_task_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1895,7 +1880,7 @@ def build_batch_get_task_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") if expand is not None: @@ -1923,7 +1908,7 @@ def build_batch_replace_task_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1935,7 +1920,7 @@ def build_batch_replace_task_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}" path_format_arguments = { @@ -1948,7 +1933,7 @@ def build_batch_replace_task_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -1972,7 +1957,7 @@ def build_batch_list_subtasks_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -1980,7 +1965,7 @@ def build_batch_list_subtasks_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -1995,7 +1980,7 @@ def build_batch_list_subtasks_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") @@ -2011,7 +1996,7 @@ def build_batch_terminate_task_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2022,7 +2007,7 @@ def build_batch_terminate_task_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/terminate" path_format_arguments = { @@ -2035,7 +2020,7 @@ def build_batch_terminate_task_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2058,7 +2043,7 @@ def build_batch_reactivate_task_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2069,7 +2054,7 @@ def build_batch_reactivate_task_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/reactivate" path_format_arguments = { @@ -2082,7 +2067,7 @@ def build_batch_reactivate_task_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2106,7 +2091,7 @@ def build_batch_delete_task_file_request( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, recursive: Optional[bool] = None, **kwargs: Any @@ -2114,7 +2099,7 @@ def build_batch_delete_task_file_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" path_format_arguments = { @@ -2128,7 +2113,7 @@ def build_batch_delete_task_file_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if recursive is not None: _params["recursive"] = _SERIALIZER.query("recursive", recursive, "bool") @@ -2144,7 +2129,7 @@ def build_batch_download_task_file_request( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2154,7 +2139,7 @@ def build_batch_download_task_file_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/octet-stream") # Construct URL @@ -2170,7 +2155,7 @@ def build_batch_download_task_file_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2191,7 +2176,7 @@ def build_batch_get_task_file_properties_internal_request( # pylint: disable=na task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2200,7 +2185,7 @@ def build_batch_get_task_file_properties_internal_request( # pylint: disable=na _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" path_format_arguments = { @@ -2214,7 +2199,7 @@ def build_batch_get_task_file_properties_internal_request( # pylint: disable=na # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2231,7 +2216,7 @@ def build_batch_list_task_files_request( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -2241,7 +2226,7 @@ def build_batch_list_task_files_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2256,7 +2241,7 @@ def build_batch_list_task_files_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -2276,7 +2261,7 @@ def build_batch_create_node_user_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: @@ -2284,7 +2269,7 @@ def build_batch_create_node_user_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/users" path_format_arguments = { @@ -2297,7 +2282,7 @@ def build_batch_create_node_user_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2312,14 +2297,14 @@ def build_batch_delete_node_user_request( node_id: str, user_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/users/{userName}" path_format_arguments = { @@ -2333,7 +2318,7 @@ def build_batch_delete_node_user_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2347,7 +2332,7 @@ def build_batch_replace_node_user_request( node_id: str, user_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: @@ -2355,7 +2340,7 @@ def build_batch_replace_node_user_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/users/{userName}" path_format_arguments = { @@ -2369,7 +2354,7 @@ def build_batch_replace_node_user_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2383,7 +2368,7 @@ def build_batch_get_node_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -2391,7 +2376,7 @@ def build_batch_get_node_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2406,7 +2391,7 @@ def build_batch_get_node_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") @@ -2422,15 +2407,15 @@ def build_batch_reboot_node_internal_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/reboot" path_format_arguments = { @@ -2443,12 +2428,13 @@ def build_batch_reboot_node_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: _headers["ocp-date"] = _SERIALIZER.header("ocp_date", ocp_date, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2457,14 +2443,14 @@ def build_batch_start_node_internal_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/start" path_format_arguments = { @@ -2477,7 +2463,7 @@ def build_batch_start_node_internal_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2490,15 +2476,15 @@ def build_batch_reimage_node_internal_request( # pylint: disable=name-too-long pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/reimage" path_format_arguments = { @@ -2511,12 +2497,13 @@ def build_batch_reimage_node_internal_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: _headers["ocp-date"] = _SERIALIZER.header("ocp_date", ocp_date, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2525,15 +2512,15 @@ def build_batch_deallocate_node_internal_request( # pylint: disable=name-too-lo pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/deallocate" path_format_arguments = { @@ -2546,12 +2533,13 @@ def build_batch_deallocate_node_internal_request( # pylint: disable=name-too-lo # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: _headers["ocp-date"] = _SERIALIZER.header("ocp_date", ocp_date, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2560,15 +2548,15 @@ def build_batch_disable_node_scheduling_request( # pylint: disable=name-too-lon pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("content-type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/disablescheduling" path_format_arguments = { @@ -2581,12 +2569,13 @@ def build_batch_disable_node_scheduling_request( # pylint: disable=name-too-lon # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: _headers["ocp-date"] = _SERIALIZER.header("ocp_date", ocp_date, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") + if content_type is not None: + _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2595,14 +2584,14 @@ def build_batch_enable_node_scheduling_request( # pylint: disable=name-too-long pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/enablescheduling" path_format_arguments = { @@ -2615,7 +2604,7 @@ def build_batch_enable_node_scheduling_request( # pylint: disable=name-too-long # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2628,14 +2617,14 @@ def build_batch_get_node_remote_login_settings_request( # pylint: disable=name- pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2650,7 +2639,7 @@ def build_batch_get_node_remote_login_settings_request( # pylint: disable=name- # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2664,7 +2653,7 @@ def build_batch_upload_node_logs_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> HttpRequest: @@ -2672,7 +2661,7 @@ def build_batch_upload_node_logs_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2687,7 +2676,7 @@ def build_batch_upload_node_logs_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2701,7 +2690,7 @@ def build_batch_upload_node_logs_request( def build_batch_list_nodes_request( pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -2711,7 +2700,7 @@ def build_batch_list_nodes_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2725,7 +2714,7 @@ def build_batch_list_nodes_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -2746,7 +2735,7 @@ def build_batch_get_node_extension_request( node_id: str, extension_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -2754,7 +2743,7 @@ def build_batch_get_node_extension_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2770,7 +2759,7 @@ def build_batch_get_node_extension_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if select is not None: _params["$select"] = _SERIALIZER.query("select", select, "[str]", div=",") @@ -2786,7 +2775,7 @@ def build_batch_list_node_extensions_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, select: Optional[list[str]] = None, @@ -2795,7 +2784,7 @@ def build_batch_list_node_extensions_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2810,7 +2799,7 @@ def build_batch_list_node_extensions_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if select is not None: @@ -2829,7 +2818,7 @@ def build_batch_delete_node_file_request( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, recursive: Optional[bool] = None, **kwargs: Any @@ -2837,7 +2826,7 @@ def build_batch_delete_node_file_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" path_format_arguments = { @@ -2851,7 +2840,7 @@ def build_batch_delete_node_file_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if recursive is not None: _params["recursive"] = _SERIALIZER.query("recursive", recursive, "bool") @@ -2867,7 +2856,7 @@ def build_batch_download_node_file_request( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2877,7 +2866,7 @@ def build_batch_download_node_file_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/octet-stream") # Construct URL @@ -2893,7 +2882,7 @@ def build_batch_download_node_file_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2914,7 +2903,7 @@ def build_batch_get_node_file_properties_internal_request( # pylint: disable=na node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2923,7 +2912,7 @@ def build_batch_get_node_file_properties_internal_request( # pylint: disable=na _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" path_format_arguments = { @@ -2937,7 +2926,7 @@ def build_batch_get_node_file_properties_internal_request( # pylint: disable=na # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") # Construct headers if ocp_date is not None: @@ -2954,7 +2943,7 @@ def build_batch_list_node_files_request( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -2964,7 +2953,7 @@ def build_batch_list_node_files_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-06-01")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-10-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -2979,7 +2968,7 @@ def build_batch_list_node_files_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if service_timeout is not None: - _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "int") + _params["timeOut"] = _SERIALIZER.query("service_timeout", service_timeout, "duration-seconds-int") if max_results is not None: _params["maxresults"] = _SERIALIZER.query("max_results", max_results, "int") if filter is not None: @@ -3003,7 +2992,7 @@ class _BatchClientOperationsMixin( # pylint: disable=too-many-public-methods def list_applications( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, **kwargs: Any @@ -3018,7 +3007,7 @@ def list_applications( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3072,7 +3061,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -3119,7 +3111,7 @@ def get_application( self, application_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchApplication: @@ -3135,7 +3127,7 @@ def get_application( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3207,150 +3199,12 @@ def get_application( return deserialized # type: ignore - @distributed_trace - def list_pool_usage_metrics( - self, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - max_results: Optional[int] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - filter: Optional[str] = None, - **kwargs: Any - ) -> ItemPaged["_models.BatchPoolUsageMetrics"]: - """Lists the usage metrics, aggregated by Pool across individual time intervals, for the specified - Account. - - If you do not specify a $filter clause including a poolId, the response includes all Pools that - existed in the Account in the time range of the returned aggregation intervals. If you do not - specify a $filter clause including a startTime or endTime these filters default to the start - and end times of the last aggregation interval currently available; that is, only the last - aggregation interval is returned. - - :keyword service_timeout: The maximum time that the server can spend processing the request, in - seconds. The default is 30 seconds. If the value is larger than 30, the default will be used - instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword max_results: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype max_results: int - :keyword start_time: The earliest time from which to include metrics. This must be at least two - and - a half hours before the current time. If not specified this defaults to the - start time of the last aggregation interval currently available. Default value is None. - :paramtype start_time: ~datetime.datetime - :keyword end_time: The latest time from which to include metrics. This must be at least two - hours - before the current time. If not specified this defaults to the end time of the - last aggregation interval currently available. Default value is None. - :paramtype end_time: ~datetime.datetime - :keyword filter: An OData $filter clause. For more information on constructing this filter, see - `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics - `_. - Default value is None. - :paramtype filter: str - :return: An iterator like instance of BatchPoolUsageMetrics - :rtype: ~azure.core.paging.ItemPaged[~azure.batch.models.BatchPoolUsageMetrics] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models.BatchPoolUsageMetrics]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_batch_list_pool_usage_metrics_request( - service_timeout=service_timeout, - ocp_date=ocp_date, - max_results=max_results, - start_time=start_time, - end_time=end_time, - filter=filter, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - list[_models.BatchPoolUsageMetrics], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("odata.nextLink") or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.BatchError, - response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - @distributed_trace def create_pool( # pylint: disable=inconsistent-return-statements self, pool: _models.BatchPoolCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -3364,7 +3218,7 @@ def create_pool( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3434,7 +3288,7 @@ def create_pool( # pylint: disable=inconsistent-return-statements def list_pools( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -3449,7 +3303,7 @@ def list_pools( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3515,7 +3369,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -3562,7 +3419,7 @@ def _delete_pool_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3588,7 +3445,7 @@ def _delete_pool_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3675,7 +3532,7 @@ def pool_exists( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3690,7 +3547,7 @@ def pool_exists( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3781,7 +3638,7 @@ def get_pool( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3798,7 +3655,7 @@ def get_pool( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3907,7 +3764,7 @@ def update_pool( # pylint: disable=inconsistent-return-statements pool_id: str, pool: _models.BatchPoolUpdateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3928,7 +3785,7 @@ def update_pool( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4025,7 +3882,7 @@ def disable_pool_auto_scale( # pylint: disable=inconsistent-return-statements self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -4038,7 +3895,7 @@ def disable_pool_auto_scale( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4104,7 +3961,7 @@ def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements pool_id: str, enable_auto_scale_options: _models.BatchPoolEnableAutoScaleOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4127,7 +3984,7 @@ def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4225,7 +4082,7 @@ def evaluate_pool_auto_scale( pool_id: str, evaluate_auto_scale_options: _models.BatchPoolEvaluateAutoScaleOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.AutoScaleRun: @@ -4244,7 +4101,7 @@ def evaluate_pool_auto_scale( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4330,7 +4187,7 @@ def _resize_pool_internal( # pylint: disable=inconsistent-return-statements pool_id: str, resize_options: _models.BatchPoolResizeOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4354,7 +4211,7 @@ def _resize_pool_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4451,7 +4308,7 @@ def _stop_pool_resize_internal( # pylint: disable=inconsistent-return-statement self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4473,7 +4330,7 @@ def _stop_pool_resize_internal( # pylint: disable=inconsistent-return-statement :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4564,7 +4421,7 @@ def replace_pool_properties( # pylint: disable=inconsistent-return-statements pool_id: str, pool: _models.BatchPoolReplaceOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -4581,7 +4438,7 @@ def replace_pool_properties( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4654,7 +4511,7 @@ def _remove_nodes_internal( # pylint: disable=inconsistent-return-statements pool_id: str, remove_options: _models.BatchNodeRemoveOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4675,7 +4532,7 @@ def _remove_nodes_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4771,7 +4628,7 @@ def _remove_nodes_internal( # pylint: disable=inconsistent-return-statements def list_supported_images( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -4784,7 +4641,7 @@ def list_supported_images( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4844,7 +4701,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -4890,7 +4750,7 @@ def get_next(next_link=None): def list_pool_node_counts( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -4902,7 +4762,7 @@ def list_pool_node_counts( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4962,7 +4822,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -5009,7 +4872,7 @@ def _delete_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5033,7 +4896,7 @@ def _delete_job_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5124,7 +4987,7 @@ def get_job( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5143,7 +5006,7 @@ def get_job( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5252,7 +5115,7 @@ def update_job( # pylint: disable=inconsistent-return-statements job_id: str, job: _models.BatchJobUpdateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5273,7 +5136,7 @@ def update_job( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5371,7 +5234,7 @@ def replace_job( # pylint: disable=inconsistent-return-statements job_id: str, job: _models.BatchJob, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5392,7 +5255,7 @@ def replace_job( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5490,7 +5353,7 @@ def _disable_job_internal( # pylint: disable=inconsistent-return-statements job_id: str, disable_options: _models.BatchJobDisableOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5515,7 +5378,7 @@ def _disable_job_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5612,7 +5475,7 @@ def _enable_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5633,7 +5496,7 @@ def _enable_job_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5722,9 +5585,9 @@ def _enable_job_internal( # pylint: disable=inconsistent-return-statements def _terminate_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, - options: Optional[_models._models.BatchJobTerminateOptions] = None, + options: Optional[_models.BatchJobTerminateOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5744,11 +5607,11 @@ def _terminate_job_internal( # pylint: disable=inconsistent-return-statements :param job_id: The ID of the Job to terminate. Required. :type job_id: str :param options: The options to use for terminating the Job. Default value is None. - :type options: ~azure.batch.models._models.BatchJobTerminateOptions + :type options: ~azure.batch.models.BatchJobTerminateOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5853,7 +5716,7 @@ def create_job( # pylint: disable=inconsistent-return-statements self, job: _models.BatchJobCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -5872,7 +5735,7 @@ def create_job( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5942,7 +5805,7 @@ def create_job( # pylint: disable=inconsistent-return-statements def list_jobs( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -5957,7 +5820,7 @@ def list_jobs( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6023,7 +5886,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -6070,7 +5936,7 @@ def list_jobs_from_schedule( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -6088,7 +5954,7 @@ def list_jobs_from_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6155,7 +6021,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -6202,7 +6071,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -6223,7 +6092,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6288,7 +6157,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -6335,7 +6207,7 @@ def get_job_task_counts( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchTaskCountsResult: @@ -6351,7 +6223,7 @@ def get_job_task_counts( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6428,7 +6300,7 @@ def job_schedule_exists( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -6445,7 +6317,7 @@ def job_schedule_exists( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6536,7 +6408,7 @@ def _delete_job_schedule_internal( # pylint: disable=inconsistent-return-statem self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -6558,7 +6430,7 @@ def _delete_job_schedule_internal( # pylint: disable=inconsistent-return-statem :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6649,7 +6521,7 @@ def get_job_schedule( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -6666,7 +6538,7 @@ def get_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6775,7 +6647,7 @@ def update_job_schedule( # pylint: disable=inconsistent-return-statements job_schedule_id: str, job_schedule: _models.BatchJobScheduleUpdateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -6797,7 +6669,7 @@ def update_job_schedule( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6895,7 +6767,7 @@ def replace_job_schedule( # pylint: disable=inconsistent-return-statements job_schedule_id: str, job_schedule: _models.BatchJobSchedule, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -6917,7 +6789,7 @@ def replace_job_schedule( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7014,7 +6886,7 @@ def disable_job_schedule( # pylint: disable=inconsistent-return-statements self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -7031,7 +6903,7 @@ def disable_job_schedule( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7121,7 +6993,7 @@ def enable_job_schedule( # pylint: disable=inconsistent-return-statements self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -7138,7 +7010,7 @@ def enable_job_schedule( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7228,7 +7100,7 @@ def _terminate_job_schedule_internal( # pylint: disable=inconsistent-return-sta self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -7246,7 +7118,7 @@ def _terminate_job_schedule_internal( # pylint: disable=inconsistent-return-sta :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7341,7 +7213,7 @@ def create_job_schedule( # pylint: disable=inconsistent-return-statements self, job_schedule: _models.BatchJobScheduleCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -7354,7 +7226,7 @@ def create_job_schedule( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7424,7 +7296,7 @@ def create_job_schedule( # pylint: disable=inconsistent-return-statements def list_job_schedules( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -7439,7 +7311,7 @@ def list_job_schedules( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7505,7 +7377,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -7553,7 +7428,7 @@ def create_task( # pylint: disable=inconsistent-return-statements job_id: str, task: _models.BatchTaskCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -7570,7 +7445,7 @@ def create_task( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7642,7 +7517,7 @@ def list_tasks( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -7660,7 +7535,7 @@ def list_tasks( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7727,7 +7602,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -7775,7 +7653,7 @@ def create_task_collection( job_id: str, task_collection: _models.BatchTaskGroup, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchCreateTaskCollectionResult: @@ -7801,7 +7679,7 @@ def create_task_collection( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7887,7 +7765,7 @@ def delete_task( # pylint: disable=inconsistent-return-statements job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -7909,7 +7787,7 @@ def delete_task( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7998,7 +7876,7 @@ def get_task( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -8020,7 +7898,7 @@ def get_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8132,7 +8010,7 @@ def replace_task( # pylint: disable=inconsistent-return-statements task_id: str, task: _models.BatchTask, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -8151,7 +8029,7 @@ def replace_task( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8250,7 +8128,7 @@ def list_subtasks( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -8266,7 +8144,7 @@ def list_subtasks( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8321,7 +8199,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -8369,7 +8250,7 @@ def terminate_task( # pylint: disable=inconsistent-return-statements job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -8390,7 +8271,7 @@ def terminate_task( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8482,7 +8363,7 @@ def reactivate_task( # pylint: disable=inconsistent-return-statements job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -8506,7 +8387,7 @@ def reactivate_task( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8599,7 +8480,7 @@ def delete_task_file( # pylint: disable=inconsistent-return-statements task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, recursive: Optional[bool] = None, **kwargs: Any @@ -8617,7 +8498,7 @@ def delete_task_file( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8690,7 +8571,7 @@ def download_task_file( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -8708,7 +8589,7 @@ def download_task_file( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8811,7 +8692,7 @@ def _get_task_file_properties_internal( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -8828,7 +8709,7 @@ def _get_task_file_properties_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8915,7 +8796,7 @@ def list_task_files( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -8933,7 +8814,7 @@ def list_task_files( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9000,7 +8881,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -9049,7 +8933,7 @@ def create_node_user( # pylint: disable=inconsistent-return-statements node_id: str, user: _models.BatchNodeUserCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9070,7 +8954,7 @@ def create_node_user( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9145,7 +9029,7 @@ def delete_node_user( # pylint: disable=inconsistent-return-statements node_id: str, user_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9166,7 +9050,7 @@ def delete_node_user( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9233,7 +9117,7 @@ def replace_node_user( # pylint: disable=inconsistent-return-statements user_name: str, update_options: _models.BatchNodeUserReplaceOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9255,7 +9139,7 @@ def replace_node_user( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9330,7 +9214,7 @@ def get_node( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -9346,7 +9230,7 @@ def get_node( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9427,9 +9311,9 @@ def _reboot_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - options: Optional[_models._models.BatchNodeRebootOptions] = None, + options: Optional[_models.BatchNodeRebootOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9442,11 +9326,11 @@ def _reboot_node_internal( # pylint: disable=inconsistent-return-statements :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str :param options: The options to use for rebooting the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeRebootOptions + :type options: ~azure.batch.models.BatchNodeRebootOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9524,7 +9408,7 @@ def _start_node_internal( # pylint: disable=inconsistent-return-statements pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9539,7 +9423,7 @@ def _start_node_internal( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9605,9 +9489,9 @@ def _reimage_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - options: Optional[_models._models.BatchNodeReimageOptions] = None, + options: Optional[_models.BatchNodeReimageOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9622,11 +9506,11 @@ def _reimage_node_internal( # pylint: disable=inconsistent-return-statements :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str :param options: The options to use for reimaging the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeReimageOptions + :type options: ~azure.batch.models.BatchNodeReimageOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9703,9 +9587,9 @@ def _deallocate_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - options: Optional[_models._models.BatchNodeDeallocateOptions] = None, + options: Optional[_models.BatchNodeDeallocateOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9718,11 +9602,11 @@ def _deallocate_node_internal( # pylint: disable=inconsistent-return-statements :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str :param options: The options to use for deallocating the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeDeallocateOptions + :type options: ~azure.batch.models.BatchNodeDeallocateOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9801,7 +9685,7 @@ def disable_node_scheduling( # pylint: disable=inconsistent-return-statements node_id: str, options: Optional[_models.BatchNodeDisableSchedulingOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9821,7 +9705,7 @@ def disable_node_scheduling( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9899,7 +9783,7 @@ def enable_node_scheduling( # pylint: disable=inconsistent-return-statements pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -9916,7 +9800,7 @@ def enable_node_scheduling( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -9983,7 +9867,7 @@ def get_node_remote_login_settings( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchNodeRemoteLoginSettings: @@ -10002,7 +9886,7 @@ def get_node_remote_login_settings( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10083,7 +9967,7 @@ def upload_node_logs( node_id: str, upload_options: _models.UploadBatchServiceLogsOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.UploadBatchServiceLogsResult: @@ -10104,7 +9988,7 @@ def upload_node_logs( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10190,7 +10074,7 @@ def list_nodes( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -10206,7 +10090,7 @@ def list_nodes( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10270,7 +10154,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -10319,7 +10206,7 @@ def get_node_extension( node_id: str, extension_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -10338,7 +10225,7 @@ def get_node_extension( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10421,7 +10308,7 @@ def list_node_extensions( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, select: Optional[list[str]] = None, @@ -10438,7 +10325,7 @@ def list_node_extensions( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10497,7 +10384,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -10546,7 +10436,7 @@ def delete_node_file( # pylint: disable=inconsistent-return-statements node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, recursive: Optional[bool] = None, **kwargs: Any @@ -10564,7 +10454,7 @@ def delete_node_file( # pylint: disable=inconsistent-return-statements :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10637,7 +10527,7 @@ def download_node_file( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -10655,7 +10545,7 @@ def download_node_file( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10758,7 +10648,7 @@ def _get_node_file_properties_internal( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -10775,7 +10665,7 @@ def _get_node_file_properties_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10862,7 +10752,7 @@ def list_node_files( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -10880,7 +10770,7 @@ def list_node_files( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -10945,7 +10835,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( diff --git a/sdk/batch/azure-batch/azure/batch/_operations/_patch.py b/sdk/batch/azure-batch/azure/batch/_operations/_patch.py index df6e89143bc7..ea765788358a 100644 --- a/sdk/batch/azure-batch/azure/batch/_operations/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/_operations/_patch.py @@ -1,1449 +1,14 @@ -# pylint: disable=too-many-lines -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import datetime -from typing import Any, Callable, cast, Deque, Dict, List, Optional, Iterable, Iterator, TypeVar -import collections -import logging -import threading -from azure.core import MatchConditions -from azure.core.exceptions import ( - HttpResponseError, -) -from azure.core.polling import LROPoller -from azure.core.rest import HttpResponse, HttpRequest -from azure.core.pipeline import PipelineResponse -from azure.core.tracing.decorator import distributed_trace - -from .. import models as _models -from ._polling import ( - DeallocateNodePollingMethod, - DeleteJobPollingMethod, - DeleteJobSchedulePollingMethod, - DeletePoolPollingMethod, - DisableJobPollingMethod, - EnableJobPollingMethod, - RebootNodePollingMethod, - ReimageNodePollingMethod, - RemoveNodePollingMethod, - ResizePoolPollingMethod, - StartNodePollingMethod, - StopPoolResizePollingMethod, - TerminateJobPollingMethod, - TerminateJobSchedulePollingMethod, -) -from ._operations import ( - _BatchClientOperationsMixin as BatchClientOperationsMixinGenerated, -) - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -MAX_TASKS_PER_REQUEST = 100 -_LOGGER = logging.getLogger(__name__) - -__all__: List[str] = [ - "_BatchClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level - - -class _BatchClientOperationsMixin(BatchClientOperationsMixinGenerated): - """Customize generated code""" - - @distributed_trace - def begin_delete_job( - self, - job_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - force: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Deletes a Job with Long Running Operation support. - - Deleting a Job also deletes all Tasks that are part of that Job, and all Job - statistics. This also overrides the retention period for Task data; that is, if - the Job contains Tasks which are still retained on Compute Nodes, the Batch - services deletes those Tasks' working directories and all their contents. When - a Delete Job request is received, the Batch service sets the Job to the - deleting state. All update operations on a Job that is in deleting state will - fail with status code 409 (Conflict), with additional information indicating - that the Job is being deleted. - - :param job_id: The ID of the Job to delete. Required. - :type job_id: str - :keyword service_timeout: The maximum time that the server can spend processing the inital request to - delete the Job, in seconds. The default is 30 seconds. If the value is larger than 30, the - default will be used instead. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword force: If true, the server will delete the Job even if the corresponding nodes have - not fully processed the deletion. The default value is false. Default value is None. - :paramtype force: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: An LROPoller that can be used to wait for the job deletion to complete - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._delete_job_internal( - job_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - force=force, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeleteJobPollingMethod( - client=self, - initial_response=pipeline_response, - deserialization_callback=None, - job_id=job_id, - polling_interval=polling_interval, - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_disable_job( - self, - job_id: str, - disable_options: _models.BatchJobDisableOptions, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Disables a Job with Long Running Operation support. - - The Batch Service immediately moves the Job to the disabling state. Batch then - uses the disableTasks parameter to determine what to do with the currently - running Tasks of the Job. The Job remains in the disabling state until the - disable operation is completed and all Tasks have been dealt with according to - the disableTasks option; the Job then moves to the disabled state. No new Tasks - are started under the Job until it moves back to active state. If you try to - disable a Job that is in any state other than active, disabling, or disabled, - the request fails with status code 409. - - :param job_id: The ID of the Job to disable. Required. - :type job_id: str - :param disable_options: The options to use for disabling the Job. Required. - :type disable_options: ~azure.batch.models.BatchJobDisableOptions - :keyword service_timeout: The maximum time that the server can spend processing the inital request to - disable the Job, in seconds. The default is 30 seconds. If the value is larger than 30, the - default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._disable_job_internal( - job_id, - disable_options=disable_options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DisableJobPollingMethod( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_enable_job( - self, - job_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Enables a Job with Long Running Operation support. - When you call this API, the Batch service sets a disabled Job to the enabling - state. After the this operation is completed, the Job moves to the active - state, and scheduling of new Tasks under the Job resumes. The Batch service - does not allow a Task to remain in the active state for more than 180 days. - Therefore, if you enable a Job containing active Tasks which were added more - than 180 days ago, those Tasks will not run. - - :param job_id: The ID of the Job to enable. Required. - :type job_id: str - :keyword service_timeout: The maximum time that the server can spend processing the intal request to - enable the Job, in seconds. The default is 30 seconds. If the value is larger than 30, the - default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._enable_job_internal( - job_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = EnableJobPollingMethod( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_delete_job_schedule( - self, - job_schedule_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Deletes a Job Schedule with Long Running Operation support. - - When you delete a Job Schedule, this also deletes all Jobs and Tasks under - that schedule. When Tasks are deleted, all the files in their working - directories on the Compute Nodes are also deleted (the retention period is - ignored). The Job Schedule statistics are no longer accessible once the Job - Schedule is deleted, though they are still counted towards Account lifetime - statistics. - - :param job_schedule_id: The ID of the Job Schedule to delete. Required. - :type job_schedule_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - delete the Job Schedule, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: An LROPoller that can be used to wait for the job schedule deletion to complete - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._delete_job_schedule_internal( - job_schedule_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeleteJobSchedulePollingMethod( - self, pipeline_response, None, job_schedule_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_delete_pool( - self, - pool_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Deletes a Pool from specified Account with Long Running Operation support. - - When you request that a Pool be deleted, the following actions occur: the Pool - state is set to deleting; any ongoing resize operation on the Pool are stopped; - the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks - running on existing Compute Nodes are terminated and requeued (as if a resize - Pool operation had been requested with the default requeue option); finally, - the Pool is removed from the system. Because running Tasks are requeued, the - user can rerun these Tasks by updating their Job to target a different Pool. - The Tasks can then run on the new Pool. If you want to override the requeue - behavior, then you should call resize Pool explicitly to shrink the Pool to - zero size before deleting the Pool. If you call an Update, Patch or Delete API - on a Pool in the deleting state, it will fail with HTTP status code 409 with - error code PoolBeingDeleted. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to delete the Pool, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._delete_pool_internal( - pool_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeletePoolPollingMethod( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_deallocate_node( - self, - pool_id: str, - node_id: str, - options: Optional[_models._models.BatchNodeDeallocateOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Deallocates a Compute Node with Long Running Operation support. - - You can deallocate a Compute Node only if it is in an idle or running state. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :param options: The options to use for deallocating the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeDeallocateOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - deallocate the Compute Node, in seconds. The default is 30 seconds. If the value is larger - than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._deallocate_node_internal( - pool_id, - node_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeallocateNodePollingMethod( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_reboot_node( - self, - pool_id: str, - node_id: str, - options: Optional[_models._models.BatchNodeRebootOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Reboots a Compute Node with Long Running Operation support. - - You can restart a Compute Node only if it is in an idle or running state. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :param options: The options to use for rebooting the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeRebootOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - reboot the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._reboot_node_internal( - pool_id, - node_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = RebootNodePollingMethod( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_reimage_node( - self, - pool_id: str, - node_id: str, - options: Optional[_models._models.BatchNodeReimageOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Reimages a Compute Node with Long Running Operation support. - - Reinstalls the operating system on the specified Compute Node - - You can reinstall the operating system on a Compute Node only if it is in an - idle or running state. This API can be invoked only on Pools created with the - cloud service configuration property. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :param options: The options to use for reimaging the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeReimageOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - reimage the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._reimage_node_internal( - pool_id, - node_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = ReimageNodePollingMethod( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_remove_nodes( - self, - pool_id: str, - remove_options: _models.BatchNodeRemoveOptions, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Removes Compute Nodes from a Pool with Long Running Operation support. - - This operation can only run when the allocation state of the Pool is steady. - When this operation runs, the allocation state changes from steady to resizing. - Each request may remove up to 100 nodes. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :param remove_options: The options to use for removing the node. Required. - :type remove_options: ~azure.batch.models._models.BatchNodeRemoveOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - remove the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._remove_nodes_internal( - pool_id, - remove_options=remove_options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = RemoveNodePollingMethod( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_resize_pool( - self, - pool_id: str, - resize_options: _models.BatchPoolResizeOptions, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Resizes a Pool with Long Running Operation support. - - You can only resize a Pool when its allocation state is steady. If the Pool is - already resizing, the request fails with status code 409. When you resize a - Pool, the Pool's allocation state changes from steady to resizing. You cannot - resize Pools which are configured for automatic scaling. If you try to do this, - the Batch service returns an error 409. If you resize a Pool downwards, the - Batch service chooses which Compute Nodes to remove. To remove specific Compute - Nodes, use the Pool remove Compute Nodes API instead. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :param resize_options: The options to use for resizing the pool. Required. - :type resize_options: ~azure.batch.models.BatchPoolResizeOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to resize the Pool, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._resize_pool_internal( - pool_id, - resize_options=resize_options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = ResizePoolPollingMethod( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_start_node( - self, - pool_id: str, - node_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Starts a Compute Node with Long Running Operation support. - - You can start a Compute Node only if it has been deallocated. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - start the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._start_node_internal( - pool_id, - node_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = StartNodePollingMethod( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_stop_pool_resize( - self, - pool_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Stops an ongoing Pool resize operation with Long Running Operation support. - - This does not restore the Pool to its previous state before the resize - operation: it only stops any further changes being made, and the Pool maintains - its current state. After stopping, the Pool stabilizes at the number of Compute - Nodes it was at when the stop operation was done. During the stop operation, - the Pool allocation state changes first to stopping and then to steady. A - resize operation need not be an explicit resize Pool request; this API can also - be used to halt the initial sizing of the Pool when it is created. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to stop the Pool resize, in seconds. The default is 30 seconds. If the value is larger than - 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._stop_pool_resize_internal( - pool_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = StopPoolResizePollingMethod( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_terminate_job( - self, - job_id: str, - options: Optional[_models._models.BatchJobTerminateOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - force: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Terminates a Job with Long Running Operation support, marking it as completed. - - When a Terminate Job request is received, the Batch service sets the Job to the - terminating state. The Batch service then terminates any running Tasks - associated with the Job and runs any required Job release Tasks. Then the Job - moves into the completed state. If there are any Tasks in the Job in the active - state, they will remain in the active state. Once a Job is terminated, new - Tasks cannot be added and any remaining active Tasks will not be scheduled. - - :param job_id: The ID of the Job to terminate. Required. - :type job_id: str - :param options: The options to use for terminating the Job. Default value is None. - :type options: ~azure.batch.models._models.BatchJobTerminateOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to terminate the Job, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword force: If true, the server will terminate the Job even if the corresponding nodes have - not fully processed the termination. The default value is false. Default value is None. - :paramtype force: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._terminate_job_internal( - job_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - force=force, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = TerminateJobPollingMethod( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - def begin_terminate_job_schedule( - self, - job_schedule_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - force: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> LROPoller[None]: - """Terminates a Job Schedule with Long Running Operation support. - - :param job_schedule_id: The ID of the Job Schedule to terminates. Required. - :type job_schedule_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - terminate the Job Schedule, in seconds. The default is 30 seconds. If the value is larger than - 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword force: If true, the server will terminate the JobSchedule even if the corresponding - nodes have not fully processed the termination. The default value is false. Default value is - None. - :paramtype force: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - self._terminate_job_schedule_internal( - job_schedule_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - force=force, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = TerminateJobSchedulePollingMethod( - self, pipeline_response, None, job_schedule_id, polling_interval=polling_interval - ) - return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - # create_task_collection renamed - @distributed_trace - def create_tasks( - self, - job_id: str, - task_collection: List[_models.BatchTaskCreateOptions], - *, - max_concurrency: Optional[int] = None, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> _models.BatchCreateTaskCollectionResult: - """Adds a collection of Tasks to the specified Job. - - Note that each Task must have a unique ID. The Batch service may not return the - results for each Task in the same order the Tasks were submitted in this - request. If the server times out or the connection is closed during the - request, the request may have been partially or fully processed, or not at all. - In such cases, the user should re-issue the request. Note that it is up to the - user to correctly handle failures when re-issuing a request. For example, you - should use the same Task IDs during a retry so that if the prior operation - succeeded, the retry will not create extra Tasks unexpectedly. If the response - contains any Tasks which failed to add, a client can retry the request. In a - retry, it is most efficient to resubmit only Tasks that failed to add, and to - omit Tasks that were successfully added on the first attempt. The maximum - lifetime of a Task from addition to completion is 180 days. If a Task has not - completed within 180 days of being added it will be terminated by the Batch - service and left in whatever state it was in at that time. - - :param job_id: The ID of the Job to which the Task collection is to be added. Required. - :type job_id: str - :param task_collection: The Tasks to be added. Required. - :type task_collection: ~azure.batch.models.BatchTaskAddCollectionResult - :keyword max_concurrency: number of threads to use in parallel when adding tasks. If specified - and greater than 0, will start additional threads to submit requests and wait for them to finish. - Otherwise will submit create_task_collection requests sequentially on main thread - :paramtype max_concurrency: int - :keyword service_timeout: The maximum time that the server can spend processing the equest to - create the task collection, in seconds. The default is 30 seconds. If the value is larger than - 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :return: BatchTaskAddCollectionResult. The BatchTaskAddCollectionResult is compatible with MutableMapping - :rtype: ~azure.batch.models.BatchTaskAddCollectionResult - :raises ~azure.batch.custom.CreateTasksError: - """ - - kwargs.update({"service_timeout": service_timeout, "ocp_date": ocp_date}) - - # deque operations(append/pop) are thread-safe - results_queue: Deque[_models.BatchTaskCreateResult] = collections.deque() - task_workflow_manager = _TaskWorkflowManager(self, job_id=job_id, task_collection=task_collection, **kwargs) - - # multi-threaded behavior - if max_concurrency: - if max_concurrency < 0: - raise ValueError("max_concurrency must be positive or 0") - - active_threads = [] - for _ in range(max_concurrency): - active_threads.append( - threading.Thread( - target=task_workflow_manager.task_collection_thread_handler, - args=(results_queue,), - ) - ) - active_threads[-1].start() - for thread in active_threads: - thread.join() - # single-threaded behavior - else: - task_workflow_manager.task_collection_thread_handler(results_queue) - - # Only define error if all threads have finished and there were failures - if task_workflow_manager.failure_tasks or task_workflow_manager.errors: - raise _models.CreateTasksError( - task_workflow_manager.tasks_to_add, - task_workflow_manager.failure_tasks, - task_workflow_manager.errors, - ) - submitted_tasks = _handle_output(results_queue) - return _models.BatchCreateTaskCollectionResult(result_values=submitted_tasks) - - @distributed_trace - def download_node_file( - self, - pool_id: str, - node_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - ocp_range: Optional[str] = None, - **kwargs: Any - ) -> Iterator[bytes]: - """Returns the content of the specified Compute Node file. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node from which you want to delete the file. Required. - :type node_id: str - :param file_path: The path to the file or directory that you want to delete. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword ocp_range: The byte range to be retrieved. The default is to retrieve the entire file. - The - format is bytes=startRange-endRange. Default value is None. - :paramtype ocp_range: str - :return: bytes - :rtype: bytes - :raises ~azure.core.exceptions.HttpResponseError: - """ - args = [pool_id, node_id, file_path] - kwargs.update( - { - "service_timeout": service_timeout, - "ocp_date": ocp_date, - "if_modified_since": if_modified_since, - "if_unmodified_since": if_unmodified_since, - "ocp_range": ocp_range, - } - ) - kwargs["stream"] = True - return super().download_node_file(*args, **kwargs) - - @distributed_trace - def get_node_file_properties( - self, - pool_id: str, - node_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> _models.BatchFileProperties: - """Gets the properties of the specified Compute Node file. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node from which you want to delete the file. Required. - :type node_id: str - :param file_path: The path to the file or directory that you want to delete. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :return: BatchFileProperties - :rtype: ~azure.batch.models.BatchFileProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def cls(_pipeline_response, _json_response, headers): - return _models.BatchFileProperties( - url=headers["ocp-batch-file-url"], - is_directory=headers["ocp-batch-file-isdirectory"], - last_modified=headers["Last-Modified"], - content_length=headers["Content-Length"], - creation_time=headers["ocp-creation-time"], - # content_type=headers["Content-Type"], # need to add to typespec - file_mode=headers["ocp-batch-file-mode"], - ) - - get_response: _models.BatchFileProperties = super()._get_node_file_properties_internal( # type: ignore - pool_id, - node_id, - file_path, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - cls=cls, - **kwargs, - ) - - return get_response - - @distributed_trace - def get_task_file_properties( - self, - job_id: str, - task_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> _models.BatchFileProperties: - """Gets the properties of the specified Task file. - - :param job_id: The ID of the Job that contains the Task. Required. - :type job_id: str - :param task_id: The ID of the Task whose file you want to retrieve. Required. - :type task_id: str - :param file_path: The path to the Task file that you want to get the content of. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :return: BatchFileProperties - :rtype: ~azure.batch.models.BatchFileProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def cls(_pipeline_response, _json_response, headers): - return _models.BatchFileProperties( - url=headers["ocp-batch-file-url"], - is_directory=headers["ocp-batch-file-isdirectory"], - last_modified=headers["Last-Modified"], - content_length=headers["Content-Length"], - creation_time=headers["ocp-creation-time"], - # content_type=headers["Content-Type"], # need to add to typespec - file_mode=headers["ocp-batch-file-mode"], - ) - - get_response: _models.BatchFileProperties = super()._get_task_file_properties_internal( # type: ignore - job_id, - task_id, - file_path, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - cls=cls, - **kwargs, - ) - - return get_response - - @distributed_trace - def download_task_file( - self, - job_id: str, - task_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - ocp_range: Optional[str] = None, - **kwargs: Any - ) -> Iterator[bytes]: - """Returns the content of the specified Task file. - - :param job_id: The ID of the Job that contains the Task. Required. - :type job_id: str - :param task_id: The ID of the Task whose file you want to retrieve. Required. - :type task_id: str - :param file_path: The path to the Task file that you want to get the content of. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword ocp_range: The byte range to be retrieved. The default is to retrieve the entire file. - The - format is bytes=startRange-endRange. Default value is None. - :paramtype ocp_range: str - :return: bytes - :rtype: bytes - :raises ~azure.core.exceptions.HttpResponseError: - """ - - args = [job_id, task_id, file_path] - kwargs.update( - { - "service_timeout": service_timeout, - "ocp_date": ocp_date, - "if_modified_since": if_modified_since, - "if_unmodified_since": if_unmodified_since, - "ocp_range": ocp_range, - } - ) - kwargs["stream"] = True - return super().download_task_file(*args, **kwargs) +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -1453,171 +18,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - - -class _TaskWorkflowManager: - """Worker class for one create_task_collection request - - :param batch_client: Parent object which instantiated this - :type batch_client: ~_BatchClientOperationsMixin - :param str job_id: The ID of the job to which the task collection is to be - added. - :param task_collection: The collection of tasks to add. - :type task_collection: Iterable[~azure.batch.models.BatchTaskCreateOptions] - :param kwargs: Additional parameters for the operation - :type kwargs: dict - """ - - def __init__( - self, - batch_client: _BatchClientOperationsMixin, - job_id: str, - task_collection: Iterable[_models.BatchTaskCreateOptions], - **kwargs - ): - # Append operations thread safe - Only read once all threads have completed - # List of tasks which failed to add due to a returned client error - self.failure_tasks: Deque[_models.BatchTaskCreateResult] = collections.deque() - # List of unknown exceptions which occurred during requests. - self.errors: Deque[Any] = collections.deque() - - # synchronized through lock variables - self._max_tasks_per_request = MAX_TASKS_PER_REQUEST - self.tasks_to_add = collections.deque(task_collection) - self._error_lock = threading.Lock() - self._max_tasks_lock = threading.Lock() - self._pending_queue_lock = threading.Lock() - - # Variables to be used for task create_task_collection requests - self._batch_client = batch_client - self._job_id = job_id - - self._kwargs = kwargs - - def _bulk_add_tasks( - self, - results_queue: collections.deque, - chunk_tasks_to_add: List[_models.BatchTaskCreateOptions], - ): - """Adds a chunk of tasks to the job - - Retry chunk if body exceeds the maximum request size and retry tasks - if failed due to server errors. - - :param results_queue: Queue to place the return value of the request - :type results_queue: collections.deque - :param chunk_tasks_to_add: Chunk of at most 100 tasks with retry details - :type chunk_tasks_to_add: list[~azure.batch.models.BatchTaskCreateOptions] - """ - - try: - create_task_collection_response: _models.BatchCreateTaskCollectionResult = ( - self._batch_client.create_task_collection( - job_id=self._job_id, - task_collection=_models.BatchTaskGroup(task_values=chunk_tasks_to_add), - **self._kwargs, - ) - ) - except HttpResponseError as e: - # In case of a chunk exceeding the MaxMessageSize split chunk in half - # and resubmit smaller chunk requests - # TODO: Replace string with constant variable once available in SDK - if e.error and e.error.code == "RequestBodyTooLarge": # pylint: disable=no-member - # In this case the task is misbehaved and will not be able to be added due to: - # 1) The task exceeding the max message size - # 2) A single cell of the task exceeds the per-cell limit, or - # 3) Sum of all cells exceeds max row limit - if len(chunk_tasks_to_add) == 1: - failed_task = chunk_tasks_to_add.pop() - self.errors.appendleft(e) - _LOGGER.error( - "Failed to add task with ID %s due to the body exceeding the maximum request size", - failed_task.id, - ) - else: - # Assumption: Tasks are relatively close in size therefore if one batch exceeds size limit - # we should decrease the initial task collection size to avoid repeating the error - # Midpoint is lower bounded by 1 due to above base case - midpoint = int(len(chunk_tasks_to_add) / 2) - # Restrict one thread at a time to do this compare and set, - # therefore forcing max_tasks_per_request to be strictly decreasing - with self._max_tasks_lock: - if midpoint < self._max_tasks_per_request: - _LOGGER.info( - "Amount of tasks per request reduced from %s to %s due to the" - " request body being too large", - str(self._max_tasks_per_request), - str(midpoint), - ) - self._max_tasks_per_request = midpoint - - # Not the most efficient solution for all cases, but the goal of this is to handle this - # exception and have it work in all cases where tasks are well behaved - # Behavior retries as a smaller chunk and - # appends extra tasks to queue to be picked up by another thread . - self.tasks_to_add.extendleft(chunk_tasks_to_add[midpoint:]) - self._bulk_add_tasks(results_queue, chunk_tasks_to_add[:midpoint]) - # Retry server side errors - elif 500 <= e.response.status_code <= 599: # type: ignore - self.tasks_to_add.extendleft(chunk_tasks_to_add) - else: - # Re-add to pending queue as unknown status / don't have result - self.tasks_to_add.extendleft(chunk_tasks_to_add) - # Unknown State - don't know if tasks failed to add or were successful - self.errors.appendleft(e) - except Exception as e: # pylint: disable=broad-except - # Re-add to pending queue as unknown status / don't have result - self.tasks_to_add.extendleft(chunk_tasks_to_add) - # Unknown State - don't know if tasks failed to add or were successful - self.errors.appendleft(e) - else: - if create_task_collection_response.result_values: - for task_result in create_task_collection_response.result_values: # pylint: disable=no-member - if task_result.status == _models.BatchTaskAddStatus.SERVER_ERROR: - # Server error will be retried - with self._pending_queue_lock: - for task in chunk_tasks_to_add: - if task.id == task_result.task_id: - self.tasks_to_add.appendleft(task) - elif task_result.status == _models.BatchTaskAddStatus.CLIENT_ERROR and not ( - task_result.error and task_result.error.code == "TaskExists" - ): - # Client error will be recorded unless Task already exists - self.failure_tasks.appendleft(task_result) - else: - results_queue.appendleft(task_result) - - def task_collection_thread_handler(self, results_queue): - """Main method for worker to run - - Pops a chunk of tasks off the collection of pending tasks to be added and submits them to be added. - - :param collections.deque results_queue: Queue for worker to output results to - """ - # Add tasks until either we run out or we run into an unexpected error - while self.tasks_to_add and not self.errors: - max_tasks = self._max_tasks_per_request # local copy - chunk_tasks_to_add = [] - with self._pending_queue_lock: - while len(chunk_tasks_to_add) < max_tasks and self.tasks_to_add: - chunk_tasks_to_add.append(self.tasks_to_add.pop()) - - if chunk_tasks_to_add: - self._bulk_add_tasks(results_queue, chunk_tasks_to_add) - - -def _handle_output(results_queue): - """Scan output for exceptions - - If there is an output from an add task collection call add it to the results. - - :param results_queue: Queue containing results of attempted create_task_collection's - :type results_queue: collections.deque - :return: list of TaskAddResults - :rtype: list[~TaskAddResult] - """ - results = [] - while results_queue: - queue_item = results_queue.pop() - results.append(queue_item) - return results diff --git a/sdk/batch/azure-batch/azure/batch/_operations/_polling.py b/sdk/batch/azure-batch/azure/batch/_operations/_polling.py deleted file mode 100644 index f50080380564..000000000000 --- a/sdk/batch/azure-batch/azure/batch/_operations/_polling.py +++ /dev/null @@ -1,1077 +0,0 @@ -# pylint: disable=too-many-lines -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -""" Custom Sync Polling Methods for Azure Batch Operations.""" - -import time -from typing import Any, Callable, Optional - -from azure.core.exceptions import AzureError, ResourceNotFoundError -from azure.core.pipeline import PipelineResponse -from azure.core.polling import PollingMethod - -from .. import models as _models - - -class DeleteJobPollingMethod(PollingMethod): - """Polling method for job delete operation. - - This class is used to poll the status of a job deletion operation. - It checks the status of the job until it is deleted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.DELETING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job no longer exists, deletion is complete - self._status = "Succeeded" - self._finished = True - except AzureError: - # Some other error occurred, operation failed - self._status = "Failed" - self._finished = True - - -class DisableJobPollingMethod(PollingMethod): - """Polling method for job disable operation. - - This class is used to poll the status of a job disable operation. - It checks the status of the job until it is disabled or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._status = "InProgress" - self._finished = False - self._job_id = job_id - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.DISABLING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # If job doesn't exist it could've been deleted while disabling - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class EnableJobPollingMethod(PollingMethod): - """Polling method for job enable operation. - - This class is used to poll the status of a job enable operation. - It checks the status of the job until it is enabled or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.ENABLING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # If job doesn't exist it could've been deleted while enabling - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class DeleteJobSchedulePollingMethod(PollingMethod): - """Polling method for job schedule delete operation. - - This class is used to poll the status of a job schedule deletion operation. - It checks the status of the job schedule until it is deleted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_schedule_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_schedule_id = job_schedule_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job_schedule = self._client.get_job_schedule(self._job_schedule_id) - - if job_schedule.state == _models.BatchJobScheduleState.DELETING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job schedule no longer exists, deletion is complete - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class DeletePoolPollingMethod(PollingMethod): - """Polling method for pool delete operation. - This class is used to poll the status of a pool deletion operation. - It checks the status of the pool until it is deleted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = self._client.get_pool(self._pool_id) - - if pool.state == _models.BatchPoolState.DELETING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Pool no longer exists, deletion is complete - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class DeallocateNodePollingMethod(PollingMethod): - """Polling method for node deallocate operation. - - This class is used to poll the status of a node deallocation operation. - It checks the status of the node until it is deallocated or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = self._client.get_node(self._pool_id, self._node_id) - - # If node not in DEALLOCATING state then completed - # DEALLOCATED is too quick of a state to check for success - if node.state == _models.BatchNodeState.DEALLOCATING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node no longer exists, might have been removed from pool - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class RebootNodePollingMethod(PollingMethod): - """Polling method for node reboot operation. - - This class is used to poll the status of a node reboot operation. - It checks the status of the node until it is rebooted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = self._client.get_node(self._pool_id, self._node_id) - - if node.state == _models.BatchNodeState.REBOOTING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node could be deleted while rebooting - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class ReimageNodePollingMethod(PollingMethod): - """Polling method for node reimage operation. - - This class is used to poll the status of a node reimage operation. - It checks the status of the node until it is reimaged or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = self._client.get_node(self._pool_id, self._node_id) - - if node.state == _models.BatchNodeState.REIMAGING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node could be deleted while reimaging - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class RemoveNodePollingMethod(PollingMethod): - """Polling method for node remove operation. - - This class is used to poll the status of a node removal operation. - It checks the status of the node until it is removed or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = self._client.get_pool(self._pool_id) - - # Node removal is complete when the pool allocation state is STEADY - # This means the pool is no longer resizing/removing nodes - if pool.allocation_state == _models.AllocationState.STEADY: - self._status = "Succeeded" - self._finished = True - else: - self._status = "InProgress" - self._finished = False - - except ResourceNotFoundError: - # Pool could be deleted while removing nodes - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class ResizePoolPollingMethod(PollingMethod): - """Polling method for pool resize operation. - - This class is used to poll the status of a pool resize operation. - It checks the status of the pool until it is resized or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = self._client.get_pool(self._pool_id) - - # Pool resize is complete when the pool allocation state is STEADY - # This means the pool is no longer resizing (adding/removing nodes) - if pool.allocation_state == _models.AllocationState.STEADY: - self._status = "Succeeded" - self._finished = True - else: - self._status = "InProgress" - self._finished = False - - except ResourceNotFoundError: - # Pool could be deleted while resizing - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class StartNodePollingMethod(PollingMethod): - """Polling method for node start operation. - - This class is used to poll the status of a node start operation. - It checks the status of the node until it is started or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = self._client.get_node(self._pool_id, self._node_id) - - if node.state == _models.BatchNodeState.STARTING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node could be deleted during starting - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class StopPoolResizePollingMethod(PollingMethod): - """Polling method for pool stop resize operation. - - This class is used to poll the status of a pool stop resize operation. - It checks the status of the pool until it is stopped or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = self._client.get_pool(self._pool_id) - - # Pool stop resize is complete when the pool allocation state is STEADY - # This means the pool has stopped resizing and is stable - if pool.allocation_state == _models.AllocationState.STEADY: - self._status = "Succeeded" - self._finished = True - else: - self._status = "InProgress" - self._finished = False - - except ResourceNotFoundError: - # Pool could be deleted during stop resize operation - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class TerminateJobPollingMethod(PollingMethod): - """Polling method for job termination operation. - - This class is used to poll the status of a job termination operation. - It checks the status of the job until it is terminated or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.TERMINATING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job could be deleted while terminating - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class TerminateJobSchedulePollingMethod(PollingMethod): - """Polling method for job schedule termination operation. - - This class is used to poll the status of a job schedule termination operation. - It checks the status of the job schedule until it is terminated or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_schedule_id: str, - *, - polling_interval: int = 5, - ): - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_schedule_id = job_schedule_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - self.update_status() - if not self.finished(): - # add a delay if not done - time.sleep(self._polling_interval) - - def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job_schedule = self._client.get_job_schedule(self._job_schedule_id) - - # Job schedule termination is complete when it's no longer in TERMINATING state - if job_schedule.state == _models.BatchJobScheduleState.TERMINATING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job schedule could be deleted while terminating - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True diff --git a/sdk/batch/azure-batch/azure/batch/_patch.py b/sdk/batch/azure-batch/azure/batch/_patch.py index 1e4ef9ed3bd1..ea765788358a 100644 --- a/sdk/batch/azure-batch/azure/batch/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/_patch.py @@ -1,204 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import base64 -import hmac -import hashlib -from datetime import datetime -from typing import Union -from azure.core.pipeline.policies import SansIOHTTPPolicy -from azure.core.credentials import AzureNamedKeyCredential, TokenCredential -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ODataV4Format, - ResourceExistsError, - ResourceModifiedError, - ResourceNotFoundError, -) -from azure.core.pipeline import PipelineResponse, PipelineRequest - -from ._client import BatchClient as GenerateBatchClient -from . import models as _models -from ._serialization import ( - Serializer, - TZ_UTC, -) -from ._utils.model_base import _failsafe_deserialize - -try: - from urlparse import urlparse, parse_qs -except ImportError: - from urllib.parse import urlparse, parse_qs -__all__ = [ - "BatchClient", -] # Add all objects you want publicly available to users at this package level - - -class BatchSharedKeyAuthPolicy(SansIOHTTPPolicy): - - headers_to_sign = [ - "content-encoding", - "content-language", - "content-length", - "content-md5", - "content-type", - "date", - "if-modified-since", - "if-match", - "if-none-match", - "if-unmodified-since", - "range", - ] - - def __init__(self, credential: AzureNamedKeyCredential): - super(BatchSharedKeyAuthPolicy, self).__init__() - self._account_name = credential.named_key.name - self._key = credential.named_key.key - - def on_request(self, request: PipelineRequest): - if not request.http_request.headers.get("ocp-date"): - now = datetime.utcnow() - now = now.replace(tzinfo=TZ_UTC) - request.http_request.headers["ocp-date"] = Serializer.serialize_rfc(now) - url = urlparse(request.http_request.url) - uri_path = url.path - - # method to sign - string_to_sign = request.http_request.method + "\n" - - # get headers to sign - request_header_dict = {key.lower(): val for key, val in request.http_request.headers.items() if val} - - if request.http_request.method not in ["GET", "HEAD"]: - if "content-length" not in request_header_dict: - request_header_dict["content-length"] = "0" - - request_headers = [str(request_header_dict.get(x, "")) for x in self.headers_to_sign] - - string_to_sign += "\n".join(request_headers) + "\n" - - # get ocp- header to sign - ocp_headers = [] - for name, value in request.http_request.headers.items(): - if "ocp-" in name and value: - ocp_headers.append((name.lower(), value)) - for name, value in sorted(ocp_headers): - string_to_sign += "{}:{}\n".format(name, value) - # get account_name and uri path to sign - string_to_sign += "/{}{}".format(self._account_name, uri_path) - - # get query string to sign if it is not table service - query_to_sign = parse_qs(url.query) - - for name in sorted(query_to_sign.keys()): - value = query_to_sign[name][0] - if value: - string_to_sign += "\n{}:{}".format(name, value) - # sign the request - auth_string = "SharedKey {}:{}".format(self._account_name, self._sign_string(string_to_sign)) - - request.http_request.headers["Authorization"] = auth_string - - return super().on_request(request) - - def _sign_string(self, string_to_sign): - - _key = self._key.encode("utf-8") - string_to_sign = string_to_sign.encode("utf-8") - - try: - key = base64.b64decode(_key) - except TypeError as exc: - raise ValueError("Invalid key value: {}".format(self._key)) from exc - signed_hmac_sha256 = hmac.HMAC(key, string_to_sign, hashlib.sha256) - digest = signed_hmac_sha256.digest() - - return base64.b64encode(digest).decode("utf-8") - - -class BatchErrorFormat(ODataV4Format): - def __init__(self, odata_error): - try: - if odata_error: - super().__init__(odata_error) - self.message = odata_error["message"]["value"] - if "values" in odata_error: - for item in odata_error["values"]: - self.details.append(ODataV4Format({"code": item["key"], "message": item["value"]})) - except KeyError: - super().__init__(odata_error) - - -class BatchExceptionPolicy(SansIOHTTPPolicy): - - def on_response(self, request: PipelineRequest, response: PipelineResponse): - req = request.http_request - res = response.http_response - - if not (res.status_code >= 200 and res.status_code < 300): - raise_error = HttpResponseError - error = _failsafe_deserialize(_models.BatchError, res) - - # for 412 status code error handling - if_match = req.headers.get("If-Match") - if_none_match = req.headers.get("If-None-Match") - - if if_match == "*": - raise_error = ResourceNotFoundError - elif if_match is not None: - raise_error = ResourceModifiedError - elif if_none_match == "*": - raise_error = ResourceNotFoundError - elif res.status_code == 401: - raise_error = ClientAuthenticationError - elif res.status_code == 404: - raise_error = ResourceNotFoundError - elif res.status_code == 409: - raise_error = ResourceExistsError - elif res.status_code == 304: - raise_error = ResourceModifiedError - - raise raise_error(response=res, model=error, error_format=BatchErrorFormat) - - -class BatchClient(GenerateBatchClient): - """BatchClient. - - :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. - :type endpoint: str - :param hub: Target hub name, which should start with alphabetic characters and only contain - alpha-numeric characters or underscore. - :type hub: str - :param credentials: Credential needed for the client to connect to Azure. - :type credentials: ~azure.identity.ClientSecretCredential, ~azure.core.credentials.AzureNamedKeyCredential, - or ~azure.identity.TokenCredentials - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, credential: Union[AzureNamedKeyCredential, TokenCredential], **kwargs) -> None: - per_call_policies = kwargs.pop("per_call_policies", []) - per_call_policies.append(BatchExceptionPolicy()) - super().__init__( - endpoint=endpoint, - credential=credential, # type: ignore - authentication_policy=kwargs.pop("authentication_policy", self._format_shared_key_credential(credential)), - per_call_policies=per_call_policies, - **kwargs - ) - - def _format_shared_key_credential(self, credential): - if isinstance(credential, AzureNamedKeyCredential): - return BatchSharedKeyAuthPolicy(credential) - return None +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/batch/azure-batch/azure/batch/_serialization.py b/sdk/batch/azure-batch/azure/batch/_serialization.py deleted file mode 100644 index 38cab8750dc3..000000000000 --- a/sdk/batch/azure-batch/azure/batch/_serialization.py +++ /dev/null @@ -1,2050 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Dict, - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, - List, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): # type: ignore[arg-type] - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec # pylint: disable=eval-used - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(List[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: Dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec # pylint: disable=eval-used - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/batch/azure-batch/azure/batch/_utils/model_base.py b/sdk/batch/azure-batch/azure/batch/_utils/model_base.py index db24930fdca9..35d5fc024978 100644 --- a/sdk/batch/azure-batch/azure/batch/_utils/model_base.py +++ b/sdk/batch/azure-batch/azure/batch/_utils/model_base.py @@ -23,14 +23,19 @@ from json import JSONEncoder import xml.etree.ElementTree as ET from collections.abc import MutableMapping -from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError from azure.core import CaseInsensitiveEnumMeta from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null + from azure.core.rest import HttpResponse +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -104,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -130,7 +158,15 @@ def _is_readonly(p): class SdkJSONEncoder(JSONEncoder): - """A JSON encoder that's capable of serializing datetime objects and bytes.""" + """A JSON encoder that's capable of serializing datetime objects and bytes. + + :param args: Additional positional arguments passed to the base ``JSONEncoder``. + :type args: typing.Any + :keyword exclude_readonly: Whether to exclude readonly properties. Defaults to False. + :paramtype exclude_readonly: bool + :keyword format: The format to use for serialization. Defaults to None. + :paramtype format: typing.Optional[str] + """ def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): super().__init__(*args, **kwargs) @@ -296,6 +332,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -308,6 +350,12 @@ def _deserialize_int_as_str(attr): return int(attr) +def _deserialize_bool_as_str(attr): + if isinstance(attr, bool): + return attr + return attr.lower() == "true" + + _DESERIALIZE_MAPPING = { datetime: _deserialize_datetime, date: _deserialize_date, @@ -325,12 +373,18 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): if annotation is int and rf and rf._format == "str": return _deserialize_int_as_str + if annotation is bool and rf and rf._format == "str": + return _deserialize_bool_as_str if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) if rf and rf._format: @@ -420,21 +474,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping's keys :rtype: ~typing.KeysView """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: """ - :returns: an object providing a view on D's values + :returns: an object providing a view on the mapping's values :rtype: ~typing.ValuesView """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: """ - :returns: set-like object providing a view on D's items + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -444,7 +498,7 @@ def get(self, key: str, default: typing.Any = None) -> typing.Any: Get the value for key if key is in the dictionary, else default. :param str key: The key to look up. :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -479,19 +533,19 @@ def popitem(self) -> tuple[str, typing.Any]: Removes and returns some (key, value) pair :returns: The (key, value) pair. :rtype: tuple - :raises KeyError: if D is empty. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ """ - Updates D from mapping/iterable E and F. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -504,10 +558,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: """ - Same as calling D.get(k, d), and setting D[k]=d if k not found + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :param str key: The key to look up. :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -559,7 +614,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass @@ -585,6 +640,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -595,11 +883,7 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ if len(args) > 1: raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") - dict_to_pass = { - rest_field._rest_name: rest_field._default - for rest_field in self._attr_to_rest_field.values() - if rest_field._default is not _UNSET - } + dict_to_pass: dict[str, typing.Any] = {} if args: if isinstance(args[0], ET.Element): dict_to_pass.update(self._init_from_xml(args[0])) @@ -619,9 +903,19 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) - def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + self, element: ET.Element + ) -> dict[str, typing.Any]: """Deserialize an XML element into a dict mapping rest field names to values. :param ET.Element element: The XML element to deserialize from. @@ -629,53 +923,89 @@ def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: :rtype: dict """ result: dict[str, typing.Any] = {} - model_meta = getattr(self, "_xml", {}) existed_attr_keys: list[str] = [] - for rf in self._attr_to_rest_field.values(): - prop_meta = getattr(rf, "_xml", {}) - xml_name = prop_meta.get("name", rf._rest_name) - xml_ns = _resolve_xml_ns(prop_meta, model_meta) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and element.get(xml_name) is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - _items_name = prop_meta.get("itemsName") - if _items_name: - xml_name = _items_name - _items_ns = prop_meta.get("itemsNs") - if _items_ns is not None: - xml_ns = _items_ns - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = element.findall(xml_name) # pyright: ignore - if len(items) > 0: + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and element.get(xml_name) is not None: existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: + result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + _items_name = prop_meta.get("itemsName") + if _items_name: + xml_name = _items_name + _items_ns = prop_meta.get("itemsNs") + if _items_ns is not None: + xml_ns = _items_ns + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = element.findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = _deserialize(rf._type, items) + elif not rf._is_optional: + existed_attr_keys.append(xml_name) + result[rf._rest_name] = [] + continue + + # text element is primitive type + if prop_meta.get("text", False): + if element.text is not None: + result[rf._rest_name] = _deserialize(rf._type, element.text) + continue + + # wrapped element could be normal property or array + item = element.find(xml_name) + if item is not None: existed_attr_keys.append(xml_name) - result[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if element.text is not None: - result[rf._rest_name] = _deserialize(rf._type, element.text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = element.find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, item) + result[rf._rest_name] = _deserialize(rf._type, item) # rest thing is additional properties for e in element: @@ -708,6 +1038,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: if not rf._rest_name_input: rf._rest_name_input = attr cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -1082,6 +1415,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ): self._type = type self._rest_name_input = name @@ -1094,6 +1428,7 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer @property def _class_type(self) -> typing.Any: @@ -1113,7 +1448,10 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # by this point, type and rest_name will have a value bc we default # them in __new__ of the Model class # Use _data.get() directly to avoid triggering __getitem__ which clears the cache - item = obj._data.get(self._rest_name) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: @@ -1126,7 +1464,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # Return the value from _data directly (it's been deserialized in place) return obj._data.get(self._rest_name) - deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) # For mutable types, store the deserialized value back in _data # so mutations directly affect _data @@ -1172,6 +1514,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ) -> typing.Any: return _RestField( name=name, @@ -1181,6 +1524,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, ) @@ -1414,6 +1758,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) diff --git a/sdk/batch/azure-batch/azure/batch/_utils/serialization.py b/sdk/batch/azure-batch/azure/batch/_utils/serialization.py index 81ec1de5922b..ae08f9d89f74 100644 --- a/sdk/batch/azure-batch/azure/batch/_utils/serialization.py +++ b/sdk/batch/azure-batch/azure/batch/_utils/serialization.py @@ -39,11 +39,15 @@ import xml.etree.ElementTree as ET import isodate # type: ignore -from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] @@ -476,7 +480,11 @@ def _decode_attribute_map_key(key): class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" + """Request object model serializer. + + :param classes: Mapping of model names to model types, used to resolve models during serialization. + :type classes: typing.Optional[typing.Mapping[str, type]] + """ basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -516,6 +524,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1105,6 +1117,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1377,6 +1444,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1389,6 +1460,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1401,7 +1476,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1411,6 +1486,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) @@ -1929,6 +2025,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/sdk/batch/azure-batch/azure/batch/_vendor.py b/sdk/batch/azure-batch/azure/batch/_vendor.py deleted file mode 100644 index 396a0128421a..000000000000 --- a/sdk/batch/azure-batch/azure/batch/_vendor.py +++ /dev/null @@ -1,57 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Optional, TYPE_CHECKING - -from azure.core import MatchConditions - -from ._configuration import BatchClientConfiguration - -if TYPE_CHECKING: - from azure.core import PipelineClient - - from ._serialization import Deserializer, Serializer - - -class BatchClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "PipelineClient" - _config: BatchClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith("W/"): - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None diff --git a/sdk/batch/azure-batch/azure/batch/_version.py b/sdk/batch/azure-batch/azure/batch/_version.py index 76bba1459abc..ed0698537fc7 100644 --- a/sdk/batch/azure-batch/azure/batch/_version.py +++ b/sdk/batch/azure-batch/azure/batch/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "15.1.0" +VERSION = "15.2.0" diff --git a/sdk/batch/azure-batch/azure/batch/aio/_client.py b/sdk/batch/azure-batch/azure/batch/aio/_client.py index cabe92fa3bd2..67c37f4a88b3 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_client.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_client.py @@ -7,8 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies @@ -18,11 +18,16 @@ from ._configuration import BatchClientConfiguration from ._operations import _BatchClientOperationsMixin +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore + if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class BatchClient(_BatchClientOperationsMixin): +class BatchClient(_BatchClientOperationsMixin): # pylint: disable=docstring-keyword-should-match-keyword-only """BatchClient. :param endpoint: Batch account endpoint (for example: @@ -31,9 +36,9 @@ class BatchClient(_BatchClientOperationsMixin): :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for this operation. Known values are "2025-06-01". - Default value is "2025-06-01". Note that overriding this default value may result in - unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-10-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ diff --git a/sdk/batch/azure-batch/azure/batch/aio/_configuration.py b/sdk/batch/azure-batch/azure/batch/aio/_configuration.py index 926eb1d35211..ba66bf657907 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_configuration.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_configuration.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -16,7 +17,7 @@ from azure.core.credentials_async import AsyncTokenCredential -class BatchClientConfiguration: # pylint: disable=too-many-instance-attributes +class BatchClientConfiguration: # pylint: disable=too-many-instance-attributes,docstring-keyword-should-match-keyword-only """Configuration for BatchClient. Note that all parameters used to create this instance are saved as instance @@ -28,14 +29,14 @@ class BatchClientConfiguration: # pylint: disable=too-many-instance-attributes :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for this operation. Known values are "2025-06-01". - Default value is "2025-06-01". Note that overriding this default value may result in - unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-10-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2025-06-01") + api_version: str = kwargs.pop("api_version", "2026-10-01") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py b/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py index e204edcdd816..9a05b6bda481 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py @@ -79,7 +79,6 @@ build_batch_list_node_files_request, build_batch_list_nodes_request, build_batch_list_pool_node_counts_request, - build_batch_list_pool_usage_metrics_request, build_batch_list_pools_request, build_batch_list_subtasks_request, build_batch_list_supported_images_request, @@ -122,7 +121,7 @@ class _BatchClientOperationsMixin( # pylint: disable=too-many-public-methods def list_applications( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, **kwargs: Any @@ -137,7 +136,7 @@ def list_applications( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -191,7 +190,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -238,7 +240,7 @@ async def get_application( self, application_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchApplication: @@ -254,7 +256,7 @@ async def get_application( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -326,150 +328,12 @@ async def get_application( return deserialized # type: ignore - @distributed_trace - def list_pool_usage_metrics( - self, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - max_results: Optional[int] = None, - start_time: Optional[datetime.datetime] = None, - end_time: Optional[datetime.datetime] = None, - filter: Optional[str] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.BatchPoolUsageMetrics"]: - """Lists the usage metrics, aggregated by Pool across individual time intervals, for the specified - Account. - - If you do not specify a $filter clause including a poolId, the response includes all Pools that - existed in the Account in the time range of the returned aggregation intervals. If you do not - specify a $filter clause including a startTime or endTime these filters default to the start - and end times of the last aggregation interval currently available; that is, only the last - aggregation interval is returned. - - :keyword service_timeout: The maximum time that the server can spend processing the request, in - seconds. The default is 30 seconds. If the value is larger than 30, the default will be used - instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword max_results: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype max_results: int - :keyword start_time: The earliest time from which to include metrics. This must be at least two - and - a half hours before the current time. If not specified this defaults to the - start time of the last aggregation interval currently available. Default value is None. - :paramtype start_time: ~datetime.datetime - :keyword end_time: The latest time from which to include metrics. This must be at least two - hours - before the current time. If not specified this defaults to the end time of the - last aggregation interval currently available. Default value is None. - :paramtype end_time: ~datetime.datetime - :keyword filter: An OData $filter clause. For more information on constructing this filter, see - `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics - `_. - Default value is None. - :paramtype filter: str - :return: An iterator like instance of BatchPoolUsageMetrics - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.batch.models.BatchPoolUsageMetrics] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[list[_models.BatchPoolUsageMetrics]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_batch_list_pool_usage_metrics_request( - service_timeout=service_timeout, - ocp_date=ocp_date, - max_results=max_results, - start_time=start_time, - end_time=end_time, - filter=filter, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - list[_models.BatchPoolUsageMetrics], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("odata.nextLink") or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.BatchError, - response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - @distributed_trace_async async def create_pool( self, pool: _models.BatchPoolCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -483,7 +347,7 @@ async def create_pool( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -553,7 +417,7 @@ async def create_pool( def list_pools( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -568,7 +432,7 @@ def list_pools( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -634,7 +498,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -681,7 +548,7 @@ async def _delete_pool_internal( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -707,7 +574,7 @@ async def _delete_pool_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -794,7 +661,7 @@ async def pool_exists( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -809,7 +676,7 @@ async def pool_exists( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -900,7 +767,7 @@ async def get_pool( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -917,7 +784,7 @@ async def get_pool( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1026,7 +893,7 @@ async def update_pool( pool_id: str, pool: _models.BatchPoolUpdateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1047,7 +914,7 @@ async def update_pool( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1144,7 +1011,7 @@ async def disable_pool_auto_scale( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -1157,7 +1024,7 @@ async def disable_pool_auto_scale( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1223,7 +1090,7 @@ async def enable_pool_auto_scale( pool_id: str, enable_auto_scale_options: _models.BatchPoolEnableAutoScaleOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1246,7 +1113,7 @@ async def enable_pool_auto_scale( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1344,7 +1211,7 @@ async def evaluate_pool_auto_scale( pool_id: str, evaluate_auto_scale_options: _models.BatchPoolEvaluateAutoScaleOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.AutoScaleRun: @@ -1363,7 +1230,7 @@ async def evaluate_pool_auto_scale( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1449,7 +1316,7 @@ async def _resize_pool_internal( pool_id: str, resize_options: _models.BatchPoolResizeOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1473,7 +1340,7 @@ async def _resize_pool_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1570,7 +1437,7 @@ async def _stop_pool_resize_internal( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1592,7 +1459,7 @@ async def _stop_pool_resize_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1683,7 +1550,7 @@ async def replace_pool_properties( pool_id: str, pool: _models.BatchPoolReplaceOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -1700,7 +1567,7 @@ async def replace_pool_properties( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1773,7 +1640,7 @@ async def _remove_nodes_internal( pool_id: str, remove_options: _models.BatchNodeRemoveOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -1794,7 +1661,7 @@ async def _remove_nodes_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1890,7 +1757,7 @@ async def _remove_nodes_internal( def list_supported_images( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -1903,7 +1770,7 @@ def list_supported_images( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -1963,7 +1830,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -2009,7 +1879,7 @@ async def get_next(next_link=None): def list_pool_node_counts( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -2021,7 +1891,7 @@ def list_pool_node_counts( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2081,7 +1951,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -2128,7 +2001,7 @@ async def _delete_job_internal( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2152,7 +2025,7 @@ async def _delete_job_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2243,7 +2116,7 @@ async def get_job( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2262,7 +2135,7 @@ async def get_job( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2371,7 +2244,7 @@ async def update_job( job_id: str, job: _models.BatchJobUpdateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2392,7 +2265,7 @@ async def update_job( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2490,7 +2363,7 @@ async def replace_job( job_id: str, job: _models.BatchJob, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2511,7 +2384,7 @@ async def replace_job( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2609,7 +2482,7 @@ async def _disable_job_internal( job_id: str, disable_options: _models.BatchJobDisableOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2634,7 +2507,7 @@ async def _disable_job_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2731,7 +2604,7 @@ async def _enable_job_internal( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2752,7 +2625,7 @@ async def _enable_job_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2841,9 +2714,9 @@ async def _enable_job_internal( async def _terminate_job_internal( self, job_id: str, - options: Optional[_models._models.BatchJobTerminateOptions] = None, + options: Optional[_models.BatchJobTerminateOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -2863,11 +2736,11 @@ async def _terminate_job_internal( :param job_id: The ID of the Job to terminate. Required. :type job_id: str :param options: The options to use for terminating the Job. Default value is None. - :type options: ~azure.batch.models._models.BatchJobTerminateOptions + :type options: ~azure.batch.models.BatchJobTerminateOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -2972,7 +2845,7 @@ async def create_job( self, job: _models.BatchJobCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -2991,7 +2864,7 @@ async def create_job( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3061,7 +2934,7 @@ async def create_job( def list_jobs( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -3076,7 +2949,7 @@ def list_jobs( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3142,7 +3015,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -3189,7 +3065,7 @@ def list_jobs_from_schedule( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -3207,7 +3083,7 @@ def list_jobs_from_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3274,7 +3150,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -3321,7 +3200,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -3342,7 +3221,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3407,7 +3286,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -3454,7 +3336,7 @@ async def get_job_task_counts( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchTaskCountsResult: @@ -3470,7 +3352,7 @@ async def get_job_task_counts( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3547,7 +3429,7 @@ async def job_schedule_exists( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3564,7 +3446,7 @@ async def job_schedule_exists( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3655,7 +3537,7 @@ async def _delete_job_schedule_internal( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3677,7 +3559,7 @@ async def _delete_job_schedule_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3768,7 +3650,7 @@ async def get_job_schedule( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3785,7 +3667,7 @@ async def get_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -3894,7 +3776,7 @@ async def update_job_schedule( job_schedule_id: str, job_schedule: _models.BatchJobScheduleUpdateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -3916,7 +3798,7 @@ async def update_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4014,7 +3896,7 @@ async def replace_job_schedule( job_schedule_id: str, job_schedule: _models.BatchJobSchedule, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4036,7 +3918,7 @@ async def replace_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4133,7 +4015,7 @@ async def disable_job_schedule( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4150,7 +4032,7 @@ async def disable_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4240,7 +4122,7 @@ async def enable_job_schedule( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4257,7 +4139,7 @@ async def enable_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4347,7 +4229,7 @@ async def _terminate_job_schedule_internal( self, job_schedule_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -4365,7 +4247,7 @@ async def _terminate_job_schedule_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4460,7 +4342,7 @@ async def create_job_schedule( self, job_schedule: _models.BatchJobScheduleCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -4473,7 +4355,7 @@ async def create_job_schedule( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4543,7 +4425,7 @@ async def create_job_schedule( def list_job_schedules( self, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -4558,7 +4440,7 @@ def list_job_schedules( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4624,7 +4506,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -4672,7 +4557,7 @@ async def create_task( job_id: str, task: _models.BatchTaskCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -4689,7 +4574,7 @@ async def create_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4761,7 +4646,7 @@ def list_tasks( self, job_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -4779,7 +4664,7 @@ def list_tasks( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -4846,7 +4731,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -4894,7 +4782,7 @@ async def create_task_collection( job_id: str, task_collection: _models.BatchTaskGroup, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchCreateTaskCollectionResult: @@ -4920,7 +4808,7 @@ async def create_task_collection( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5006,7 +4894,7 @@ async def delete_task( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5028,7 +4916,7 @@ async def delete_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5117,7 +5005,7 @@ async def get_task( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5139,7 +5027,7 @@ async def get_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5251,7 +5139,7 @@ async def replace_task( task_id: str, task: _models.BatchTask, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5270,7 +5158,7 @@ async def replace_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5369,7 +5257,7 @@ def list_subtasks( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -5385,7 +5273,7 @@ def list_subtasks( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5440,7 +5328,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -5488,7 +5379,7 @@ async def terminate_task( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5509,7 +5400,7 @@ async def terminate_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5601,7 +5492,7 @@ async def reactivate_task( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5625,7 +5516,7 @@ async def reactivate_task( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5718,7 +5609,7 @@ async def delete_task_file( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, recursive: Optional[bool] = None, **kwargs: Any @@ -5736,7 +5627,7 @@ async def delete_task_file( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5809,7 +5700,7 @@ async def download_task_file( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5827,7 +5718,7 @@ async def download_task_file( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -5930,7 +5821,7 @@ async def _get_task_file_properties_internal( task_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -5947,7 +5838,7 @@ async def _get_task_file_properties_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6034,7 +5925,7 @@ def list_task_files( job_id: str, task_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -6052,7 +5943,7 @@ def list_task_files( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6119,7 +6010,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -6168,7 +6062,7 @@ async def create_node_user( node_id: str, user: _models.BatchNodeUserCreateOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6189,7 +6083,7 @@ async def create_node_user( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6264,7 +6158,7 @@ async def delete_node_user( node_id: str, user_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6285,7 +6179,7 @@ async def delete_node_user( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6352,7 +6246,7 @@ async def replace_node_user( user_name: str, update_options: _models.BatchNodeUserReplaceOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6374,7 +6268,7 @@ async def replace_node_user( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6449,7 +6343,7 @@ async def get_node( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -6465,7 +6359,7 @@ async def get_node( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6546,9 +6440,9 @@ async def _reboot_node_internal( self, pool_id: str, node_id: str, - options: Optional[_models._models.BatchNodeRebootOptions] = None, + options: Optional[_models.BatchNodeRebootOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6561,11 +6455,11 @@ async def _reboot_node_internal( :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str :param options: The options to use for rebooting the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeRebootOptions + :type options: ~azure.batch.models.BatchNodeRebootOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6643,7 +6537,7 @@ async def _start_node_internal( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6658,7 +6552,7 @@ async def _start_node_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6724,9 +6618,9 @@ async def _reimage_node_internal( self, pool_id: str, node_id: str, - options: Optional[_models._models.BatchNodeReimageOptions] = None, + options: Optional[_models.BatchNodeReimageOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6741,11 +6635,11 @@ async def _reimage_node_internal( :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str :param options: The options to use for reimaging the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeReimageOptions + :type options: ~azure.batch.models.BatchNodeReimageOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6822,9 +6716,9 @@ async def _deallocate_node_internal( self, pool_id: str, node_id: str, - options: Optional[_models._models.BatchNodeDeallocateOptions] = None, + options: Optional[_models.BatchNodeDeallocateOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6837,11 +6731,11 @@ async def _deallocate_node_internal( :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str :param options: The options to use for deallocating the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeDeallocateOptions + :type options: ~azure.batch.models.BatchNodeDeallocateOptions :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -6920,7 +6814,7 @@ async def disable_node_scheduling( node_id: str, options: Optional[_models.BatchNodeDisableSchedulingOptions] = None, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -6940,7 +6834,7 @@ async def disable_node_scheduling( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7018,7 +6912,7 @@ async def enable_node_scheduling( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> None: @@ -7035,7 +6929,7 @@ async def enable_node_scheduling( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7102,7 +6996,7 @@ async def get_node_remote_login_settings( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.BatchNodeRemoteLoginSettings: @@ -7121,7 +7015,7 @@ async def get_node_remote_login_settings( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7202,7 +7096,7 @@ async def upload_node_logs( node_id: str, upload_options: _models.UploadBatchServiceLogsOptions, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, **kwargs: Any ) -> _models.UploadBatchServiceLogsResult: @@ -7223,7 +7117,7 @@ async def upload_node_logs( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7309,7 +7203,7 @@ def list_nodes( self, pool_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -7325,7 +7219,7 @@ def list_nodes( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7389,7 +7283,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -7438,7 +7335,7 @@ async def get_node_extension( node_id: str, extension_name: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, select: Optional[list[str]] = None, **kwargs: Any @@ -7457,7 +7354,7 @@ async def get_node_extension( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7540,7 +7437,7 @@ def list_node_extensions( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, select: Optional[list[str]] = None, @@ -7557,7 +7454,7 @@ def list_node_extensions( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7616,7 +7513,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -7665,7 +7565,7 @@ async def delete_node_file( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, recursive: Optional[bool] = None, **kwargs: Any @@ -7683,7 +7583,7 @@ async def delete_node_file( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7756,7 +7656,7 @@ async def download_node_file( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -7774,7 +7674,7 @@ async def download_node_file( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7877,7 +7777,7 @@ async def _get_node_file_properties_internal( node_id: str, file_path: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, @@ -7894,7 +7794,7 @@ async def _get_node_file_properties_internal( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -7981,7 +7881,7 @@ def list_node_files( pool_id: str, node_id: str, *, - service_timeout: Optional[int] = None, + service_timeout: Optional[datetime.timedelta] = None, ocp_date: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, @@ -7999,7 +7899,7 @@ def list_node_files( :keyword service_timeout: The maximum time that the server can spend processing the request, in seconds. The default is 30 seconds. If the value is larger than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int + :paramtype service_timeout: ~datetime.timedelta :keyword ocp_date: The time the request was issued. Client libraries typically set this to the current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. @@ -8064,7 +7964,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( diff --git a/sdk/batch/azure-batch/azure/batch/aio/_operations/_patch.py b/sdk/batch/azure-batch/azure/batch/aio/_operations/_patch.py index f28ceee2301a..ea765788358a 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_operations/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_operations/_patch.py @@ -1,1579 +1,14 @@ -# pylint: disable=too-many-lines, C4763 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import asyncio -import datetime -import collections -import logging -from typing import Any, cast, Callable, Deque, Dict, AsyncIterator, List, Iterable, Optional, TypeVar -from azure.batch import models as _models -from azure.core import MatchConditions -from azure.core.exceptions import ( - HttpResponseError, -) -from azure.core.polling import AsyncLROPoller -from azure.core.rest import HttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.pipeline import PipelineResponse - -from ._polling_async import ( - DeallocateNodePollingMethodAsync, - DeleteJobPollingMethodAsync, - DeleteJobSchedulePollingMethodAsync, - DeletePoolPollingMethodAsync, - DisableJobPollingMethodAsync, - EnableJobPollingMethodAsync, - RebootNodePollingMethodAsync, - ReimageNodePollingMethodAsync, - RemoveNodePollingMethodAsync, - ResizePoolPollingMethodAsync, - StartNodePollingMethodAsync, - StopPoolResizePollingMethodAsync, - TerminateJobPollingMethodAsync, - TerminateJobSchedulePollingMethodAsync, -) -from ._operations import ( - _BatchClientOperationsMixin as BatchClientOperationsMixinGenerated, -) - - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - -MAX_TASKS_PER_REQUEST = 100 -_LOGGER = logging.getLogger(__name__) - -__all__: List[str] = [ - "_BatchClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level - - -class _BatchClientOperationsMixin(BatchClientOperationsMixinGenerated): - """Customize generated code""" - - @distributed_trace - async def begin_delete_job( - self, - job_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - force: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes a Job with Long Running Operation support. - - Deleting a Job also deletes all Tasks that are part of that Job, and all Job - statistics. This also overrides the retention period for Task data; that is, if - the Job contains Tasks which are still retained on Compute Nodes, the Batch - services deletes those Tasks' working directories and all their contents. When - a Delete Job request is received, the Batch service sets the Job to the - deleting state. All update operations on a Job that is in deleting state will - fail with status code 409 (Conflict), with additional information indicating - that the Job is being deleted. - - :param job_id: The ID of the Job to delete. Required. - :type job_id: str - :keyword service_timeout: The maximum time that the server can spend processing the inital request to - delete the Job, in seconds. The default is 30 seconds. If the value is larger than 30, the - default will be used instead. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword force: If true, the server will delete the Job even if the corresponding nodes have - not fully processed the deletion. The default value is false. Default value is None. - :paramtype force: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: An LROPoller that can be used to wait for the job deletion to complete - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - # cast otherwise mypy complains about incompatible return type - pipeline_response = cast( - PipelineResponse, - await self._delete_job_internal( - job_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - force=force, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeleteJobPollingMethodAsync( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_disable_job( - self, - job_id: str, - disable_options: _models.BatchJobDisableOptions, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Disables a Job with Long Running Operation support. - - The Batch Service immediately moves the Job to the disabling state. Batch then - uses the disableTasks parameter to determine what to do with the currently - running Tasks of the Job. The Job remains in the disabling state until the - disable operation is completed and all Tasks have been dealt with according to - the disableTasks option; the Job then moves to the disabled state. No new Tasks - are started under the Job until it moves back to active state. If you try to - disable a Job that is in any state other than active, disabling, or disabled, - the request fails with status code 409. - - :param job_id: The ID of the Job to disable. Required. - :type job_id: str - :param disable_options: The options to use for disabling the Job. Required. - :type disable_options: ~azure.batch.models.BatchJobDisableOptions - :keyword service_timeout: The maximum time that the server can spend processing the inital request to - disable the Job, in seconds. The default is 30 seconds. If the value is larger than 30, the - default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._disable_job_internal( - job_id, - disable_options=disable_options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DisableJobPollingMethodAsync( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_enable_job( - self, - job_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Enables a Job with Long Running Operation support. - When you call this API, the Batch service sets a disabled Job to the enabling - state. After the this operation is completed, the Job moves to the active - state, and scheduling of new Tasks under the Job resumes. The Batch service - does not allow a Task to remain in the active state for more than 180 days. - Therefore, if you enable a Job containing active Tasks which were added more - than 180 days ago, those Tasks will not run. - - :param job_id: The ID of the Job to enable. Required. - :type job_id: str - :keyword service_timeout: The maximum time that the server can spend processing the intal request to - enable the Job, in seconds. The default is 30 seconds. If the value is larger than 30, the - default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._enable_job_internal( - job_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = EnableJobPollingMethodAsync( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_delete_job_schedule( - self, - job_schedule_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes a Job Schedule with Long Running Operation support. - - When you delete a Job Schedule, this also deletes all Jobs and Tasks under - that schedule. When Tasks are deleted, all the files in their working - directories on the Compute Nodes are also deleted (the retention period is - ignored). The Job Schedule statistics are no longer accessible once the Job - Schedule is deleted, though they are still counted towards Account lifetime - statistics. - - :param job_schedule_id: The ID of the Job Schedule to delete. Required. - :type job_schedule_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - delete the Job Schedule, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: An LROPoller that can be used to wait for the job schedule deletion to complete - :rtype: ~azure.core.polling.LROPoller[None] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._delete_job_schedule_internal( - job_schedule_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeleteJobSchedulePollingMethodAsync( - self, pipeline_response, None, job_schedule_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_delete_pool( - self, - pool_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deletes a Pool from specified Account with Long Running Operation support. - - When you request that a Pool be deleted, the following actions occur: the Pool - state is set to deleting; any ongoing resize operation on the Pool are stopped; - the Batch service starts resizing the Pool to zero Compute Nodes; any Tasks - running on existing Compute Nodes are terminated and requeued (as if a resize - Pool operation had been requested with the default requeue option); finally, - the Pool is removed from the system. Because running Tasks are requeued, the - user can rerun these Tasks by updating their Job to target a different Pool. - The Tasks can then run on the new Pool. If you want to override the requeue - behavior, then you should call resize Pool explicitly to shrink the Pool to - zero size before deleting the Pool. If you call an Update, Patch or Delete API - on a Pool in the deleting state, it will fail with HTTP status code 409 with - error code PoolBeingDeleted. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to delete the Pool, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._delete_pool_internal( - pool_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeletePoolPollingMethodAsync( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_deallocate_node( - self, - pool_id: str, - node_id: str, - options: Optional[_models._models.BatchNodeDeallocateOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Deallocates a Compute Node with Long Running Operation support. - - You can deallocate a Compute Node only if it is in an idle or running state. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :param options: The options to use for deallocating the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeDeallocateOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - deallocate the Compute Node, in seconds. The default is 30 seconds. If the value is larger - than 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._deallocate_node_internal( - pool_id, - node_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = DeallocateNodePollingMethodAsync( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_reboot_node( - self, - pool_id: str, - node_id: str, - options: Optional[_models._models.BatchNodeRebootOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Reboots a Compute Node with Long Running Operation support. - - You can restart a Compute Node only if it is in an idle or running state. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :param options: The options to use for rebooting the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeRebootOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - reboot the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._reboot_node_internal( - pool_id, - node_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = RebootNodePollingMethodAsync( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_reimage_node( - self, - pool_id: str, - node_id: str, - options: Optional[_models._models.BatchNodeReimageOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Reimages a Compute Node with Long Running Operation support. - - Reinstalls the operating system on the specified Compute Node - - You can reinstall the operating system on a Compute Node only if it is in an - idle or running state. This API can be invoked only on Pools created with the - cloud service configuration property. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :param options: The options to use for reimaging the Compute Node. Default value is None. - :type options: ~azure.batch.models._models.BatchNodeReimageOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - reimage the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._reimage_node_internal( - pool_id, - node_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = ReimageNodePollingMethodAsync( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_remove_nodes( - self, - pool_id: str, - remove_options: _models.BatchNodeRemoveOptions, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Removes Compute Nodes from a Pool with Long Running Operation support. - - This operation can only run when the allocation state of the Pool is steady. - When this operation runs, the allocation state changes from steady to resizing. - Each request may remove up to 100 nodes. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :param remove_options: The options to use for removing the node. Required. - :type remove_options: ~azure.batch.models.BatchNodeRemoveOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - remove the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._remove_nodes_internal( - pool_id, - remove_options=remove_options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = RemoveNodePollingMethodAsync( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_resize_pool( - self, - pool_id: str, - resize_options: _models.BatchPoolResizeOptions, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Resizes a Pool with Long Running Operation support. - - You can only resize a Pool when its allocation state is steady. If the Pool is - already resizing, the request fails with status code 409. When you resize a - Pool, the Pool's allocation state changes from steady to resizing. You cannot - resize Pools which are configured for automatic scaling. If you try to do this, - the Batch service returns an error 409. If you resize a Pool downwards, the - Batch service chooses which Compute Nodes to remove. To remove specific Compute - Nodes, use the Pool remove Compute Nodes API instead. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :param resize_options: The options to use for resizing the pool. Required. - :type resize_options: ~azure.batch.models.BatchPoolResizeOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to resize the Pool, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._resize_pool_internal( - pool_id, - resize_options=resize_options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = ResizePoolPollingMethodAsync( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_start_node( - self, - pool_id: str, - node_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Starts a Compute Node with Long Running Operation support. - - You can start a Compute Node only if it has been deallocated. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node that you want to restart. Required. - :type node_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - start the Compute Node, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._start_node_internal( - pool_id, - node_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = StartNodePollingMethodAsync( - self, pipeline_response, None, pool_id, node_id=node_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_stop_pool_resize( - self, - pool_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Stops an ongoing Pool resize operation with Long Running Operation support. - - This does not restore the Pool to its previous state before the resize - operation: it only stops any further changes being made, and the Pool maintains - its current state. After stopping, the Pool stabilizes at the number of Compute - Nodes it was at when the stop operation was done. During the stop operation, - the Pool allocation state changes first to stopping and then to steady. A - resize operation need not be an explicit resize Pool request; this API can also - be used to halt the initial sizing of the Pool when it is created. - - :param pool_id: The ID of the Pool to get. Required. - :type pool_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to stop the Pool resize, in seconds. The default is 30 seconds. If the value is larger than - 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._stop_pool_resize_internal( - pool_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = StopPoolResizePollingMethodAsync( - self, pipeline_response, None, pool_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_terminate_job( - self, - job_id: str, - options: Optional[_models._models.BatchJobTerminateOptions] = None, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - force: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Terminates a Job with Long Running Operation support, marking it as completed. - - When a Terminate Job request is received, the Batch service sets the Job to the - terminating state. The Batch service then terminates any running Tasks - associated with the Job and runs any required Job release Tasks. Then the Job - moves into the completed state. If there are any Tasks in the Job in the active - state, they will remain in the active state. Once a Job is terminated, new - Tasks cannot be added and any remaining active Tasks will not be scheduled. - - :param job_id: The ID of the Job to terminate. Required. - :type job_id: str - :param options: The options to use for terminating the Job. Default value is None. - :type options: ~azure.batch.models._models.BatchJobTerminateOptions - :keyword service_timeout: The maximum time that the server can spend processing the initial request - to terminate the Job, in seconds. The default is 30 seconds. If the value is larger than 30, - the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword force: If true, the server will terminate the Job even if the corresponding nodes have - not fully processed the termination. The default value is false. Default value is None. - :paramtype force: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._terminate_job_internal( - job_id, - options=options, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - force=force, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = TerminateJobPollingMethodAsync( - self, pipeline_response, None, job_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - @distributed_trace - async def begin_terminate_job_schedule( - self, - job_schedule_id: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - force: Optional[bool] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - polling_interval: int = 5, - **kwargs: Any - ) -> AsyncLROPoller[None]: - """Terminates a Job Schedule with Long Running Operation support. - - :param job_schedule_id: The ID of the Job Schedule to terminates. Required. - :type job_schedule_id: str - :keyword service_timeout: The maximum time that the server can spend processing the initial request to - terminate the Job Schedule, in seconds. The default is 30 seconds. If the value is larger than - 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword force: If true, the server will terminate the JobSchedule even if the corresponding - nodes have not fully processed the termination. The default value is false. Default value is - None. - :paramtype force: bool - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. - :paramtype polling_interval: int - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def capture_pipeline_response(pipeline_response, _deserialized, _response_headers): - return pipeline_response - - pipeline_response = cast( - PipelineResponse, - await self._terminate_job_schedule_internal( - job_schedule_id, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - force=force, - etag=etag, - match_condition=match_condition, - cls=capture_pipeline_response, - **kwargs, - ), - ) - - polling_method = TerminateJobSchedulePollingMethodAsync( - self, pipeline_response, None, job_schedule_id, polling_interval=polling_interval - ) - return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) - - # create_task_collection renamed - @distributed_trace - async def create_tasks( - self, - job_id: str, - task_collection: List[_models.BatchTaskCreateOptions], - *, - max_concurrency: Optional[int] = None, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> _models.BatchCreateTaskCollectionResult: - """Adds a collection of Tasks to the specified Job. - - Note that each Task must have a unique ID. The Batch service may not return the - results for each Task in the same order the Tasks were submitted in this - request. If the server times out or the connection is closed during the - request, the request may have been partially or fully processed, or not at all. - In such cases, the user should re-issue the request. Note that it is up to the - user to correctly handle failures when re-issuing a request. For example, you - should use the same Task IDs during a retry so that if the prior operation - succeeded, the retry will not create extra Tasks unexpectedly. If the response - contains any Tasks which failed to add, a client can retry the request. In a - retry, it is most efficient to resubmit only Tasks that failed to add, and to - omit Tasks that were successfully added on the first attempt. The maximum - lifetime of a Task from addition to completion is 180 days. If a Task has not - completed within 180 days of being added it will be terminated by the Batch - service and left in whatever state it was in at that time. - - :param job_id: The ID of the Job to which the Task collection is to be added. Required. - :type job_id: str - :param task_collection: The Tasks to be added. Required. - :type task_collection: ~azure.batch.models.BatchTaskAddCollectionResult - :keyword max_concurrency: number of coroutines to use in parallel when adding tasks. If specified - and greater than 0, will start additional coroutines to submit requests and wait for them to finish. - Otherwise will submit create_task_collection requests sequentially on main thread - :paramtype max_concurrency: int - :keyword service_timeout: The maximum time that the server can spend processing the equest to - create the task collection, in seconds. The default is 30 seconds. If the value is larger than - 30, the default will be used instead.". Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :return: BatchTaskAddCollectionResult. The BatchTaskAddCollectionResult is compatible with MutableMapping - :rtype: ~azure.batch.models.BatchTaskAddCollectionResult - :raises ~azure.batch.custom.CreateTasksError: - """ - - kwargs.update({"service_timeout": service_timeout, "ocp_date": ocp_date}) - - results_queue: Deque[_models.BatchTaskCreateResult] = collections.deque() - task_workflow_manager = _TaskWorkflowManager(self, job_id=job_id, task_collection=task_collection, **kwargs) - - if max_concurrency: - if max_concurrency < 0: - raise ValueError("max_concurrency must be positive or 0") - - coroutines = [] - for _ in range(max_concurrency): - coroutines.append(task_workflow_manager.task_collection_handler(results_queue)) - await asyncio.gather(*coroutines) - else: - await task_workflow_manager.task_collection_handler(results_queue) - - # Only define error if all coroutines have finished and there were failures - if task_workflow_manager.failure_tasks or task_workflow_manager.errors: - raise _models.CreateTasksError( - task_workflow_manager.tasks_to_add, - task_workflow_manager.failure_tasks, - task_workflow_manager.errors, - ) - submitted_tasks = _handle_output(results_queue) - return _models.BatchCreateTaskCollectionResult(result_values=submitted_tasks) - - @distributed_trace - async def download_node_file( - self, - pool_id: str, - node_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - ocp_range: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - """Returns the content of the specified Compute Node file. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node from which you want to delete the file. Required. - :type node_id: str - :param file_path: The path to the file or directory that you want to delete. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword ocp_range: The byte range to be retrieved. The default is to retrieve the entire file. - The - format is bytes=startRange-endRange. Default value is None. - :paramtype ocp_range: str - :return: bytes - :rtype: bytes - :raises ~azure.core.exceptions.HttpResponseError: - """ - args = [pool_id, node_id, file_path] - kwargs.update( - { - "service_timeout": service_timeout, - "ocp_date": ocp_date, - "if_modified_since": if_modified_since, - "if_unmodified_since": if_unmodified_since, - "ocp_range": ocp_range, - } - ) - kwargs["stream"] = True - return await super().download_node_file(*args, **kwargs) - - @distributed_trace - async def get_node_file_properties( - self, - pool_id: str, - node_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> _models.BatchFileProperties: - """Gets the properties of the specified Compute Node file. - - :param pool_id: The ID of the Pool that contains the Compute Node. Required. - :type pool_id: str - :param node_id: The ID of the Compute Node from which you want to delete the file. Required. - :type node_id: str - :param file_path: The path to the file or directory that you want to delete. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :return: BatchFileProperties - :rtype: ~azure.batch.models.BatchFileProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def cls(_pipeline_response, _json_response, headers): - return _models.BatchFileProperties( - url=headers["ocp-batch-file-url"], - is_directory=headers["ocp-batch-file-isdirectory"], - last_modified=headers["Last-Modified"], - content_length=headers["Content-Length"], - creation_time=headers["ocp-creation-time"], - # content_type=headers["Content-Type"], # need to add to typespec - file_mode=headers["ocp-batch-file-mode"], - ) - - get_response: _models.BatchFileProperties = await super()._get_node_file_properties_internal( # type: ignore - pool_id, - node_id, - file_path, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - cls=cls, - **kwargs, - ) - - return get_response - - @distributed_trace - async def get_task_file_properties( - self, - job_id: str, - task_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - **kwargs: Any - ) -> _models.BatchFileProperties: - """Gets the properties of the specified Task file. - - :param job_id: The ID of the Job that contains the Task. Required. - :type job_id: str - :param task_id: The ID of the Task whose file you want to retrieve. Required. - :type task_id: str - :param file_path: The path to the Task file that you want to get the content of. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :return: BatchFileProperties - :rtype: ~azure.batch.models.BatchFileProperties - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def cls(_pipeline_response, _json_response, headers): - return _models.BatchFileProperties( - url=headers["ocp-batch-file-url"], - is_directory=headers["ocp-batch-file-isdirectory"], - last_modified=headers["Last-Modified"], - content_length=headers["Content-Length"], - creation_time=headers["ocp-creation-time"], - # content_type=headers["Content-Type"], # need to add to typespec - file_mode=headers["ocp-batch-file-mode"], - ) - - get_response: _models.BatchFileProperties = await super()._get_task_file_properties_internal( # type: ignore - job_id, - task_id, - file_path, - service_timeout=service_timeout, - ocp_date=ocp_date, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, - cls=cls, - **kwargs, - ) - - return get_response - - @distributed_trace - async def download_task_file( - self, - job_id: str, - task_id: str, - file_path: str, - *, - service_timeout: Optional[int] = None, - ocp_date: Optional[datetime.datetime] = None, - if_modified_since: Optional[datetime.datetime] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - ocp_range: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - """Returns the content of the specified Task file. - - :param job_id: The ID of the Job that contains the Task. Required. - :type job_id: str - :param task_id: The ID of the Task whose file you want to retrieve. Required. - :type task_id: str - :param file_path: The path to the Task file that you want to get the content of. Required. - :type file_path: str - :keyword service_timeout: The maximum number of items to return in the response. A maximum of 1000 - applications can be returned. Default value is None. - :paramtype service_timeout: int - :keyword ocp_date: The time the request was issued. Client libraries typically set this to the - current system clock time; set it explicitly if you are calling the REST API - directly. Default value is None. - :paramtype ocp_date: ~datetime.datetime - :keyword if_modified_since: A timestamp indicating the last modified time of the resource known - to the - client. The operation will be performed only if the resource on the service has - been modified since the specified time. Default value is None. - :paramtype if_modified_since: ~datetime.datetime - :keyword if_unmodified_since: A timestamp indicating the last modified time of the resource - known to the - client. The operation will be performed only if the resource on the service has - not been modified since the specified time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword ocp_range: The byte range to be retrieved. The default is to retrieve the entire file. - The - format is bytes=startRange-endRange. Default value is None. - :paramtype ocp_range: str - :return: bytes - :rtype: bytes - :raises ~azure.core.exceptions.HttpResponseError: - """ - - args = [job_id, task_id, file_path] - kwargs.update( - { - "service_timeout": service_timeout, - "ocp_date": ocp_date, - "if_modified_since": if_modified_since, - "if_unmodified_since": if_unmodified_since, - "ocp_range": ocp_range, - } - ) - kwargs["stream"] = True - return await super().download_task_file(*args, **kwargs) - - -class _TaskWorkflowManager: - """Worker class for one create_task_collection request - - :param str job_id: The ID of the job to which the task collection is to be - added. - :ivar tasks_to_add: The collection of tasks to add. - :vartype tasks_to_add: Iterable[~azure.batch.models.BatchTaskCreateContent] - :param task_create_task_collection_options: Additional parameters for the - operation - :type task_create_task_collection_options: :class:`TaskAddCollectionOptions - ` - """ - - def __init__( - self, - batch_client: _BatchClientOperationsMixin, - job_id: str, - task_collection: Iterable[_models.BatchTaskCreateOptions], - **kwargs - ): - # List of tasks which failed to add due to a returned client error - self.failure_tasks: Deque[_models.BatchTaskCreateResult] = collections.deque() - # List of unknown exceptions which occurred during requests. - self.errors: Deque[Any] = collections.deque() - - # synchronized through lock variables - self._max_tasks_per_request = MAX_TASKS_PER_REQUEST - self.tasks_to_add = collections.deque(task_collection) - - # Variables to be used for task create_task_collection requests - self._batch_client = batch_client - self._job_id = job_id - - self._kwargs = kwargs - - async def _bulk_add_tasks( - self, - results_queue: collections.deque, - chunk_tasks_to_add: List[_models.BatchTaskCreateOptions], - ): - """Adds a chunk of tasks to the job - - Retry chunk if body exceeds the maximum request size and retry tasks - if failed due to server errors. - - :param results_queue: Queue to place the return value of the request - :type results_queue: collections.deque - :param chunk_tasks_to_add: Chunk of at most 100 tasks with retry details - :type chunk_tasks_to_add: list[~azure.batch.models.BatchTaskCreateOptions] - """ - - try: - create_task_collection_response: _models.BatchCreateTaskCollectionResult = ( - await self._batch_client.create_task_collection( - job_id=self._job_id, - task_collection=_models.BatchTaskGroup(task_values=chunk_tasks_to_add), - **self._kwargs, - ) - ) - except HttpResponseError as e: - # In case of a chunk exceeding the MaxMessageSize split chunk in half - # and resubmit smaller chunk requests - # TODO: Replace string with constant variable once available in SDK - if e.error and e.error.code == "RequestBodyTooLarge": # pylint: disable=no-member - # In this case the task is misbehaved and will not be able to be added due to: - # 1) The task exceeding the max message size - # 2) A single cell of the task exceeds the per-cell limit, or - # 3) Sum of all cells exceeds max row limit - if len(chunk_tasks_to_add) == 1: - failed_task = chunk_tasks_to_add.pop() - self.errors.appendleft(e) - _LOGGER.error( - "Failed to add task with ID %s due to the body exceeding the maximum request size", - failed_task.id, - ) - else: - # Assumption: Tasks are relatively close in size therefore if one batch exceeds size limit - # we should decrease the initial task collection size to avoid repeating the error - # Midpoint is lower bounded by 1 due to above base case - midpoint = int(len(chunk_tasks_to_add) / 2) - if midpoint < self._max_tasks_per_request: - _LOGGER.info( - "Amount of tasks per request reduced from %s to %s due to the" - " request body being too large", - str(self._max_tasks_per_request), - str(midpoint), - ) - self._max_tasks_per_request = midpoint - - # Not the most efficient solution for all cases, but the goal of this is to handle this - # exception and have it work in all cases where tasks are well behaved - # Behavior retries as a smaller chunk and - # appends extra tasks to queue to be picked up by another coroutines . - self.tasks_to_add.extendleft(chunk_tasks_to_add[midpoint:]) - await self._bulk_add_tasks(results_queue, chunk_tasks_to_add[:midpoint]) - # Retry server side errors - elif 500 <= e.response.status_code <= 599: # type: ignore - self.tasks_to_add.extendleft(chunk_tasks_to_add) - else: - # Re-add to pending queue as unknown status / don't have result - self.tasks_to_add.extendleft(chunk_tasks_to_add) - # Unknown State - don't know if tasks failed to add or were successful - self.errors.appendleft(e) - except Exception as e: # pylint: disable=broad-except - # Re-add to pending queue as unknown status / don't have result - self.tasks_to_add.extendleft(chunk_tasks_to_add) - # Unknown State - don't know if tasks failed to add or were successful - self.errors.appendleft(e) - else: - if create_task_collection_response.result_values: - for task_result in create_task_collection_response.result_values: - if task_result.status == _models.BatchTaskAddStatus.SERVER_ERROR: - # Server error will be retried - for task in chunk_tasks_to_add: - if task.id == task_result.task_id: - self.tasks_to_add.appendleft(task) - elif task_result.status == _models.BatchTaskAddStatus.CLIENT_ERROR and not ( - task_result.error and task_result.error.code == "TaskExists" - ): - # Client error will be recorded unless Task already exists - self.failure_tasks.appendleft(task_result) - else: - results_queue.appendleft(task_result) - - async def task_collection_handler(self, results_queue): - """Main method for worker to run - - Pops a chunk of tasks off the collection of pending tasks to be added and submits them to be added. - - :param collections.deque results_queue: Queue for worker to output results to - """ - # Add tasks until either we run out or we run into an unexpected error - while self.tasks_to_add and not self.errors: - max_tasks = self._max_tasks_per_request # local copy - chunk_tasks_to_add = [] - while len(chunk_tasks_to_add) < max_tasks and self.tasks_to_add: - chunk_tasks_to_add.append(self.tasks_to_add.pop()) - - if chunk_tasks_to_add: - await self._bulk_add_tasks(results_queue, chunk_tasks_to_add) +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -1583,20 +18,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - - -def _handle_output(results_queue): - """Scan output for exceptions - - If there is an output from an add task collection call add it to the results. - - :param results_queue: Queue containing results of attempted create_task_collection's - :type results_queue: collections.deque - :return: list of TaskAddResults - :rtype: list[~TaskAddResult] - """ - results = [] - while results_queue: - queue_item = results_queue.pop() - results.append(queue_item) - return results diff --git a/sdk/batch/azure-batch/azure/batch/aio/_operations/_polling_async.py b/sdk/batch/azure-batch/azure/batch/aio/_operations/_polling_async.py deleted file mode 100644 index f84a903fc7dc..000000000000 --- a/sdk/batch/azure-batch/azure/batch/aio/_operations/_polling_async.py +++ /dev/null @@ -1,1406 +0,0 @@ -# pylint: disable=too-many-lines, C4763 -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -""" Custom Async Polling Methods for Azure Batch Operations.""" - -import asyncio - -from typing import Any, Callable, Optional - -from azure.core.exceptions import AzureError, ResourceNotFoundError -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncPollingMethod - -from ... import models as _models - - -class DeleteJobPollingMethodAsync(AsyncPollingMethod): - """Polling method for job delete operation. - - This class is used to poll the status of a job deletion operation. - It checks the status of the job until it is deleted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the DeleteJobPollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the job - deletion status. - - :param client: An instance of the Batch client used to make API calls for - checking job status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - delete job API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param job_id: The unique identifier of the job being deleted. - :type job_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._polling_interval = polling_interval - self._status = "InProgress" - self._finished = False - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = await self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.DELETING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job no longer exists, deletion is complete - self._status = "Succeeded" - self._finished = True - except AzureError: - # Some other error occurred, operation failed - self._status = "Failed" - self._finished = True - - -class DisableJobPollingMethodAsync(AsyncPollingMethod): - """Polling method for job disable operation. - - This class is used to poll the status of a job disable operation. - It checks the status of the job until it is disabled or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the DisableJobPollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the job - disable operation status. - - :param client: An instance of the Batch client used to make API calls for - checking job status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - disable job API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param job_id: The unique identifier of the job being disabled. - :type job_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._polling_interval = polling_interval - self._status = "InProgress" - self._finished = False - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = await self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.DISABLING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # If job doesn't exist it could've been deleted while disabling - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class EnableJobPollingMethodAsync(AsyncPollingMethod): - """Polling method for job enable operation. - - This class is used to poll the status of a job enable operation. - It checks the status of the job until it is enabled or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the EnableJobPollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the job - enable operation status. - - :param client: An instance of the Batch client used to make API calls for - checking job status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - enable job API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param job_id: The unique identifier of the job being enabled. - :type job_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._polling_interval = polling_interval - self._status = "InProgress" - self._finished = False - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = await self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.ENABLING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # If job doesn't exist it could've been deleted while enabling - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class DeleteJobSchedulePollingMethodAsync(AsyncPollingMethod): - """Polling method for job schedule delete operation. - - This class is used to poll the status of a job schedule deletion operation. - It checks the status of the job schedule until it is deleted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_schedule_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the DeleteJobSchedulePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the job - schedule deletion status. - - :param client: An instance of the Batch client used to make API calls for - checking job schedule status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - delete job schedule API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param job_schedule_id: The unique identifier of the job schedule being deleted. - :type job_schedule_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_schedule_id = job_schedule_id - self._polling_interval = polling_interval - self._status = "InProgress" - self._finished = False - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job_schedule = await self._client.get_job_schedule(self._job_schedule_id) - - if job_schedule.state == _models.BatchJobScheduleState.DELETING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job schedule no longer exists, deletion is complete - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class DeletePoolPollingMethodAsync(AsyncPollingMethod): - """Polling method for pool delete operation. - This class is used to poll the status of a pool deletion operation. - It checks the status of the pool until it is deleted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the DeletePoolPollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the pool - deletion status. - - :param client: An instance of the Batch client used to make API calls for - checking pool status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - delete pool API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool being deleted. - :type pool_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._polling_interval = polling_interval - self._status = "InProgress" - self._finished = False - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = await self._client.get_pool(self._pool_id) - - if pool.state == _models.BatchPoolState.DELETING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Pool no longer exists, deletion is complete - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class DeallocateNodePollingMethodAsync(AsyncPollingMethod): - """Polling method for node deallocate operation. - - This class is used to poll the status of a node deallocation operation. - It checks the status of the node until it is deallocated or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - """Initialize the DeallocateNodePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the node - deallocation status. - - :param client: An instance of the Batch client used to make API calls for - checking node status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - deallocate node API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool containing the node - to be deallocated. - :type pool_id: str - :keyword node_id: The unique identifier of the node to be deallocated. - :paramtype node_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = await self._client.get_node(self._pool_id, self._node_id) - - # If node not in DEALLOCATING state then completed - # DEALLOCATED is too quick of a state to check for success - if node.state == _models.BatchNodeState.DEALLOCATING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node no longer exists, might have been removed from pool - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class RebootNodePollingMethodAsync(AsyncPollingMethod): - """Polling method for node reboot operation. - - This class is used to poll the status of a node reboot operation. - It checks the status of the node until it is rebooted or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - """Initialize the RebootNodePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the node - reboot status. - - :param client: An instance of the Batch client used to make API calls for - checking node status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - reboot node API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool containing the node - to be rebooted. - :type pool_id: str - :keyword node_id: The unique identifier of the node to be rebooted. - :paramtype node_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = await self._client.get_node(self._pool_id, self._node_id) - - if node.state == _models.BatchNodeState.REBOOTING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node could be deleted while rebooting - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class ReimageNodePollingMethodAsync(AsyncPollingMethod): - """Polling method for node reimage operation. - - This class is used to poll the status of a node reimage operation. - It checks the status of the node until it is reimaged or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - """Initialize the ReimageNodePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the node - reimage status. - - :param client: An instance of the Batch client used to make API calls for - checking node status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - reimage node API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool containing the node - to be reimaged. - :type pool_id: str - :keyword node_id: The unique identifier of the node to be reimaged. - :paramtype node_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = await self._client.get_node(self._pool_id, self._node_id) - - if node.state == _models.BatchNodeState.REIMAGING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node could be deleted while reimaging - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class RemoveNodePollingMethodAsync(AsyncPollingMethod): - """Polling method for node remove operation. - - This class is used to poll the status of a node removal operation. - It checks the status of the node until it is removed or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the RemoveNodePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the node - removal status. - - :param client: An instance of the Batch client used to make API calls for - checking pool status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - remove node API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool from which nodes - are being removed. - :type pool_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = await self._client.get_pool(self._pool_id) - - # Node removal is complete when the pool allocation state is STEADY - # This means the pool is no longer resizing/removing nodes - if pool.allocation_state == _models.AllocationState.STEADY: - self._status = "Succeeded" - self._finished = True - else: - self._status = "InProgress" - self._finished = False - - except ResourceNotFoundError: - # Pool could be deleted while removing nodes - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class ResizePoolPollingMethodAsync(AsyncPollingMethod): - """Polling method for pool resize operation. - - This class is used to poll the status of a pool resize operation. - It checks the status of the pool until it is resized or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the ResizePoolPollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the pool - resize status. - - :param client: An instance of the Batch client used to make API calls for - checking pool status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - resize pool API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool being resized. - :type pool_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = await self._client.get_pool(self._pool_id) - - # Pool resize is complete when the pool allocation state is STEADY - # This means the pool is no longer resizing (adding/removing nodes) - if pool.allocation_state == _models.AllocationState.STEADY: - self._status = "Succeeded" - self._finished = True - else: - self._status = "InProgress" - self._finished = False - - except ResourceNotFoundError: - # Pool could be deleted while resizing - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class StartNodePollingMethodAsync(AsyncPollingMethod): - """Polling method for node start operation. - - This class is used to poll the status of a node start operation. - It checks the status of the node until it is started or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - node_id: str, - polling_interval: int = 5, - ): - """Initialize the StartNodePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the node - start status. - - :param client: An instance of the Batch client used to make API calls for - checking node status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - start node API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool containing the node - to be started. - :type pool_id: str - :keyword node_id: The unique identifier of the node to be started. - :paramtype node_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._node_id = node_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - node = await self._client.get_node(self._pool_id, self._node_id) - - if node.state == _models.BatchNodeState.STARTING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Node could be deleted during starting - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class StopPoolResizePollingMethodAsync(AsyncPollingMethod): - """Polling method for pool stop resize operation. - - This class is used to poll the status of a pool stop resize operation. - It checks the status of the pool until it is stopped or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - pool_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the StopPoolResizePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the pool - stop resize status. - - :param client: An instance of the Batch client used to make API calls for - checking pool status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - stop pool resize API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param pool_id: The unique identifier of the pool for which resize is - being stopped. - :type pool_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._pool_id = pool_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - pool = await self._client.get_pool(self._pool_id) - - # Pool stop resize is complete when the pool allocation state is STEADY - # This means the pool has stopped resizing and is stable - if pool.allocation_state == _models.AllocationState.STEADY: - self._status = "Succeeded" - self._finished = True - else: - self._status = "InProgress" - self._finished = False - - except ResourceNotFoundError: - # Pool could be deleted during stop resize operation - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class TerminateJobPollingMethodAsync(AsyncPollingMethod): - """Polling method for job termination operation. - - This class is used to poll the status of a job termination operation. - It checks the status of the job until it is terminated or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the TerminateJobPollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the job - termination status. - - :param client: An instance of the Batch client used to make API calls for - checking job status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - terminate job API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param job_id: The unique identifier of the job being terminated. - :type job_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_id = job_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job = await self._client.get_job(self._job_id) - - if job.state == _models.BatchJobState.TERMINATING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job could be deleted while terminating - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True - - -class TerminateJobSchedulePollingMethodAsync(AsyncPollingMethod): - """Polling method for job schedule termination operation. - - This class is used to poll the status of a job schedule termination operation. - It checks the status of the job schedule until it is terminated or an error occurs. - """ - - def __init__( - self, - client: Any, - initial_response: PipelineResponse, - deserialization_callback: Optional[Callable], - job_schedule_id: str, - *, - polling_interval: int = 5, - ): - """Initialize the TerminateJobSchedulePollingMethodAsync. - - Sets the initial status of this long-running operation, verifies that polling - is possible, and initializes all necessary components for polling the job - schedule termination status. - - :param client: An instance of the Batch client used to make API calls for - checking job schedule status during polling. - :type client: Any - :param initial_response: The PipelineResponse returned from the initial - terminate job schedule API call. - :type initial_response: ~azure.core.pipeline.PipelineResponse - :param deserialization_callback: A callable function to transform the final - result before returning to the end user. Can be None if no transformation - is needed. - :type deserialization_callback: Optional[Callable] - :param job_schedule_id: The unique identifier of the job schedule being - terminated. - :type job_schedule_id: str - :keyword polling_interval: The time interval in seconds between polling - attempts. Defaults to 5 seconds. - :paramtype polling_interval: int - """ - self._client = client - self._initial_response = initial_response - self._deserialization_callback = deserialization_callback - self._job_schedule_id = job_schedule_id - self._status = "InProgress" - self._finished = False - self._polling_interval = polling_interval - - def initialize( - self, client: Any, initial_response: PipelineResponse, deserialization_callback: Optional[Callable] - ) -> None: - pass - - def status(self) -> str: - return self._status - - def finished(self) -> bool: - return self._finished - - def resource(self) -> Optional[Any]: - if self._deserialization_callback and self._finished: - return self._deserialization_callback() - return None - - async def run(self) -> None: - """The polling loop. - - The polling should call the status monitor, evaluate and set the current status, - insert delay between polls, and continue polling until a terminal state is reached. - """ - while not self.finished(): - await self.update_status() - if not self.finished(): - # add a delay if not done - await asyncio.sleep(self._polling_interval) - - async def update_status(self) -> None: - """Update the current status of the LRO by calling the status monitor - and then using the polling strategy's get_status() to set the status.""" - try: - job_schedule = await self._client.get_job_schedule(self._job_schedule_id) - - # Job schedule termination is complete when it's no longer in TERMINATING state - if job_schedule.state == _models.BatchJobScheduleState.TERMINATING: - self._status = "InProgress" - self._finished = False - else: - self._status = "Succeeded" - self._finished = True - - except ResourceNotFoundError: - # Job schedule could be deleted while terminating - self._status = "Succeeded" - self._finished = True - except AzureError: - # Another error occurred so LRO failed - self._status = "Failed" - self._finished = True diff --git a/sdk/batch/azure-batch/azure/batch/aio/_patch.py b/sdk/batch/azure-batch/azure/batch/aio/_patch.py index 0e143d513f25..ea765788358a 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_patch.py @@ -1,58 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import Union - -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.credentials import AzureNamedKeyCredential - -from ._client import BatchClient as GenerateBatchClient -from .._patch import BatchExceptionPolicy, BatchSharedKeyAuthPolicy - -__all__ = [ - "BatchClient", -] # Add all objects you want publicly available to users at this package level - - -class BatchClient(GenerateBatchClient): - """BatchClient. - - :param endpoint: HTTP or HTTPS endpoint for the Web PubSub service instance. - :type endpoint: str - :param hub: Target hub name, which should start with alphabetic characters and only contain - alpha-numeric characters or underscore. - :type hub: str - :param credentials: Credential needed for the client to connect to Azure. - :type credentials: ~azure.identity.ClientSecretCredential, ~azure.core.credentials.AzureNamedKeyCredential, - or ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. The default value is "2021-10-01". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, endpoint: str, credential: Union[AzureNamedKeyCredential, AsyncTokenCredential], **kwargs - ) -> None: - per_call_policies = kwargs.pop("per_call_policies", []) - per_call_policies.append(BatchExceptionPolicy()) - super().__init__( - endpoint=endpoint, - credential=credential, # type: ignore - authentication_policy=kwargs.pop("authentication_policy", self._format_shared_key_credential(credential)), - per_call_policies=per_call_policies, - **kwargs - ) - - def _format_shared_key_credential(self, credential): - if isinstance(credential, AzureNamedKeyCredential): - return BatchSharedKeyAuthPolicy(credential) - return None +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/batch/azure-batch/azure/batch/aio/_vendor.py b/sdk/batch/azure-batch/azure/batch/aio/_vendor.py deleted file mode 100644 index baee6ee7264c..000000000000 --- a/sdk/batch/azure-batch/azure/batch/aio/_vendor.py +++ /dev/null @@ -1,57 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Optional, TYPE_CHECKING - -from azure.core import MatchConditions - -from ._configuration import BatchClientConfiguration - -if TYPE_CHECKING: - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class BatchClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: BatchClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith("W/"): - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None diff --git a/sdk/batch/azure-batch/azure/batch/models/__init__.py b/sdk/batch/azure-batch/azure/batch/models/__init__.py index 5d61f090be5a..7a246e1320be 100644 --- a/sdk/batch/azure-batch/azure/batch/models/__init__.py +++ b/sdk/batch/azure-batch/azure/batch/models/__init__.py @@ -52,11 +52,13 @@ BatchJobSchedulingError, BatchJobSpecification, BatchJobStatistics, + BatchJobTerminateOptions, BatchJobUpdateOptions, BatchMetadataItem, BatchNode, BatchNodeAgentInfo, BatchNodeCounts, + BatchNodeDeallocateOptions, BatchNodeDisableSchedulingOptions, BatchNodeEndpointConfiguration, BatchNodeError, @@ -64,6 +66,8 @@ BatchNodeIdentityReference, BatchNodeInfo, BatchNodePlacementConfiguration, + BatchNodeRebootOptions, + BatchNodeReimageOptions, BatchNodeRemoteLoginSettings, BatchNodeRemoveOptions, BatchNodeUserCreateOptions, @@ -85,8 +89,6 @@ BatchPoolSpecification, BatchPoolStatistics, BatchPoolUpdateOptions, - BatchPoolUsageMetrics, - BatchPoolUsageStatistics, BatchPublicIpAddressConfiguration, BatchStartTask, BatchStartTaskInfo, @@ -126,12 +128,14 @@ ExitConditions, ExitOptions, FileProperties, + HardwareProfile, HostEndpointSettings, IPTag, InboundEndpoint, InstanceViewStatus, LinuxUserConfiguration, ManagedDisk, + MaxInstancePercentPerZonePolicy, MountConfiguration, MultiInstanceSettings, NameValuePair, @@ -143,8 +147,10 @@ OutputFileDestination, OutputFileUploadConfiguration, OutputFileUploadHeader, + Placement, ProxyAgentSettings, RecentBatchJob, + ResiliencyPolicy, ResizeError, ResourceFile, RollingUpgradePolicy, @@ -157,10 +163,14 @@ UserIdentity, VMExtension, VMExtensionInstanceView, + VMSizeProperties, VirtualMachineConfiguration, VirtualMachineInfo, + VirtualMachineSkuProfile, + VirtualMachineSkuProfileVmSize, WindowsConfiguration, WindowsUserConfiguration, + ZoneAllocationPolicy, ) from ._enums import ( # type: ignore @@ -174,10 +184,13 @@ BatchJobReleaseTaskState, BatchJobScheduleState, BatchJobState, + BatchNodeDeallocateOption, BatchNodeDeallocationOption, BatchNodeDisableSchedulingOption, BatchNodeFillType, BatchNodePlacementPolicyType, + BatchNodeRebootKind, + BatchNodeReimageOption, BatchNodeState, BatchPoolIdentityType, BatchPoolLifetimeOption, @@ -213,6 +226,8 @@ StatusLevelTypes, StorageAccountType, UpgradeMode, + VirtualMachineSkuAllocationStrategy, + ZonePlacementPolicyType, ) from ._patch import __all__ as _patch_all from ._patch import * @@ -257,11 +272,13 @@ "BatchJobSchedulingError", "BatchJobSpecification", "BatchJobStatistics", + "BatchJobTerminateOptions", "BatchJobUpdateOptions", "BatchMetadataItem", "BatchNode", "BatchNodeAgentInfo", "BatchNodeCounts", + "BatchNodeDeallocateOptions", "BatchNodeDisableSchedulingOptions", "BatchNodeEndpointConfiguration", "BatchNodeError", @@ -269,6 +286,8 @@ "BatchNodeIdentityReference", "BatchNodeInfo", "BatchNodePlacementConfiguration", + "BatchNodeRebootOptions", + "BatchNodeReimageOptions", "BatchNodeRemoteLoginSettings", "BatchNodeRemoveOptions", "BatchNodeUserCreateOptions", @@ -290,8 +309,6 @@ "BatchPoolSpecification", "BatchPoolStatistics", "BatchPoolUpdateOptions", - "BatchPoolUsageMetrics", - "BatchPoolUsageStatistics", "BatchPublicIpAddressConfiguration", "BatchStartTask", "BatchStartTaskInfo", @@ -331,12 +348,14 @@ "ExitConditions", "ExitOptions", "FileProperties", + "HardwareProfile", "HostEndpointSettings", "IPTag", "InboundEndpoint", "InstanceViewStatus", "LinuxUserConfiguration", "ManagedDisk", + "MaxInstancePercentPerZonePolicy", "MountConfiguration", "MultiInstanceSettings", "NameValuePair", @@ -348,8 +367,10 @@ "OutputFileDestination", "OutputFileUploadConfiguration", "OutputFileUploadHeader", + "Placement", "ProxyAgentSettings", "RecentBatchJob", + "ResiliencyPolicy", "ResizeError", "ResourceFile", "RollingUpgradePolicy", @@ -362,10 +383,14 @@ "UserIdentity", "VMExtension", "VMExtensionInstanceView", + "VMSizeProperties", "VirtualMachineConfiguration", "VirtualMachineInfo", + "VirtualMachineSkuProfile", + "VirtualMachineSkuProfileVmSize", "WindowsConfiguration", "WindowsUserConfiguration", + "ZoneAllocationPolicy", "AllocationState", "AutoUserScope", "BatchAllTasksCompleteMode", @@ -376,10 +401,13 @@ "BatchJobReleaseTaskState", "BatchJobScheduleState", "BatchJobState", + "BatchNodeDeallocateOption", "BatchNodeDeallocationOption", "BatchNodeDisableSchedulingOption", "BatchNodeFillType", "BatchNodePlacementPolicyType", + "BatchNodeRebootKind", + "BatchNodeReimageOption", "BatchNodeState", "BatchPoolIdentityType", "BatchPoolLifetimeOption", @@ -415,6 +443,8 @@ "StatusLevelTypes", "StorageAccountType", "UpgradeMode", + "VirtualMachineSkuAllocationStrategy", + "ZonePlacementPolicyType", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/batch/azure-batch/azure/batch/models/_enums.py b/sdk/batch/azure-batch/azure/batch/models/_enums.py index decff47f8623..38d0ed56971e 100644 --- a/sdk/batch/azure-batch/azure/batch/models/_enums.py +++ b/sdk/batch/azure-batch/azure/batch/models/_enums.py @@ -61,7 +61,7 @@ class BatchJobActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Disable the Job. This is equivalent to calling the disable Job API, with a disableTasks value of requeue.""" TERMINATE = "terminate" - """Terminate the Job. The terminationReason in the Job's executionInfo is set to "TaskFailed".""" + """Terminate the Job. The terminationReason in the Job's executionInfo is set to \"TaskFailed\".""" class BatchJobDefaultOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -155,11 +155,6 @@ class BatchNodeDeallocateOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): TASK_COMPLETION = "taskcompletion" """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Deallocate the Compute Node when all Tasks have completed.""" - RETAINED_DATA = "retaineddata" - """Deprecated, we encourage you to upload task data to Azure Storage in your task and use - ``TaskCompletion`` instead. Allow currently running Tasks to complete, then wait for all Task - data retention periods to expire. Schedule no new Tasks while waiting. Deallocate the Compute - Node when all Task retention periods have expired.""" class BatchNodeDeallocationOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -174,11 +169,6 @@ class BatchNodeDeallocationOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): TASK_COMPLETION = "taskcompletion" """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Remove Compute Nodes when all Tasks have completed.""" - RETAINED_DATA = "retaineddata" - """Deprecated, we encourage you to upload task data to Azure Storage in your task and use - ``TaskCompletion`` instead. Allow currently running Tasks to complete, then wait for all Task - data retention periods to expire. Schedule no new Tasks while waiting. Remove Compute Nodes - when all Task retention periods have expired.""" class BatchNodeDisableSchedulingOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -229,11 +219,6 @@ class BatchNodeRebootKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): TASK_COMPLETION = "taskcompletion" """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Restart the Compute Node when all Tasks have completed.""" - RETAINED_DATA = "retaineddata" - """Deprecated, we encourage you to upload task data to Azure Storage in your task and use - ``TaskCompletion`` instead. Allow currently running Tasks to complete, then wait for all Task - data retention periods to expire. Schedule no new Tasks while waiting. Restart the Compute Node - when all Task retention periods have expired.""" class BatchNodeReimageOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -249,11 +234,6 @@ class BatchNodeReimageOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): TASK_COMPLETION = "taskcompletion" """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Reimage the Compute Node when all Tasks have completed.""" - RETAINED_DATA = "retaineddata" - """Deprecated, we encourage you to upload task data to Azure Storage in your task and use - ``TaskCompletion`` instead. Allow currently running Tasks to complete, then wait for all Task - data retention periods to expire. Schedule no new Tasks while waiting. Reimage the Compute Node - when all Task retention periods have expired.""" class BatchNodeState(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -697,3 +677,25 @@ class UpgradeMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The existing instances in a scale set are brought down in batches to be upgraded. Once the upgraded batch is complete, the instances will begin taking traffic again and the next batch will begin. This continues until all instances brought up-to-date.""" + + +class VirtualMachineSkuAllocationStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Specifies the allocation strategy that the Fungible Compute Platform uses to select VM sizes + from the vmSkuProfile when allocating Compute Nodes for an Instance Mix Pool. + """ + + LOWEST_PRICE = "lowestPrice" + """Select the cheapest available SKU in the region. This is the default strategy.""" + CAPACITY_OPTIMIZED = "capacityOptimized" + """Select the SKU with the most regional physical capacity.""" + PRIORITIZED = "prioritized" + """Follow the customer-defined ranking via the 0-based rank, falling back to the next rank when a + preferred SKU is unavailable.""" + + +class ZonePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The zone placement policy for Compute Nodes in a Pool.""" + + AUTO = "Auto" + """The Virtual Machine Scale Set automatically selects availability zones and balances instances + across them.""" diff --git a/sdk/batch/azure-batch/azure/batch/models/_models.py b/sdk/batch/azure-batch/azure/batch/models/_models.py index e28224578b5d..6edde7a1776b 100644 --- a/sdk/batch/azure-batch/azure/batch/models/_models.py +++ b/sdk/batch/azure-batch/azure/batch/models/_models.py @@ -17,7 +17,7 @@ from .. import models as _models -class AutomaticOsUpgradePolicy(_Model): +class AutomaticOsUpgradePolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The configuration parameters used for performing automatic OS upgrade. :ivar disable_automatic_rollback: Whether OS image rollback feature should be disabled. @@ -80,7 +80,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutoScaleRun(_Model): +class AutoScaleRun(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The results and errors from an execution of a Pool autoscale formula. :ivar timestamp: The time at which the autoscale formula was last evaluated. Required. @@ -128,7 +128,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutoScaleRunError(_Model): +class AutoScaleRunError(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An error that occurred when executing or evaluating a Pool autoscale formula. :ivar code: An identifier for the autoscale error. Codes are invariant and are intended to be @@ -172,7 +172,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutoUserSpecification(_Model): +class AutoUserSpecification(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies the options for the auto user that runs an Azure Batch Task. :ivar scope: The scope for the auto user. The default value is pool. If the pool is running @@ -217,7 +217,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureBlobFileSystemConfiguration(_Model): +class AzureBlobFileSystemConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information used to connect to an Azure Storage Container using Blobfuse. :ivar account_name: The Azure Storage Account name. Required. @@ -296,7 +296,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureFileShareConfiguration(_Model): +class AzureFileShareConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information used to connect to an Azure Fileshare. :ivar account_name: The Azure Storage account name. Required. @@ -355,7 +355,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchAffinityInfo(_Model): +class BatchAffinityInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A locality hint that can be used by the Batch service to select a Compute Node on which to start a Task. @@ -391,7 +391,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchApplication(_Model): +class BatchApplication(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains information about an application in an Azure Batch Account. :ivar id: A string that uniquely identifies the application within the Account. Required. @@ -429,7 +429,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchApplicationPackageReference(_Model): +class BatchApplicationPackageReference(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A reference to an Package to be deployed to Compute Nodes. :ivar application_id: The ID of the application to deploy. When creating a pool, the package's @@ -476,7 +476,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchAutoPoolSpecification(_Model): +class BatchAutoPoolSpecification(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies characteristics for a temporary 'auto pool'. The Batch service will create this auto Pool when the Job is submitted. @@ -543,7 +543,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchContainerConfiguration(_Model): +class BatchContainerConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The configuration for container-enabled Pools. :ivar type: The container technology to be used. Required. Known values are: "dockerCompatible" @@ -595,7 +595,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchCreateTaskCollectionResult(_Model): +class BatchCreateTaskCollectionResult(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The result of creating a collection of Tasks to a Job. :ivar result_values: The results of the create Task collection operation. @@ -625,7 +625,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchDiffDiskSettings(_Model): +class BatchDiffDiskSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies the ephemeral Disk Settings for the operating system disk used by the compute node (VM). @@ -674,7 +674,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchError(_Model): +class BatchError(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An error response received from the Azure Batch service. :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed @@ -720,7 +720,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchErrorDetail(_Model): +class BatchErrorDetail(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An item of additional information included in an Azure Batch error response. :ivar key: An identifier specifying the meaning of the Value property. @@ -753,7 +753,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchErrorMessage(_Model): +class BatchErrorMessage(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An error message received in an Azure Batch error response. :ivar lang: The language code of the error message. @@ -786,7 +786,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchInboundNatPool(_Model): +class BatchInboundNatPool(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A inbound NAT Pool that can be used to address specific ports on Compute Nodes in a Batch Pool externally. @@ -886,7 +886,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJob(_Model): +class BatchJob(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An Azure Batch Job. :ivar id: A string that uniquely identifies the Job within the Account. The ID is @@ -1119,7 +1119,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobConstraints(_Model): +class BatchJobConstraints(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The execution constraints for a Job. :ivar max_wall_clock_time: The maximum elapsed time that the Job may run, measured from the @@ -1176,7 +1176,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobCreateOptions(_Model): +class BatchJobCreateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for creating an Azure Batch Job. :ivar id: A string that uniquely identifies the Job within the Account. The ID can contain any @@ -1394,7 +1394,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobDisableOptions(_Model): +class BatchJobDisableOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for disabling an Azure Batch Job. :ivar disable_tasks: What to do with active Tasks associated with the Job. Required. Known @@ -1426,7 +1426,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobExecutionInfo(_Model): +class BatchJobExecutionInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains information about the execution of a Job in the Azure Batch service. :ivar start_time: The start time of the Job. This is the time at which the Job was created. @@ -1513,7 +1513,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobManagerTask(_Model): +class BatchJobManagerTask(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies details of a Job Manager Task. The Job Manager Task is automatically started when the Job is created. The Batch service tries to schedule the Job Manager Task before any other Tasks in the Job. When shrinking a Pool, the Batch service tries to preserve Nodes where Job Manager @@ -1746,7 +1746,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobNetworkConfiguration(_Model): +class BatchJobNetworkConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """(This property is not available by default. Please contact support for more information) The network configuration for the Job. @@ -1824,7 +1824,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobPreparationAndReleaseTaskStatus(_Model): +class BatchJobPreparationAndReleaseTaskStatus(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The status of the Job Preparation and Job Release Tasks on a Compute Node. :ivar pool_id: The ID of the Pool containing the Compute Node to which this entry refers. @@ -1881,7 +1881,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobPreparationTask(_Model): +class BatchJobPreparationTask(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A Job Preparation Task to run before any Tasks of the Job on any given Compute Node. You can use Job Preparation to prepare a Node to run Tasks for the Job. Activities commonly performed in Job Preparation include: Downloading common resource files used by all the Tasks in the Job. @@ -2066,7 +2066,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobPreparationTaskExecutionInfo(_Model): +class BatchJobPreparationTaskExecutionInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains information about the execution of a Job Preparation Task on a Compute Node. :ivar start_time: The time at which the Task started running. If the Task has been restarted or @@ -2207,7 +2207,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobReleaseTask(_Model): +class BatchJobReleaseTask(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A Job Release Task to run on Job completion on any Compute Node where the Job has run. The Job Release Task runs when the Job ends, because of one of the following: The user calls the Terminate Job API, or the Delete Job API while the Job is still active, the Job's maximum wall @@ -2362,7 +2362,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobReleaseTaskExecutionInfo(_Model): +class BatchJobReleaseTaskExecutionInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains information about the execution of a Job Release Task on a Compute Node. :ivar start_time: The time at which the Task started running. If the Task has been restarted or @@ -2472,7 +2472,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobSchedule(_Model): +class BatchJobSchedule(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A Job Schedule that allows recurring Jobs by specifying when to run Jobs and a specification used to create each Job. @@ -2602,7 +2602,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleConfiguration(_Model): +class BatchJobScheduleConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The schedule according to which Jobs will be created. All times are fixed respective to UTC and are not impacted by daylight saving time. @@ -2706,7 +2706,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleCreateOptions(_Model): +class BatchJobScheduleCreateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for creating an Azure Batch Job Schedule. :ivar id: A string that uniquely identifies the schedule within the Account. The ID can contain @@ -2774,7 +2774,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleExecutionInfo(_Model): +class BatchJobScheduleExecutionInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains information about Jobs that have been and will be run under a Job Schedule. :ivar next_run_time: The next time at which a Job will be created under this schedule. This @@ -2828,7 +2828,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleStatistics(_Model): +class BatchJobScheduleStatistics(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Resource usage statistics for a Job Schedule. :ivar url: The URL of the statistics. Required. @@ -2988,7 +2988,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleUpdateOptions(_Model): +class BatchJobScheduleUpdateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for updating an Azure Batch Job Schedule. :ivar schedule: The schedule according to which Jobs will be created. All times are fixed @@ -3042,7 +3042,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobSchedulingError(_Model): +class BatchJobSchedulingError(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An error encountered by the Batch service when scheduling a Job. :ivar category: The category of the Job scheduling error. Required. Known values are: @@ -3095,7 +3095,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobSpecification(_Model): +class BatchJobSpecification(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies details of the Jobs to be created on a schedule. :ivar priority: The priority of Jobs created under this schedule. Priority values can range @@ -3306,7 +3306,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobStatistics(_Model): +class BatchJobStatistics(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Resource usage statistics for a Job. :ivar url: The URL of the statistics. Required. @@ -3455,7 +3455,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobTerminateOptions(_Model): +class BatchJobTerminateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for terminating an Azure Batch Job. :ivar termination_reason: The text you want to appear as the Job's TerminationReason. The @@ -3486,7 +3486,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobUpdateOptions(_Model): +class BatchJobUpdateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for updating an Azure Batch Job. :ivar priority: The priority of the Job. Priority values can range from -1000 to 1000, with @@ -3610,7 +3610,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchMetadataItem(_Model): +class BatchMetadataItem(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The Batch service does not assign any meaning to this metadata; it is solely for the use of user code. @@ -3682,6 +3682,18 @@ class BatchNode(_Model): reclaimed and could be reused for new Compute Nodes. This property will not be present if the Pool is not configured for IPv6. Required. :vartype ipv6_address: str + :ivar public_ip_address: The public IPv4 address (load balancer front-end VIP) used to reach + this Compute Node from outside the virtual network. For Pools that use the Batch-managed or + User-managed public load balancer, this is the load balancer's front-end public IPv4 address. + The value is present regardless of whether SSH or RDP remote access is enabled, so callers can + perform IP-based validation even when remote login is disabled. The property is omitted when + the Pool is configured with no public IP addresses (for example, private link or BYO VNet with + NoPublicIPAddresses). + :vartype public_ip_address: str + :ivar public_ipv6_address: The public IPv6 address (load balancer front-end VIP) used to reach + this Compute Node from outside the virtual network. Populated only when the Pool is configured + for IPv6 / dual-stack public networking. The property is omitted otherwise. + :vartype public_ipv6_address: str :ivar affinity_id: An identifier which can be passed when adding a Task to request that the Task be scheduled on this Compute Node. Note that this is just a soft affinity. If the target Compute Node is busy or unavailable at the time the Task is scheduled, then the Task will be @@ -3768,6 +3780,18 @@ class BatchNode(_Model): removed from a Pool, all of its local files are deleted, and the IP address is reclaimed and could be reused for new Compute Nodes. This property will not be present if the Pool is not configured for IPv6. Required.""" + public_ip_address: Optional[str] = rest_field(name="publicIPAddress", visibility=["read"]) + """The public IPv4 address (load balancer front-end VIP) used to reach this Compute Node from + outside the virtual network. For Pools that use the Batch-managed or User-managed public load + balancer, this is the load balancer's front-end public IPv4 address. The value is present + regardless of whether SSH or RDP remote access is enabled, so callers can perform IP-based + validation even when remote login is disabled. The property is omitted when the Pool is + configured with no public IP addresses (for example, private link or BYO VNet with + NoPublicIPAddresses).""" + public_ipv6_address: Optional[str] = rest_field(name="publicIPv6Address", visibility=["read"]) + """The public IPv6 address (load balancer front-end VIP) used to reach this Compute Node from + outside the virtual network. Populated only when the Pool is configured for IPv6 / dual-stack + public networking. The property is omitted otherwise.""" affinity_id: str = rest_field(name="affinityId", visibility=["read"]) """An identifier which can be passed when adding a Task to request that the Task be scheduled on this Compute Node. Note that this is just a soft affinity. If the target Compute Node is busy @@ -3815,7 +3839,7 @@ class BatchNode(_Model): """Info about the current state of the virtual machine. Required.""" -class BatchNodeAgentInfo(_Model): +class BatchNodeAgentInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The Batch Compute Node agent is a program that runs on each Compute Node in the Pool and provides Batch capability on the Compute Node. @@ -3860,7 +3884,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeCounts(_Model): +class BatchNodeCounts(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The number of Compute Nodes in each Compute Node state. :ivar creating: The number of Compute Nodes in the creating state. Required. @@ -3973,27 +3997,26 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeDeallocateOptions(_Model): +class BatchNodeDeallocateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Options for deallocating a Compute Node. :ivar node_deallocate_option: When to deallocate the Compute Node and what to do with currently - running Tasks. The default value is requeue. Known values are: "requeue", "terminate", - "taskcompletion", and "retaineddata". + running Tasks. The default value is requeue. Known values are: "requeue", "terminate", and + "taskcompletion". :vartype node_deallocate_option: str or ~azure.batch.models.BatchNodeDeallocateOption """ - node_deallocate_option: Optional[Union[str, "_models._enums.BatchNodeDeallocateOption"]] = rest_field( + node_deallocate_option: Optional[Union[str, "_models.BatchNodeDeallocateOption"]] = rest_field( name="nodeDeallocateOption", visibility=["read", "create", "update", "delete", "query"] ) """When to deallocate the Compute Node and what to do with currently running Tasks. The default - value is requeue. Known values are: \"requeue\", \"terminate\", \"taskcompletion\", and - \"retaineddata\".""" + value is requeue. Known values are: \"requeue\", \"terminate\", and \"taskcompletion\".""" @overload def __init__( self, *, - node_deallocate_option: Optional[Union[str, "_models._enums.BatchNodeDeallocateOption"]] = None, + node_deallocate_option: Optional[Union[str, "_models.BatchNodeDeallocateOption"]] = None, ) -> None: ... @overload @@ -4007,7 +4030,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeDisableSchedulingOptions(_Model): +class BatchNodeDisableSchedulingOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for disabling scheduling on an Azure Batch Compute Node. :ivar node_disable_scheduling_option: What to do with currently running Tasks when disabling @@ -4041,7 +4064,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeEndpointConfiguration(_Model): +class BatchNodeEndpointConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The endpoint configuration for the Compute Node. :ivar inbound_endpoints: The list of inbound endpoints that are accessible on the Compute Node. @@ -4072,7 +4095,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeError(_Model): +class BatchNodeError(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An error encountered by a Compute Node. :ivar code: An identifier for the Compute Node error. Codes are invariant and are intended to @@ -4116,7 +4139,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeFile(_Model): +class BatchNodeFile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about a file or directory on a Compute Node. :ivar name: The file path. @@ -4163,7 +4186,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeIdentityReference(_Model): +class BatchNodeIdentityReference(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The reference to a user assigned identity associated with the Batch pool which a compute node will use. @@ -4194,7 +4217,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeInfo(_Model): +class BatchNodeInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about the Compute Node on which a Task ran. :ivar affinity_id: An identifier for the Node on which the Task ran, which can be passed when @@ -4255,7 +4278,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodePlacementConfiguration(_Model): +class BatchNodePlacementConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """For regional placement, nodes in the pool will be allocated in the same region. For zonal placement, nodes in the pool will be spread across different zones with best effort balancing. @@ -4290,27 +4313,26 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeRebootOptions(_Model): +class BatchNodeRebootOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for rebooting an Azure Batch Compute Node. :ivar node_reboot_kind: When to reboot the Compute Node and what to do with currently running - Tasks. The default value is requeue. Known values are: "requeue", "terminate", - "taskcompletion", and "retaineddata". + Tasks. The default value is requeue. Known values are: "requeue", "terminate", and + "taskcompletion". :vartype node_reboot_kind: str or ~azure.batch.models.BatchNodeRebootKind """ - node_reboot_kind: Optional[Union[str, "_models._enums.BatchNodeRebootKind"]] = rest_field( + node_reboot_kind: Optional[Union[str, "_models.BatchNodeRebootKind"]] = rest_field( name="nodeRebootOption", visibility=["read", "create", "update", "delete", "query"] ) """When to reboot the Compute Node and what to do with currently running Tasks. The default value - is requeue. Known values are: \"requeue\", \"terminate\", \"taskcompletion\", and - \"retaineddata\".""" + is requeue. Known values are: \"requeue\", \"terminate\", and \"taskcompletion\".""" @overload def __init__( self, *, - node_reboot_kind: Optional[Union[str, "_models._enums.BatchNodeRebootKind"]] = None, + node_reboot_kind: Optional[Union[str, "_models.BatchNodeRebootKind"]] = None, ) -> None: ... @overload @@ -4324,27 +4346,26 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeReimageOptions(_Model): +class BatchNodeReimageOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for reimaging an Azure Batch Compute Node. :ivar node_reimage_option: When to reimage the Compute Node and what to do with currently - running Tasks. The default value is requeue. Known values are: "requeue", "terminate", - "taskcompletion", and "retaineddata". + running Tasks. The default value is requeue. Known values are: "requeue", "terminate", and + "taskcompletion". :vartype node_reimage_option: str or ~azure.batch.models.BatchNodeReimageOption """ - node_reimage_option: Optional[Union[str, "_models._enums.BatchNodeReimageOption"]] = rest_field( + node_reimage_option: Optional[Union[str, "_models.BatchNodeReimageOption"]] = rest_field( name="nodeReimageOption", visibility=["read", "create", "update", "delete", "query"] ) """When to reimage the Compute Node and what to do with currently running Tasks. The default value - is requeue. Known values are: \"requeue\", \"terminate\", \"taskcompletion\", and - \"retaineddata\".""" + is requeue. Known values are: \"requeue\", \"terminate\", and \"taskcompletion\".""" @overload def __init__( self, *, - node_reimage_option: Optional[Union[str, "_models._enums.BatchNodeReimageOption"]] = None, + node_reimage_option: Optional[Union[str, "_models.BatchNodeReimageOption"]] = None, ) -> None: ... @overload @@ -4358,7 +4379,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeRemoteLoginSettings(_Model): +class BatchNodeRemoteLoginSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The remote login settings for a Compute Node. :ivar ipv6_remote_login_ip_address: The IPv6 address used for remote login to the Compute Node. @@ -4410,7 +4431,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeRemoveOptions(_Model): +class BatchNodeRemoveOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for removing nodes from an Azure Batch Pool. :ivar node_ids: A list containing the IDs of the Compute Nodes to be removed from the specified @@ -4423,7 +4444,7 @@ class BatchNodeRemoveOptions(_Model): :vartype resize_timeout: ~datetime.timedelta :ivar node_deallocation_option: Determines what to do with a Compute Node and its running task(s) after it has been selected for deallocation. The default value is requeue. Known values - are: "requeue", "terminate", "taskcompletion", and "retaineddata". + are: "requeue", "terminate", and "taskcompletion". :vartype node_deallocation_option: str or ~azure.batch.models.BatchNodeDeallocationOption """ @@ -4442,7 +4463,7 @@ class BatchNodeRemoveOptions(_Model): ) """Determines what to do with a Compute Node and its running task(s) after it has been selected for deallocation. The default value is requeue. Known values are: \"requeue\", \"terminate\", - \"taskcompletion\", and \"retaineddata\".""" + and \"taskcompletion\".""" @overload def __init__( @@ -4464,7 +4485,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeUserCreateOptions(_Model): +class BatchNodeUserCreateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for creating a user account for RDP or SSH access on an Azure Batch Compute Node. :ivar name: The user name of the Account. Required. @@ -4530,7 +4551,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeUserReplaceOptions(_Model): +class BatchNodeUserReplaceOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for updating a user account for RDP or SSH access on an Azure Batch Compute Node. :ivar password: The password of the Account. The password is required for Windows Compute @@ -4587,7 +4608,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeVMExtension(_Model): +class BatchNodeVMExtension(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The configuration for virtual machine extension instance view. :ivar provisioning_state: The provisioning state of the virtual machine extension. @@ -4631,7 +4652,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchOsDisk(_Model): +class BatchOsDisk(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Settings for the operating system disk of the compute node (VM). :ivar ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating @@ -4696,7 +4717,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPool(_Model): +class BatchPool(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A Pool in the Azure Batch service. :ivar id: A string that uniquely identifies the Pool within the Account. The ID can contain any @@ -4740,6 +4761,10 @@ class BatchPool(_Model): :ivar virtual_machine_configuration: The virtual machine configuration for the Pool. This property must be specified. :vartype virtual_machine_configuration: ~azure.batch.models.VirtualMachineConfiguration + :ivar vm_sku_profile: Specifies the profile of VM sizes and the allocation strategy used to + allocate Compute Nodes for an Instance Mix Pool. When specified, vmSize must be 'Mix'. This + property can only be changed while the Pool has no Compute Nodes. + :vartype vm_sku_profile: ~azure.batch.models.VirtualMachineSkuProfile :ivar resize_timeout: The timeout for allocation of Compute Nodes to the Pool. This is the timeout for the most recent resize operation. (The initial sizing when the Pool is created counts as a resize.) The default value is 15 minutes. The time duration is specified in ISO @@ -4867,6 +4892,10 @@ class BatchPool(_Model): name="virtualMachineConfiguration", visibility=["read"] ) """The virtual machine configuration for the Pool. This property must be specified.""" + vm_sku_profile: Optional["_models.VirtualMachineSkuProfile"] = rest_field(name="vmSkuProfile", visibility=["read"]) + """Specifies the profile of VM sizes and the allocation strategy used to allocate Compute Nodes + for an Instance Mix Pool. When specified, vmSize must be 'Mix'. This property can only be + changed while the Pool has no Compute Nodes.""" resize_timeout: Optional[datetime.timedelta] = rest_field(name="resizeTimeout", visibility=["read"]) """The timeout for allocation of Compute Nodes to the Pool. This is the timeout for the most recent resize operation. (The initial sizing when the Pool is created counts as a resize.) The @@ -4974,7 +5003,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolCreateOptions(_Model): +class BatchPoolCreateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for creating an Azure Batch Pool. :ivar id: A string that uniquely identifies the Pool within the Account. The ID can contain any @@ -4996,6 +5025,10 @@ class BatchPoolCreateOptions(_Model): :ivar virtual_machine_configuration: The virtual machine configuration for the Pool. This property must be specified. :vartype virtual_machine_configuration: ~azure.batch.models.VirtualMachineConfiguration + :ivar vm_sku_profile: Specifies the profile of VM sizes and the allocation strategy used to + allocate Compute Nodes for an Instance Mix Pool. When specified, vmSize must be 'Mix'. This + property can only be changed while the Pool has no Compute Nodes. + :vartype vm_sku_profile: ~azure.batch.models.VirtualMachineSkuProfile :ivar resize_timeout: The timeout for allocation of Compute Nodes to the Pool. This timeout applies only to manual scaling; it has no effect when enableAutoScale is set to true. The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 @@ -5092,6 +5125,12 @@ class BatchPoolCreateOptions(_Model): name="virtualMachineConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The virtual machine configuration for the Pool. This property must be specified.""" + vm_sku_profile: Optional["_models.VirtualMachineSkuProfile"] = rest_field( + name="vmSkuProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the profile of VM sizes and the allocation strategy used to allocate Compute Nodes + for an Instance Mix Pool. When specified, vmSize must be 'Mix'. This property can only be + changed while the Pool has no Compute Nodes.""" resize_timeout: Optional[datetime.timedelta] = rest_field( name="resizeTimeout", visibility=["read", "create", "update", "delete", "query"] ) @@ -5200,6 +5239,7 @@ def __init__( vm_size: str, display_name: Optional[str] = None, virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, + vm_sku_profile: Optional["_models.VirtualMachineSkuProfile"] = None, resize_timeout: Optional[datetime.timedelta] = None, target_dedicated_nodes: Optional[int] = None, target_low_priority_nodes: Optional[int] = None, @@ -5229,7 +5269,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolEnableAutoScaleOptions(_Model): +class BatchPoolEnableAutoScaleOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for enabling automatic scaling on an Azure Batch Pool. :ivar auto_scale_formula: The formula for the desired number of Compute Nodes in the Pool. The @@ -5292,7 +5332,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolEndpointConfiguration(_Model): +class BatchPoolEndpointConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The endpoint configuration for a Pool. :ivar inbound_nat_pools: A list of inbound NAT Pools that can be used to address specific ports @@ -5329,7 +5369,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolEvaluateAutoScaleOptions(_Model): +class BatchPoolEvaluateAutoScaleOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for evaluating an automatic scaling formula on an Azure Batch Pool. :ivar auto_scale_formula: The formula for the desired number of Compute Nodes in the Pool. The @@ -5369,7 +5409,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolIdentity(_Model): +class BatchPoolIdentity(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The identity of the Batch pool, if configured. :ivar type: The identity of the Batch pool, if configured. The list of user identities @@ -5417,7 +5457,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolIdentityReference(_Model): +class BatchPoolIdentityReference(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The reference of one of the pool identities to encrypt Disk. This identity will be used to access the key vault. @@ -5450,7 +5490,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolInfo(_Model): +class BatchPoolInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies how a Job should be assigned to a Pool. :ivar pool_id: The ID of an existing Pool. All the Tasks of the Job will run on the specified @@ -5507,7 +5547,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolNodeCounts(_Model): +class BatchPoolNodeCounts(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The number of Compute Nodes in each state for a Pool. :ivar pool_id: The ID of the Pool. Required. @@ -5549,7 +5589,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolReplaceOptions(_Model): +class BatchPoolReplaceOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for replacing properties on an Azure Batch Pool. :ivar start_task: A Task to run on each Compute Node as it joins the Pool. The Task runs when @@ -5614,7 +5654,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolResizeOptions(_Model): +class BatchPoolResizeOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for changing the size of an Azure Batch Pool. :ivar target_dedicated_nodes: The desired number of dedicated Compute Nodes in the Pool. @@ -5630,7 +5670,7 @@ class BatchPoolResizeOptions(_Model): :vartype resize_timeout: ~datetime.timedelta :ivar node_deallocation_option: Determines what to do with a Compute Node and its running task(s) if the Pool size is decreasing. The default value is requeue. Known values are: - "requeue", "terminate", "taskcompletion", and "retaineddata". + "requeue", "terminate", and "taskcompletion". :vartype node_deallocation_option: str or ~azure.batch.models.BatchNodeDeallocationOption """ @@ -5653,8 +5693,8 @@ class BatchPoolResizeOptions(_Model): name="nodeDeallocationOption", visibility=["read", "create", "update", "delete", "query"] ) """Determines what to do with a Compute Node and its running task(s) if the Pool size is - decreasing. The default value is requeue. Known values are: \"requeue\", \"terminate\", - \"taskcompletion\", and \"retaineddata\".""" + decreasing. The default value is requeue. Known values are: \"requeue\", \"terminate\", and + \"taskcompletion\".""" @overload def __init__( @@ -5677,7 +5717,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolResourceStatistics(_Model): +class BatchPoolResourceStatistics(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Statistics related to resource consumption by Compute Nodes in a Pool. :ivar start_time: The start time of the time range covered by the statistics. Required. @@ -5743,13 +5783,9 @@ class BatchPoolResourceStatistics(_Model): """The average used disk space in GiB across all Compute Nodes in the Pool. Required.""" peak_disk_gib: float = rest_field(name="peakDiskGiB", visibility=["read", "create", "update", "delete", "query"]) """The peak used disk space in GiB across all Compute Nodes in the Pool. Required.""" - disk_read_iops: int = rest_field( - name="diskReadIOps", visibility=["read", "create", "update", "delete", "query"], format="str" - ) + disk_read_iops: int = rest_field(name="diskReadIOps", visibility=["read", "create", "update", "delete", "query"]) """The total number of disk read operations across all Compute Nodes in the Pool. Required.""" - disk_write_iops: int = rest_field( - name="diskWriteIOps", visibility=["read", "create", "update", "delete", "query"], format="str" - ) + disk_write_iops: int = rest_field(name="diskWriteIOps", visibility=["read", "create", "update", "delete", "query"]) """The total number of disk write operations across all Compute Nodes in the Pool. Required.""" disk_read_gib: float = rest_field(name="diskReadGiB", visibility=["read", "create", "update", "delete", "query"]) """The total amount of data in GiB of disk reads across all Compute Nodes in the Pool. Required.""" @@ -5796,7 +5832,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolSpecification(_Model): +class BatchPoolSpecification(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specification for creating a new Pool. :ivar display_name: The display name for the Pool. The display name need not be unique and can @@ -6032,7 +6068,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolStatistics(_Model): +class BatchPoolStatistics(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains utilization and resource usage statistics for the lifetime of a Pool. :ivar url: The URL for the statistics. Required. @@ -6042,8 +6078,6 @@ class BatchPoolStatistics(_Model): :ivar last_update_time: The time at which the statistics were last updated. All statistics are limited to the range between startTime and lastUpdateTime. Required. :vartype last_update_time: ~datetime.datetime - :ivar usage_statistics: Statistics related to Pool usage, such as the amount of core-time used. - :vartype usage_statistics: ~azure.batch.models.BatchPoolUsageStatistics :ivar resource_statistics: Statistics related to resource consumption by Compute Nodes in the Pool. :vartype resource_statistics: ~azure.batch.models.BatchPoolResourceStatistics @@ -6060,10 +6094,6 @@ class BatchPoolStatistics(_Model): ) """The time at which the statistics were last updated. All statistics are limited to the range between startTime and lastUpdateTime. Required.""" - usage_statistics: Optional["_models.BatchPoolUsageStatistics"] = rest_field( - name="usageStats", visibility=["read", "create", "update", "delete", "query"] - ) - """Statistics related to Pool usage, such as the amount of core-time used.""" resource_statistics: Optional["_models.BatchPoolResourceStatistics"] = rest_field( name="resourceStats", visibility=["read", "create", "update", "delete", "query"] ) @@ -6076,7 +6106,6 @@ def __init__( url: str, start_time: datetime.datetime, last_update_time: datetime.datetime, - usage_statistics: Optional["_models.BatchPoolUsageStatistics"] = None, resource_statistics: Optional["_models.BatchPoolResourceStatistics"] = None, ) -> None: ... @@ -6091,7 +6120,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolUpdateOptions(_Model): +class BatchPoolUpdateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for updating an Azure Batch Pool. :ivar display_name: The display name for the Pool. The display name need not be unique and can @@ -6131,6 +6160,10 @@ class BatchPoolUpdateOptions(_Model): :ivar virtual_machine_configuration: The virtual machine configuration for the Pool. This property must be specified.

This field can be updated only when the pool is empty. :vartype virtual_machine_configuration: ~azure.batch.models.VirtualMachineConfiguration + :ivar vm_sku_profile: Specifies the profile of VM sizes and the allocation strategy used to + allocate Compute Nodes for an Instance Mix Pool. When specified, vmSize must be 'Mix'.

This field can be updated only when the pool is empty. + :vartype vm_sku_profile: ~azure.batch.models.VirtualMachineSkuProfile :ivar task_slots_per_node: The number of task slots that can be used to run concurrent tasks on a single compute node in the pool. The default value is 1. The maximum value is the smaller of 4 times the number of cores of the vmSize of the pool or 256.

This field can be @@ -6200,6 +6233,12 @@ class BatchPoolUpdateOptions(_Model): ) """The virtual machine configuration for the Pool. This property must be specified.

This field can be updated only when the pool is empty.""" + vm_sku_profile: Optional["_models.VirtualMachineSkuProfile"] = rest_field( + name="vmSkuProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the profile of VM sizes and the allocation strategy used to allocate Compute Nodes + for an Instance Mix Pool. When specified, vmSize must be 'Mix'.

This field can be + updated only when the pool is empty.""" task_slots_per_node: Optional[int] = rest_field( name="taskSlotsPerNode", visibility=["read", "create", "update", "delete", "query"] ) @@ -6244,6 +6283,7 @@ def __init__( application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = None, metadata: Optional[list["_models.BatchMetadataItem"]] = None, virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, + vm_sku_profile: Optional["_models.VirtualMachineSkuProfile"] = None, task_slots_per_node: Optional[int] = None, task_scheduling_policy: Optional["_models.BatchTaskSchedulingPolicy"] = None, network_configuration: Optional["_models.NetworkConfiguration"] = None, @@ -6263,117 +6303,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolUsageMetrics(_Model): - """Usage metrics for a Pool across an aggregation interval. - - :ivar pool_id: The ID of the Pool whose metrics are aggregated in this entry. Required. - :vartype pool_id: str - :ivar start_time: The start time of the aggregation interval covered by this entry. Required. - :vartype start_time: ~datetime.datetime - :ivar end_time: The end time of the aggregation interval covered by this entry. Required. - :vartype end_time: ~datetime.datetime - :ivar vm_size: The size of virtual machines in the Pool. All VMs in a Pool are the same size. - For information about available sizes of virtual machines in Pools, see Choose a VM size for - Compute Nodes in an Azure Batch Pool - (`https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes - `_). Required. - :vartype vm_size: str - :ivar total_core_hours: The total core hours used in the Pool during this aggregation interval. - Required. - :vartype total_core_hours: float - """ - - pool_id: str = rest_field(name="poolId", visibility=["read", "create", "update", "delete", "query"]) - """The ID of the Pool whose metrics are aggregated in this entry. Required.""" - start_time: datetime.datetime = rest_field( - name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """The start time of the aggregation interval covered by this entry. Required.""" - end_time: datetime.datetime = rest_field( - name="endTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """The end time of the aggregation interval covered by this entry. Required.""" - vm_size: str = rest_field(name="vmSize", visibility=["read", "create", "update", "delete", "query"]) - """The size of virtual machines in the Pool. All VMs in a Pool are the same size. For information - about available sizes of virtual machines in Pools, see Choose a VM size for Compute Nodes in - an Azure Batch Pool (`https://learn.microsoft.com/azure/batch/batch-pool-vm-sizes - `_). Required.""" - total_core_hours: float = rest_field( - name="totalCoreHours", visibility=["read", "create", "update", "delete", "query"] - ) - """The total core hours used in the Pool during this aggregation interval. Required.""" - - @overload - def __init__( - self, - *, - pool_id: str, - start_time: datetime.datetime, - end_time: datetime.datetime, - vm_size: str, - total_core_hours: float, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BatchPoolUsageStatistics(_Model): - """Statistics related to Pool usage information. - - :ivar start_time: The start time of the time range covered by the statistics. Required. - :vartype start_time: ~datetime.datetime - :ivar last_update_time: The time at which the statistics were last updated. All statistics are - limited to the range between startTime and lastUpdateTime. Required. - :vartype last_update_time: ~datetime.datetime - :ivar dedicated_core_time: The aggregated wall-clock time of the dedicated Compute Node cores - being part of the Pool. The time duration is specified in ISO 8601 format. Required. - :vartype dedicated_core_time: ~datetime.timedelta - """ - - start_time: datetime.datetime = rest_field( - name="startTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """The start time of the time range covered by the statistics. Required.""" - last_update_time: datetime.datetime = rest_field( - name="lastUpdateTime", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """The time at which the statistics were last updated. All statistics are limited to the range - between startTime and lastUpdateTime. Required.""" - dedicated_core_time: datetime.timedelta = rest_field( - name="dedicatedCoreTime", visibility=["read", "create", "update", "delete", "query"] - ) - """The aggregated wall-clock time of the dedicated Compute Node cores being part of the Pool. The - time duration is specified in ISO 8601 format. Required.""" - - @overload - def __init__( - self, - *, - start_time: datetime.datetime, - last_update_time: datetime.datetime, - dedicated_core_time: datetime.timedelta, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BatchPublicIpAddressConfiguration(_Model): +class BatchPublicIpAddressConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The public IP Address configuration of the networking configuration of a Pool. :ivar ip_address_provisioning_type: The provisioning type for Public IP Addresses for the Pool. @@ -6443,7 +6373,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchStartTask(_Model): +class BatchStartTask(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Batch will retry Tasks when a recovery operation is triggered on a Node. Examples of recovery operations include (but are not limited to) when an unhealthy Node is rebooted or a Compute Node disappeared due to host failure. Retries due to recovery operations are independent of and @@ -6592,7 +6522,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchStartTaskInfo(_Model): +class BatchStartTaskInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about a StartTask running on a Compute Node. :ivar state: The state of the StartTask on the Compute Node. Required. Known values are: @@ -6717,7 +6647,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchSubtask(_Model): +class BatchSubtask(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about an Azure Batch subtask. :ivar id: The ID of the subtask. @@ -6849,7 +6779,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchSupportedImage(_Model): +class BatchSupportedImage(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A reference to the Azure Virtual Machines Marketplace Image and additional information about the Image. @@ -6925,7 +6855,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTask(_Model): +class BatchTask(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Batch will retry Tasks when a recovery operation is triggered on a Node. Examples of recovery operations include (but are not limited to) when an unhealthy Node is rebooted or a Compute Node disappeared due to host failure. Retries due to recovery operations are independent of and @@ -7171,7 +7101,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskConstraints(_Model): +class BatchTaskConstraints(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Execution constraints to apply to a Task. :ivar max_wall_clock_time: The maximum elapsed time that the Task may run, measured from the @@ -7243,7 +7173,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskContainerExecutionInfo(_Model): +class BatchTaskContainerExecutionInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains information about the container which a Task is executing. :ivar container_id: The ID of the container. @@ -7289,7 +7219,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskContainerSettings(_Model): +class BatchTaskContainerSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The container settings for a Task. :ivar container_run_options: Additional options to the container create command. These @@ -7363,7 +7293,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCounts(_Model): +class BatchTaskCounts(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The Task counts for a Job. :ivar active: The number of Tasks in the active state. Required. @@ -7415,7 +7345,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCountsResult(_Model): +class BatchTaskCountsResult(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The Task and TaskSlot counts for a Job. :ivar task_counts: The number of Tasks per state. Required. @@ -7452,7 +7382,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCreateOptions(_Model): +class BatchTaskCreateOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Parameters for creating an Azure Batch Task. :ivar id: A string that uniquely identifies the Task within the Job. The ID can contain any @@ -7668,7 +7598,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCreateResult(_Model): +class BatchTaskCreateResult(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Result for a single Task created as part of an add Task collection operation. :ivar status: The status of the add Task request. Required. Known values are: "success", @@ -7733,7 +7663,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskDependencies(_Model): +class BatchTaskDependencies(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies any dependencies of a Task. Any Task that is explicitly specified or within a dependency range must complete before the dependant Task will be scheduled. @@ -7781,7 +7711,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskExecutionInfo(_Model): +class BatchTaskExecutionInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about the execution of a Task. :ivar start_time: The time at which the Task started running. 'Running' corresponds to the @@ -7921,7 +7851,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskFailureInfo(_Model): +class BatchTaskFailureInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about a Task failure. :ivar category: The category of the Task error. Required. Known values are: "usererror" and @@ -7972,7 +7902,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskGroup(_Model): +class BatchTaskGroup(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A collection of Azure Batch Tasks to add. :ivar task_values: The collection of Tasks to add. The maximum count of Tasks is 100. The total @@ -8008,7 +7938,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskIdRange(_Model): +class BatchTaskIdRange(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The start and end of the range are inclusive. For example, if a range has start 9 and end 12, then it represents Tasks '9', '10', '11' and '12'. @@ -8042,7 +7972,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskInfo(_Model): +class BatchTaskInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about a Task running on a Compute Node. :ivar task_url: The URL of the Task. @@ -8101,7 +8031,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskSchedulingPolicy(_Model): +class BatchTaskSchedulingPolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies how Tasks should be distributed across Compute Nodes. :ivar job_default_order: The order for scheduling tasks from different jobs with the same @@ -8142,7 +8072,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskSlotCounts(_Model): +class BatchTaskSlotCounts(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The TaskSlot counts for a Job. :ivar active: The number of TaskSlots for active Tasks. Required. @@ -8190,7 +8120,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskStatistics(_Model): +class BatchTaskStatistics(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Resource usage statistics for a Task. :ivar url: The URL of the statistics. Required. @@ -8304,7 +8234,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchUefiSettings(_Model): +class BatchUefiSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies the security settings like secure boot and vTPM used while creating the virtual machine. @@ -8343,7 +8273,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchUserAssignedIdentity(_Model): +class BatchUserAssignedIdentity(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The user assigned Identity. :ivar resource_id: The ARM resource id of the user assigned identity. Required. @@ -8379,7 +8309,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchVmDiskSecurityProfile(_Model): +class BatchVmDiskSecurityProfile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies the security profile settings for the managed disk. **Note**: It can only be set for Confidential VMs and required when using Confidential VMs. @@ -8418,7 +8348,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchVmImageReference(_Model): +class BatchVmImageReference(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A reference to an Azure Virtual Machines Marketplace Image or a Azure Compute Gallery Image. To get the list of all Azure Marketplace Image references verified by Azure Batch, see the ' List Supported Images ' operation. @@ -8527,7 +8457,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CifsMountConfiguration(_Model): +class CifsMountConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information used to connect to a CIFS file system. :ivar username: The user to use for authentication against the CIFS file system. Required. @@ -8585,7 +8515,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ContainerHostBatchBindMountEntry(_Model): +class ContainerHostBatchBindMountEntry(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The entry of path and mount mode you want to mount into task container. :ivar source: The path which be mounted to container customer can select. Known values are: @@ -8631,7 +8561,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ContainerRegistryReference(_Model): +class ContainerRegistryReference(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A private container registry. :ivar username: The user name to log into the registry server. @@ -8680,7 +8610,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DataDisk(_Model): +class DataDisk(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Settings which will be used by the data disks associated to Compute Nodes in the Pool. When using attached data disks, you need to mount and format the disks from within a VM to use them. @@ -8740,7 +8670,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DiskCustomerManagedKey(_Model): +class DiskCustomerManagedKey(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The Customer Managed Key reference to encrypt the Disk. :ivar identity_reference: The reference of one of the pool identities to encrypt Disk. This @@ -8788,7 +8718,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DiskEncryptionConfiguration(_Model): +class DiskEncryptionConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The disk encryption configuration applied on compute nodes in the pool. Disk encryption configuration is not supported on Linux pool created with Azure Compute Gallery Image. @@ -8834,7 +8764,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DiskEncryptionSetParameters(_Model): +class DiskEncryptionSetParameters(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The ARM resource id of the disk encryption set. :ivar id: The ARM resource id of the disk encryption set. The resource must be in the same @@ -8864,7 +8794,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class EnvironmentSetting(_Model): +class EnvironmentSetting(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An environment variable to be set on a Task process. :ivar name: The name of the environment variable. Required. @@ -8897,7 +8827,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitCodeMapping(_Model): +class ExitCodeMapping(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """How the Batch service should respond if a Task exits with a particular exit code. :ivar code: A process exit code. Required. @@ -8933,7 +8863,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitCodeRangeMapping(_Model): +class ExitCodeRangeMapping(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A range of exit codes and how the Batch service should respond to exit codes within that range. :ivar start: The first exit code in the range. Required. @@ -8975,7 +8905,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitConditions(_Model): +class ExitConditions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies how the Batch service should respond when the Task completes. :ivar exit_codes: A list of individual Task exit codes and how the Batch service should respond @@ -9048,7 +8978,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitOptions(_Model): +class ExitOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies how the Batch service responds to a particular exit condition. :ivar job_action: An action to take on the Job containing the Task, if the Task completes with @@ -9102,7 +9032,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class FileProperties(_Model): +class FileProperties(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The properties of a file on a Compute Node. :ivar creation_time: The file creation time. The creation time is not returned for files on @@ -9161,7 +9091,38 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class HostEndpointSettings(_Model): +class HardwareProfile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """Specifies the hardware settings for the Compute Nodes. + + :ivar vm_size_properties: Specifies the properties for customizing the size of the virtual + machine. + :vartype vm_size_properties: ~azure.batch.models.VMSizeProperties + """ + + vm_size_properties: Optional["_models.VMSizeProperties"] = rest_field( + name="vmSizeProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the properties for customizing the size of the virtual machine.""" + + @overload + def __init__( + self, + *, + vm_size_properties: Optional["_models.VMSizeProperties"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class HostEndpointSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies particular host endpoint settings. :ivar in_vm_access_control_profile_reference_id: Specifies the reference to the @@ -9203,7 +9164,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class InboundEndpoint(_Model): +class InboundEndpoint(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An inbound endpoint on a Compute Node. :ivar name: The name of the endpoint. Required. @@ -9260,7 +9221,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class InstanceViewStatus(_Model): +class InstanceViewStatus(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The instance view status. :ivar code: The status code. @@ -9314,7 +9275,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class IPTag(_Model): +class IPTag(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Contains the IP tag associated with the public IP address. :ivar ip_tag_type: The IP Tag type. Example: FirstPartyUsage. @@ -9349,7 +9310,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class LinuxUserConfiguration(_Model): +class LinuxUserConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Properties used to create a user Account on a Linux Compute Node. :ivar uid: The user ID of the user Account. The uid and gid properties must be specified @@ -9404,7 +9365,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ManagedDisk(_Model): +class ManagedDisk(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The managed disk parameters. :ivar disk_encryption_set: Specifies the customer managed disk encryption set resource id for @@ -9452,7 +9413,43 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MountConfiguration(_Model): +class MaxInstancePercentPerZonePolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """The policy that limits the percentage of Pool instances that may be allocated in a single + availability zone. + + :ivar enabled: Whether the maximum instance percentage policy is enabled. + :vartype enabled: bool + :ivar value: The maximum percentage of Pool instances that may be allocated in a single + availability zone. Required. + :vartype value: int + """ + + enabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether the maximum instance percentage policy is enabled.""" + value: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The maximum percentage of Pool instances that may be allocated in a single availability zone. + Required.""" + + @overload + def __init__( + self, + *, + value: int, + enabled: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MountConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The file system to mount on each node. :ivar azure_blob_file_system_configuration: The Azure Storage Container to mount using blob @@ -9512,7 +9509,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MultiInstanceSettings(_Model): +class MultiInstanceSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Multi-instance Tasks are commonly used to support MPI Tasks. In the MPI case, if any of the subtasks fail (for example due to exiting with a non-zero exit code) the entire multi-instance Task fails. The multi-instance Task is then terminated and retried, up to its retry limit. @@ -9581,7 +9578,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NameValuePair(_Model): +class NameValuePair(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Represents a name-value pair. :ivar name: The name in the name-value pair. @@ -9614,7 +9611,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NetworkConfiguration(_Model): +class NetworkConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The network configuration for a Pool. :ivar subnet_id: The ARM resource identifier of the virtual network subnet which the Compute @@ -9715,7 +9712,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NetworkSecurityGroupRule(_Model): +class NetworkSecurityGroupRule(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A network security group rule to apply to an inbound endpoint. :ivar priority: The priority for this rule. Priorities within a Pool must be unique and are @@ -9789,7 +9786,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NfsMountConfiguration(_Model): +class NfsMountConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information used to connect to an NFS file system. :ivar source: The URI of the file system to mount. Required. @@ -9837,10 +9834,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -# TODO: Open Sphinx issue that needs to be addressed through TypeSpec. -# See: https://github.com/microsoft/typespec/issues/8654 -# Revert any changes made here with `*` and `\`. -class OutputFile(_Model): +class OutputFile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """On every file uploads, Batch service writes two log files to the compute node, 'fileuploadout.txt' and 'fileuploaderr.txt'. These log files are used to learn more about a specific failure. @@ -9848,14 +9842,14 @@ class OutputFile(_Model): :ivar file_pattern: A pattern indicating which file(s) to upload. Both relative and absolute paths are supported. Relative paths are relative to the Task working directory. The following wildcards are supported: * matches 0 or more characters (for example pattern abc* would match - abc or abcdef), \\*\\* matches any directory, ? matches any single character, [abc] matches one + abc or abcdef), ** matches any directory, ? matches any single character, [abc] matches one character in the brackets, and [a-c] matches one character in the range. Brackets can include a negation to match any character not specified (for example [!abc] matches any character but a, b, or c). If a file name starts with "." it is ignored by default but may be matched by specifying it explicitly (for example *.gif will not match .a.gif, but .*.gif will). A simple - example: \\*\\*\\\\*.txt matches any file that does not start in '.' and ends with .txt in the Task + example: **\\*.txt matches any file that does not start in '.' and ends with .txt in the Task working directory or any subdirectory. If the filename contains a wildcard character it can be - escaped using brackets (for example abc[*] would match a file named abc*). Note that both \\\\ + escaped using brackets (for example abc[*] would match a file named abc*). Note that both \\ and / are treated as directory separators on Windows, but only / is on Linux. Environment variables (%var% on Windows or $var on Linux) are expanded prior to the pattern being applied. Required. @@ -9868,20 +9862,19 @@ class OutputFile(_Model): """ file_pattern: str = rest_field(name="filePattern", visibility=["read", "create", "update", "delete", "query"]) - """A pattern indicating which file(s) to upload. Both relative and absolute - paths are supported. Relative paths are relative to the Task working directory. The following - wildcards are supported: * matches 0 or more characters (for example pattern abc* would match - abc or abcdef), \\*\\* matches any directory, ? matches any single character, [abc] matches one - character in the brackets, and [a-c] matches one character in the range. Brackets can include a - negation to match any character not specified (for example [!abc] matches any character but a, - b, or c). If a file name starts with "." it is ignored by default but may be matched by - specifying it explicitly (for example *.gif will not match .a.gif, but .*.gif will). A simple - example: \\*\\*\\\\*.txt matches any file that does not start in '.' and ends with .txt in the Task - working directory or any subdirectory. If the filename contains a wildcard character it can be - escaped using brackets (for example abc[*] would match a file named abc*). Note that both \\\\ - and / are treated as directory separators on Windows, but only / is on Linux. Environment - variables (%var% on Windows or $var on Linux) are expanded prior to the pattern being applied. - Required.""" + """A pattern indicating which file(s) to upload. Both relative and absolute paths are supported. + Relative paths are relative to the Task working directory. The following wildcards are + supported: * matches 0 or more characters (for example pattern abc* would match abc or abcdef), + ** matches any directory, ? matches any single character, [abc] matches one character in the + brackets, and [a-c] matches one character in the range. Brackets can include a negation to + match any character not specified (for example [!abc] matches any character but a, b, or c). If + a file name starts with \".\" it is ignored by default but may be matched by specifying it + explicitly (for example *.gif will not match .a.gif, but .*.gif will). A simple example: + **\\*.txt matches any file that does not start in '.' and ends with .txt in the Task working + directory or any subdirectory. If the filename contains a wildcard character it can be escaped + using brackets (for example abc[*] would match a file named abc*). Note that both \\ and / are + treated as directory separators on Windows, but only / is on Linux. Environment variables + (%var% on Windows or $var on Linux) are expanded prior to the pattern being applied. Required.""" destination: "_models.OutputFileDestination" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -9912,7 +9905,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileBlobContainerDestination(_Model): +class OutputFileBlobContainerDestination(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies a file upload destination within an Azure blob storage container. :ivar path: The destination blob or virtual directory within the Azure Storage container. If @@ -9984,7 +9977,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileDestination(_Model): +class OutputFileDestination(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The destination to which a file should be uploaded. :ivar container: A location in Azure blob storage to which files are uploaded. @@ -10014,7 +10007,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileUploadConfiguration(_Model): +class OutputFileUploadConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Options for an output file upload operation, including under what conditions to perform the upload. @@ -10049,7 +10042,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileUploadHeader(_Model): +class OutputFileUploadHeader(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An HTTP header name-value pair. :ivar name: The case-insensitive name of the header to be used while uploading output files. @@ -10083,7 +10076,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ProxyAgentSettings(_Model): +class Placement(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """The placement policy for Compute Nodes in a Pool. + + :ivar zone_placement_policy: The zone placement policy. Auto delegates zone selection and + balancing to the Virtual Machine Scale Set. Required. "Auto" + :vartype zone_placement_policy: str or ~azure.batch.models.ZonePlacementPolicyType + """ + + zone_placement_policy: Union[str, "_models.ZonePlacementPolicyType"] = rest_field( + name="zonePlacementPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The zone placement policy. Auto delegates zone selection and balancing to the Virtual Machine + Scale Set. Required. \"Auto\"""" + + @overload + def __init__( + self, + *, + zone_placement_policy: Union[str, "_models.ZonePlacementPolicyType"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ProxyAgentSettings(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies ProxyAgent settings while creating the virtual machine. :ivar enabled: Specifies whether Metadata Security Protocol feature should be enabled on the @@ -10127,7 +10152,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RecentBatchJob(_Model): +class RecentBatchJob(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Information about the most recent Job to run under the Job Schedule. :ivar id: The ID of the Job. @@ -10160,7 +10185,38 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResizeError(_Model): +class ResiliencyPolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """The resiliency policy for Compute Nodes in a Pool. + + :ivar zone_allocation_policy: The policy that controls allocation across availability zones. + Required. + :vartype zone_allocation_policy: ~azure.batch.models.ZoneAllocationPolicy + """ + + zone_allocation_policy: "_models.ZoneAllocationPolicy" = rest_field( + name="zoneAllocationPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The policy that controls allocation across availability zones. Required.""" + + @overload + def __init__( + self, + *, + zone_allocation_policy: "_models.ZoneAllocationPolicy", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ResizeError(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """An error that occurred when resizing a Pool. :ivar code: An identifier for the Pool resize error. Codes are invariant and are intended to be @@ -10204,7 +10260,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResourceFile(_Model): +class ResourceFile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """A single file or multiple files to be downloaded to a Compute Node. :ivar auto_storage_container_name: The storage container name in the auto storage Account. The @@ -10324,13 +10380,14 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RollingUpgradePolicy(_Model): +class RollingUpgradePolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The configuration parameters used while performing a rolling upgrade. :ivar enable_cross_zone_upgrade: Allow VMSS to ignore AZ boundaries when constructing upgrade batches. Take into consideration the Update Domain and maxBatchInstancePercent to determine the - batch size. This field is able to be set to true or false only when using - NodePlacementConfiguration as Zonal. + batch size. This field can be set to true or false only when nodePlacementConfiguration.policy + is Zonal or placement.zonePlacementPolicy is Auto. Auto placement is supported starting with + API version 2026-10-01. :vartype enable_cross_zone_upgrade: bool :ivar max_batch_instance_percent: The maximum percent of total virtual machine instances that will be upgraded simultaneously by the rolling upgrade in one batch. As this is a maximum, @@ -10369,8 +10426,10 @@ class RollingUpgradePolicy(_Model): name="enableCrossZoneUpgrade", visibility=["read", "create", "update", "delete", "query"] ) """Allow VMSS to ignore AZ boundaries when constructing upgrade batches. Take into consideration - the Update Domain and maxBatchInstancePercent to determine the batch size. This field is able - to be set to true or false only when using NodePlacementConfiguration as Zonal.""" + the Update Domain and maxBatchInstancePercent to determine the batch size. This field can be + set to true or false only when nodePlacementConfiguration.policy is Zonal or + placement.zonePlacementPolicy is Auto. Auto placement is supported starting with API version + 2026-10-01.""" max_batch_instance_percent: Optional[int] = rest_field( name="maxBatchInstancePercent", visibility=["read", "create", "update", "delete", "query"] ) @@ -10435,7 +10494,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SecurityProfile(_Model): +class SecurityProfile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies the security profile settings for the virtual machine or virtual machine scale set. :ivar encryption_at_host: This property can be used by user in the request to enable or disable @@ -10502,7 +10561,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ServiceArtifactReference(_Model): +class ServiceArtifactReference(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Specifies the service artifact reference id used to set same image version for all virtual machines in the scale set when using 'latest' image version. @@ -10537,7 +10596,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UpgradePolicy(_Model): +class UpgradePolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Describes an upgrade policy - automatic, manual, or rolling. :ivar mode: Specifies the mode of an upgrade to virtual machines in the scale set.

@@ -10592,7 +10651,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UploadBatchServiceLogsOptions(_Model): +class UploadBatchServiceLogsOptions(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The Azure Batch service log files upload parameters for a Compute Node. :ivar container_url: The URL of the container within Azure Blob Storage to which to upload the @@ -10666,7 +10725,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UploadBatchServiceLogsResult(_Model): +class UploadBatchServiceLogsResult(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The result of uploading Batch service log files from a specific Compute Node. :ivar virtual_directory_name: The virtual directory within Azure Blob Storage container to @@ -10708,7 +10767,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UserAccount(_Model): +class UserAccount(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Properties used to create a user used to execute Tasks on an Azure Batch Compute Node. :ivar name: The name of the user Account. Names can contain any Unicode characters up to a @@ -10773,7 +10832,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UserIdentity(_Model): +class UserIdentity(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The definition of the user identity under which the Task is run. Specify either the userName or autoUser property, but not both. @@ -10813,7 +10872,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VirtualMachineConfiguration(_Model): +class VirtualMachineConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The configuration for Compute Nodes in a Pool based on the Azure Virtual Machines infrastructure. @@ -10848,8 +10907,11 @@ class VirtualMachineConfiguration(_Model): :ivar license_type: This only applies to Images that contain the Windows operating system, and should only be used when you hold valid on-premises licenses for the Compute Nodes which will be deployed. If omitted, no on-premises licensing discount is - applied. Values are: Windows_Server (the on-premises license is for Windows - Server) and Windows_Client (the on-premises license is for Windows Client). + applied. Values are: + + Windows_Server - The on-premises license is for Windows + Server. + Windows_Client - The on-premises license is for Windows Client. :vartype license_type: str :ivar container_configuration: The container configuration for the Pool. If specified, setup is performed on each Compute Node in the Pool to allow Tasks to run in containers. All regular @@ -10875,6 +10937,22 @@ class VirtualMachineConfiguration(_Model): service artifact reference id in the form of /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName}. :vartype service_artifact_reference: ~azure.batch.models.ServiceArtifactReference + :ivar hardware_profile: Specifies the hardware settings for the Compute Nodes. This property is + not supported for pools created via auto-pool (as part of a job or job schedule); the request + will be rejected if it is specified in that context. + :vartype hardware_profile: ~azure.batch.models.HardwareProfile + :ivar placement: The availability zone placement policy for Compute Nodes in the Pool. Set + zonePlacementPolicy to Auto to delegate availability zone selection and balancing to the + Virtual Machine Scale Set. On Pool creation, if placement is omitted, Batch uses + nodePlacementConfiguration when it is specified; otherwise, the Pool uses Regional placement, + which provides no availability zone distribution guarantee. This property cannot be combined + with nodePlacementConfiguration. On PATCH, omitting placement preserves the existing placement + policy, including when virtualMachineConfiguration is supplied. + :vartype placement: ~azure.batch.models.Placement + :ivar resiliency_policy: The resiliency policy for Compute Nodes in the Pool. This property + requires placement.zonePlacementPolicy to be Auto. On PATCH, omitting resiliencyPolicy + preserves the existing resiliency policy independently of whether placement is supplied. + :vartype resiliency_policy: ~azure.batch.models.ResiliencyPolicy """ image_reference: "_models.BatchVmImageReference" = rest_field( @@ -10919,6 +10997,7 @@ class VirtualMachineConfiguration(_Model): Nodes which will be deployed. If omitted, no on-premises licensing discount is applied. Values are: + Windows_Server - The on-premises license is for Windows Server. Windows_Client - The on-premises license is for Windows Client.""" container_configuration: Optional["_models.BatchContainerConfiguration"] = rest_field( @@ -10957,6 +11036,26 @@ class VirtualMachineConfiguration(_Model): machines in the scale set when using 'latest' image version. The service artifact reference id in the form of /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/serviceArtifacts/{serviceArtifactName}/vmArtifactsProfiles/{vmArtifactsProfilesName}.""" + hardware_profile: Optional["_models.HardwareProfile"] = rest_field( + name="hardwareProfile", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the hardware settings for the Compute Nodes. This property is not supported for pools + created via auto-pool (as part of a job or job schedule); the request will be rejected if it is + specified in that context.""" + placement: Optional["_models.Placement"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The availability zone placement policy for Compute Nodes in the Pool. Set zonePlacementPolicy + to Auto to delegate availability zone selection and balancing to the Virtual Machine Scale Set. + On Pool creation, if placement is omitted, Batch uses nodePlacementConfiguration when it is + specified; otherwise, the Pool uses Regional placement, which provides no availability zone + distribution guarantee. This property cannot be combined with nodePlacementConfiguration. On + PATCH, omitting placement preserves the existing placement policy, including when + virtualMachineConfiguration is supplied.""" + resiliency_policy: Optional["_models.ResiliencyPolicy"] = rest_field( + name="resiliencyPolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The resiliency policy for Compute Nodes in the Pool. This property requires + placement.zonePlacementPolicy to be Auto. On PATCH, omitting resiliencyPolicy preserves the + existing resiliency policy independently of whether placement is supplied.""" @overload def __init__( @@ -10974,6 +11073,9 @@ def __init__( os_disk: Optional["_models.BatchOsDisk"] = None, security_profile: Optional["_models.SecurityProfile"] = None, service_artifact_reference: Optional["_models.ServiceArtifactReference"] = None, + hardware_profile: Optional["_models.HardwareProfile"] = None, + placement: Optional["_models.Placement"] = None, + resiliency_policy: Optional["_models.ResiliencyPolicy"] = None, ) -> None: ... @overload @@ -10987,7 +11089,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VirtualMachineInfo(_Model): +class VirtualMachineInfo(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Info about the current state of the virtual machine. :ivar image_reference: The reference to the Azure Virtual Machine's Marketplace Image. @@ -11027,7 +11129,91 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VMExtension(_Model): +class VirtualMachineSkuProfile(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """Specifies the set of VM sizes and the allocation strategy used to allocate Compute Nodes for an + Instance Mix Pool. + + :ivar vm_sizes: The list of VM sizes (up to 5) that may be allocated for the Pool. VM sizes may + span the supported A, B, D, E, and F VM families, but must have the same vCPU count and CPU + architecture and compatible VM capabilities. This must be specified when the vmSkuProfile is + provided during Pool creation. + :vartype vm_sizes: list[~azure.batch.models.VirtualMachineSkuProfileVmSize] + :ivar allocation_strategy: The allocation strategy used to select VM sizes from vmSizes. + Defaults to lowestPrice when not specified. Known values are: "lowestPrice", + "capacityOptimized", and "prioritized". + :vartype allocation_strategy: str or ~azure.batch.models.VirtualMachineSkuAllocationStrategy + """ + + vm_sizes: Optional[list["_models.VirtualMachineSkuProfileVmSize"]] = rest_field( + name="vmSizes", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of VM sizes (up to 5) that may be allocated for the Pool. VM sizes may span the + supported A, B, D, E, and F VM families, but must have the same vCPU count and CPU architecture + and compatible VM capabilities. This must be specified when the vmSkuProfile is provided during + Pool creation.""" + allocation_strategy: Optional[Union[str, "_models.VirtualMachineSkuAllocationStrategy"]] = rest_field( + name="allocationStrategy", visibility=["read", "create", "update", "delete", "query"] + ) + """The allocation strategy used to select VM sizes from vmSizes. Defaults to lowestPrice when not + specified. Known values are: \"lowestPrice\", \"capacityOptimized\", and \"prioritized\".""" + + @overload + def __init__( + self, + *, + vm_sizes: Optional[list["_models.VirtualMachineSkuProfileVmSize"]] = None, + allocation_strategy: Optional[Union[str, "_models.VirtualMachineSkuAllocationStrategy"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VirtualMachineSkuProfileVmSize(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """Specifies a single VM size that may be allocated for an Instance Mix Pool. + + :ivar name: The name of the VM size (for example, 'Standard_D8s_v5'). Required. + :vartype name: str + :ivar rank: The 0-based rank (a.k.a. priority) associated with this VM size. Lower values + indicate higher priority. Rank is required only when the allocation strategy is 'prioritized' + and must be omitted otherwise. + :vartype rank: int + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the VM size (for example, 'Standard_D8s_v5'). Required.""" + rank: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The 0-based rank (a.k.a. priority) associated with this VM size. Lower values indicate higher + priority. Rank is required only when the allocation strategy is 'prioritized' and must be + omitted otherwise.""" + + @overload + def __init__( + self, + *, + name: str, + rank: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class VMExtension(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The configuration for virtual machine extensions. :ivar name: The name of the virtual machine extension. Required. @@ -11115,7 +11301,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VMExtensionInstanceView(_Model): +class VMExtensionInstanceView(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """The vm extension instance view. :ivar name: The name of the vm extension instance view. @@ -11157,7 +11343,52 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class WindowsConfiguration(_Model): +class VMSizeProperties(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """Specifies the properties for customizing the size of the virtual machine. + + :ivar v_cpus_available: Specifies the number of vCPUs available for the VM. When this property + is not specified in the request body the default behavior is to set it to the value of vCPUs + available for that VM size. + :vartype v_cpus_available: int + :ivar v_cpus_per_core: Specifies the vCPU to physical core ratio. When this property is not + specified in the request body the default behavior is set to the value of vCPUsPerCore for the + VM Size. Setting this property to 1 also means that hyper-threading is disabled. + :vartype v_cpus_per_core: int + """ + + v_cpus_available: Optional[int] = rest_field( + name="vCPUsAvailable", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the number of vCPUs available for the VM. When this property is not specified in the + request body the default behavior is to set it to the value of vCPUs available for that VM + size.""" + v_cpus_per_core: Optional[int] = rest_field( + name="vCPUsPerCore", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the vCPU to physical core ratio. When this property is not specified in the request + body the default behavior is set to the value of vCPUsPerCore for the VM Size. Setting this + property to 1 also means that hyper-threading is disabled.""" + + @overload + def __init__( + self, + *, + v_cpus_available: Optional[int] = None, + v_cpus_per_core: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class WindowsConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Windows operating system settings to apply to the virtual machine. :ivar enable_automatic_updates: Whether automatic updates are enabled on the virtual machine. @@ -11189,7 +11420,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class WindowsUserConfiguration(_Model): +class WindowsUserConfiguration(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only """Properties used to create a user Account on a Windows Compute Node. :ivar login_mode: The login mode for the user. The default is 'batch'. Known values are: @@ -11219,3 +11450,45 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + + +class ZoneAllocationPolicy(_Model): # pylint: disable=docstring-keyword-should-match-keyword-only + """The policy that controls allocation across availability zones. + + :ivar max_zone_count: The maximum number of availability zones that may be used. The value + cannot exceed the number of zones supported by the region. + :vartype max_zone_count: int + :ivar max_instance_percent_per_zone_policy: The policy that limits the percentage of Pool + instances that may be allocated in a single availability zone. + :vartype max_instance_percent_per_zone_policy: + ~azure.batch.models.MaxInstancePercentPerZonePolicy + """ + + max_zone_count: Optional[int] = rest_field( + name="maxZoneCount", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of availability zones that may be used. The value cannot exceed the number + of zones supported by the region.""" + max_instance_percent_per_zone_policy: Optional["_models.MaxInstancePercentPerZonePolicy"] = rest_field( + name="maxInstancePercentPerZonePolicy", visibility=["read", "create", "update", "delete", "query"] + ) + """The policy that limits the percentage of Pool instances that may be allocated in a single + availability zone.""" + + @overload + def __init__( + self, + *, + max_zone_count: Optional[int] = None, + max_instance_percent_per_zone_policy: Optional["_models.MaxInstancePercentPerZonePolicy"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) diff --git a/sdk/batch/azure-batch/azure/batch/models/_patch.py b/sdk/batch/azure-batch/azure/batch/models/_patch.py index 2d7154cae4a5..ea765788358a 100644 --- a/sdk/batch/azure-batch/azure/batch/models/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/models/_patch.py @@ -1,130 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import datetime -from typing import List, Optional -from azure.core.exceptions import HttpResponseError - - -__all__: List[str] = [ - "CreateTasksError", - "BatchFileProperties", -] # Add all objects you want publicly available to users at this package level - - -class CreateTasksError(HttpResponseError): - """Aggregate Exception containing details for any failures from a task add operation. - - :param pending_tasks: List of tasks remaining to be submitted. - :type pending_tasks: Optional[List[~_models.BatchTaskCreateOptions]] - :param failure_tasks: List of tasks which failed to add - :type failure_tasks: Optional[List[~_models.BatchTaskCreateResult]] - :param errors: List of unknown errors forcing early termination - :type errors: Optional[List[~Exception]] - """ - - def __init__(self, pending_tasks=None, failure_tasks=None, errors=None) -> None: - if pending_tasks is None: - pending_tasks = [] - if failure_tasks is None: - failure_tasks = [] - if errors is None: - errors = [] - self.pending_tasks = pending_tasks - self.failure_tasks = failure_tasks - self.errors = errors - if failure_tasks and errors: - self.message = ( - "Multiple errors encountered. Check the `failure_tasks` and " - "`errors` properties for additional details." - ) - elif errors: - if len(errors) > 1: - self.message = ( - "Multiple errors occurred when submitting add_collection " - "requests. Check the `errors` property for the inner " - "exceptions." - ) - else: - self.message = str(errors[0]) - elif failure_tasks: - if len(failure_tasks) > 1: - self.message = ( - "Multiple client side errors occurred when adding the " - "tasks. Check the `failure_tasks` property for details on" - " these tasks." - ) - else: - result = failure_tasks[0] - self.message = "Task with id `%s` failed due to client error - %s::%s" % ( - result.task_id, - result.error.code, - result.error.message, - ) - super(CreateTasksError, self).__init__(self.message) - - -class BatchFileProperties: - """Information about a file or directory on a Compute Node with additional properties. - - :ivar url: The URL of the file. - :vartype url: str - :ivar is_directory: Whether the object represents a directory. - :vartype is_directory: bool - :ivar creation_time: The file creation time. The creation time is not returned for files on - Linux Compute Nodes. - :vartype creation_time: ~datetime.datetime - :ivar last_modified: The time at which the file was last modified. Required. - :vartype last_modified: ~datetime.datetime - :ivar content_length: The length of the file. Required. - :vartype content_length: int - :ivar content_type: The content type of the file. - :vartype content_type: str - :ivar file_mode: The file mode attribute in octal format. The file mode is returned only for - files on Linux Compute Nodes. - :vartype file_mode: str - """ - - url: Optional[str] - """The URL of the file.""" - is_directory: Optional[bool] - """Whether the object represents a directory.""" - creation_time: Optional[datetime.datetime] - """The file creation time. The creation time is not returned for files on Linux Compute Nodes.""" - last_modified: datetime.datetime - """The time at which the file was last modified. Required.""" - content_length: int - """The length of the file. Required.""" - content_type: Optional[str] - """The content type of the file.""" - file_mode: Optional[str] - """The file mode attribute in octal format. The file mode is returned only for files on Linux - Compute Nodes.""" - - def __init__( - self, - *, - url: Optional[str] = None, - is_directory: Optional[bool] = None, - last_modified: datetime.datetime, - content_length: int, - creation_time: Optional[datetime.datetime] = None, - content_type: Optional[str] = None, - file_mode: Optional[str] = None, - ) -> None: - self.url = url - self.is_directory = is_directory - self.creation_time = creation_time - self.last_modified = last_modified - self.content_length = content_length - self.content_type = content_type - self.file_mode = file_mode +__all__: list[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/batch/azure-batch/pyproject.toml b/sdk/batch/azure-batch/pyproject.toml index 173ba8ba5601..e2b538756330 100644 --- a/sdk/batch/azure-batch/pyproject.toml +++ b/sdk/batch/azure-batch/pyproject.toml @@ -1,50 +1,55 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - [build-system] -requires = ["setuptools>=77.0.3", "wheel"] +requires = [ + "setuptools>=77.0.3", + "wheel", +] build-backend = "setuptools.build_meta" [project] name = "azure-batch" authors = [ - { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, ] description = "Microsoft Corporation Azure Batch Client Library for Python" license = "MIT" classifiers = [ - "Development Status :: 5 - Production/Stable", + "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", +] +requires-python = ">=3.10" +keywords = [ + "azure", + "azure sdk", ] -requires-python = ">=3.9" -keywords = ["azure", "azure sdk"] - dependencies = [ "isodate>=0.6.1", "azure-core>=1.37.0", "typing-extensions>=4.6.0", ] dynamic = [ -"version", "readme" + "version", + "readme", ] [project.urls] repository = "https://github.com/Azure/azure-sdk-for-python" -[tool.setuptools.dynamic] -version = {attr = "azure.batch._version.VERSION"} -readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} +[tool.setuptools.dynamic.version] +attr = "azure.batch._version.VERSION" + +[tool.setuptools.dynamic.readme] +file = [ + "README.md", + "CHANGELOG.md", +] +content-type = "text/markdown" [tool.setuptools.packages.find] exclude = [ @@ -57,7 +62,9 @@ exclude = [ ] [tool.setuptools.package-data] -pytyped = ["py.typed"] +pytyped = [ + "py.typed", +] [tool.azure-sdk-build] pylint = true @@ -70,3 +77,12 @@ whl_no_aio = false [tool.azure-sdk-conda] in_bundle = false + +[packaging] +package_name = "azure-batch" +package_nspkg = "azure-nspkg" +package_pprint_name = "Batch" +package_doc_id = "batch" +is_stable = true +is_arm = false +auto_update = false diff --git a/sdk/batch/azure-batch/samples/batch_automatic_scaling.py b/sdk/batch/azure-batch/samples/batch_automatic_scaling.py index f15e33a8455c..4dec52742a31 100644 --- a/sdk/batch/azure-batch/samples/batch_automatic_scaling.py +++ b/sdk/batch/azure-batch/samples/batch_automatic_scaling.py @@ -5,8 +5,7 @@ # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- -"""Snippets extracted from articles/batch/batch-automatic-scaling.md. -""" +"""Snippets extracted from articles/batch/batch-automatic-scaling.md.""" import datetime diff --git a/sdk/batch/azure-batch/samples/batch_docker_container_workloads.py b/sdk/batch/azure-batch/samples/batch_docker_container_workloads.py index 271475a4d0ce..100fd47452b6 100644 --- a/sdk/batch/azure-batch/samples/batch_docker_container_workloads.py +++ b/sdk/batch/azure-batch/samples/batch_docker_container_workloads.py @@ -15,22 +15,22 @@ def make_pool_no_prefetch(pool_id: str): # [START docker_pool_no_prefetch_python] image_ref_to_use = models.BatchVmImageReference( - publisher='microsoft-dsvm', - offer='ubuntu-hpc', - sku='2204', - version='latest') + publisher="microsoft-dsvm", offer="ubuntu-hpc", sku="2204", version="latest" + ) # Specify container configuration. This is required even though there are no prefetched images. - container_conf = models.BatchContainerConfiguration(type='dockerCompatible') + container_conf = models.BatchContainerConfiguration(type="dockerCompatible") new_pool = models.BatchPoolCreateOptions( id=pool_id, virtual_machine_configuration=models.VirtualMachineConfiguration( image_reference=image_ref_to_use, container_configuration=container_conf, - node_agent_sku_id='batch.node.ubuntu 22.04'), - vm_size='STANDARD_D2S_V3', - target_dedicated_nodes=1) + node_agent_sku_id="batch.node.ubuntu 22.04", + ), + vm_size="STANDARD_D2S_V3", + target_dedicated_nodes=1, + ) # [END docker_pool_no_prefetch_python] return new_pool @@ -38,24 +38,22 @@ def make_pool_no_prefetch(pool_id: str): def make_pool_dockerhub_prefetch(pool_id: str): # [START docker_pool_dockerhub_prefetch_python] image_ref_to_use = models.BatchVmImageReference( - publisher='microsoft-dsvm', - offer='ubuntu-hpc', - sku='2204', - version='latest') + publisher="microsoft-dsvm", offer="ubuntu-hpc", sku="2204", version="latest" + ) # Specify container configuration, fetching the official Ubuntu container image from Docker Hub. - container_conf = models.BatchContainerConfiguration( - type='dockerCompatible', - container_image_names=['ubuntu']) + container_conf = models.BatchContainerConfiguration(type="dockerCompatible", container_image_names=["ubuntu"]) new_pool = models.BatchPoolCreateOptions( id=pool_id, virtual_machine_configuration=models.VirtualMachineConfiguration( image_reference=image_ref_to_use, container_configuration=container_conf, - node_agent_sku_id='batch.node.ubuntu 22.04'), - vm_size='STANDARD_D2S_V3', - target_dedicated_nodes=1) + node_agent_sku_id="batch.node.ubuntu 22.04", + ), + vm_size="STANDARD_D2S_V3", + target_dedicated_nodes=1, + ) # [END docker_pool_dockerhub_prefetch_python] return new_pool @@ -63,10 +61,8 @@ def make_pool_dockerhub_prefetch(pool_id: str): def make_pool_acr_prefetch(): # [START docker_pool_acr_prefetch_python] image_ref_to_use = models.BatchVmImageReference( - publisher='microsoft-dsvm', - offer='ubuntu-hpc', - sku='2204', - version='latest') + publisher="microsoft-dsvm", offer="ubuntu-hpc", sku="2204", version="latest" + ) # Specify a container registry subscription_id = "yyyy-yyy-yyy-yyy-yyy" @@ -79,36 +75,40 @@ def make_pool_acr_prefetch(): container_registry = models.ContainerRegistryReference( registry_server="myRegistry.azurecr.io", - identity_reference=models.BatchNodeIdentityReference(resource_id=resource_id)) + identity_reference=models.BatchNodeIdentityReference(resource_id=resource_id), + ) # Create container configuration, prefetching Docker images from the container registry container_conf = models.BatchContainerConfiguration( - type='dockerCompatible', + type="dockerCompatible", container_image_names=["myRegistry.azurecr.io/samples/myImage"], - container_registries=[container_registry]) + container_registries=[container_registry], + ) new_pool = models.BatchPoolCreateOptions( id="myPool", virtual_machine_configuration=models.VirtualMachineConfiguration( image_reference=image_ref_to_use, container_configuration=container_conf, - node_agent_sku_id='batch.node.ubuntu 22.04'), - vm_size='STANDARD_D2S_V3', - target_dedicated_nodes=1) + node_agent_sku_id="batch.node.ubuntu 22.04", + ), + vm_size="STANDARD_D2S_V3", + target_dedicated_nodes=1, + ) # [END docker_pool_acr_prefetch_python] return new_pool def make_container_task(): # [START docker_container_task_python] - task_id = 'sampletask' + task_id = "sampletask" task_container_settings = models.BatchTaskContainerSettings( - image_name='myimage', - container_run_options='--rm --workdir /') + image_name="myimage", container_run_options="--rm --workdir /" + ) task = models.BatchTaskCreateOptions( id=task_id, - command_line='/bin/sh -c "echo \'hello world\' > $AZ_BATCH_TASK_WORKING_DIR/output.txt"', - container_settings=task_container_settings + command_line="/bin/sh -c \"echo 'hello world' > $AZ_BATCH_TASK_WORKING_DIR/output.txt\"", + container_settings=task_container_settings, ) # [END docker_container_task_python] return task diff --git a/sdk/batch/azure-batch/samples/batch_linux_nodes.py b/sdk/batch/azure-batch/samples/batch_linux_nodes.py index 07133faac0b1..b8b22be2e2d5 100644 --- a/sdk/batch/azure-batch/samples/batch_linux_nodes.py +++ b/sdk/batch/azure-batch/samples/batch_linux_nodes.py @@ -45,17 +45,13 @@ def create_pool_explicit_image(): # Create an ImageReference which specifies the Marketplace # virtual machine image to install on the nodes ir = models.BatchVmImageReference( - publisher="canonical", - offer="0001-com-ubuntu-server-focal", - sku="20_04-lts", - version="latest") + publisher="canonical", offer="0001-com-ubuntu-server-focal", sku="20_04-lts", version="latest" + ) # Create the VirtualMachineConfiguration, specifying # the VM image reference and the Batch node agent # to install on the node - vmc = models.VirtualMachineConfiguration( - image_reference=ir, - node_agent_sku_id="batch.node.ubuntu 20.04") + vmc = models.VirtualMachineConfiguration(image_reference=ir, node_agent_sku_id="batch.node.ubuntu 20.04") # Create the unbound pool new_pool = models.BatchPoolCreateOptions( @@ -80,20 +76,25 @@ def vm_config_from_supported_images(client: BatchClient): # Obtain the desired image reference image = None for img in images: - if (img.image_reference.publisher and img.image_reference.publisher.lower() == "canonical" and - img.image_reference.offer and img.image_reference.offer.lower() == "0001-com-ubuntu-server-focal" and - img.image_reference.sku and img.image_reference.sku.lower() == "20_04-lts"): + if ( + img.image_reference.publisher + and img.image_reference.publisher.lower() == "canonical" + and img.image_reference.offer + and img.image_reference.offer.lower() == "0001-com-ubuntu-server-focal" + and img.image_reference.sku + and img.image_reference.sku.lower() == "20_04-lts" + ): image = img break if image is None: - raise RuntimeError('invalid image reference for desired configuration') + raise RuntimeError("invalid image reference for desired configuration") # Create the VirtualMachineConfiguration, specifying the VM image # reference and the Batch node agent to be installed on the node vmc = models.VirtualMachineConfiguration( - image_reference=image.image_reference, - node_agent_sku_id=image.node_agent_sku_id) + image_reference=image.image_reference, node_agent_sku_id=image.node_agent_sku_id + ) # [END linux_nodes_image_reference_python] return vmc @@ -101,16 +102,16 @@ def vm_config_from_supported_images(client: BatchClient): def ssh_create_user_demo_inputs(): # [START linux_nodes_ssh_user_python] # Specify your own account credentials - batch_account_name = '' - batch_account_key = '' - batch_account_url = '' + batch_account_name = "" + batch_account_key = "" + batch_account_url = "" # Specify the ID of an existing pool containing Linux nodes # currently in the 'idle' state - pool_id = '' + pool_id = "" # Specify the username and prompt for a password - username = 'linuxuser' + username = "linuxuser" password = getpass.getpass() # Create a BatchClient @@ -131,5 +132,7 @@ def ssh_create_user_demo_inputs(): for node in nodes: batch_client.create_node_user(pool_id=pool_id, node_id=node.id, user=user) login_settings = batch_client.get_node_remote_login_settings(pool_id=pool_id, node_id=node.id) - print(f"{node.id}: ssh {username}@{login_settings.remote_login_ip_address} -p {login_settings.remote_login_port}") + print( + f"{node.id}: ssh {username}@{login_settings.remote_login_ip_address} -p {login_settings.remote_login_port}" + ) # [END linux_nodes_ssh_user_python] diff --git a/sdk/batch/azure-batch/samples/batch_samples_hello_world.py b/sdk/batch/azure-batch/samples/batch_samples_hello_world.py index 386d6a0e8012..45020679da38 100644 --- a/sdk/batch/azure-batch/samples/batch_samples_hello_world.py +++ b/sdk/batch/azure-batch/samples/batch_samples_hello_world.py @@ -7,13 +7,13 @@ # -------------------------------------------------------------------------- """ -FILE: +FILE: batch_samples_hello_world.py DESCRIPTION: - Azure Batch sample. + Azure Batch sample. -USAGE: +USAGE: python batch_samples_hello_world.py """ diff --git a/sdk/batch/azure-batch/samples/batch_user_accounts.py b/sdk/batch/azure-batch/samples/batch_user_accounts.py index 30bfd4eaa418..41d76aa2544b 100644 --- a/sdk/batch/azure-batch/samples/batch_user_accounts.py +++ b/sdk/batch/azure-batch/samples/batch_user_accounts.py @@ -15,12 +15,10 @@ def add_admin_autouser_task(batch_client: BatchClient, jobid: str) -> None: # [START user_accounts_admin_autouser_python] user = models.UserIdentity( auto_user=models.AutoUserSpecification( - elevation_level=models.ElevationLevel.ADMIN, - scope=models.AutoUserScope.TASK)) - task = models.BatchTaskCreateOptions( - id='task_1', - command_line='cmd /c "echo hello world"', - user_identity=user) + elevation_level=models.ElevationLevel.ADMIN, scope=models.AutoUserScope.TASK + ) + ) + task = models.BatchTaskCreateOptions(id="task_1", command_line='cmd /c "echo hello world"', user_identity=user) batch_client.create_task(job_id=jobid, task=task) # [END user_accounts_admin_autouser_python] @@ -28,22 +26,19 @@ def add_admin_autouser_task(batch_client: BatchClient, jobid: str) -> None: def make_named_user_pool(pool_id: str, image_ref_to_use, sku_to_use, vm_size: str, vm_count: int): # [START user_accounts_pool_python] users = [ + models.UserAccount(name="pool-admin", password="", elevation_level=models.ElevationLevel.ADMIN), models.UserAccount( - name='pool-admin', - password='', - elevation_level=models.ElevationLevel.ADMIN), - models.UserAccount( - name='pool-nonadmin', - password='', - elevation_level=models.ElevationLevel.NON_ADMIN), + name="pool-nonadmin", password="", elevation_level=models.ElevationLevel.NON_ADMIN + ), ] pool = models.BatchPoolCreateOptions( id=pool_id, user_accounts=users, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=image_ref_to_use, - node_agent_sku_id=sku_to_use), + image_reference=image_ref_to_use, node_agent_sku_id=sku_to_use + ), vm_size=vm_size, - target_dedicated_nodes=vm_count) + target_dedicated_nodes=vm_count, + ) # [END user_accounts_pool_python] return pool diff --git a/sdk/batch/azure-batch/samples/create_pool_ephemeral_os_disk.py b/sdk/batch/azure-batch/samples/create_pool_ephemeral_os_disk.py index 6870f90de11f..21ed3fd43cf4 100644 --- a/sdk/batch/azure-batch/samples/create_pool_ephemeral_os_disk.py +++ b/sdk/batch/azure-batch/samples/create_pool_ephemeral_os_disk.py @@ -17,10 +17,8 @@ def make_vm_configuration(image_ref_to_use, node_sku_id): image_reference=image_ref_to_use, node_agent_sku_id=node_sku_id, os_disk=models.BatchOsDisk( - ephemeral_os_disk_settings=models.BatchDiffDiskSettings( - placement=models.DiffDiskPlacement.CACHE_DISK - ) - ) + ephemeral_os_disk_settings=models.BatchDiffDiskSettings(placement=models.DiffDiskPlacement.CACHE_DISK) + ), ) # [END ephemeral_os_disk_vm_config] return virtual_machine_configuration diff --git a/sdk/batch/azure-batch/samples/pool_endpoint_configuration.py b/sdk/batch/azure-batch/samples/pool_endpoint_configuration.py index cf1477c91b78..3f39f9e943c8 100644 --- a/sdk/batch/azure-batch/samples/pool_endpoint_configuration.py +++ b/sdk/batch/azure-batch/samples/pool_endpoint_configuration.py @@ -16,25 +16,26 @@ def set_ports_pool(self, pool, **kwargs): # [START endpoint_config_allow_subnet_python] pool.network_configuration = models.NetworkConfiguration( endpoint_configuration=models.BatchPoolEndpointConfiguration( - inbound_nat_pools=[models.BatchInboundNatPool( - name='SSH', - protocol=models.InboundEndpointProtocol.TCP, - backend_port=22, - frontend_port_range_start=4000, - frontend_port_range_end=4100, - network_security_group_rules=[ - models.NetworkSecurityGroupRule( - priority=170, - access=models.NetworkSecurityGroupRuleAccess.ALLOW, - source_address_prefix='192.168.1.0/24' - ), - models.NetworkSecurityGroupRule( - priority=175, - access=models.NetworkSecurityGroupRuleAccess.DENY, - source_address_prefix='*' - ) - ] - ) + inbound_nat_pools=[ + models.BatchInboundNatPool( + name="SSH", + protocol=models.InboundEndpointProtocol.TCP, + backend_port=22, + frontend_port_range_start=4000, + frontend_port_range_end=4100, + network_security_group_rules=[ + models.NetworkSecurityGroupRule( + priority=170, + access=models.NetworkSecurityGroupRuleAccess.ALLOW, + source_address_prefix="192.168.1.0/24", + ), + models.NetworkSecurityGroupRule( + priority=175, + access=models.NetworkSecurityGroupRuleAccess.DENY, + source_address_prefix="*", + ), + ], + ) ] ) ) @@ -46,20 +47,21 @@ def set_ports_pool(self, pool, **kwargs): # [START endpoint_config_deny_ssh_python] pool.network_configuration = models.NetworkConfiguration( endpoint_configuration=models.BatchPoolEndpointConfiguration( - inbound_nat_pools=[models.BatchInboundNatPool( - name='SSH', - protocol=models.InboundEndpointProtocol.TCP, - backend_port=22, - frontend_port_range_start=4000, - frontend_port_range_end=4100, - network_security_group_rules=[ - models.NetworkSecurityGroupRule( - priority=170, - access=models.NetworkSecurityGroupRuleAccess.DENY, - source_address_prefix='Internet' - ) - ] - ) + inbound_nat_pools=[ + models.BatchInboundNatPool( + name="SSH", + protocol=models.InboundEndpointProtocol.TCP, + backend_port=22, + frontend_port_range_start=4000, + frontend_port_range_end=4100, + network_security_group_rules=[ + models.NetworkSecurityGroupRule( + priority=170, + access=models.NetworkSecurityGroupRuleAccess.DENY, + source_address_prefix="Internet", + ) + ], + ) ] ) ) diff --git a/sdk/batch/azure-batch/samples/quick_run_python.py b/sdk/batch/azure-batch/samples/quick_run_python.py index 922163e4855d..d2bc36147539 100644 --- a/sdk/batch/azure-batch/samples/quick_run_python.py +++ b/sdk/batch/azure-batch/samples/quick_run_python.py @@ -19,34 +19,33 @@ def make_blob_service_client(config): # [START quickrun_python_blob_client] blob_service_client = BlobServiceClient( - account_url=f"https://{config.STORAGE_ACCOUNT_NAME}.{config.STORAGE_ACCOUNT_DOMAIN}/", - credential=config.STORAGE_ACCOUNT_KEY - ) + account_url=f"https://{config.STORAGE_ACCOUNT_NAME}.{config.STORAGE_ACCOUNT_DOMAIN}/", + credential=config.STORAGE_ACCOUNT_KEY, + ) # [END quickrun_python_blob_client] return blob_service_client def upload_inputs(blob_service_client, input_container_name, upload_file_to_container): # [START quickrun_python_upload_inputs] - input_file_paths = [os.path.join(sys.path[0], 'taskdata0.txt'), - os.path.join(sys.path[0], 'taskdata1.txt'), - os.path.join(sys.path[0], 'taskdata2.txt')] + input_file_paths = [ + os.path.join(sys.path[0], "taskdata0.txt"), + os.path.join(sys.path[0], "taskdata1.txt"), + os.path.join(sys.path[0], "taskdata2.txt"), + ] input_files = [ - upload_file_to_container(blob_service_client, input_container_name, file_path) - for file_path in input_file_paths] + upload_file_to_container(blob_service_client, input_container_name, file_path) for file_path in input_file_paths + ] # [END quickrun_python_upload_inputs] return input_files def make_batch_client(config): # [START quickrun_python_batch_client] - credentials = AzureNamedKeyCredential(config.BATCH_ACCOUNT_NAME, - config.BATCH_ACCOUNT_KEY) + credentials = AzureNamedKeyCredential(config.BATCH_ACCOUNT_NAME, config.BATCH_ACCOUNT_KEY) - batch_client = BatchClient( - endpoint=config.BATCH_ACCOUNT_URL, - credential=credentials) + batch_client = BatchClient(endpoint=config.BATCH_ACCOUNT_URL, credential=credentials) # [END quickrun_python_batch_client] return batch_client @@ -54,27 +53,23 @@ def make_batch_client(config): def create_pool(batch_client: BatchClient, pool_id: str, config): # [START quickrun_python_create_pool] new_pool = models.BatchPoolCreateOptions( - id=pool_id, - virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.BatchVmImageReference( - publisher="canonical", - offer="0001-com-ubuntu-server-focal", - sku="22_04-lts", - version="latest" - ), - node_agent_sku_id="batch.node.ubuntu 22.04"), - vm_size=config.POOL_VM_SIZE, - target_dedicated_nodes=config.POOL_NODE_COUNT - ) + id=pool_id, + virtual_machine_configuration=models.VirtualMachineConfiguration( + image_reference=models.BatchVmImageReference( + publisher="canonical", offer="0001-com-ubuntu-server-focal", sku="22_04-lts", version="latest" + ), + node_agent_sku_id="batch.node.ubuntu 22.04", + ), + vm_size=config.POOL_VM_SIZE, + target_dedicated_nodes=config.POOL_NODE_COUNT, + ) batch_client.create_pool(pool=new_pool) # [END quickrun_python_create_pool] def create_job(batch_client: BatchClient, job_id: str, pool_id: str): # [START quickrun_python_create_job] - job = models.BatchJobCreateOptions( - id=job_id, - pool_info=models.BatchPoolInfo(pool_id=pool_id)) + job = models.BatchJobCreateOptions(id=job_id, pool_info=models.BatchPoolInfo(pool_id=pool_id)) batch_client.create_job(job=job) # [END quickrun_python_create_job] @@ -85,13 +80,8 @@ def add_tasks(batch_client: BatchClient, job_id: str, resource_input_files): tasks = [] for idx, input_file in enumerate(resource_input_files): - command = f"/bin/bash -c \"cat {input_file.file_path}\"" - tasks.append(models.BatchTaskCreateOptions( - id=f'Task{idx}', - command_line=command, - resource_files=[input_file] - ) - ) + command = f'/bin/bash -c "cat {input_file.file_path}"' + tasks.append(models.BatchTaskCreateOptions(id=f"Task{idx}", command_line=command, resource_files=[input_file])) batch_client.create_tasks(job_id=job_id, task_collection=tasks) # [END quickrun_python_add_tasks] @@ -109,10 +99,9 @@ def view_task_output(batch_client: BatchClient, job_id: str, config, _read_strea print(f"Node: {node_id}") stream = batch_client.download_task_file( - job_id=job_id, task_id=task.id, file_path=config.STANDARD_OUT_FILE_NAME) + job_id=job_id, task_id=task.id, file_path=config.STANDARD_OUT_FILE_NAME + ) - file_text = _read_stream_as_string( - stream, - text_encoding) + file_text = _read_stream_as_string(stream, text_encoding) print(file_text) # [END quickrun_python_view_output] diff --git a/sdk/batch/azure-batch/samples/tutorial_parallel_python.py b/sdk/batch/azure-batch/samples/tutorial_parallel_python.py index b89f6c27646d..0ffa9806e8e2 100644 --- a/sdk/batch/azure-batch/samples/tutorial_parallel_python.py +++ b/sdk/batch/azure-batch/samples/tutorial_parallel_python.py @@ -18,33 +18,29 @@ from azure.core.credentials import AzureNamedKeyCredential from azure.storage.blob import BlobServiceClient - # [START tutorial_parallel_config] -_BATCH_ACCOUNT_NAME = os.getenv('AZURE_BATCH_ACCOUNT_NAME', '') -_BATCH_ACCOUNT_KEY = os.getenv('AZURE_BATCH_ACCOUNT_KEY', '') -_BATCH_ACCOUNT_URL = os.getenv('AZURE_BATCH_ACCOUNT_URL', 'https://yourbatchaccount.yourbatchregion.batch.azure.com') -_STORAGE_ACCOUNT_NAME = os.getenv('AZURE_STORAGE_ACCOUNT_NAME', '') -_STORAGE_ACCOUNT_KEY = os.getenv('AZURE_STORAGE_ACCOUNT_KEY', '') +_BATCH_ACCOUNT_NAME = os.getenv("AZURE_BATCH_ACCOUNT_NAME", "") +_BATCH_ACCOUNT_KEY = os.getenv("AZURE_BATCH_ACCOUNT_KEY", "") +_BATCH_ACCOUNT_URL = os.getenv("AZURE_BATCH_ACCOUNT_URL", "https://yourbatchaccount.yourbatchregion.batch.azure.com") +_STORAGE_ACCOUNT_NAME = os.getenv("AZURE_STORAGE_ACCOUNT_NAME", "") +_STORAGE_ACCOUNT_KEY = os.getenv("AZURE_STORAGE_ACCOUNT_KEY", "") # [END tutorial_parallel_config] def make_blob_client(): # [START tutorial_parallel_blob_client] blob_service_client = BlobServiceClient( - account_url=f"https://{_STORAGE_ACCOUNT_NAME}.blob.core.windows.net/", - credential=_STORAGE_ACCOUNT_KEY) + account_url=f"https://{_STORAGE_ACCOUNT_NAME}.blob.core.windows.net/", credential=_STORAGE_ACCOUNT_KEY + ) # [END tutorial_parallel_blob_client] return blob_service_client def make_batch_client(): # [START tutorial_parallel_batch_client] - credentials = AzureNamedKeyCredential(_BATCH_ACCOUNT_NAME, - _BATCH_ACCOUNT_KEY) + credentials = AzureNamedKeyCredential(_BATCH_ACCOUNT_NAME, _BATCH_ACCOUNT_KEY) - batch_client = BatchClient( - endpoint=_BATCH_ACCOUNT_URL, - credential=credentials) + batch_client = BatchClient(endpoint=_BATCH_ACCOUNT_URL, credential=credentials) # [END tutorial_parallel_batch_client] return batch_client @@ -55,44 +51,43 @@ def upload_inputs(blob_service_client, input_container_name, output_container_na blob_service_client.create_container(output_container_name) input_file_paths = [] - for folder, subs, files in os.walk(os.path.join(sys.path[0], './InputFiles/')): + for folder, subs, files in os.walk(os.path.join(sys.path[0], "./InputFiles/")): for filename in files: if filename.endswith(".mp4"): - input_file_paths.append(os.path.abspath( - os.path.join(folder, filename))) + input_file_paths.append(os.path.abspath(os.path.join(folder, filename))) # Upload the input files. This is the collection of files that are to be processed by the tasks. input_files = [ - upload_file_to_container(blob_service_client, input_container_name, file_path) - for file_path in input_file_paths] + upload_file_to_container(blob_service_client, input_container_name, file_path) for file_path in input_file_paths + ] # [END tutorial_parallel_upload_inputs] return input_files -def create_pool(batch_client: BatchClient, pool_id: str, pool_vm_size: str, - dedicated_node_count: int, low_priority_node_count: int): +def create_pool( + batch_client: BatchClient, pool_id: str, pool_vm_size: str, dedicated_node_count: int, low_priority_node_count: int +): # [START tutorial_parallel_create_pool] new_pool = models.BatchPoolCreateOptions( id=pool_id, virtual_machine_configuration=models.VirtualMachineConfiguration( image_reference=models.BatchVmImageReference( - publisher="Canonical", - offer="UbuntuServer", - sku="20.04-LTS", - version="latest" + publisher="Canonical", offer="UbuntuServer", sku="20.04-LTS", version="latest" ), - node_agent_sku_id="batch.node.ubuntu 20.04"), + node_agent_sku_id="batch.node.ubuntu 20.04", + ), vm_size=pool_vm_size, target_dedicated_nodes=dedicated_node_count, target_low_priority_nodes=low_priority_node_count, start_task=models.BatchStartTask( - command_line="/bin/bash -c \"apt-get update && apt-get install -y ffmpeg\"", + command_line='/bin/bash -c "apt-get update && apt-get install -y ffmpeg"', wait_for_success=True, user_identity=models.UserIdentity( auto_user=models.AutoUserSpecification( - scope=models.AutoUserScope.POOL, - elevation_level=models.ElevationLevel.ADMIN)), - ) + scope=models.AutoUserScope.POOL, elevation_level=models.ElevationLevel.ADMIN + ) + ), + ), ) batch_client.create_pool(pool=new_pool) # [END tutorial_parallel_create_pool] @@ -100,9 +95,7 @@ def create_pool(batch_client: BatchClient, pool_id: str, pool_vm_size: str, def create_job(batch_client: BatchClient, job_id: str, pool_id: str): # [START tutorial_parallel_create_job] - job = models.BatchJobCreateOptions( - id=job_id, - pool_info=models.BatchPoolInfo(pool_id=pool_id)) + job = models.BatchJobCreateOptions(id=job_id, pool_info=models.BatchPoolInfo(pool_id=pool_id)) batch_client.create_job(job=job) # [END tutorial_parallel_create_job] @@ -114,21 +107,25 @@ def add_tasks(batch_client: BatchClient, job_id: str, input_files, output_contai for idx, input_file in enumerate(input_files): input_file_path = input_file.file_path - output_file_path = "".join((input_file_path).split('.')[:-1]) + '.mp3' - command = "/bin/bash -c \"ffmpeg -i {} {}\"".format( - shlex.quote(input_file_path), shlex.quote(output_file_path)) - tasks.append(models.BatchTaskCreateOptions( - id='Task{}'.format(idx), - command_line=command, - resource_files=[input_file], - output_files=[models.OutputFile( - file_pattern=output_file_path, - destination=models.OutputFileDestination( - container=models.OutputFileBlobContainerDestination( - container_url=output_container_sas_url)), - upload_options=models.OutputFileUploadConfiguration( - upload_condition=models.OutputFileUploadCondition.TASK_SUCCESS))] - ) + output_file_path = "".join((input_file_path).split(".")[:-1]) + ".mp3" + command = '/bin/bash -c "ffmpeg -i {} {}"'.format(shlex.quote(input_file_path), shlex.quote(output_file_path)) + tasks.append( + models.BatchTaskCreateOptions( + id="Task{}".format(idx), + command_line=command, + resource_files=[input_file], + output_files=[ + models.OutputFile( + file_pattern=output_file_path, + destination=models.OutputFileDestination( + container=models.OutputFileBlobContainerDestination(container_url=output_container_sas_url) + ), + upload_options=models.OutputFileUploadConfiguration( + upload_condition=models.OutputFileUploadCondition.TASK_SUCCESS + ), + ) + ], + ) ) batch_client.create_tasks(job_id=job_id, task_collection=tasks) # [END tutorial_parallel_add_tasks] @@ -137,12 +134,11 @@ def add_tasks(batch_client: BatchClient, job_id: str, input_files, output_contai def wait_for_tasks(batch_client: BatchClient, job_id: str, timeout_expiration): # [START tutorial_parallel_wait_tasks] while datetime.datetime.now() < timeout_expiration: - print('.', end='') + print(".", end="") sys.stdout.flush() tasks = batch_client.list_tasks(job_id=job_id) - incomplete_tasks = [task for task in tasks if - task.state != models.BatchTaskState.COMPLETED] + incomplete_tasks = [task for task in tasks if task.state != models.BatchTaskState.COMPLETED] if not incomplete_tasks: print() return True diff --git a/sdk/batch/azure-batch/sdk_packaging.toml b/sdk/batch/azure-batch/sdk_packaging.toml deleted file mode 100644 index 5f5fa94fc1bd..000000000000 --- a/sdk/batch/azure-batch/sdk_packaging.toml +++ /dev/null @@ -1,8 +0,0 @@ -[packaging] -package_name = "azure-batch" -package_nspkg = "azure-nspkg" -package_pprint_name = "Batch" -package_doc_id = "batch" -is_stable = true -is_arm = false -auto_update = false \ No newline at end of file diff --git a/sdk/batch/azure-batch/tests/async_wrapper.py b/sdk/batch/azure-batch/tests/async_wrapper.py index 665b13620450..d84ae8cc953a 100644 --- a/sdk/batch/azure-batch/tests/async_wrapper.py +++ b/sdk/batch/azure-batch/tests/async_wrapper.py @@ -24,7 +24,7 @@ async def wrap_list_result(result: Union[Iterable[T], AsyncIterable[T]]) -> Iter async def wrap_file_result( - result: Union[Iterator[bytes], Coroutine[Any, Any, AsyncIterator[bytes]]] + result: Union[Iterator[bytes], Coroutine[Any, Any, AsyncIterator[bytes]]], ) -> Iterator[bytes]: """Handle a file download operation result and convert to an Iterator if it's async""" if inspect.iscoroutine(result): diff --git a/sdk/batch/azure-batch/tsp-location.yaml b/sdk/batch/azure-batch/tsp-location.yaml index 10585eca31f4..f9ba4ba36a0a 100644 --- a/sdk/batch/azure-batch/tsp-location.yaml +++ b/sdk/batch/azure-batch/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/batch/data-plane/Batch -commit: cf020d27e5e1b74872a5ff14419b667c893ac77f +commit: 0b01059c3d95a84bc84ff16a4bb0fd10f66f3abd repo: Azure/azure-rest-api-specs additionalDirectories: