diff --git a/sdk/batch/azure-batch/CHANGELOG.md b/sdk/batch/azure-batch/CHANGELOG.md index 1535db87b9ca..73fefdeb32e9 100644 --- a/sdk/batch/azure-batch/CHANGELOG.md +++ b/sdk/batch/azure-batch/CHANGELOG.md @@ -1,5 +1,82 @@ # Release History +## 15.0.0b3 (2025-09-01) + +### Features Added + +- Added Long Running Operation (LRO) support for the following operation methods: + - `delete_job` -> `begin_delete_job` + - `disable_job` -> `begin_disable_job` + - `enable_job` -> `begin_enable_job` + - `delete_job_schedule` -> `begin_delete_job_schedule` + - `delete_pool` -> `begin_delete_pool` + - `delete_certificate` -> `begin_delete_certificate` + - `deallocate_node` -> `begin_deallocate_node` + - `reboot_node` -> `begin_reboot_node` + - `reimage_node` -> `begin_reimage_node` + - `remove_nodes` -> `begin_remove_nodes` + - `resize_pool` -> `begin_resize_pool` + - `start_node` -> `begin_start_node` + - `stop_pool_resize` -> `begin_stop_pool_resize` + - `terminate_job` -> `begin_terminate_job` + - `terminate_job_schedule` -> `begin_terminate_job_schedule` + +### Breaking Changes + +- Renamed the following models. These name changes include several models with the suffix `Content` being renamed to have the suffix `Options`. + - `AccessScope` -> `BatchAccessScope` + - `AffinityInfo` -> `BatchAffinityInfo` + - `BatchJobAction` -> `BatchJobActionKind` + - `BatchJobCreateContent` -> `BatchJobCreateOptions` + - `BatchJobDisableContent` -> `BatchJobDisableOptions` + - `BatchJobScheduleCreateContent` -> `BatchJobScheduleCreateOptions` + - `BatchJobScheduleUpdateContent` -> `BatchJobScheduleUpdateOptions` + - `BatchJobTerminateContent` -> `BatchJobTerminateOptions` + - `BatchJobUpdateContent` -> `BatchJobUpdateOptions` + - `BatchNodeDeallocateContent` -> `BatchNodeDeallocateOptions` + - `BatchNodeDisableSchedulingContent` -> `BatchNodeDisableSchedulingOptions` + - `BatchNodeRebootContent` -> `BatchNodeRebootOptions` + - `BatchNodeRebootOption` -> `BatchNodeRebootKind` + - `BatchNodeReimageContent` -> `BatchNodeReimageOptions` + - `BatchNodeRemoveContent` -> `BatchNodeRemoveOptions` + - `BatchNodeUserCreateContent` -> `BatchNodeUserCreateOptions` + - `BatchNodeUserUpdateContent` -> `BatchNodeUserUpdateOptions` + - `BatchPoolCreateContent` -> `BatchPoolCreateOptions` + - `BatchPoolEnableAutoScaleContent` -> `BatchPoolEnableAutoScaleOptions` + - `BatchPoolEvaluateAutoScaleContent` -> `BatchPoolEvaluateAutoScaleOptions` + - `BatchPoolReplaceContent` -> `BatchPoolReplaceOptions` + - `BatchPoolResizeContent` -> `BatchPoolResizeOptions` + - `BatchPoolUpdateContent` -> `BatchPoolUpdateOptions` + - `BatchTaskCreateContent` -> `BatchTaskCreateOptions` + - `ContainerConfiguration` -> `BatchContainerConfiguration` + - `ContainerConfigurationUpdate` -> `BatchContainerConfigurationUpdate` + - `DeleteBatchCertificateError` -> `BatchCertificateDeleteError` + - `DiffDiskSettings` -> `BatchDiffDiskSettings` + - `ErrorCategory` -> `BatchErrorSourceCategory` + - `HttpHeader` -> `OutputFileUploadHeader` + - `ImageReference` -> `BatchVmImageReference` + - `OSDisk` -> `BatchOsDisk` + - `OnAllBatchTasksComplete` -> `BatchAllTasksCompleteMode` + - `OnBatchTaskFailure` -> `BatchAllTasksCompleteMode` + - `PublicIpAddressConfiguration` -> `BatchPublicIpAddressConfiguration` + - `UefiSettings` -> `BatchUefiSettings` + - `UploadBatchServiceLogsContent` -> `UploadBatchServiceLogsOptions` + - `VMDiskSecurityProfile` -> `BatchVMDiskSecurityProfile` + +- Renamed parameters in the following operation methods: + - `begin_disable_job` changed `content` parameter to `disable_options` + - `begin_deallocate_node` changed `parameters` parameter to `options` + - `begin_remove_nodes` changed `content` parameter to `remove_options`. + - `begin_resize_pool` changed `content` parameter to `resize_options`. + - `begin_terminate_job` changed `parameters` parameter to `options`. + - `begin_reboot_node` changed `parameters` parameter to `options`. + - `begin_reimage_node` changed `parameters` parameter to `options`. + - `disable_node_scheduling` changed `parameters` parameter to `options`. + - `enable_pool_auto_scale` changed `content` parameter to `enable_auto_scale_options`. + - `evaluate_pool_auto_scale` changed `content` parameter to `evaluate_auto_scale_options`. + - `upload_node_logs` changed `content` parameter to `upload_options`. + - `replace_node_user` changed `content` parameter to `update_options`. + ## 15.0.0b2 (2025-03-01) ### Features Added diff --git a/sdk/batch/azure-batch/MANIFEST.in b/sdk/batch/azure-batch/MANIFEST.in index cb1e2b1128cb..06208ba9fde2 100644 --- a/sdk/batch/azure-batch/MANIFEST.in +++ b/sdk/batch/azure-batch/MANIFEST.in @@ -3,4 +3,4 @@ include LICENSE include azure/batch/py.typed recursive-include tests *.py recursive-include samples *.py *.md -include azure/__init__.py \ No newline at end of file +include azure/__init__.py diff --git a/sdk/batch/azure-batch/apiview-properties.json b/sdk/batch/azure-batch/apiview-properties.json new file mode 100644 index 000000000000..5e71f4f8e488 --- /dev/null +++ b/sdk/batch/azure-batch/apiview-properties.json @@ -0,0 +1,329 @@ +{ + "CrossLanguagePackageId": "Azure.Batch", + "CrossLanguageDefinitionId": { + "azure.batch.models.AuthenticationTokenSettings": "Azure.Batch.AuthenticationTokenSettings", + "azure.batch.models.AutomaticOsUpgradePolicy": "Azure.Batch.AutomaticOsUpgradePolicy", + "azure.batch.models.AutoScaleRun": "Azure.Batch.AutoScaleRun", + "azure.batch.models.AutoScaleRunError": "Azure.Batch.AutoScaleRunError", + "azure.batch.models.AutoUserSpecification": "Azure.Batch.AutoUserSpecification", + "azure.batch.models.AzureBlobFileSystemConfiguration": "Azure.Batch.AzureBlobFileSystemConfiguration", + "azure.batch.models.AzureFileShareConfiguration": "Azure.Batch.AzureFileShareConfiguration", + "azure.batch.models.BatchAffinityInfo": "Azure.Batch.BatchAffinityInfo", + "azure.batch.models.BatchApplication": "Azure.Batch.BatchApplication", + "azure.batch.models.BatchApplicationPackageReference": "Azure.Batch.BatchApplicationPackageReference", + "azure.batch.models.BatchAutoPoolSpecification": "Azure.Batch.BatchAutoPoolSpecification", + "azure.batch.models.BatchCertificate": "Azure.Batch.BatchCertificate", + "azure.batch.models.BatchCertificateDeleteError": "Azure.Batch.BatchCertificateDeleteError", + "azure.batch.models.BatchCertificateReference": "Azure.Batch.BatchCertificateReference", + "azure.batch.models.BatchContainerConfiguration": "Azure.Batch.BatchContainerConfiguration", + "azure.batch.models.BatchCreateTaskCollectionResult": "Azure.Batch.BatchCreateTaskCollectionResult", + "azure.batch.models.BatchDiffDiskSettings": "Azure.Batch.BatchDiffDiskSettings", + "azure.batch.models.BatchError": "Azure.Batch.BatchError", + "azure.batch.models.BatchErrorDetail": "Azure.Batch.BatchErrorDetail", + "azure.batch.models.BatchErrorMessage": "Azure.Batch.BatchErrorMessage", + "azure.batch.models.BatchInboundNatPool": "Azure.Batch.BatchInboundNatPool", + "azure.batch.models.BatchJob": "Azure.Batch.BatchJob", + "azure.batch.models.BatchJobConstraints": "Azure.Batch.BatchJobConstraints", + "azure.batch.models.BatchJobCreateOptions": "Azure.Batch.BatchJobCreateOptions", + "azure.batch.models.BatchJobDisableOptions": "Azure.Batch.BatchJobDisableOptions", + "azure.batch.models.BatchJobExecutionInfo": "Azure.Batch.BatchJobExecutionInfo", + "azure.batch.models.BatchJobManagerTask": "Azure.Batch.BatchJobManagerTask", + "azure.batch.models.BatchJobNetworkConfiguration": "Azure.Batch.BatchJobNetworkConfiguration", + "azure.batch.models.BatchJobPreparationAndReleaseTaskStatus": "Azure.Batch.BatchJobPreparationAndReleaseTaskStatus", + "azure.batch.models.BatchJobPreparationTask": "Azure.Batch.BatchJobPreparationTask", + "azure.batch.models.BatchJobPreparationTaskExecutionInfo": "Azure.Batch.BatchJobPreparationTaskExecutionInfo", + "azure.batch.models.BatchJobReleaseTask": "Azure.Batch.BatchJobReleaseTask", + "azure.batch.models.BatchJobReleaseTaskExecutionInfo": "Azure.Batch.BatchJobReleaseTaskExecutionInfo", + "azure.batch.models.BatchJobSchedule": "Azure.Batch.BatchJobSchedule", + "azure.batch.models.BatchJobScheduleConfiguration": "Azure.Batch.BatchJobScheduleConfiguration", + "azure.batch.models.BatchJobScheduleCreateOptions": "Azure.Batch.BatchJobScheduleCreateOptions", + "azure.batch.models.BatchJobScheduleExecutionInfo": "Azure.Batch.BatchJobScheduleExecutionInfo", + "azure.batch.models.BatchJobScheduleStatistics": "Azure.Batch.BatchJobScheduleStatistics", + "azure.batch.models.BatchJobScheduleUpdateOptions": "Azure.Batch.BatchJobScheduleUpdateOptions", + "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", + "azure.batch.models.BatchNodeFile": "Azure.Batch.BatchNodeFile", + "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", + "azure.batch.models.BatchNodeUserUpdateOptions": "Azure.Batch.BatchNodeUserUpdateOptions", + "azure.batch.models.BatchNodeVMExtension": "Azure.Batch.BatchNodeVMExtension", + "azure.batch.models.BatchOsDisk": "Azure.Batch.BatchOsDisk", + "azure.batch.models.BatchPool": "Azure.Batch.BatchPool", + "azure.batch.models.BatchPoolCreateOptions": "Azure.Batch.BatchPoolCreateOptions", + "azure.batch.models.BatchPoolEnableAutoScaleOptions": "Azure.Batch.BatchPoolEnableAutoScaleOptions", + "azure.batch.models.BatchPoolEndpointConfiguration": "Azure.Batch.BatchPoolEndpointConfiguration", + "azure.batch.models.BatchPoolEvaluateAutoScaleOptions": "Azure.Batch.BatchPoolEvaluateAutoScaleOptions", + "azure.batch.models.BatchPoolIdentity": "Azure.Batch.BatchPoolIdentity", + "azure.batch.models.BatchPoolInfo": "Azure.Batch.BatchPoolInfo", + "azure.batch.models.BatchPoolNodeCounts": "Azure.Batch.BatchPoolNodeCounts", + "azure.batch.models.BatchPoolReplaceOptions": "Azure.Batch.BatchPoolReplaceOptions", + "azure.batch.models.BatchPoolResizeOptions": "Azure.Batch.BatchPoolResizeOptions", + "azure.batch.models.BatchPoolResourceStatistics": "Azure.Batch.BatchPoolResourceStatistics", + "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", + "azure.batch.models.BatchSubtask": "Azure.Batch.BatchSubtask", + "azure.batch.models.BatchSupportedImage": "Azure.Batch.BatchSupportedImage", + "azure.batch.models.BatchTask": "Azure.Batch.BatchTask", + "azure.batch.models.BatchTaskConstraints": "Azure.Batch.BatchTaskConstraints", + "azure.batch.models.BatchTaskContainerExecutionInfo": "Azure.Batch.BatchTaskContainerExecutionInfo", + "azure.batch.models.BatchTaskContainerSettings": "Azure.Batch.BatchTaskContainerSettings", + "azure.batch.models.BatchTaskCounts": "Azure.Batch.BatchTaskCounts", + "azure.batch.models.BatchTaskCountsResult": "Azure.Batch.BatchTaskCountsResult", + "azure.batch.models.BatchTaskCreateOptions": "Azure.Batch.BatchTaskCreateOptions", + "azure.batch.models.BatchTaskCreateResult": "Azure.Batch.BatchTaskCreateResult", + "azure.batch.models.BatchTaskDependencies": "Azure.Batch.BatchTaskDependencies", + "azure.batch.models.BatchTaskExecutionInfo": "Azure.Batch.BatchTaskExecutionInfo", + "azure.batch.models.BatchTaskFailureInfo": "Azure.Batch.BatchTaskFailureInfo", + "azure.batch.models.BatchTaskGroup": "Azure.Batch.BatchTaskGroup", + "azure.batch.models.BatchTaskIdRange": "Azure.Batch.BatchTaskIdRange", + "azure.batch.models.BatchTaskInfo": "Azure.Batch.BatchTaskInfo", + "azure.batch.models.BatchTaskSchedulingPolicy": "Azure.Batch.BatchTaskSchedulingPolicy", + "azure.batch.models.BatchTaskSlotCounts": "Azure.Batch.BatchTaskSlotCounts", + "azure.batch.models.BatchTaskStatistics": "Azure.Batch.BatchTaskStatistics", + "azure.batch.models.BatchUefiSettings": "Azure.Batch.BatchUefiSettings", + "azure.batch.models.BatchUserAssignedIdentity": "Azure.Batch.BatchUserAssignedIdentity", + "azure.batch.models.BatchVmDiskSecurityProfile": "Azure.Batch.BatchVmDiskSecurityProfile", + "azure.batch.models.BatchVmImageReference": "Azure.Batch.BatchVmImageReference", + "azure.batch.models.CifsMountConfiguration": "Azure.Batch.CifsMountConfiguration", + "azure.batch.models.ContainerHostBatchBindMountEntry": "Azure.Batch.ContainerHostBatchBindMountEntry", + "azure.batch.models.ContainerRegistryReference": "Azure.Batch.ContainerRegistryReference", + "azure.batch.models.DataDisk": "Azure.Batch.DataDisk", + "azure.batch.models.DiskEncryptionConfiguration": "Azure.Batch.DiskEncryptionConfiguration", + "azure.batch.models.EnvironmentSetting": "Azure.Batch.EnvironmentSetting", + "azure.batch.models.ExitCodeMapping": "Azure.Batch.ExitCodeMapping", + "azure.batch.models.ExitCodeRangeMapping": "Azure.Batch.ExitCodeRangeMapping", + "azure.batch.models.ExitConditions": "Azure.Batch.ExitConditions", + "azure.batch.models.ExitOptions": "Azure.Batch.ExitOptions", + "azure.batch.models.FileProperties": "Azure.Batch.FileProperties", + "azure.batch.models.InboundEndpoint": "Azure.Batch.InboundEndpoint", + "azure.batch.models.InstanceViewStatus": "Azure.Batch.InstanceViewStatus", + "azure.batch.models.LinuxUserConfiguration": "Azure.Batch.LinuxUserConfiguration", + "azure.batch.models.ManagedDisk": "Azure.Batch.ManagedDisk", + "azure.batch.models.MountConfiguration": "Azure.Batch.MountConfiguration", + "azure.batch.models.MultiInstanceSettings": "Azure.Batch.MultiInstanceSettings", + "azure.batch.models.NameValuePair": "Azure.Batch.NameValuePair", + "azure.batch.models.NetworkConfiguration": "Azure.Batch.NetworkConfiguration", + "azure.batch.models.NetworkSecurityGroupRule": "Azure.Batch.NetworkSecurityGroupRule", + "azure.batch.models.NfsMountConfiguration": "Azure.Batch.NfsMountConfiguration", + "azure.batch.models.OutputFile": "Azure.Batch.OutputFile", + "azure.batch.models.OutputFileBlobContainerDestination": "Azure.Batch.OutputFileBlobContainerDestination", + "azure.batch.models.OutputFileDestination": "Azure.Batch.OutputFileDestination", + "azure.batch.models.OutputFileUploadConfig": "Azure.Batch.OutputFileUploadConfig", + "azure.batch.models.OutputFileUploadHeader": "Azure.Batch.OutputFileUploadHeader", + "azure.batch.models.RecentBatchJob": "Azure.Batch.RecentBatchJob", + "azure.batch.models.ResizeError": "Azure.Batch.ResizeError", + "azure.batch.models.ResourceFile": "Azure.Batch.ResourceFile", + "azure.batch.models.RollingUpgradePolicy": "Azure.Batch.RollingUpgradePolicy", + "azure.batch.models.SecurityProfile": "Azure.Batch.SecurityProfile", + "azure.batch.models.ServiceArtifactReference": "Azure.Batch.ServiceArtifactReference", + "azure.batch.models.UpgradePolicy": "Azure.Batch.UpgradePolicy", + "azure.batch.models.UploadBatchServiceLogsOptions": "Azure.Batch.UploadBatchServiceLogsOptions", + "azure.batch.models.UploadBatchServiceLogsResult": "Azure.Batch.UploadBatchServiceLogsResult", + "azure.batch.models.UserAccount": "Azure.Batch.UserAccount", + "azure.batch.models.UserIdentity": "Azure.Batch.UserIdentity", + "azure.batch.models.VirtualMachineConfiguration": "Azure.Batch.VirtualMachineConfiguration", + "azure.batch.models.VirtualMachineInfo": "Azure.Batch.VirtualMachineInfo", + "azure.batch.models.VMExtension": "Azure.Batch.VMExtension", + "azure.batch.models.VMExtensionInstanceView": "Azure.Batch.VMExtensionInstanceView", + "azure.batch.models.WindowsConfiguration": "Azure.Batch.WindowsConfiguration", + "azure.batch.models.WindowsUserConfiguration": "Azure.Batch.WindowsUserConfiguration", + "azure.batch.models.CachingType": "Azure.Batch.CachingType", + "azure.batch.models.StorageAccountType": "Azure.Batch.StorageAccountType", + "azure.batch.models.ContainerType": "Azure.Batch.ContainerType", + "azure.batch.models.DiskEncryptionTarget": "Azure.Batch.DiskEncryptionTarget", + "azure.batch.models.BatchNodePlacementPolicyType": "Azure.Batch.BatchNodePlacementPolicyType", + "azure.batch.models.DiffDiskPlacement": "Azure.Batch.DiffDiskPlacement", + "azure.batch.models.SecurityEncryptionTypes": "Azure.Batch.SecurityEncryptionTypes", + "azure.batch.models.SecurityTypes": "Azure.Batch.SecurityTypes", + "azure.batch.models.DynamicVNetAssignmentScope": "Azure.Batch.DynamicVNetAssignmentScope", + "azure.batch.models.InboundEndpointProtocol": "Azure.Batch.InboundEndpointProtocol", + "azure.batch.models.NetworkSecurityGroupRuleAccess": "Azure.Batch.NetworkSecurityGroupRuleAccess", + "azure.batch.models.IpAddressProvisioningType": "Azure.Batch.IpAddressProvisioningType", + "azure.batch.models.ContainerWorkingDirectory": "Azure.Batch.ContainerWorkingDirectory", + "azure.batch.models.ContainerHostDataPath": "Azure.Batch.ContainerHostDataPath", + "azure.batch.models.AutoUserScope": "Azure.Batch.AutoUserScope", + "azure.batch.models.ElevationLevel": "Azure.Batch.ElevationLevel", + "azure.batch.models.BatchCertificateStoreLocation": "Azure.Batch.BatchCertificateStoreLocation", + "azure.batch.models.BatchCertificateVisibility": "Azure.Batch.BatchCertificateVisibility", + "azure.batch.models.BatchNodeFillType": "Azure.Batch.BatchNodeFillType", + "azure.batch.models.LoginMode": "Azure.Batch.LoginMode", + "azure.batch.models.BatchNodeCommunicationMode": "Azure.Batch.BatchNodeCommunicationMode", + "azure.batch.models.UpgradeMode": "Azure.Batch.UpgradeMode", + "azure.batch.models.BatchPoolState": "Azure.Batch.BatchPoolState", + "azure.batch.models.AllocationState": "Azure.Batch.AllocationState", + "azure.batch.models.BatchPoolIdentityType": "Azure.Batch.BatchPoolIdentityType", + "azure.batch.models.BatchNodeDeallocationOption": "Azure.Batch.BatchNodeDeallocationOption", + "azure.batch.models.OSType": "Azure.Batch.OSType", + "azure.batch.models.ImageVerificationType": "Azure.Batch.ImageVerificationType", + "azure.batch.models.BatchJobState": "Azure.Batch.BatchJobState", + "azure.batch.models.OutputFileUploadCondition": "Azure.Batch.OutputFileUploadCondition", + "azure.batch.models.BatchAccessScope": "Azure.Batch.BatchAccessScope", + "azure.batch.models.BatchPoolLifetimeOption": "Azure.Batch.BatchPoolLifetimeOption", + "azure.batch.models.BatchAllTasksCompleteMode": "Azure.Batch.BatchAllTasksCompleteMode", + "azure.batch.models.BatchTaskFailureMode": "Azure.Batch.BatchTaskFailureMode", + "azure.batch.models.BatchErrorSourceCategory": "Azure.Batch.BatchErrorSourceCategory", + "azure.batch.models.DisableBatchJobOption": "Azure.Batch.DisableBatchJobOption", + "azure.batch.models.BatchJobPreparationTaskState": "Azure.Batch.BatchJobPreparationTaskState", + "azure.batch.models.BatchTaskExecutionResult": "Azure.Batch.BatchTaskExecutionResult", + "azure.batch.models.BatchJobReleaseTaskState": "Azure.Batch.BatchJobReleaseTaskState", + "azure.batch.models.BatchCertificateState": "Azure.Batch.BatchCertificateState", + "azure.batch.models.BatchCertificateFormat": "Azure.Batch.BatchCertificateFormat", + "azure.batch.models.BatchJobScheduleState": "Azure.Batch.BatchJobScheduleState", + "azure.batch.models.BatchJobActionKind": "Azure.Batch.BatchJobActionKind", + "azure.batch.models.DependencyAction": "Azure.Batch.DependencyAction", + "azure.batch.models.BatchTaskState": "Azure.Batch.BatchTaskState", + "azure.batch.models.BatchTaskAddStatus": "Azure.Batch.BatchTaskAddStatus", + "azure.batch.models.BatchSubtaskState": "Azure.Batch.BatchSubtaskState", + "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", + "azure.batch.aio.BatchClient.list_pools": "Client.BatchClient.listPools", + "azure.batch.BatchClient.pool_exists": "Client.BatchClient.poolExists", + "azure.batch.aio.BatchClient.pool_exists": "Client.BatchClient.poolExists", + "azure.batch.BatchClient.get_pool": "Client.BatchClient.getPool", + "azure.batch.aio.BatchClient.get_pool": "Client.BatchClient.getPool", + "azure.batch.BatchClient.update_pool": "Client.BatchClient.updatePool", + "azure.batch.aio.BatchClient.update_pool": "Client.BatchClient.updatePool", + "azure.batch.BatchClient.disable_pool_auto_scale": "Client.BatchClient.disablePoolAutoScale", + "azure.batch.aio.BatchClient.disable_pool_auto_scale": "Client.BatchClient.disablePoolAutoScale", + "azure.batch.BatchClient.enable_pool_auto_scale": "Client.BatchClient.enablePoolAutoScale", + "azure.batch.aio.BatchClient.enable_pool_auto_scale": "Client.BatchClient.enablePoolAutoScale", + "azure.batch.BatchClient.evaluate_pool_auto_scale": "Client.BatchClient.evaluatePoolAutoScale", + "azure.batch.aio.BatchClient.evaluate_pool_auto_scale": "Client.BatchClient.evaluatePoolAutoScale", + "azure.batch.BatchClient.replace_pool_properties": "Client.BatchClient.replacePoolProperties", + "azure.batch.aio.BatchClient.replace_pool_properties": "Client.BatchClient.replacePoolProperties", + "azure.batch.BatchClient.list_supported_images": "Client.BatchClient.listSupportedImages", + "azure.batch.aio.BatchClient.list_supported_images": "Client.BatchClient.listSupportedImages", + "azure.batch.BatchClient.list_pool_node_counts": "Client.BatchClient.listPoolNodeCounts", + "azure.batch.aio.BatchClient.list_pool_node_counts": "Client.BatchClient.listPoolNodeCounts", + "azure.batch.BatchClient.get_job": "Client.BatchClient.getJob", + "azure.batch.aio.BatchClient.get_job": "Client.BatchClient.getJob", + "azure.batch.BatchClient.update_job": "Client.BatchClient.updateJob", + "azure.batch.aio.BatchClient.update_job": "Client.BatchClient.updateJob", + "azure.batch.BatchClient.replace_job": "Client.BatchClient.replaceJob", + "azure.batch.aio.BatchClient.replace_job": "Client.BatchClient.replaceJob", + "azure.batch.BatchClient.create_job": "Client.BatchClient.createJob", + "azure.batch.aio.BatchClient.create_job": "Client.BatchClient.createJob", + "azure.batch.BatchClient.list_jobs": "Client.BatchClient.listJobs", + "azure.batch.aio.BatchClient.list_jobs": "Client.BatchClient.listJobs", + "azure.batch.BatchClient.list_jobs_from_schedule": "Client.BatchClient.listJobsFromSchedule", + "azure.batch.aio.BatchClient.list_jobs_from_schedule": "Client.BatchClient.listJobsFromSchedule", + "azure.batch.BatchClient.list_job_preparation_and_release_task_status": "Client.BatchClient.listJobPreparationAndReleaseTaskStatus", + "azure.batch.aio.BatchClient.list_job_preparation_and_release_task_status": "Client.BatchClient.listJobPreparationAndReleaseTaskStatus", + "azure.batch.BatchClient.get_job_task_counts": "Client.BatchClient.getJobTaskCounts", + "azure.batch.aio.BatchClient.get_job_task_counts": "Client.BatchClient.getJobTaskCounts", + "azure.batch.BatchClient.create_certificate": "Client.BatchClient.createCertificate", + "azure.batch.aio.BatchClient.create_certificate": "Client.BatchClient.createCertificate", + "azure.batch.BatchClient.list_certificates": "Client.BatchClient.listCertificates", + "azure.batch.aio.BatchClient.list_certificates": "Client.BatchClient.listCertificates", + "azure.batch.BatchClient.cancel_certificate_deletion": "Client.BatchClient.cancelCertificateDeletion", + "azure.batch.aio.BatchClient.cancel_certificate_deletion": "Client.BatchClient.cancelCertificateDeletion", + "azure.batch.BatchClient.get_certificate": "Client.BatchClient.getCertificate", + "azure.batch.aio.BatchClient.get_certificate": "Client.BatchClient.getCertificate", + "azure.batch.BatchClient.job_schedule_exists": "Client.BatchClient.jobScheduleExists", + "azure.batch.aio.BatchClient.job_schedule_exists": "Client.BatchClient.jobScheduleExists", + "azure.batch.BatchClient.get_job_schedule": "Client.BatchClient.getJobSchedule", + "azure.batch.aio.BatchClient.get_job_schedule": "Client.BatchClient.getJobSchedule", + "azure.batch.BatchClient.update_job_schedule": "Client.BatchClient.updateJobSchedule", + "azure.batch.aio.BatchClient.update_job_schedule": "Client.BatchClient.updateJobSchedule", + "azure.batch.BatchClient.replace_job_schedule": "Client.BatchClient.replaceJobSchedule", + "azure.batch.aio.BatchClient.replace_job_schedule": "Client.BatchClient.replaceJobSchedule", + "azure.batch.BatchClient.disable_job_schedule": "Client.BatchClient.disableJobSchedule", + "azure.batch.aio.BatchClient.disable_job_schedule": "Client.BatchClient.disableJobSchedule", + "azure.batch.BatchClient.enable_job_schedule": "Client.BatchClient.enableJobSchedule", + "azure.batch.aio.BatchClient.enable_job_schedule": "Client.BatchClient.enableJobSchedule", + "azure.batch.BatchClient.create_job_schedule": "Client.BatchClient.createJobSchedule", + "azure.batch.aio.BatchClient.create_job_schedule": "Client.BatchClient.createJobSchedule", + "azure.batch.BatchClient.list_job_schedules": "Client.BatchClient.listJobSchedules", + "azure.batch.aio.BatchClient.list_job_schedules": "Client.BatchClient.listJobSchedules", + "azure.batch.BatchClient.create_task": "Client.BatchClient.createTask", + "azure.batch.aio.BatchClient.create_task": "Client.BatchClient.createTask", + "azure.batch.BatchClient.list_tasks": "Client.BatchClient.listTasks", + "azure.batch.aio.BatchClient.list_tasks": "Client.BatchClient.listTasks", + "azure.batch.BatchClient.create_task_collection": "Client.BatchClient.createTaskCollection", + "azure.batch.aio.BatchClient.create_task_collection": "Client.BatchClient.createTaskCollection", + "azure.batch.BatchClient.delete_task": "Client.BatchClient.deleteTask", + "azure.batch.aio.BatchClient.delete_task": "Client.BatchClient.deleteTask", + "azure.batch.BatchClient.get_task": "Client.BatchClient.getTask", + "azure.batch.aio.BatchClient.get_task": "Client.BatchClient.getTask", + "azure.batch.BatchClient.replace_task": "Client.BatchClient.replaceTask", + "azure.batch.aio.BatchClient.replace_task": "Client.BatchClient.replaceTask", + "azure.batch.BatchClient.list_sub_tasks": "Client.BatchClient.listSubTasks", + "azure.batch.aio.BatchClient.list_sub_tasks": "Client.BatchClient.listSubTasks", + "azure.batch.BatchClient.terminate_task": "Client.BatchClient.terminateTask", + "azure.batch.aio.BatchClient.terminate_task": "Client.BatchClient.terminateTask", + "azure.batch.BatchClient.reactivate_task": "Client.BatchClient.reactivateTask", + "azure.batch.aio.BatchClient.reactivate_task": "Client.BatchClient.reactivateTask", + "azure.batch.BatchClient.delete_task_file": "Client.BatchClient.deleteTaskFile", + "azure.batch.aio.BatchClient.delete_task_file": "Client.BatchClient.deleteTaskFile", + "azure.batch.BatchClient.get_task_file": "Client.BatchClient.getTaskFile", + "azure.batch.aio.BatchClient.get_task_file": "Client.BatchClient.getTaskFile", + "azure.batch.BatchClient.list_task_files": "Client.BatchClient.listTaskFiles", + "azure.batch.aio.BatchClient.list_task_files": "Client.BatchClient.listTaskFiles", + "azure.batch.BatchClient.create_node_user": "Client.BatchClient.createNodeUser", + "azure.batch.aio.BatchClient.create_node_user": "Client.BatchClient.createNodeUser", + "azure.batch.BatchClient.delete_node_user": "Client.BatchClient.deleteNodeUser", + "azure.batch.aio.BatchClient.delete_node_user": "Client.BatchClient.deleteNodeUser", + "azure.batch.BatchClient.replace_node_user": "Client.BatchClient.replaceNodeUser", + "azure.batch.aio.BatchClient.replace_node_user": "Client.BatchClient.replaceNodeUser", + "azure.batch.BatchClient.get_node": "Client.BatchClient.getNode", + "azure.batch.aio.BatchClient.get_node": "Client.BatchClient.getNode", + "azure.batch.BatchClient.disable_node_scheduling": "Client.BatchClient.disableNodeScheduling", + "azure.batch.aio.BatchClient.disable_node_scheduling": "Client.BatchClient.disableNodeScheduling", + "azure.batch.BatchClient.enable_node_scheduling": "Client.BatchClient.enableNodeScheduling", + "azure.batch.aio.BatchClient.enable_node_scheduling": "Client.BatchClient.enableNodeScheduling", + "azure.batch.BatchClient.get_node_remote_login_settings": "Client.BatchClient.getNodeRemoteLoginSettings", + "azure.batch.aio.BatchClient.get_node_remote_login_settings": "Client.BatchClient.getNodeRemoteLoginSettings", + "azure.batch.BatchClient.upload_node_logs": "Client.BatchClient.uploadNodeLogs", + "azure.batch.aio.BatchClient.upload_node_logs": "Client.BatchClient.uploadNodeLogs", + "azure.batch.BatchClient.list_nodes": "Client.BatchClient.listNodes", + "azure.batch.aio.BatchClient.list_nodes": "Client.BatchClient.listNodes", + "azure.batch.BatchClient.get_node_extension": "Client.BatchClient.getNodeExtension", + "azure.batch.aio.BatchClient.get_node_extension": "Client.BatchClient.getNodeExtension", + "azure.batch.BatchClient.list_node_extensions": "Client.BatchClient.listNodeExtensions", + "azure.batch.aio.BatchClient.list_node_extensions": "Client.BatchClient.listNodeExtensions", + "azure.batch.BatchClient.delete_node_file": "Client.BatchClient.deleteNodeFile", + "azure.batch.aio.BatchClient.delete_node_file": "Client.BatchClient.deleteNodeFile", + "azure.batch.BatchClient.get_node_file": "Client.BatchClient.getNodeFile", + "azure.batch.aio.BatchClient.get_node_file": "Client.BatchClient.getNodeFile", + "azure.batch.BatchClient.list_node_files": "Client.BatchClient.listNodeFiles", + "azure.batch.aio.BatchClient.list_node_files": "Client.BatchClient.listNodeFiles" + } +} \ No newline at end of file diff --git a/sdk/batch/azure-batch/assets.json b/sdk/batch/azure-batch/assets.json index fdfd842ff4cd..4f63b63016dc 100644 --- a/sdk/batch/azure-batch/assets.json +++ b/sdk/batch/azure-batch/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/batch/azure-batch", - "Tag": "python/batch/azure-batch_8d51b2d53f" + "Tag": "python/batch/azure-batch_dad65083c9" } diff --git a/sdk/batch/azure-batch/azure/batch/_client.py b/sdk/batch/azure-batch/azure/batch/_client.py index 4ce5c282dbf4..3657c6c6ed45 100644 --- a/sdk/batch/azure-batch/azure/batch/_client.py +++ b/sdk/batch/azure-batch/azure/batch/_client.py @@ -16,7 +16,7 @@ from ._configuration import BatchClientConfiguration from ._operations import BatchClientOperationsMixin -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -39,6 +39,7 @@ class BatchClient(BatchClientOperationsMixin): def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" self._config = BatchClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + kwargs["request_id_header_name"] = "client-request-id" _policies = kwargs.pop("policies", None) if _policies is None: diff --git a/sdk/batch/azure-batch/azure/batch/_model_base.py b/sdk/batch/azure-batch/azure/batch/_model_base.py index 3072ee252ed9..228610c1f0c6 100644 --- a/sdk/batch/azure-batch/azure/batch/_model_base.py +++ b/sdk/batch/azure-batch/azure/batch/_model_base.py @@ -680,7 +680,7 @@ def _deserialize(cls, data, exist_discriminators): 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 + 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]: diff --git a/sdk/batch/azure-batch/azure/batch/_operations/__init__.py b/sdk/batch/azure-batch/azure/batch/_operations/__init__.py index ea39f177e86d..cb9c4e3de8e2 100644 --- a/sdk/batch/azure-batch/azure/batch/_operations/__init__.py +++ b/sdk/batch/azure-batch/azure/batch/_operations/__init__.py @@ -12,14 +12,17 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import BatchClientOperationsMixin # type: ignore +from ._operations import _BatchClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk +# TODO: Check if we need to add this to the __all__ for async and sync LATER +# maybe it can be removed (like what the generator wanted) +# too many BatchClientOperationMixins everywhere ... maybe rename this one to internal? __all__ = [ - "BatchClientOperationsMixin", + "_BatchClientOperationsMixin", ] __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/_operations/_operations.py b/sdk/batch/azure-batch/azure/batch/_operations/_operations.py index 14c180e935e8..fc006d7bed67 100644 --- a/sdk/batch/azure-batch/azure/batch/_operations/_operations.py +++ b/sdk/batch/azure-batch/azure/batch/_operations/_operations.py @@ -6,13 +6,13 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime import json -import sys -from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TypeVar +from typing import Any, Callable, Iterator, Optional, TypeVar import urllib.parse -from azure.core import MatchConditions +from azure.core import MatchConditions, PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -31,16 +31,13 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize -from .._serialization import Serializer -from .._vendor import BatchClientMixinABC, prep_if_match, prep_if_none_match - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore +from .._configuration import BatchClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match + T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False @@ -155,8 +152,6 @@ def build_batch_create_pool_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools" @@ -169,7 +164,6 @@ def build_batch_create_pool_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -180,8 +174,8 @@ def build_batch_list_pools_request( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -214,7 +208,7 @@ def build_batch_list_pools_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_delete_pool_request( +def build_batch_delete_pool_internal_request( pool_id: str, *, timeout: Optional[int] = None, @@ -229,8 +223,6 @@ def build_batch_delete_pool_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}" path_format_arguments = { @@ -251,7 +243,6 @@ def build_batch_delete_pool_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -277,8 +268,6 @@ def build_batch_pool_exists_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}" path_format_arguments = { @@ -299,7 +288,6 @@ def build_batch_pool_exists_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -317,8 +305,8 @@ def build_batch_get_pool_request( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -380,8 +368,6 @@ def build_batch_update_pool_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}" path_format_arguments = { @@ -403,7 +389,6 @@ def build_batch_update_pool_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -421,8 +406,6 @@ def build_batch_disable_pool_auto_scale_request( # pylint: disable=name-too-lon _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/disableautoscale" path_format_arguments = { @@ -439,7 +422,6 @@ def build_batch_disable_pool_auto_scale_request( # pylint: disable=name-too-lon # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -460,8 +442,6 @@ def build_batch_enable_pool_auto_scale_request( # pylint: disable=name-too-long content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/enableautoscale" path_format_arguments = { @@ -478,12 +458,11 @@ def build_batch_enable_pool_auto_scale_request( # pylint: disable=name-too-long # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") + _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: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -526,7 +505,7 @@ def build_batch_evaluate_pool_auto_scale_request( # pylint: disable=name-too-lo return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_resize_pool_request( +def build_batch_resize_pool_internal_request( pool_id: str, *, timeout: Optional[int] = None, @@ -542,8 +521,6 @@ def build_batch_resize_pool_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/resize" path_format_arguments = { @@ -560,12 +537,11 @@ def build_batch_resize_pool_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") + _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: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -576,7 +552,7 @@ def build_batch_resize_pool_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_stop_pool_resize_request( +def build_batch_stop_pool_resize_internal_request( # pylint: disable=name-too-long pool_id: str, *, timeout: Optional[int] = None, @@ -591,8 +567,6 @@ def build_batch_stop_pool_resize_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/stopresize" path_format_arguments = { @@ -613,7 +587,6 @@ def build_batch_stop_pool_resize_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -632,8 +605,6 @@ def build_batch_replace_pool_properties_request( # pylint: disable=name-too-lon content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/updateproperties" path_format_arguments = { @@ -651,12 +622,11 @@ def build_batch_replace_pool_properties_request( # pylint: disable=name-too-lon if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_remove_nodes_request( +def build_batch_remove_nodes_internal_request( # pylint: disable=name-too-long pool_id: str, *, timeout: Optional[int] = None, @@ -672,8 +642,6 @@ def build_batch_remove_nodes_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/removenodes" path_format_arguments = { @@ -690,12 +658,11 @@ def build_batch_remove_nodes_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") + _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: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -774,7 +741,7 @@ def build_batch_list_pool_node_counts_request( # pylint: disable=name-too-long return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_delete_job_request( +def build_batch_delete_job_internal_request( job_id: str, *, timeout: Optional[int] = None, @@ -790,8 +757,6 @@ def build_batch_delete_job_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}" path_format_arguments = { @@ -814,7 +779,6 @@ def build_batch_delete_job_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -832,8 +796,8 @@ def build_batch_get_job_request( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -895,8 +859,6 @@ def build_batch_update_job_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}" path_format_arguments = { @@ -918,7 +880,6 @@ def build_batch_update_job_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -945,8 +906,6 @@ def build_batch_replace_job_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}" path_format_arguments = { @@ -968,7 +927,6 @@ def build_batch_replace_job_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -979,7 +937,7 @@ def build_batch_replace_job_request( return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_disable_job_request( +def build_batch_disable_job_internal_request( job_id: str, *, timeout: Optional[int] = None, @@ -995,8 +953,6 @@ def build_batch_disable_job_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/disable" path_format_arguments = { @@ -1013,12 +969,11 @@ def build_batch_disable_job_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") + _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: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1029,7 +984,7 @@ def build_batch_disable_job_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_enable_job_request( +def build_batch_enable_job_internal_request( job_id: str, *, timeout: Optional[int] = None, @@ -1044,8 +999,6 @@ def build_batch_enable_job_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/enable" path_format_arguments = { @@ -1066,7 +1019,6 @@ def build_batch_enable_job_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1077,7 +1029,7 @@ def build_batch_enable_job_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_terminate_job_request( +def build_batch_terminate_job_internal_request( # pylint: disable=name-too-long job_id: str, *, timeout: Optional[int] = None, @@ -1094,8 +1046,6 @@ def build_batch_terminate_job_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/terminate" path_format_arguments = { @@ -1114,12 +1064,11 @@ def build_batch_terminate_job_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") + _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: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1138,8 +1087,6 @@ def build_batch_create_job_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs" @@ -1152,7 +1099,6 @@ def build_batch_create_job_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -1163,8 +1109,8 @@ def build_batch_list_jobs_request( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1204,8 +1150,8 @@ def build_batch_list_jobs_from_schedule_request( # pylint: disable=name-too-lon ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1250,7 +1196,7 @@ def build_batch_list_job_preparation_and_release_task_status_request( # pylint: ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1324,8 +1270,6 @@ def build_batch_create_certificate_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/certificates" @@ -1338,7 +1282,6 @@ def build_batch_create_certificate_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -1349,7 +1292,7 @@ def build_batch_list_certificates_request( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1392,8 +1335,6 @@ def build_batch_cancel_certificate_deletion_request( # pylint: disable=name-too _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})/canceldelete" path_format_arguments = { @@ -1411,12 +1352,11 @@ def build_batch_cancel_certificate_deletion_request( # pylint: disable=name-too # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_delete_certificate_request( +def build_batch_delete_certificate_internal_request( # pylint: disable=name-too-long thumbprint_algorithm: str, thumbprint: str, *, @@ -1428,8 +1368,6 @@ def build_batch_delete_certificate_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/certificates(thumbprintAlgorithm={thumbprintAlgorithm},thumbprint={thumbprint})" path_format_arguments = { @@ -1447,7 +1385,6 @@ def build_batch_delete_certificate_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) @@ -1458,7 +1395,7 @@ def build_batch_get_certificate_request( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1506,8 +1443,6 @@ def build_batch_job_schedule_exists_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1528,7 +1463,6 @@ def build_batch_job_schedule_exists_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1539,7 +1473,7 @@ def build_batch_job_schedule_exists_request( return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_delete_job_schedule_request( +def build_batch_delete_job_schedule_internal_request( # pylint: disable=name-too-long job_schedule_id: str, *, timeout: Optional[int] = None, @@ -1555,8 +1489,6 @@ def build_batch_delete_job_schedule_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1579,7 +1511,6 @@ def build_batch_delete_job_schedule_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1597,8 +1528,8 @@ def build_batch_get_job_schedule_request( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -1660,8 +1591,6 @@ def build_batch_update_job_schedule_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1683,7 +1612,6 @@ def build_batch_update_job_schedule_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1710,8 +1638,6 @@ def build_batch_replace_job_schedule_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}" path_format_arguments = { @@ -1733,7 +1659,6 @@ def build_batch_replace_job_schedule_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1759,8 +1684,6 @@ def build_batch_disable_job_schedule_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}/disable" path_format_arguments = { @@ -1781,7 +1704,6 @@ def build_batch_disable_job_schedule_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1807,8 +1729,6 @@ def build_batch_enable_job_schedule_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}/enable" path_format_arguments = { @@ -1829,7 +1749,6 @@ def build_batch_enable_job_schedule_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1840,7 +1759,7 @@ def build_batch_enable_job_schedule_request( return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_terminate_job_schedule_request( # pylint: disable=name-too-long +def build_batch_terminate_job_schedule_internal_request( # pylint: disable=name-too-long job_schedule_id: str, *, timeout: Optional[int] = None, @@ -1856,8 +1775,6 @@ def build_batch_terminate_job_schedule_request( # pylint: disable=name-too-long _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules/{jobScheduleId}/terminate" path_format_arguments = { @@ -1880,7 +1797,6 @@ def build_batch_terminate_job_schedule_request( # pylint: disable=name-too-long _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -1899,8 +1815,6 @@ def build_batch_create_job_schedule_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobschedules" @@ -1913,7 +1827,6 @@ def build_batch_create_job_schedule_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -1924,8 +1837,8 @@ def build_batch_list_job_schedules_request( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1966,8 +1879,6 @@ def build_batch_create_task_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks" path_format_arguments = { @@ -1985,7 +1896,6 @@ def build_batch_create_task_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -1997,8 +1907,8 @@ def build_batch_list_tasks_request( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -2084,8 +1994,6 @@ def build_batch_delete_task_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}" path_format_arguments = { @@ -2107,7 +2015,6 @@ def build_batch_delete_task_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -2126,8 +2033,8 @@ def build_batch_get_task_request( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -2191,8 +2098,6 @@ def build_batch_replace_task_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}" path_format_arguments = { @@ -2215,7 +2120,6 @@ def build_batch_replace_task_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -2232,7 +2136,7 @@ def build_batch_list_sub_tasks_request( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -2281,8 +2185,6 @@ def build_batch_terminate_task_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/terminate" path_format_arguments = { @@ -2304,7 +2206,6 @@ def build_batch_terminate_task_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -2331,8 +2232,6 @@ def build_batch_reactivate_task_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/reactivate" path_format_arguments = { @@ -2354,7 +2253,6 @@ def build_batch_reactivate_task_request( _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if_match = prep_if_match(etag, match_condition) if if_match is not None: _headers["If-Match"] = _SERIALIZER.header("if_match", if_match, "str") @@ -2379,8 +2277,6 @@ def build_batch_delete_task_file_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" path_format_arguments = { @@ -2401,7 +2297,6 @@ def build_batch_delete_task_file_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) @@ -2453,7 +2348,7 @@ def build_batch_get_task_file_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_get_task_file_properties_request( # pylint: disable=name-too-long +def build_batch_get_task_file_properties_internal_request( # pylint: disable=name-too-long job_id: str, task_id: str, file_path: str, @@ -2468,8 +2363,6 @@ def build_batch_get_task_file_properties_request( # pylint: disable=name-too-lo _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/jobs/{jobId}/tasks/{taskId}/files/{filePath}" path_format_arguments = { @@ -2492,7 +2385,6 @@ def build_batch_get_task_file_properties_request( # pylint: disable=name-too-lo _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) @@ -2555,8 +2447,6 @@ def build_batch_create_node_user_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/users" path_format_arguments = { @@ -2575,7 +2465,6 @@ def build_batch_create_node_user_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2593,8 +2482,6 @@ def build_batch_delete_node_user_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/users/{userName}" path_format_arguments = { @@ -2613,7 +2500,6 @@ def build_batch_delete_node_user_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) @@ -2632,8 +2518,6 @@ def build_batch_replace_node_user_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/users/{userName}" path_format_arguments = { @@ -2653,7 +2537,6 @@ def build_batch_replace_node_user_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) @@ -2664,7 +2547,7 @@ def build_batch_get_node_request( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -2697,7 +2580,7 @@ def build_batch_get_node_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_reboot_node_request( +def build_batch_reboot_node_internal_request( pool_id: str, node_id: str, *, @@ -2710,8 +2593,6 @@ def build_batch_reboot_node_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/reboot" path_format_arguments = { @@ -2730,12 +2611,11 @@ def build_batch_reboot_node_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_start_node_request( +def build_batch_start_node_internal_request( pool_id: str, node_id: str, *, @@ -2747,8 +2627,6 @@ def build_batch_start_node_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/start" path_format_arguments = { @@ -2766,12 +2644,11 @@ def build_batch_start_node_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_reimage_node_request( +def build_batch_reimage_node_internal_request( # pylint: disable=name-too-long pool_id: str, node_id: str, *, @@ -2784,8 +2661,6 @@ def build_batch_reimage_node_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/reimage" path_format_arguments = { @@ -2804,12 +2679,11 @@ def build_batch_reimage_node_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_deallocate_node_request( +def build_batch_deallocate_node_internal_request( # pylint: disable=name-too-long pool_id: str, node_id: str, *, @@ -2822,8 +2696,6 @@ def build_batch_deallocate_node_request( content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/deallocate" path_format_arguments = { @@ -2842,7 +2714,6 @@ def build_batch_deallocate_node_request( if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2860,8 +2731,6 @@ def build_batch_disable_node_scheduling_request( # pylint: disable=name-too-lon content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/disablescheduling" path_format_arguments = { @@ -2880,7 +2749,6 @@ def build_batch_disable_node_scheduling_request( # pylint: disable=name-too-lon if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") _headers["content-type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -2897,8 +2765,6 @@ def build_batch_enable_node_scheduling_request( # pylint: disable=name-too-long _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/enablescheduling" path_format_arguments = { @@ -2916,7 +2782,6 @@ def build_batch_enable_node_scheduling_request( # pylint: disable=name-too-long # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -3002,7 +2867,7 @@ def build_batch_list_nodes_request( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -3045,7 +2910,7 @@ def build_batch_get_node_extension_request( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -3086,7 +2951,7 @@ def build_batch_list_node_extensions_request( timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -3135,8 +3000,6 @@ def build_batch_delete_node_file_request( _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" path_format_arguments = { @@ -3157,7 +3020,6 @@ def build_batch_delete_node_file_request( # Construct headers if ocpdate is not None: _headers["ocp-date"] = _SERIALIZER.header("ocpdate", ocpdate, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) @@ -3209,7 +3071,7 @@ def build_batch_get_node_file_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_batch_get_node_file_properties_request( # pylint: disable=name-too-long +def build_batch_get_node_file_properties_internal_request( # pylint: disable=name-too-long pool_id: str, node_id: str, file_path: str, @@ -3224,8 +3086,6 @@ def build_batch_get_node_file_properties_request( # pylint: disable=name-too-lo _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01.20.0")) - accept = _headers.pop("Accept", "application/json") - # Construct URL _url = "/pools/{poolId}/nodes/{nodeId}/files/{filePath}" path_format_arguments = { @@ -3248,7 +3108,6 @@ def build_batch_get_node_file_properties_request( # pylint: disable=name-too-lo _headers["If-Modified-Since"] = _SERIALIZER.header("if_modified_since", if_modified_since, "rfc-1123") if if_unmodified_since is not None: _headers["If-Unmodified-Since"] = _SERIALIZER.header("if_unmodified_since", if_unmodified_since, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) @@ -3298,7 +3157,9 @@ def build_batch_list_node_files_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class BatchClientOperationsMixin(BatchClientMixinABC): # pylint: disable=too-many-public-methods +class _BatchClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], BatchClientConfiguration] +): @distributed_trace def list_applications( @@ -3308,7 +3169,7 @@ def list_applications( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, **kwargs: Any - ) -> Iterable["_models.BatchApplication"]: + ) -> ItemPaged["_models.BatchApplication"]: """Lists all of the applications available in the specified Account. This operation returns only Applications and versions that are available for @@ -3335,7 +3196,7 @@ def list_applications( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchApplication]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchApplication]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3387,7 +3248,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchApplication], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchApplication], 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) @@ -3403,7 +3264,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3481,7 +3342,7 @@ def get_application( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3511,7 +3372,7 @@ def list_pool_usage_metrics( endtime: Optional[datetime.datetime] = None, filter: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.BatchPoolUsageMetrics"]: + ) -> ItemPaged["_models.BatchPoolUsageMetrics"]: """Lists the usage metrics, aggregated by Pool across individual time intervals, for the specified Account. @@ -3544,7 +3405,7 @@ def list_pool_usage_metrics( last aggregation interval currently available. Default value is None. :paramtype endtime: ~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 + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics `_. Default value is None. :paramtype filter: str @@ -3555,7 +3416,7 @@ def list_pool_usage_metrics( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchPoolUsageMetrics]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchPoolUsageMetrics]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3610,7 +3471,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchPoolUsageMetrics], deserialized["value"]) + 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) @@ -3626,7 +3487,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3636,7 +3497,7 @@ def get_next(next_link=None): @distributed_trace def create_pool( # pylint: disable=inconsistent-return-statements self, - pool: _models.BatchPoolCreateContent, + pool: _models.BatchPoolCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -3649,7 +3510,7 @@ def create_pool( # pylint: disable=inconsistent-return-statements to Microsoft Support engineers. :param pool: The Pool to be created. Required. - :type pool: ~azure.batch.models.BatchPoolCreateContent + :type pool: ~azure.batch.models.BatchPoolCreateOptions :keyword 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. @@ -3703,7 +3564,7 @@ def create_pool( # pylint: disable=inconsistent-return-statements if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3724,10 +3585,10 @@ def list_pools( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchPool"]: + ) -> ItemPaged["_models.BatchPool"]: """Lists all of the Pools which be mounted. Lists all of the Pools which be mounted. @@ -3759,7 +3620,7 @@ def list_pools( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchPool]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchPool]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3814,7 +3675,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchPool], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchPool], 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) @@ -3830,7 +3691,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3838,7 +3699,7 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def delete_pool( # pylint: disable=inconsistent-return-statements + def _delete_pool_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, *, @@ -3913,7 +3774,7 @@ def delete_pool( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_pool_request( + _request = build_batch_delete_pool_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -3939,7 +3800,7 @@ def delete_pool( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4038,7 +3899,7 @@ def pool_exists( if response.status_code not in [200, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4061,8 +3922,8 @@ def get_pool( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -4154,7 +4015,7 @@ def get_pool( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4177,7 +4038,7 @@ def get_pool( def update_pool( # pylint: disable=inconsistent-return-statements self, pool_id: str, - pool: _models.BatchPoolUpdateContent, + pool: _models.BatchPoolUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4196,7 +4057,7 @@ def update_pool( # pylint: disable=inconsistent-return-statements :param pool_id: The ID of the Pool to get. Required. :type pool_id: str :param pool: The pool properties to update. Required. - :type pool: ~azure.batch.models.BatchPoolUpdateContent + :type pool: ~azure.batch.models.BatchPoolUpdateOptions :keyword 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. @@ -4276,7 +4137,7 @@ def update_pool( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4346,7 +4207,7 @@ def disable_pool_auto_scale( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4363,7 +4224,7 @@ def disable_pool_auto_scale( # pylint: disable=inconsistent-return-statements def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements self, pool_id: str, - content: _models.BatchPoolEnableAutoScaleContent, + enable_auto_scale_options: _models.BatchPoolEnableAutoScaleOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4384,8 +4245,8 @@ def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements :param pool_id: The ID of the Pool to get. Required. :type pool_id: str - :param content: The options to use for enabling automatic scaling. Required. - :type content: ~azure.batch.models.BatchPoolEnableAutoScaleContent + :param enable_auto_scale_options: The options to use for enabling automatic scaling. Required. + :type enable_auto_scale_options: ~azure.batch.models.BatchPoolEnableAutoScaleOptions :keyword 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. @@ -4435,7 +4296,7 @@ def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(enable_auto_scale_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_enable_pool_auto_scale_request( pool_id=pool_id, @@ -4465,7 +4326,7 @@ def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4482,7 +4343,7 @@ def enable_pool_auto_scale( # pylint: disable=inconsistent-return-statements def evaluate_pool_auto_scale( self, pool_id: str, - content: _models.BatchPoolEvaluateAutoScaleContent, + evaluate_auto_scale_options: _models.BatchPoolEvaluateAutoScaleOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4497,8 +4358,9 @@ def evaluate_pool_auto_scale( :param pool_id: The ID of the Pool on which to evaluate the automatic scaling formula. Required. :type pool_id: str - :param content: The options to use for evaluating the automatic scaling formula. Required. - :type content: ~azure.batch.models.BatchPoolEvaluateAutoScaleContent + :param evaluate_auto_scale_options: The options to use for evaluating the automatic scaling + formula. Required. + :type evaluate_auto_scale_options: ~azure.batch.models.BatchPoolEvaluateAutoScaleOptions :keyword 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. @@ -4527,7 +4389,7 @@ def evaluate_pool_auto_scale( ) cls: ClsType[_models.AutoScaleRun] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluate_auto_scale_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_evaluate_pool_auto_scale_request( pool_id=pool_id, @@ -4558,7 +4420,7 @@ def evaluate_pool_auto_scale( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4579,10 +4441,10 @@ def evaluate_pool_auto_scale( return deserialized # type: ignore @distributed_trace - def resize_pool( # pylint: disable=inconsistent-return-statements + def _resize_pool_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, - content: _models.BatchPoolResizeContent, + resize_options: _models.BatchPoolResizeOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4604,8 +4466,8 @@ def resize_pool( # pylint: disable=inconsistent-return-statements :param pool_id: The ID of the Pool to get. Required. :type pool_id: str - :param content: The options to use for resizing the pool. Required. - :type content: ~azure.batch.models.BatchPoolResizeContent + :param resize_options: The options to use for resizing the pool. Required. + :type resize_options: ~azure.batch.models.BatchPoolResizeOptions :keyword 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. @@ -4655,9 +4517,9 @@ def resize_pool( # pylint: disable=inconsistent-return-statements ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(resize_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_batch_resize_pool_request( + _request = build_batch_resize_pool_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -4685,7 +4547,7 @@ def resize_pool( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4699,7 +4561,7 @@ def resize_pool( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def stop_pool_resize( # pylint: disable=inconsistent-return-statements + def _stop_pool_resize_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, *, @@ -4769,7 +4631,7 @@ def stop_pool_resize( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_stop_pool_resize_request( + _request = build_batch_stop_pool_resize_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -4795,7 +4657,7 @@ def stop_pool_resize( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4812,7 +4674,7 @@ def stop_pool_resize( # pylint: disable=inconsistent-return-statements def replace_pool_properties( # pylint: disable=inconsistent-return-statements self, pool_id: str, - pool: _models.BatchPoolReplaceContent, + pool: _models.BatchPoolReplaceOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4827,7 +4689,7 @@ def replace_pool_properties( # pylint: disable=inconsistent-return-statements :param pool_id: The ID of the Pool to update. Required. :type pool_id: str :param pool: The options to use for replacing properties on the pool. Required. - :type pool: ~azure.batch.models.BatchPoolReplaceContent + :type pool: ~azure.batch.models.BatchPoolReplaceOptions :keyword 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. @@ -4882,7 +4744,7 @@ def replace_pool_properties( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4896,10 +4758,10 @@ def replace_pool_properties( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def remove_nodes( # pylint: disable=inconsistent-return-statements + def _remove_nodes_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, - content: _models.BatchNodeRemoveContent, + remove_options: _models.BatchNodeRemoveOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4917,8 +4779,8 @@ def remove_nodes( # pylint: disable=inconsistent-return-statements :param pool_id: The ID of the Pool to get. Required. :type pool_id: str - :param content: The options to use for removing the node. Required. - :type content: ~azure.batch.models.BatchNodeRemoveContent + :param remove_options: The options to use for removing the node. Required. + :type remove_options: ~azure.batch.models.BatchNodeRemoveOptions :keyword 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. @@ -4968,9 +4830,9 @@ def remove_nodes( # pylint: disable=inconsistent-return-statements ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(remove_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_batch_remove_nodes_request( + _request = build_batch_remove_nodes_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -4998,7 +4860,7 @@ def remove_nodes( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5020,7 +4882,7 @@ def list_supported_images( max_results: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.BatchSupportedImage"]: + ) -> ItemPaged["_models.BatchSupportedImage"]: """Lists all Virtual Machine Images supported by the Azure Batch service. Lists all Virtual Machine Images supported by the Azure Batch service. @@ -5048,7 +4910,7 @@ def list_supported_images( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchSupportedImage]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchSupportedImage]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -5101,7 +4963,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchSupportedImage], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchSupportedImage], 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) @@ -5117,7 +4979,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -5133,7 +4995,7 @@ def list_pool_node_counts( max_results: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any - ) -> Iterable["_models.BatchPoolNodeCounts"]: + ) -> ItemPaged["_models.BatchPoolNodeCounts"]: """Gets the number of Compute Nodes in each state, grouped by Pool. Note that the numbers returned may not always be up to date. If you need exact node counts, use a list query. @@ -5161,7 +5023,7 @@ def list_pool_node_counts( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchPoolNodeCounts]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchPoolNodeCounts]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -5214,7 +5076,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchPoolNodeCounts], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchPoolNodeCounts], 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) @@ -5230,7 +5092,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -5238,7 +5100,7 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def delete_job( # pylint: disable=inconsistent-return-statements + def _delete_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, *, @@ -5313,7 +5175,7 @@ def delete_job( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_job_request( + _request = build_batch_delete_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -5340,7 +5202,7 @@ def delete_job( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5359,8 +5221,8 @@ def get_job( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -5454,7 +5316,7 @@ def get_job( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5477,7 +5339,7 @@ def get_job( def update_job( # pylint: disable=inconsistent-return-statements self, job_id: str, - job: _models.BatchJobUpdateContent, + job: _models.BatchJobUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -5496,7 +5358,7 @@ def update_job( # pylint: disable=inconsistent-return-statements :param job_id: The ID of the Job whose properties you want to update. Required. :type job_id: str :param job: The options to use for updating the Job. Required. - :type job: ~azure.batch.models.BatchJobUpdateContent + :type job: ~azure.batch.models.BatchJobUpdateOptions :keyword 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. @@ -5576,7 +5438,7 @@ def update_job( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5692,7 +5554,7 @@ def replace_job( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5706,10 +5568,10 @@ def replace_job( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def disable_job( # pylint: disable=inconsistent-return-statements + def _disable_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, - content: _models.BatchJobDisableContent, + disable_options: _models.BatchJobDisableOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -5732,8 +5594,8 @@ def disable_job( # pylint: disable=inconsistent-return-statements :param job_id: The ID of the Job to disable. Required. :type job_id: str - :param content: The options to use for disabling the Job. Required. - :type content: ~azure.batch.models.BatchJobDisableContent + :param disable_options: The options to use for disabling the Job. Required. + :type disable_options: ~azure.batch.models.BatchJobDisableOptions :keyword 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. @@ -5783,9 +5645,9 @@ def disable_job( # pylint: disable=inconsistent-return-statements ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(disable_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_batch_disable_job_request( + _request = build_batch_disable_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -5813,7 +5675,7 @@ def disable_job( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5827,7 +5689,7 @@ def disable_job( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def enable_job( # pylint: disable=inconsistent-return-statements + def _enable_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, *, @@ -5896,7 +5758,7 @@ def enable_job( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_enable_job_request( + _request = build_batch_enable_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -5922,7 +5784,7 @@ def enable_job( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5936,10 +5798,10 @@ def enable_job( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def terminate_job( # pylint: disable=inconsistent-return-statements + def _terminate_job_internal( # pylint: disable=inconsistent-return-statements self, job_id: str, - parameters: Optional[_models.BatchJobTerminateContent] = None, + options: Optional[_models.BatchJobTerminateOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -5961,8 +5823,8 @@ def terminate_job( # pylint: disable=inconsistent-return-statements :param job_id: The ID of the Job to terminate. Required. :type job_id: str - :param parameters: The options to use for terminating the Job. Default value is None. - :type parameters: ~azure.batch.models.BatchJobTerminateContent + :param options: The options to use for terminating the Job. Default value is None. + :type options: ~azure.batch.models.BatchJobTerminateOptions :keyword 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. @@ -6010,17 +5872,18 @@ def terminate_job( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_terminate_job_request( + _request = build_batch_terminate_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -6049,7 +5912,7 @@ def terminate_job( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6065,7 +5928,7 @@ def terminate_job( # pylint: disable=inconsistent-return-statements @distributed_trace def create_job( # pylint: disable=inconsistent-return-statements self, - job: _models.BatchJobCreateContent, + job: _models.BatchJobCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -6084,7 +5947,7 @@ def create_job( # pylint: disable=inconsistent-return-statements engineers. :param job: The Job to be created. Required. - :type job: ~azure.batch.models.BatchJobCreateContent + :type job: ~azure.batch.models.BatchJobCreateOptions :keyword 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. @@ -6138,7 +6001,7 @@ def create_job( # pylint: disable=inconsistent-return-statements if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6159,10 +6022,10 @@ def list_jobs( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchJob"]: + ) -> ItemPaged["_models.BatchJob"]: """Lists all of the Jobs in the specified Account. Lists all of the Jobs in the specified Account. @@ -6194,7 +6057,7 @@ def list_jobs( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJob]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6249,7 +6112,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJob], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchJob], 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) @@ -6265,7 +6128,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -6281,10 +6144,10 @@ def list_jobs_from_schedule( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchJob"]: + ) -> ItemPaged["_models.BatchJob"]: """Lists the Jobs that have been created under the specified Job Schedule. Lists the Jobs that have been created under the specified Job Schedule. @@ -6304,7 +6167,7 @@ def list_jobs_from_schedule( applications can be returned. Default value is None. :paramtype max_results: int :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-jobs-in-a-job-schedule + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule `_. Default value is None. :paramtype filter: str @@ -6319,7 +6182,7 @@ def list_jobs_from_schedule( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJob]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6375,7 +6238,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJob], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchJob], 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) @@ -6391,7 +6254,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -6407,9 +6270,9 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchJobPreparationAndReleaseTaskStatus"]: + ) -> ItemPaged["_models.BatchJobPreparationAndReleaseTaskStatus"]: """Lists the execution status of the Job Preparation and Job Release Task for the specified Job across the Compute Nodes where the Job has run. @@ -6434,7 +6297,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo applications can be returned. Default value is None. :paramtype max_results: int :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-job-preparation-and-release-status + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status `_. Default value is None. :paramtype filter: str @@ -6448,7 +6311,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJobPreparationAndReleaseTaskStatus]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJobPreparationAndReleaseTaskStatus]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6503,7 +6366,9 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJobPreparationAndReleaseTaskStatus], deserialized["value"]) + list_of_elem = _deserialize( + list[_models.BatchJobPreparationAndReleaseTaskStatus], 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) @@ -6519,7 +6384,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -6591,7 +6456,7 @@ def get_job_task_counts( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6678,7 +6543,7 @@ def create_certificate( # pylint: disable=inconsistent-return-statements if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6699,9 +6564,9 @@ def list_certificates( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchCertificate"]: + ) -> ItemPaged["_models.BatchCertificate"]: """Lists all of the Certificates that have been added to the specified Account. Lists all of the Certificates that have been added to the specified Account. @@ -6718,7 +6583,7 @@ def list_certificates( applications can be returned. Default value is None. :paramtype max_results: int :keyword filter: An OData $filter clause. For more information on constructing this filter, see - `https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates + `https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates `_. Default value is None. :paramtype filter: str @@ -6731,7 +6596,7 @@ def list_certificates( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchCertificate]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchCertificate]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6785,7 +6650,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchCertificate], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchCertificate], 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) @@ -6801,7 +6666,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -6881,7 +6746,7 @@ def cancel_certificate_deletion( # pylint: disable=inconsistent-return-statemen if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6895,7 +6760,7 @@ def cancel_certificate_deletion( # pylint: disable=inconsistent-return-statemen return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def delete_certificate( # pylint: disable=inconsistent-return-statements + def _delete_certificate_internal( # pylint: disable=inconsistent-return-statements self, thumbprint_algorithm: str, thumbprint: str, @@ -6946,7 +6811,7 @@ def delete_certificate( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_certificate_request( + _request = build_batch_delete_certificate_internal_request( thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, timeout=timeout, @@ -6969,7 +6834,7 @@ def delete_certificate( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6989,9 +6854,9 @@ def get_certificate( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> _models.GetCertificateResponse: + ) -> _models.BatchCertificate: """Gets information about the specified Certificate. :param thumbprint_algorithm: The algorithm used to derive the thumbprint parameter. This must @@ -7009,8 +6874,8 @@ def get_certificate( :paramtype ocpdate: ~datetime.datetime :keyword select: An OData $select clause. Default value is None. :paramtype select: list[str] - :return: GetCertificateResponse. The GetCertificateResponse is compatible with MutableMapping - :rtype: ~azure.batch.models.GetCertificateResponse + :return: BatchCertificate. The BatchCertificate is compatible with MutableMapping + :rtype: ~azure.batch.models.BatchCertificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7024,7 +6889,7 @@ def get_certificate( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.GetCertificateResponse] = kwargs.pop("cls", None) + cls: ClsType[_models.BatchCertificate] = kwargs.pop("cls", None) _request = build_batch_get_certificate_request( thumbprint_algorithm=thumbprint_algorithm, @@ -7055,7 +6920,7 @@ def get_certificate( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7067,7 +6932,7 @@ def get_certificate( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.GetCertificateResponse, response.json()) + deserialized = _deserialize(_models.BatchCertificate, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -7165,7 +7030,7 @@ def job_schedule_exists( if response.status_code not in [200, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7180,7 +7045,7 @@ def job_schedule_exists( return 200 <= response.status_code <= 299 @distributed_trace - def delete_job_schedule( # pylint: disable=inconsistent-return-statements + def _delete_job_schedule_internal( # pylint: disable=inconsistent-return-statements self, job_schedule_id: str, *, @@ -7252,7 +7117,7 @@ def delete_job_schedule( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_job_schedule_request( + _request = build_batch_delete_job_schedule_internal_request( job_schedule_id=job_schedule_id, timeout=timeout, ocpdate=ocpdate, @@ -7279,7 +7144,7 @@ def delete_job_schedule( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7298,8 +7163,8 @@ def get_job_schedule( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -7391,7 +7256,7 @@ def get_job_schedule( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7414,7 +7279,7 @@ def get_job_schedule( def update_job_schedule( # pylint: disable=inconsistent-return-statements self, job_schedule_id: str, - job_schedule: _models.BatchJobScheduleUpdateContent, + job_schedule: _models.BatchJobScheduleUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -7435,7 +7300,7 @@ def update_job_schedule( # pylint: disable=inconsistent-return-statements :param job_schedule_id: The ID of the Job Schedule to update. Required. :type job_schedule_id: str :param job_schedule: The options to use for updating the Job Schedule. Required. - :type job_schedule: ~azure.batch.models.BatchJobScheduleUpdateContent + :type job_schedule: ~azure.batch.models.BatchJobScheduleUpdateOptions :keyword 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. @@ -7515,7 +7380,7 @@ def update_job_schedule( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7633,7 +7498,7 @@ def replace_job_schedule( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7737,7 +7602,7 @@ def disable_job_schedule( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7841,7 +7706,7 @@ def enable_job_schedule( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7855,7 +7720,7 @@ def enable_job_schedule( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def terminate_job_schedule( # pylint: disable=inconsistent-return-statements + def _terminate_job_schedule_internal( # pylint: disable=inconsistent-return-statements self, job_schedule_id: str, *, @@ -7924,7 +7789,7 @@ def terminate_job_schedule( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_terminate_job_schedule_request( + _request = build_batch_terminate_job_schedule_internal_request( job_schedule_id=job_schedule_id, timeout=timeout, ocpdate=ocpdate, @@ -7951,7 +7816,7 @@ def terminate_job_schedule( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7967,7 +7832,7 @@ def terminate_job_schedule( # pylint: disable=inconsistent-return-statements @distributed_trace def create_job_schedule( # pylint: disable=inconsistent-return-statements self, - job_schedule: _models.BatchJobScheduleCreateContent, + job_schedule: _models.BatchJobScheduleCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -7978,7 +7843,7 @@ def create_job_schedule( # pylint: disable=inconsistent-return-statements Creates a Job Schedule to the specified Account. :param job_schedule: The Job Schedule to be created. Required. - :type job_schedule: ~azure.batch.models.BatchJobScheduleCreateContent + :type job_schedule: ~azure.batch.models.BatchJobScheduleCreateOptions :keyword 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. @@ -8032,7 +7897,7 @@ def create_job_schedule( # pylint: disable=inconsistent-return-statements if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8053,10 +7918,10 @@ def list_job_schedules( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchJobSchedule"]: + ) -> ItemPaged["_models.BatchJobSchedule"]: """Lists all of the Job Schedules in the specified Account. Lists all of the Job Schedules in the specified Account. @@ -8088,7 +7953,7 @@ def list_job_schedules( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJobSchedule]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJobSchedule]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -8143,7 +8008,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJobSchedule], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchJobSchedule], 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) @@ -8159,7 +8024,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -8170,7 +8035,7 @@ def get_next(next_link=None): def create_task( # pylint: disable=inconsistent-return-statements self, job_id: str, - task: _models.BatchTaskCreateContent, + task: _models.BatchTaskCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -8185,7 +8050,7 @@ def create_task( # pylint: disable=inconsistent-return-statements :param job_id: The ID of the Job to which the Task is to be created. Required. :type job_id: str :param task: The Task to be created. Required. - :type task: ~azure.batch.models.BatchTaskCreateContent + :type task: ~azure.batch.models.BatchTaskCreateOptions :keyword 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. @@ -8240,7 +8105,7 @@ def create_task( # pylint: disable=inconsistent-return-statements if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8262,10 +8127,10 @@ def list_tasks( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchTask"]: + ) -> ItemPaged["_models.BatchTask"]: """Lists all of the Tasks that are associated with the specified Job. For multi-instance Tasks, information such as affinityId, executionInfo and @@ -8301,7 +8166,7 @@ def list_tasks( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchTask]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchTask]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -8357,7 +8222,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchTask], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchTask], 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) @@ -8373,7 +8238,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -8389,7 +8254,7 @@ def create_task_collection( timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, **kwargs: Any - ) -> _models.BatchTaskAddCollectionResult: + ) -> _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 @@ -8419,9 +8284,9 @@ def create_task_collection( current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. :paramtype ocpdate: ~datetime.datetime - :return: BatchTaskAddCollectionResult. The BatchTaskAddCollectionResult is compatible with - MutableMapping - :rtype: ~azure.batch.models.BatchTaskAddCollectionResult + :return: BatchCreateTaskCollectionResult. The BatchCreateTaskCollectionResult is compatible + with MutableMapping + :rtype: ~azure.batch.models.BatchCreateTaskCollectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8438,7 +8303,7 @@ def create_task_collection( content_type: str = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) - cls: ClsType[_models.BatchTaskAddCollectionResult] = kwargs.pop("cls", None) + cls: ClsType[_models.BatchCreateTaskCollectionResult] = kwargs.pop("cls", None) _content = json.dumps(task_collection, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -8471,7 +8336,7 @@ def create_task_collection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8483,7 +8348,7 @@ def create_task_collection( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.BatchTaskAddCollectionResult, response.json()) + deserialized = _deserialize(_models.BatchCreateTaskCollectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -8589,7 +8454,7 @@ def delete_task( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8609,8 +8474,8 @@ def get_task( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -8709,7 +8574,7 @@ def get_task( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8832,7 +8697,7 @@ def replace_task( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8853,9 +8718,9 @@ def list_sub_tasks( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchSubtask"]: + ) -> ItemPaged["_models.BatchSubtask"]: """Lists all of the subtasks that are associated with the specified multi-instance Task. @@ -8882,7 +8747,7 @@ def list_sub_tasks( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchSubtask]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchSubtask]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -8936,7 +8801,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchSubtask], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchSubtask], 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) @@ -8952,7 +8817,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -9056,7 +8921,7 @@ def terminate_task( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9171,7 +9036,7 @@ def reactivate_task( # pylint: disable=inconsistent-return-statements if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9262,7 +9127,7 @@ def delete_task_file( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9365,7 +9230,7 @@ def get_task_file( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9389,8 +9254,6 @@ def get_task_file( return deserialized # type: ignore - # manually renamed - # rename will be through typespec in next version @distributed_trace def _get_task_file_properties_internal( self, @@ -9447,7 +9310,7 @@ def _get_task_file_properties_internal( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_get_task_file_properties_request( + _request = build_batch_get_task_file_properties_internal_request( job_id=job_id, task_id=task_id, file_path=file_path, @@ -9473,7 +9336,7 @@ def _get_task_file_properties_internal( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9505,7 +9368,7 @@ def list_task_files( filter: Optional[str] = None, recursive: Optional[bool] = None, **kwargs: Any - ) -> Iterable["_models.BatchNodeFile"]: + ) -> ItemPaged["_models.BatchNodeFile"]: """Lists the files in a Task's directory on its Compute Node. Lists the files in a Task's directory on its Compute Node. @@ -9541,7 +9404,7 @@ def list_task_files( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNodeFile]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNodeFile]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -9597,7 +9460,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNodeFile], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNodeFile], 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) @@ -9613,7 +9476,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -9625,7 +9488,7 @@ def create_node_user( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - user: _models.BatchNodeUserCreateContent, + user: _models.BatchNodeUserCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -9641,7 +9504,7 @@ def create_node_user( # pylint: disable=inconsistent-return-statements :param node_id: The ID of the machine on which you want to create a user Account. Required. :type node_id: str :param user: The options to use for creating the user. Required. - :type user: ~azure.batch.models.BatchNodeUserCreateContent + :type user: ~azure.batch.models.BatchNodeUserCreateOptions :keyword 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. @@ -9697,7 +9560,7 @@ def create_node_user( # pylint: disable=inconsistent-return-statements if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9781,7 +9644,7 @@ def delete_node_user( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9797,7 +9660,7 @@ def replace_node_user( # pylint: disable=inconsistent-return-statements pool_id: str, node_id: str, user_name: str, - content: _models.BatchNodeUserUpdateContent, + update_options: _models.BatchNodeUserUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -9816,8 +9679,8 @@ def replace_node_user( # pylint: disable=inconsistent-return-statements :type node_id: str :param user_name: The name of the user Account to update. Required. :type user_name: str - :param content: The options to use for updating the user. Required. - :type content: ~azure.batch.models.BatchNodeUserUpdateContent + :param update_options: The options to use for updating the user. Required. + :type update_options: ~azure.batch.models.BatchNodeUserUpdateOptions :keyword 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. @@ -9846,7 +9709,7 @@ def replace_node_user( # pylint: disable=inconsistent-return-statements ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(update_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_replace_node_user_request( pool_id=pool_id, @@ -9874,7 +9737,7 @@ def replace_node_user( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9895,7 +9758,7 @@ def get_node( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> _models.BatchNode: """Gets information about the specified Compute Node. @@ -9962,7 +9825,7 @@ def get_node( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -9982,11 +9845,11 @@ def get_node( return deserialized # type: ignore @distributed_trace - def reboot_node( # pylint: disable=inconsistent-return-statements + def _reboot_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeRebootContent] = None, + options: Optional[_models.BatchNodeRebootOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -10000,8 +9863,8 @@ def reboot_node( # pylint: disable=inconsistent-return-statements :type pool_id: str :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str - :param parameters: The options to use for rebooting the Compute Node. Default value is None. - :type parameters: ~azure.batch.models.BatchNodeRebootContent + :param options: The options to use for rebooting the Compute Node. Default value is None. + :type options: ~azure.batch.models.BatchNodeRebootOptions :keyword 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. @@ -10025,17 +9888,18 @@ def reboot_node( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_reboot_node_request( + _request = build_batch_reboot_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -10060,7 +9924,7 @@ def reboot_node( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10074,7 +9938,7 @@ def reboot_node( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def start_node( # pylint: disable=inconsistent-return-statements + def _start_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, @@ -10116,7 +9980,7 @@ def start_node( # pylint: disable=inconsistent-return-statements cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_start_node_request( + _request = build_batch_start_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -10139,7 +10003,7 @@ def start_node( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10153,11 +10017,11 @@ def start_node( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def reimage_node( # pylint: disable=inconsistent-return-statements + def _reimage_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeReimageContent] = None, + options: Optional[_models.BatchNodeReimageOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -10173,8 +10037,8 @@ def reimage_node( # pylint: disable=inconsistent-return-statements :type pool_id: str :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str - :param parameters: The options to use for reimaging the Compute Node. Default value is None. - :type parameters: ~azure.batch.models.BatchNodeReimageContent + :param options: The options to use for reimaging the Compute Node. Default value is None. + :type options: ~azure.batch.models.BatchNodeReimageOptions :keyword 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. @@ -10198,17 +10062,18 @@ def reimage_node( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_reimage_node_request( + _request = build_batch_reimage_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -10233,7 +10098,7 @@ def reimage_node( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10247,11 +10112,11 @@ def reimage_node( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace - def deallocate_node( # pylint: disable=inconsistent-return-statements + def _deallocate_node_internal( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeDeallocateContent] = None, + options: Optional[_models.BatchNodeDeallocateOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -10265,8 +10130,8 @@ def deallocate_node( # pylint: disable=inconsistent-return-statements :type pool_id: str :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str - :param parameters: The options to use for deallocating the Compute Node. Default value is None. - :type parameters: ~azure.batch.models.BatchNodeDeallocateContent + :param options: The options to use for deallocating the Compute Node. Default value is None. + :type options: ~azure.batch.models.BatchNodeDeallocateOptions :keyword 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. @@ -10290,17 +10155,18 @@ def deallocate_node( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_deallocate_node_request( + _request = build_batch_deallocate_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -10325,7 +10191,7 @@ def deallocate_node( # pylint: disable=inconsistent-return-statements if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10343,7 +10209,7 @@ def disable_node_scheduling( # pylint: disable=inconsistent-return-statements self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeDisableSchedulingContent] = None, + options: Optional[_models.BatchNodeDisableSchedulingOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -10359,9 +10225,9 @@ def disable_node_scheduling( # pylint: disable=inconsistent-return-statements :param node_id: The ID of the Compute Node on which you want to disable Task scheduling. Required. :type node_id: str - :param parameters: The options to use for disabling scheduling on the Compute Node. Default - value is None. - :type parameters: ~azure.batch.models.BatchNodeDisableSchedulingContent + :param options: The options to use for disabling scheduling on the Compute Node. Default value + is None. + :type options: ~azure.batch.models.BatchNodeDisableSchedulingOptions :keyword 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. @@ -10385,13 +10251,14 @@ def disable_node_scheduling( # pylint: disable=inconsistent-return-statements _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None @@ -10420,7 +10287,7 @@ def disable_node_scheduling( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10501,7 +10368,7 @@ def enable_node_scheduling( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10588,7 +10455,7 @@ def get_node_remote_login_settings( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10612,7 +10479,7 @@ def upload_node_logs( self, pool_id: str, node_id: str, - content: _models.UploadBatchServiceLogsContent, + upload_options: _models.UploadBatchServiceLogsOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -10631,8 +10498,8 @@ def upload_node_logs( :param node_id: The ID of the Compute Node for which you want to get the Remote Desktop Protocol file. Required. :type node_id: str - :param content: The Azure Batch service log files upload options. Required. - :type content: ~azure.batch.models.UploadBatchServiceLogsContent + :param upload_options: The Azure Batch service log files upload options. Required. + :type upload_options: ~azure.batch.models.UploadBatchServiceLogsOptions :keyword 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. @@ -10662,7 +10529,7 @@ def upload_node_logs( ) cls: ClsType[_models.UploadBatchServiceLogsResult] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(upload_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_upload_node_logs_request( pool_id=pool_id, @@ -10694,7 +10561,7 @@ def upload_node_logs( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10722,9 +10589,9 @@ def list_nodes( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchNode"]: + ) -> ItemPaged["_models.BatchNode"]: """Lists the Compute Nodes in the specified Pool. Lists the Compute Nodes in the specified Pool. @@ -10756,7 +10623,7 @@ def list_nodes( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNode]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNode]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -10811,7 +10678,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNode], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNode], 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) @@ -10827,7 +10694,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -10843,7 +10710,7 @@ def get_node_extension( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> _models.BatchNodeVMExtension: """Gets information about the specified Compute Node Extension. @@ -10914,7 +10781,7 @@ def get_node_extension( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -10942,9 +10809,9 @@ def list_node_extensions( timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> Iterable["_models.BatchNodeVMExtension"]: + ) -> ItemPaged["_models.BatchNodeVMExtension"]: """Lists the Compute Nodes Extensions in the specified Pool. Lists the Compute Nodes Extensions in the specified Pool. @@ -10973,7 +10840,7 @@ def list_node_extensions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNodeVMExtension]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNodeVMExtension]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -11028,7 +10895,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNodeVMExtension], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNodeVMExtension], 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) @@ -11044,7 +10911,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -11129,7 +10996,7 @@ def delete_node_file( # pylint: disable=inconsistent-return-statements 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -11232,7 +11099,7 @@ def get_node_file( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -11256,8 +11123,6 @@ def get_node_file( return deserialized # type: ignore - # manually renamed - # rename will be through typespec in next version @distributed_trace def _get_node_file_properties_internal( self, @@ -11314,7 +11179,7 @@ def _get_node_file_properties_internal( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_get_node_file_properties_request( + _request = build_batch_get_node_file_properties_internal_request( pool_id=pool_id, node_id=node_id, file_path=file_path, @@ -11340,7 +11205,7 @@ def _get_node_file_properties_internal( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -11372,7 +11237,7 @@ def list_node_files( filter: Optional[str] = None, recursive: Optional[bool] = None, **kwargs: Any - ) -> Iterable["_models.BatchNodeFile"]: + ) -> ItemPaged["_models.BatchNodeFile"]: """Lists all of the files in Task directories on the specified Compute Node. Lists all of the files in Task directories on the specified Compute Node. @@ -11393,7 +11258,7 @@ def list_node_files( applications can be returned. Default value is None. :paramtype max_results: int :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-compute-node-files + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files `_. Default value is None. :paramtype filter: str @@ -11406,7 +11271,7 @@ def list_node_files( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNodeFile]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNodeFile]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -11462,7 +11327,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNodeFile], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNodeFile], 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) @@ -11478,7 +11343,7 @@ def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response diff --git a/sdk/batch/azure-batch/azure/batch/_operations/_patch.py b/sdk/batch/azure-batch/azure/batch/_operations/_patch.py index 4e0857b30791..13af9930edeb 100644 --- a/sdk/batch/azure-batch/azure/batch/_operations/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/_operations/_patch.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -7,44 +8,1148 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ import datetime -from typing import Any, Deque, List, Optional, Iterable, Iterator, overload +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.rest import HttpResponse +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 ( + DeleteCertificatePollingMethod, + DeallocateNodePollingMethod, + DeleteJobPollingMethod, + DeleteJobSchedulePollingMethod, + DeletePoolPollingMethod, + DisableJobPollingMethod, + EnableJobPollingMethod, + RebootNodePollingMethod, + ReimageNodePollingMethod, + RemoveNodePollingMethod, + ResizePoolPollingMethod, + StartNodePollingMethod, + StopPoolResizePollingMethod, + TerminateJobPollingMethod, + TerminateJobSchedulePollingMethod, +) from ._operations import ( - BatchClientOperationsMixin as BatchClientOperationsMixinGenerated, + _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" + "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, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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(self, pipeline_response, None, job_id, 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, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_enable_job( + self, + job_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_delete_job_schedule( + self, + job_schedule_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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 + ) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_delete_pool( + self, + pool_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_delete_certificate( + self, + thumbprint_algorithm: str, + thumbprint: str, + *, + timeout: Optional[int] = None, + ocpdate: Optional[datetime.datetime] = None, + polling_interval: int = 5, + **kwargs: Any + ) -> LROPoller[None]: + """Deletes a Certificate from the specified Account with Long Running Operation support. + + You cannot delete a Certificate if a resource (Pool or Compute Node) is using + it. Before you can delete a Certificate, you must therefore make sure that the + Certificate is not associated with any existing Pools, the Certificate is not + installed on any Nodes (even if you remove a Certificate from a Pool, it is not + removed from existing Compute Nodes in that Pool until they restart), and no + running Tasks depend on the Certificate. If you try to delete a Certificate + that is in use, the deletion fails. The Certificate status changes to + deleteFailed. You can use Cancel Delete Certificate to set the status back to + active if you decide that you want to continue using the Certificate. + + :param thumbprint_algorithm: The algorithm used to derive the thumbprint parameter. This must + be sha1. Required. + :type thumbprint_algorithm: str + :param thumbprint: The thumbprint of the Certificate to be deleted. Required. + :type thumbprint: str + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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._delete_certificate_internal( + thumbprint_algorithm, + thumbprint, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = DeleteCertificatePollingMethod( + self, pipeline_response, None, thumbprint_algorithm, thumbprint, 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.BatchNodeDeallocateOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeDeallocateOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = DeallocateNodePollingMethod(self, pipeline_response, None, pool_id, node_id, 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.BatchNodeRebootOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeRebootOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = RebootNodePollingMethod(self, pipeline_response, None, pool_id, node_id, 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.BatchNodeReimageOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeReimageOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = ReimageNodePollingMethod(self, pipeline_response, None, pool_id, node_id, 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, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeRemoveOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_resize_pool( + self, + pool_id: str, + resize_options: _models.BatchPoolResizeOptions, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_start_node( + self, + pool_id: str, + node_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = StartNodePollingMethod(self, pipeline_response, None, pool_id, node_id, polling_interval) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_stop_pool_resize( + self, + pool_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_terminate_job( + self, + job_id: str, + options: Optional[_models.BatchJobTerminateOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchJobTerminateOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return LROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + def begin_terminate_job_schedule( + self, + job_schedule_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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 + ) + 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.BatchTaskCreateContent], + task_collection: List[_models.BatchTaskCreateOptions], concurrencies: int = 0, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, **kwargs: Any - ) -> _models.BatchTaskAddCollectionResult: + ) -> _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 @@ -67,8 +1172,8 @@ def create_tasks( :param task_collection: The Tasks to be added. Required. :type task_collection: ~azure.batch.models.BatchTaskAddCollectionResult :param concurrencies: 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 + 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 :type concurrencies: int :keyword timeout: The maximum number of items to return in the response. A maximum of 1000 applications can be returned. Default value is None. @@ -77,23 +1182,16 @@ def create_tasks( current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. :paramtype ocpdate: ~datetime.datetime - :keyword content_type: Type of content. Default value is "application/json; - odata=minimalmetadata". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: BatchTaskAddCollectionResult. The BatchTaskAddCollectionResult is compatible with MutableMapping :rtype: ~azure.batch.models.BatchTaskAddCollectionResult - :raises ~azure.batch.custom.CreateTasksError + :raises ~azure.batch.custom.CreateTasksError: """ kwargs.update({"timeout": timeout, "ocpdate": ocpdate}) # deque operations(append/pop) are thread-safe - results_queue: Deque[_models.BatchTaskAddResult] = collections.deque() - task_workflow_manager = _TaskWorkflowManager( - self, job_id=job_id, task_collection=task_collection, **kwargs - ) + 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 concurrencies: @@ -101,7 +1199,7 @@ def create_tasks( raise ValueError("Concurrencies must be positive or 0") active_threads = [] - for i in range(concurrencies): + for _ in range(concurrencies): active_threads.append( threading.Thread( target=task_workflow_manager.task_collection_thread_handler, @@ -122,9 +1220,8 @@ def create_tasks( task_workflow_manager.failure_tasks, task_workflow_manager.errors, ) - else: - submitted_tasks = _handle_output(results_queue) - return _models.BatchTaskAddCollectionResult(value=submitted_tasks) + submitted_tasks = _handle_output(results_queue) + return _models.BatchCreateTaskCollectionResult(values_property=submitted_tasks) @distributed_trace def get_node_file( @@ -169,8 +1266,6 @@ def get_node_file( The format is bytes=startRange-endRange. Default value is None. :paramtype ocp_range: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: bytes :rtype: bytes :raises ~azure.core.exceptions.HttpResponseError: @@ -226,33 +1321,33 @@ def get_node_file_properties( 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 bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: BatchFileProperties :rtype: ~azure.batch.models.BatchFileProperties :raises ~azure.core.exceptions.HttpResponseError: """ - cls = lambda pipeline_response, json_response, headers: _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"], + 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, - timeout=timeout, - ocpdate=ocpdate, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, + + get_response: _models.BatchFileProperties = super()._get_node_file_properties_internal( # type: ignore + pool_id, + node_id, + file_path, + timeout=timeout, + ocpdate=ocpdate, + if_modified_since=if_modified_since, + if_unmodified_since=if_unmodified_since, cls=cls, - **kwargs) + **kwargs, + ) return get_response @@ -294,33 +1389,33 @@ def get_task_file_properties( 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 bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: BatchFileProperties :rtype: ~azure.batch.models.BatchFileProperties :raises ~azure.core.exceptions.HttpResponseError: """ - cls = lambda pipeline_response, json_response, headers: _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"], + 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, - timeout=timeout, - ocpdate=ocpdate, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, + + get_response: _models.BatchFileProperties = super()._get_task_file_properties_internal( # type: ignore + job_id, + task_id, + file_path, + timeout=timeout, + ocpdate=ocpdate, + if_modified_since=if_modified_since, + if_unmodified_since=if_unmodified_since, cls=cls, - **kwargs) + **kwargs, + ) return get_response @@ -367,8 +1462,6 @@ def get_task_file( The format is bytes=startRange-endRange. Default value is None. :paramtype ocp_range: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: bytes :rtype: bytes :raises ~azure.core.exceptions.HttpResponseError: @@ -416,12 +1509,12 @@ def __init__( self, batch_client: BatchClientOperationsMixin, job_id: str, - task_collection: Iterable[_models.BatchTaskCreateContent], + 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.BatchTaskAddResult] = collections.deque() + self.failure_tasks: Deque[_models.BatchTaskCreateResult] = collections.deque() # List of unknown exceptions which occurred during requests. self.errors: Deque[Any] = collections.deque() @@ -438,7 +1531,11 @@ def __init__( self._kwargs = kwargs - def _bulk_add_tasks(self, results_queue, chunk_tasks_to_add): + 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 @@ -447,15 +1544,15 @@ def _bulk_add_tasks(self, results_queue, chunk_tasks_to_add): :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[~BatchTaskAddResult] + :type chunk_tasks_to_add: list[~azure.batch.models.BatchTaskCreateOptions] """ try: - create_task_collection_response: _models.BatchTaskAddCollectionResult = ( + create_task_collection_response: _models.BatchCreateTaskCollectionResult = ( self._batch_client.create_task_collection( job_id=self._job_id, - task_collection=_models.BatchTaskGroup(value=chunk_tasks_to_add), - **self._kwargs + task_collection=_models.BatchTaskGroup(values_property=chunk_tasks_to_add), + **self._kwargs, ) ) except HttpResponseError as e: @@ -471,7 +1568,7 @@ def _bulk_add_tasks(self, results_queue, chunk_tasks_to_add): 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 to add task with ID %s due to the body exceeding the maximum request size", failed_task.id, ) else: @@ -498,7 +1595,7 @@ def _bulk_add_tasks(self, results_queue, chunk_tasks_to_add): 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: + 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 @@ -511,21 +1608,16 @@ def _bulk_add_tasks(self, results_queue, chunk_tasks_to_add): # Unknown State - don't know if tasks failed to add or were successful self.errors.appendleft(e) else: - try: - create_task_collection_response = create_task_collection_response.output - except AttributeError: - pass - if create_task_collection_response.value: - for task_result in create_task_collection_response.value: # pylint: disable=no-member + if create_task_collection_response.values_property: + for task_result in create_task_collection_response.values_property: # 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") + 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) diff --git a/sdk/batch/azure-batch/azure/batch/_operations/_polling.py b/sdk/batch/azure-batch/azure/batch/_operations/_polling.py new file mode 100644 index 000000000000..7599f5530833 --- /dev/null +++ b/sdk/batch/azure-batch/azure/batch/_operations/_polling.py @@ -0,0 +1,1135 @@ +# 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 DeleteCertificatePollingMethod(PollingMethod): + """Polling method for certificate delete operation. + + This class is used to poll the status of a certificate deletion operation. + It checks the status of the certificate until it is deleted or an error occurs. + """ + + def __init__( + self, + client: Any, + initial_response: PipelineResponse, + deserialization_callback: Optional[Callable], + thumbprint_algorithm: str, + thumbprint: str, + polling_interval: int = 5, + ): + self._client = client + self._initial_response = initial_response + self._deserialization_callback = deserialization_callback + self._thumbprint_algorithm = thumbprint_algorithm + self._thumbprint = thumbprint + 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: + certificate = self._client.get_certificate(self._thumbprint_algorithm, self._thumbprint) + + # check certificate state is DELETING state (if not in deleting state then it's succeeded) + if certificate.state == _models.BatchCertificateState.DELETING: + self._status = "InProgress" + self._finished = False + else: + self._status = "Succeeded" + self._finished = True + + except ResourceNotFoundError: + # Certificate 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 a9f1f6eeca2a..1e4ef9ed3bd1 100644 --- a/sdk/batch/azure-batch/azure/batch/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/_patch.py @@ -9,21 +9,28 @@ import base64 import hmac import hashlib -import importlib from datetime import datetime -from typing import TYPE_CHECKING, TypeVar, Any, Union +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 azure.core.pipeline.transport import HttpResponse -from azure.core.rest import HttpRequest 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 @@ -33,17 +40,6 @@ "BatchClient", ] # Add all objects you want publicly available to users at this package level -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Any, Callable, Dict, Optional, TypeVar, Union - - from azure.core.credentials import TokenCredential - from azure.core.pipeline import PipelineRequest - - ClientType = TypeVar("ClientType", bound="BatchClient") - T = TypeVar("T") - ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] - class BatchSharedKeyAuthPolicy(SansIOHTTPPolicy): @@ -119,14 +115,59 @@ def _sign_string(self, string_to_sign): try: key = base64.b64decode(_key) - except TypeError: - raise ValueError("Invalid key value: {}".format(self._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. @@ -143,17 +184,18 @@ class BatchClient(GenerateBatchClient): :paramtype api_version: str """ - def __init__(self, endpoint: str, credential: Union[AzureNamedKeyCredential, TokenCredential], **kwargs): + 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) - ), + 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, account_name, credential): + def _format_shared_key_credential(self, credential): if isinstance(credential, AzureNamedKeyCredential): return BatchSharedKeyAuthPolicy(credential) return None diff --git a/sdk/batch/azure-batch/azure/batch/_utils/__init__.py b/sdk/batch/azure-batch/azure/batch/_utils/__init__.py new file mode 100644 index 000000000000..8026245c2abc --- /dev/null +++ b/sdk/batch/azure-batch/azure/batch/_utils/__init__.py @@ -0,0 +1,6 @@ +# -------------------------------------------------------------------------- +# 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. +# -------------------------------------------------------------------------- diff --git a/sdk/batch/azure-batch/azure/batch/_utils/model_base.py b/sdk/batch/azure-batch/azure/batch/_utils/model_base.py new file mode 100644 index 000000000000..12926fa98dcf --- /dev/null +++ b/sdk/batch/azure-batch/azure/batch/_utils/model_base.py @@ -0,0 +1,1237 @@ +# pylint: disable=line-too-long,useless-suppression,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. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +# 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 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 + +_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]): + def __init__(self, data: 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: ... # pylint: disable=arguments-differ + + @typing.overload + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs + + @typing.overload + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs + + 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) -> 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: # pylint: disable=arguments-differ + """ + 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: ... # pylint: disable=signature-differs + + 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: 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: 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: 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: dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) + + 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) -> 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: 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: 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: list[typing.Any]) -> 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-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 + 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 + ) + + 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 + 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: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() == "dict": + 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: + annotation_name = ( + annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore + ) + if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: + 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, + response: HttpResponse, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, response.json(), 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, + response: HttpResponse, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, response.text()) + 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[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[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[list[str]] = None, + default: typing.Any = _UNSET, + format: typing.Optional[str] = None, + is_multipart_file_input: bool = False, + xml: typing.Optional[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[list[str]] = None, + xml: typing.Optional[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[dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, 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[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: 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: 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/_utils/serialization.py b/sdk/batch/azure-batch/azure/batch/_utils/serialization.py new file mode 100644 index 000000000000..45a3e44e45cb --- /dev/null +++ b/sdk/batch/azure-batch/azure/batch/_utils/serialization.py @@ -0,0 +1,2030 @@ +# pylint: disable=line-too-long,useless-suppression,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. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +# 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 ( + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + MutableMapping, +) + +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 |= 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 |= 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, cast(type, data.__class__)) + if issubclass(enum_type, Enum): + 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/utils.py b/sdk/batch/azure-batch/azure/batch/_utils/utils.py new file mode 100644 index 000000000000..927adb7c8ae2 --- /dev/null +++ b/sdk/batch/azure-batch/azure/batch/_utils/utils.py @@ -0,0 +1,57 @@ +# -------------------------------------------------------------------------- +# 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 Generic, Optional, TYPE_CHECKING, TypeVar + +from azure.core import MatchConditions + +if TYPE_CHECKING: + from .serialization import Deserializer, Serializer + + +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") + + +class ClientMixinABC(ABC, Generic[TClient, TConfig]): + """DO NOT use this class. It is for internal typing use only.""" + + _client: TClient + _config: TConfig + _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 0068a9979d9d..8cc664488da0 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.0.0b2" +VERSION = "15.0.0b3" diff --git a/sdk/batch/azure-batch/azure/batch/aio/_client.py b/sdk/batch/azure-batch/azure/batch/aio/_client.py index 6a2133679d27..6a1093347c66 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_client.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_client.py @@ -14,7 +14,7 @@ from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import BatchClientConfiguration from ._operations import BatchClientOperationsMixin @@ -39,6 +39,7 @@ class BatchClient(BatchClientOperationsMixin): def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" self._config = BatchClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + kwargs["request_id_header_name"] = "client-request-id" _policies = kwargs.pop("policies", None) if _policies is None: diff --git a/sdk/batch/azure-batch/azure/batch/aio/_operations/__init__.py b/sdk/batch/azure-batch/azure/batch/aio/_operations/__init__.py index ea39f177e86d..582b1d915285 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_operations/__init__.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_operations/__init__.py @@ -12,14 +12,14 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import BatchClientOperationsMixin # type: ignore +from ._operations import _BatchClientOperationsMixin # type: ignore # pylint: disable=unused-import from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "BatchClientOperationsMixin", + "_BatchClientOperationsMixin", ] __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/aio/_operations/_operations.py b/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py index ddda2a1d449d..21da9053296e 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_operations/_operations.py @@ -6,13 +6,13 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime import json -import sys -from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, List, Optional, TypeVar +from typing import Any, AsyncIterator, Callable, Optional, TypeVar import urllib.parse -from azure.core import MatchConditions +from azure.core import AsyncPipelineClient, MatchConditions from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -32,7 +32,6 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ..._model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize from ..._operations._operations import ( build_batch_cancel_certificate_deletion_request, build_batch_create_certificate_request, @@ -42,20 +41,20 @@ build_batch_create_pool_request, build_batch_create_task_collection_request, build_batch_create_task_request, - build_batch_deallocate_node_request, - build_batch_delete_certificate_request, - build_batch_delete_job_request, - build_batch_delete_job_schedule_request, + build_batch_deallocate_node_internal_request, + build_batch_delete_certificate_internal_request, + build_batch_delete_job_internal_request, + build_batch_delete_job_schedule_internal_request, build_batch_delete_node_file_request, build_batch_delete_node_user_request, - build_batch_delete_pool_request, + build_batch_delete_pool_internal_request, build_batch_delete_task_file_request, build_batch_delete_task_request, - build_batch_disable_job_request, + build_batch_disable_job_internal_request, build_batch_disable_job_schedule_request, build_batch_disable_node_scheduling_request, build_batch_disable_pool_auto_scale_request, - build_batch_enable_job_request, + build_batch_enable_job_internal_request, build_batch_enable_job_schedule_request, build_batch_enable_node_scheduling_request, build_batch_enable_pool_auto_scale_request, @@ -66,12 +65,12 @@ build_batch_get_job_schedule_request, build_batch_get_job_task_counts_request, build_batch_get_node_extension_request, - build_batch_get_node_file_properties_request, + build_batch_get_node_file_properties_internal_request, build_batch_get_node_file_request, build_batch_get_node_remote_login_settings_request, build_batch_get_node_request, build_batch_get_pool_request, - build_batch_get_task_file_properties_request, + build_batch_get_task_file_properties_internal_request, build_batch_get_task_file_request, build_batch_get_task_request, build_batch_job_schedule_exists_request, @@ -93,36 +92,36 @@ build_batch_list_tasks_request, build_batch_pool_exists_request, build_batch_reactivate_task_request, - build_batch_reboot_node_request, - build_batch_reimage_node_request, - build_batch_remove_nodes_request, + build_batch_reboot_node_internal_request, + build_batch_reimage_node_internal_request, + build_batch_remove_nodes_internal_request, build_batch_replace_job_request, build_batch_replace_job_schedule_request, build_batch_replace_node_user_request, build_batch_replace_pool_properties_request, build_batch_replace_task_request, - build_batch_resize_pool_request, - build_batch_start_node_request, - build_batch_stop_pool_resize_request, - build_batch_terminate_job_request, - build_batch_terminate_job_schedule_request, + build_batch_resize_pool_internal_request, + build_batch_start_node_internal_request, + build_batch_stop_pool_resize_internal_request, + build_batch_terminate_job_internal_request, + build_batch_terminate_job_schedule_internal_request, build_batch_terminate_task_request, build_batch_update_job_request, build_batch_update_job_schedule_request, build_batch_update_pool_request, build_batch_upload_node_logs_request, ) -from .._vendor import BatchClientMixinABC +from ..._utils.model_base import SdkJSONEncoder, _deserialize, _failsafe_deserialize +from ..._utils.utils import ClientMixinABC +from .._configuration import BatchClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -class BatchClientOperationsMixin(BatchClientMixinABC): # pylint: disable=too-many-public-methods +class _BatchClientOperationsMixin( # pylint: disable=too-many-public-methods + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], BatchClientConfiguration] +): @distributed_trace def list_applications( @@ -132,7 +131,7 @@ def list_applications( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchApplication"]: + ) -> AsyncItemPaged["_models.BatchApplication"]: """Lists all of the applications available in the specified Account. This operation returns only Applications and versions that are available for @@ -159,7 +158,7 @@ def list_applications( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchApplication]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchApplication]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -211,7 +210,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchApplication], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchApplication], 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) @@ -227,7 +226,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -305,7 +304,7 @@ async def get_application( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -335,7 +334,7 @@ def list_pool_usage_metrics( endtime: Optional[datetime.datetime] = None, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchPoolUsageMetrics"]: + ) -> AsyncItemPaged["_models.BatchPoolUsageMetrics"]: """Lists the usage metrics, aggregated by Pool across individual time intervals, for the specified Account. @@ -368,7 +367,7 @@ def list_pool_usage_metrics( last aggregation interval currently available. Default value is None. :paramtype endtime: ~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 + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-account-usage-metrics `_. Default value is None. :paramtype filter: str @@ -379,7 +378,7 @@ def list_pool_usage_metrics( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchPoolUsageMetrics]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchPoolUsageMetrics]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -434,7 +433,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchPoolUsageMetrics], deserialized["value"]) + 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) @@ -450,7 +449,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -460,7 +459,7 @@ async def get_next(next_link=None): @distributed_trace_async async def create_pool( self, - pool: _models.BatchPoolCreateContent, + pool: _models.BatchPoolCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -473,7 +472,7 @@ async def create_pool( to Microsoft Support engineers. :param pool: The Pool to be created. Required. - :type pool: ~azure.batch.models.BatchPoolCreateContent + :type pool: ~azure.batch.models.BatchPoolCreateOptions :keyword 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. @@ -527,7 +526,7 @@ async def create_pool( if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -548,10 +547,10 @@ def list_pools( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchPool"]: + ) -> AsyncItemPaged["_models.BatchPool"]: """Lists all of the Pools which be mounted. Lists all of the Pools which be mounted. @@ -583,7 +582,7 @@ def list_pools( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchPool]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchPool]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -638,7 +637,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchPool], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchPool], 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) @@ -654,7 +653,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -662,7 +661,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_pool( + async def _delete_pool_internal( self, pool_id: str, *, @@ -737,7 +736,7 @@ async def delete_pool( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_pool_request( + _request = build_batch_delete_pool_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -763,7 +762,7 @@ async def delete_pool( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -862,7 +861,7 @@ async def pool_exists( if response.status_code not in [200, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -885,8 +884,8 @@ async def get_pool( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -978,7 +977,7 @@ async def get_pool( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1001,7 +1000,7 @@ async def get_pool( async def update_pool( self, pool_id: str, - pool: _models.BatchPoolUpdateContent, + pool: _models.BatchPoolUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -1020,7 +1019,7 @@ async def update_pool( :param pool_id: The ID of the Pool to get. Required. :type pool_id: str :param pool: The pool properties to update. Required. - :type pool: ~azure.batch.models.BatchPoolUpdateContent + :type pool: ~azure.batch.models.BatchPoolUpdateOptions :keyword 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. @@ -1100,7 +1099,7 @@ async def update_pool( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1170,7 +1169,7 @@ async def disable_pool_auto_scale( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1187,7 +1186,7 @@ async def disable_pool_auto_scale( async def enable_pool_auto_scale( self, pool_id: str, - content: _models.BatchPoolEnableAutoScaleContent, + enable_auto_scale_options: _models.BatchPoolEnableAutoScaleOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -1208,8 +1207,8 @@ async def enable_pool_auto_scale( :param pool_id: The ID of the Pool to get. Required. :type pool_id: str - :param content: The options to use for enabling automatic scaling. Required. - :type content: ~azure.batch.models.BatchPoolEnableAutoScaleContent + :param enable_auto_scale_options: The options to use for enabling automatic scaling. Required. + :type enable_auto_scale_options: ~azure.batch.models.BatchPoolEnableAutoScaleOptions :keyword 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. @@ -1259,7 +1258,7 @@ async def enable_pool_auto_scale( ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(enable_auto_scale_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_enable_pool_auto_scale_request( pool_id=pool_id, @@ -1289,7 +1288,7 @@ async def enable_pool_auto_scale( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1306,7 +1305,7 @@ async def enable_pool_auto_scale( async def evaluate_pool_auto_scale( self, pool_id: str, - content: _models.BatchPoolEvaluateAutoScaleContent, + evaluate_auto_scale_options: _models.BatchPoolEvaluateAutoScaleOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -1321,8 +1320,9 @@ async def evaluate_pool_auto_scale( :param pool_id: The ID of the Pool on which to evaluate the automatic scaling formula. Required. :type pool_id: str - :param content: The options to use for evaluating the automatic scaling formula. Required. - :type content: ~azure.batch.models.BatchPoolEvaluateAutoScaleContent + :param evaluate_auto_scale_options: The options to use for evaluating the automatic scaling + formula. Required. + :type evaluate_auto_scale_options: ~azure.batch.models.BatchPoolEvaluateAutoScaleOptions :keyword 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. @@ -1351,7 +1351,7 @@ async def evaluate_pool_auto_scale( ) cls: ClsType[_models.AutoScaleRun] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluate_auto_scale_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_evaluate_pool_auto_scale_request( pool_id=pool_id, @@ -1382,7 +1382,7 @@ async def evaluate_pool_auto_scale( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1403,10 +1403,10 @@ async def evaluate_pool_auto_scale( return deserialized # type: ignore @distributed_trace_async - async def resize_pool( + async def _resize_pool_internal( self, pool_id: str, - content: _models.BatchPoolResizeContent, + resize_options: _models.BatchPoolResizeOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -1428,8 +1428,8 @@ async def resize_pool( :param pool_id: The ID of the Pool to get. Required. :type pool_id: str - :param content: The options to use for resizing the pool. Required. - :type content: ~azure.batch.models.BatchPoolResizeContent + :param resize_options: The options to use for resizing the pool. Required. + :type resize_options: ~azure.batch.models.BatchPoolResizeOptions :keyword 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. @@ -1479,9 +1479,9 @@ async def resize_pool( ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(resize_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_batch_resize_pool_request( + _request = build_batch_resize_pool_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -1509,7 +1509,7 @@ async def resize_pool( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1523,7 +1523,7 @@ async def resize_pool( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def stop_pool_resize( + async def _stop_pool_resize_internal( self, pool_id: str, *, @@ -1593,7 +1593,7 @@ async def stop_pool_resize( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_stop_pool_resize_request( + _request = build_batch_stop_pool_resize_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -1619,7 +1619,7 @@ async def stop_pool_resize( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1636,7 +1636,7 @@ async def stop_pool_resize( async def replace_pool_properties( self, pool_id: str, - pool: _models.BatchPoolReplaceContent, + pool: _models.BatchPoolReplaceOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -1651,7 +1651,7 @@ async def replace_pool_properties( :param pool_id: The ID of the Pool to update. Required. :type pool_id: str :param pool: The options to use for replacing properties on the pool. Required. - :type pool: ~azure.batch.models.BatchPoolReplaceContent + :type pool: ~azure.batch.models.BatchPoolReplaceOptions :keyword 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. @@ -1706,7 +1706,7 @@ async def replace_pool_properties( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1720,10 +1720,10 @@ async def replace_pool_properties( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def remove_nodes( + async def _remove_nodes_internal( self, pool_id: str, - content: _models.BatchNodeRemoveContent, + remove_options: _models.BatchNodeRemoveOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -1741,8 +1741,8 @@ async def remove_nodes( :param pool_id: The ID of the Pool to get. Required. :type pool_id: str - :param content: The options to use for removing the node. Required. - :type content: ~azure.batch.models.BatchNodeRemoveContent + :param remove_options: The options to use for removing the node. Required. + :type remove_options: ~azure.batch.models.BatchNodeRemoveOptions :keyword 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. @@ -1792,9 +1792,9 @@ async def remove_nodes( ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(remove_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_batch_remove_nodes_request( + _request = build_batch_remove_nodes_internal_request( pool_id=pool_id, timeout=timeout, ocpdate=ocpdate, @@ -1822,7 +1822,7 @@ async def remove_nodes( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -1844,7 +1844,7 @@ def list_supported_images( max_results: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchSupportedImage"]: + ) -> AsyncItemPaged["_models.BatchSupportedImage"]: """Lists all Virtual Machine Images supported by the Azure Batch service. Lists all Virtual Machine Images supported by the Azure Batch service. @@ -1872,7 +1872,7 @@ def list_supported_images( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchSupportedImage]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchSupportedImage]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -1925,7 +1925,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchSupportedImage], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchSupportedImage], 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) @@ -1941,7 +1941,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -1957,7 +1957,7 @@ def list_pool_node_counts( max_results: Optional[int] = None, filter: Optional[str] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchPoolNodeCounts"]: + ) -> AsyncItemPaged["_models.BatchPoolNodeCounts"]: """Gets the number of Compute Nodes in each state, grouped by Pool. Note that the numbers returned may not always be up to date. If you need exact node counts, use a list query. @@ -1985,7 +1985,7 @@ def list_pool_node_counts( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchPoolNodeCounts]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchPoolNodeCounts]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -2038,7 +2038,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchPoolNodeCounts], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchPoolNodeCounts], 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) @@ -2054,7 +2054,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -2062,7 +2062,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_job( + async def _delete_job_internal( self, job_id: str, *, @@ -2137,7 +2137,7 @@ async def delete_job( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_job_request( + _request = build_batch_delete_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -2164,7 +2164,7 @@ async def delete_job( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2183,8 +2183,8 @@ async def get_job( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -2278,7 +2278,7 @@ async def get_job( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2301,7 +2301,7 @@ async def get_job( async def update_job( self, job_id: str, - job: _models.BatchJobUpdateContent, + job: _models.BatchJobUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -2320,7 +2320,7 @@ async def update_job( :param job_id: The ID of the Job whose properties you want to update. Required. :type job_id: str :param job: The options to use for updating the Job. Required. - :type job: ~azure.batch.models.BatchJobUpdateContent + :type job: ~azure.batch.models.BatchJobUpdateOptions :keyword 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. @@ -2400,7 +2400,7 @@ async def update_job( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2516,7 +2516,7 @@ async def replace_job( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2530,10 +2530,10 @@ async def replace_job( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def disable_job( + async def _disable_job_internal( self, job_id: str, - content: _models.BatchJobDisableContent, + disable_options: _models.BatchJobDisableOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -2556,8 +2556,8 @@ async def disable_job( :param job_id: The ID of the Job to disable. Required. :type job_id: str - :param content: The options to use for disabling the Job. Required. - :type content: ~azure.batch.models.BatchJobDisableContent + :param disable_options: The options to use for disabling the Job. Required. + :type disable_options: ~azure.batch.models.BatchJobDisableOptions :keyword 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. @@ -2607,9 +2607,9 @@ async def disable_job( ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(disable_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_batch_disable_job_request( + _request = build_batch_disable_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -2637,7 +2637,7 @@ async def disable_job( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2651,7 +2651,7 @@ async def disable_job( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def enable_job( + async def _enable_job_internal( self, job_id: str, *, @@ -2720,7 +2720,7 @@ async def enable_job( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_enable_job_request( + _request = build_batch_enable_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -2746,7 +2746,7 @@ async def enable_job( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2760,10 +2760,10 @@ async def enable_job( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def terminate_job( + async def _terminate_job_internal( self, job_id: str, - parameters: Optional[_models.BatchJobTerminateContent] = None, + options: Optional[_models.BatchJobTerminateOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -2785,8 +2785,8 @@ async def terminate_job( :param job_id: The ID of the Job to terminate. Required. :type job_id: str - :param parameters: The options to use for terminating the Job. Default value is None. - :type parameters: ~azure.batch.models.BatchJobTerminateContent + :param options: The options to use for terminating the Job. Default value is None. + :type options: ~azure.batch.models.BatchJobTerminateOptions :keyword 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. @@ -2834,17 +2834,18 @@ async def terminate_job( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_terminate_job_request( + _request = build_batch_terminate_job_internal_request( job_id=job_id, timeout=timeout, ocpdate=ocpdate, @@ -2873,7 +2874,7 @@ async def terminate_job( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2889,7 +2890,7 @@ async def terminate_job( @distributed_trace_async async def create_job( self, - job: _models.BatchJobCreateContent, + job: _models.BatchJobCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -2908,7 +2909,7 @@ async def create_job( engineers. :param job: The Job to be created. Required. - :type job: ~azure.batch.models.BatchJobCreateContent + :type job: ~azure.batch.models.BatchJobCreateOptions :keyword 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. @@ -2962,7 +2963,7 @@ async def create_job( if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -2983,10 +2984,10 @@ def list_jobs( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchJob"]: + ) -> AsyncItemPaged["_models.BatchJob"]: """Lists all of the Jobs in the specified Account. Lists all of the Jobs in the specified Account. @@ -3018,7 +3019,7 @@ def list_jobs( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJob]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3073,7 +3074,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJob], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchJob], 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) @@ -3089,7 +3090,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3105,10 +3106,10 @@ def list_jobs_from_schedule( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchJob"]: + ) -> AsyncItemPaged["_models.BatchJob"]: """Lists the Jobs that have been created under the specified Job Schedule. Lists the Jobs that have been created under the specified Job Schedule. @@ -3128,7 +3129,7 @@ def list_jobs_from_schedule( applications can be returned. Default value is None. :paramtype max_results: int :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-jobs-in-a-job-schedule + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-jobs-in-a-job-schedule `_. Default value is None. :paramtype filter: str @@ -3143,7 +3144,7 @@ def list_jobs_from_schedule( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJob]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3199,7 +3200,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJob], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchJob], 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) @@ -3215,7 +3216,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3231,9 +3232,9 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchJobPreparationAndReleaseTaskStatus"]: + ) -> AsyncItemPaged["_models.BatchJobPreparationAndReleaseTaskStatus"]: """Lists the execution status of the Job Preparation and Job Release Task for the specified Job across the Compute Nodes where the Job has run. @@ -3258,7 +3259,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo applications can be returned. Default value is None. :paramtype max_results: int :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-job-preparation-and-release-status + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-job-preparation-and-release-status `_. Default value is None. :paramtype filter: str @@ -3272,7 +3273,7 @@ def list_job_preparation_and_release_task_status( # pylint: disable=name-too-lo _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJobPreparationAndReleaseTaskStatus]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJobPreparationAndReleaseTaskStatus]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3327,7 +3328,9 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJobPreparationAndReleaseTaskStatus], deserialized["value"]) + list_of_elem = _deserialize( + list[_models.BatchJobPreparationAndReleaseTaskStatus], 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) @@ -3343,7 +3346,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3415,7 +3418,7 @@ async def get_job_task_counts( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3502,7 +3505,7 @@ async def create_certificate( if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3523,9 +3526,9 @@ def list_certificates( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchCertificate"]: + ) -> AsyncItemPaged["_models.BatchCertificate"]: """Lists all of the Certificates that have been added to the specified Account. Lists all of the Certificates that have been added to the specified Account. @@ -3542,7 +3545,7 @@ def list_certificates( applications can be returned. Default value is None. :paramtype max_results: int :keyword filter: An OData $filter clause. For more information on constructing this filter, see - `https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates + `https://docs.microsoft.com/en-us/rest/api/batchservice/odata-filters-in-batch#list-certificates `_. Default value is None. :paramtype filter: str @@ -3555,7 +3558,7 @@ def list_certificates( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchCertificate]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchCertificate]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3609,7 +3612,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchCertificate], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchCertificate], 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) @@ -3625,7 +3628,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -3705,7 +3708,7 @@ async def cancel_certificate_deletion( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3719,7 +3722,7 @@ async def cancel_certificate_deletion( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def delete_certificate( + async def _delete_certificate_internal( self, thumbprint_algorithm: str, thumbprint: str, @@ -3770,7 +3773,7 @@ async def delete_certificate( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_certificate_request( + _request = build_batch_delete_certificate_internal_request( thumbprint_algorithm=thumbprint_algorithm, thumbprint=thumbprint, timeout=timeout, @@ -3793,7 +3796,7 @@ async def delete_certificate( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3813,9 +3816,9 @@ async def get_certificate( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> _models.GetCertificateResponse: + ) -> _models.BatchCertificate: """Gets information about the specified Certificate. :param thumbprint_algorithm: The algorithm used to derive the thumbprint parameter. This must @@ -3833,8 +3836,8 @@ async def get_certificate( :paramtype ocpdate: ~datetime.datetime :keyword select: An OData $select clause. Default value is None. :paramtype select: list[str] - :return: GetCertificateResponse. The GetCertificateResponse is compatible with MutableMapping - :rtype: ~azure.batch.models.GetCertificateResponse + :return: BatchCertificate. The BatchCertificate is compatible with MutableMapping + :rtype: ~azure.batch.models.BatchCertificate :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3848,7 +3851,7 @@ async def get_certificate( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.GetCertificateResponse] = kwargs.pop("cls", None) + cls: ClsType[_models.BatchCertificate] = kwargs.pop("cls", None) _request = build_batch_get_certificate_request( thumbprint_algorithm=thumbprint_algorithm, @@ -3879,7 +3882,7 @@ async def get_certificate( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -3891,7 +3894,7 @@ async def get_certificate( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.GetCertificateResponse, response.json()) + deserialized = _deserialize(_models.BatchCertificate, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3989,7 +3992,7 @@ async def job_schedule_exists( if response.status_code not in [200, 404]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4004,7 +4007,7 @@ async def job_schedule_exists( return 200 <= response.status_code <= 299 @distributed_trace_async - async def delete_job_schedule( + async def _delete_job_schedule_internal( self, job_schedule_id: str, *, @@ -4076,7 +4079,7 @@ async def delete_job_schedule( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_delete_job_schedule_request( + _request = build_batch_delete_job_schedule_internal_request( job_schedule_id=job_schedule_id, timeout=timeout, ocpdate=ocpdate, @@ -4103,7 +4106,7 @@ async def delete_job_schedule( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4122,8 +4125,8 @@ async def get_job_schedule( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -4215,7 +4218,7 @@ async def get_job_schedule( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4238,7 +4241,7 @@ async def get_job_schedule( async def update_job_schedule( self, job_schedule_id: str, - job_schedule: _models.BatchJobScheduleUpdateContent, + job_schedule: _models.BatchJobScheduleUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4259,7 +4262,7 @@ async def update_job_schedule( :param job_schedule_id: The ID of the Job Schedule to update. Required. :type job_schedule_id: str :param job_schedule: The options to use for updating the Job Schedule. Required. - :type job_schedule: ~azure.batch.models.BatchJobScheduleUpdateContent + :type job_schedule: ~azure.batch.models.BatchJobScheduleUpdateOptions :keyword 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. @@ -4339,7 +4342,7 @@ async def update_job_schedule( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4457,7 +4460,7 @@ async def replace_job_schedule( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4561,7 +4564,7 @@ async def disable_job_schedule( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4665,7 +4668,7 @@ async def enable_job_schedule( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4679,7 +4682,7 @@ async def enable_job_schedule( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def terminate_job_schedule( + async def _terminate_job_schedule_internal( self, job_schedule_id: str, *, @@ -4748,7 +4751,7 @@ async def terminate_job_schedule( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_terminate_job_schedule_request( + _request = build_batch_terminate_job_schedule_internal_request( job_schedule_id=job_schedule_id, timeout=timeout, ocpdate=ocpdate, @@ -4775,7 +4778,7 @@ async def terminate_job_schedule( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4791,7 +4794,7 @@ async def terminate_job_schedule( @distributed_trace_async async def create_job_schedule( self, - job_schedule: _models.BatchJobScheduleCreateContent, + job_schedule: _models.BatchJobScheduleCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -4802,7 +4805,7 @@ async def create_job_schedule( Creates a Job Schedule to the specified Account. :param job_schedule: The Job Schedule to be created. Required. - :type job_schedule: ~azure.batch.models.BatchJobScheduleCreateContent + :type job_schedule: ~azure.batch.models.BatchJobScheduleCreateOptions :keyword 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. @@ -4856,7 +4859,7 @@ async def create_job_schedule( if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -4877,10 +4880,10 @@ def list_job_schedules( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchJobSchedule"]: + ) -> AsyncItemPaged["_models.BatchJobSchedule"]: """Lists all of the Job Schedules in the specified Account. Lists all of the Job Schedules in the specified Account. @@ -4912,7 +4915,7 @@ def list_job_schedules( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchJobSchedule]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchJobSchedule]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -4967,7 +4970,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchJobSchedule], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchJobSchedule], 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) @@ -4983,7 +4986,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -4994,7 +4997,7 @@ async def get_next(next_link=None): async def create_task( self, job_id: str, - task: _models.BatchTaskCreateContent, + task: _models.BatchTaskCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -5009,7 +5012,7 @@ async def create_task( :param job_id: The ID of the Job to which the Task is to be created. Required. :type job_id: str :param task: The Task to be created. Required. - :type task: ~azure.batch.models.BatchTaskCreateContent + :type task: ~azure.batch.models.BatchTaskCreateOptions :keyword 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. @@ -5064,7 +5067,7 @@ async def create_task( if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5086,10 +5089,10 @@ def list_tasks( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchTask"]: + ) -> AsyncItemPaged["_models.BatchTask"]: """Lists all of the Tasks that are associated with the specified Job. For multi-instance Tasks, information such as affinityId, executionInfo and @@ -5125,7 +5128,7 @@ def list_tasks( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchTask]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchTask]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -5181,7 +5184,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchTask], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchTask], 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) @@ -5197,7 +5200,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -5213,7 +5216,7 @@ async def create_task_collection( timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, **kwargs: Any - ) -> _models.BatchTaskAddCollectionResult: + ) -> _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 @@ -5243,9 +5246,9 @@ async def create_task_collection( current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. :paramtype ocpdate: ~datetime.datetime - :return: BatchTaskAddCollectionResult. The BatchTaskAddCollectionResult is compatible with - MutableMapping - :rtype: ~azure.batch.models.BatchTaskAddCollectionResult + :return: BatchCreateTaskCollectionResult. The BatchCreateTaskCollectionResult is compatible + with MutableMapping + :rtype: ~azure.batch.models.BatchCreateTaskCollectionResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5262,7 +5265,7 @@ async def create_task_collection( content_type: str = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) - cls: ClsType[_models.BatchTaskAddCollectionResult] = kwargs.pop("cls", None) + cls: ClsType[_models.BatchCreateTaskCollectionResult] = kwargs.pop("cls", None) _content = json.dumps(task_collection, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore @@ -5295,7 +5298,7 @@ async def create_task_collection( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5307,7 +5310,7 @@ async def create_task_collection( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.BatchTaskAddCollectionResult, response.json()) + deserialized = _deserialize(_models.BatchCreateTaskCollectionResult, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -5413,7 +5416,7 @@ async def delete_task( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5433,8 +5436,8 @@ async def get_task( ocpdate: Optional[datetime.datetime] = None, if_modified_since: Optional[datetime.datetime] = None, if_unmodified_since: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, - expand: Optional[List[str]] = None, + select: Optional[list[str]] = None, + expand: Optional[list[str]] = None, etag: Optional[str] = None, match_condition: Optional[MatchConditions] = None, **kwargs: Any @@ -5533,7 +5536,7 @@ async def get_task( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5656,7 +5659,7 @@ async def replace_task( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5677,9 +5680,9 @@ def list_sub_tasks( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchSubtask"]: + ) -> AsyncItemPaged["_models.BatchSubtask"]: """Lists all of the subtasks that are associated with the specified multi-instance Task. @@ -5706,7 +5709,7 @@ def list_sub_tasks( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchSubtask]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchSubtask]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -5760,7 +5763,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchSubtask], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchSubtask], 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) @@ -5776,7 +5779,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -5880,7 +5883,7 @@ async def terminate_task( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -5995,7 +5998,7 @@ async def reactivate_task( if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6086,7 +6089,7 @@ async def delete_task_file( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6189,7 +6192,7 @@ async def get_task_file( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6213,8 +6216,6 @@ async def get_task_file( return deserialized # type: ignore - # manually renamed - # rename will be through typespec in next version @distributed_trace_async async def _get_task_file_properties_internal( self, @@ -6271,7 +6272,7 @@ async def _get_task_file_properties_internal( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_get_task_file_properties_request( + _request = build_batch_get_task_file_properties_internal_request( job_id=job_id, task_id=task_id, file_path=file_path, @@ -6297,7 +6298,7 @@ async def _get_task_file_properties_internal( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6329,7 +6330,7 @@ def list_task_files( filter: Optional[str] = None, recursive: Optional[bool] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchNodeFile"]: + ) -> AsyncItemPaged["_models.BatchNodeFile"]: """Lists the files in a Task's directory on its Compute Node. Lists the files in a Task's directory on its Compute Node. @@ -6365,7 +6366,7 @@ def list_task_files( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNodeFile]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNodeFile]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6421,7 +6422,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNodeFile], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNodeFile], 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) @@ -6437,7 +6438,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -6449,7 +6450,7 @@ async def create_node_user( self, pool_id: str, node_id: str, - user: _models.BatchNodeUserCreateContent, + user: _models.BatchNodeUserCreateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -6465,7 +6466,7 @@ async def create_node_user( :param node_id: The ID of the machine on which you want to create a user Account. Required. :type node_id: str :param user: The options to use for creating the user. Required. - :type user: ~azure.batch.models.BatchNodeUserCreateContent + :type user: ~azure.batch.models.BatchNodeUserCreateOptions :keyword 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. @@ -6521,7 +6522,7 @@ async def create_node_user( if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6605,7 +6606,7 @@ async def delete_node_user( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6621,7 +6622,7 @@ async def replace_node_user( pool_id: str, node_id: str, user_name: str, - content: _models.BatchNodeUserUpdateContent, + update_options: _models.BatchNodeUserUpdateOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -6640,8 +6641,8 @@ async def replace_node_user( :type node_id: str :param user_name: The name of the user Account to update. Required. :type user_name: str - :param content: The options to use for updating the user. Required. - :type content: ~azure.batch.models.BatchNodeUserUpdateContent + :param update_options: The options to use for updating the user. Required. + :type update_options: ~azure.batch.models.BatchNodeUserUpdateOptions :keyword 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. @@ -6670,7 +6671,7 @@ async def replace_node_user( ) cls: ClsType[None] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(update_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_replace_node_user_request( pool_id=pool_id, @@ -6698,7 +6699,7 @@ async def replace_node_user( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6719,7 +6720,7 @@ async def get_node( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> _models.BatchNode: """Gets information about the specified Compute Node. @@ -6786,7 +6787,7 @@ async def get_node( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6806,11 +6807,11 @@ async def get_node( return deserialized # type: ignore @distributed_trace_async - async def reboot_node( + async def _reboot_node_internal( self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeRebootContent] = None, + options: Optional[_models.BatchNodeRebootOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -6824,8 +6825,8 @@ async def reboot_node( :type pool_id: str :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str - :param parameters: The options to use for rebooting the Compute Node. Default value is None. - :type parameters: ~azure.batch.models.BatchNodeRebootContent + :param options: The options to use for rebooting the Compute Node. Default value is None. + :type options: ~azure.batch.models.BatchNodeRebootOptions :keyword 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. @@ -6849,17 +6850,18 @@ async def reboot_node( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_reboot_node_request( + _request = build_batch_reboot_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -6884,7 +6886,7 @@ async def reboot_node( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6898,7 +6900,7 @@ async def reboot_node( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def start_node( + async def _start_node_internal( self, pool_id: str, node_id: str, @@ -6940,7 +6942,7 @@ async def start_node( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_start_node_request( + _request = build_batch_start_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -6963,7 +6965,7 @@ async def start_node( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -6977,11 +6979,11 @@ async def start_node( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def reimage_node( + async def _reimage_node_internal( self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeReimageContent] = None, + options: Optional[_models.BatchNodeReimageOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -6997,8 +6999,8 @@ async def reimage_node( :type pool_id: str :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str - :param parameters: The options to use for reimaging the Compute Node. Default value is None. - :type parameters: ~azure.batch.models.BatchNodeReimageContent + :param options: The options to use for reimaging the Compute Node. Default value is None. + :type options: ~azure.batch.models.BatchNodeReimageOptions :keyword 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. @@ -7022,17 +7024,18 @@ async def reimage_node( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_reimage_node_request( + _request = build_batch_reimage_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -7057,7 +7060,7 @@ async def reimage_node( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7071,11 +7074,11 @@ async def reimage_node( return cls(pipeline_response, None, response_headers) # type: ignore @distributed_trace_async - async def deallocate_node( + async def _deallocate_node_internal( self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeDeallocateContent] = None, + options: Optional[_models.BatchNodeDeallocateOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -7089,8 +7092,8 @@ async def deallocate_node( :type pool_id: str :param node_id: The ID of the Compute Node that you want to restart. Required. :type node_id: str - :param parameters: The options to use for deallocating the Compute Node. Default value is None. - :type parameters: ~azure.batch.models.BatchNodeDeallocateContent + :param options: The options to use for deallocating the Compute Node. Default value is None. + :type options: ~azure.batch.models.BatchNodeDeallocateOptions :keyword 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. @@ -7114,17 +7117,18 @@ async def deallocate_node( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None - _request = build_batch_deallocate_node_request( + _request = build_batch_deallocate_node_internal_request( pool_id=pool_id, node_id=node_id, timeout=timeout, @@ -7149,7 +7153,7 @@ async def deallocate_node( if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7167,7 +7171,7 @@ async def disable_node_scheduling( self, pool_id: str, node_id: str, - parameters: Optional[_models.BatchNodeDisableSchedulingContent] = None, + options: Optional[_models.BatchNodeDisableSchedulingOptions] = None, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -7183,9 +7187,9 @@ async def disable_node_scheduling( :param node_id: The ID of the Compute Node on which you want to disable Task scheduling. Required. :type node_id: str - :param parameters: The options to use for disabling scheduling on the Compute Node. Default - value is None. - :type parameters: ~azure.batch.models.BatchNodeDisableSchedulingContent + :param options: The options to use for disabling scheduling on the Compute Node. Default value + is None. + :type options: ~azure.batch.models.BatchNodeDisableSchedulingOptions :keyword 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. @@ -7209,13 +7213,14 @@ async def disable_node_scheduling( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: str = kwargs.pop( + content_type: Optional[str] = kwargs.pop( "content_type", _headers.pop("content-type", "application/json; odata=minimalmetadata") ) + content_type = content_type if options else None cls: ClsType[None] = kwargs.pop("cls", None) - if parameters is not None: - _content = json.dumps(parameters, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + if options is not None: + _content = json.dumps(options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore else: _content = None @@ -7244,7 +7249,7 @@ async def disable_node_scheduling( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7325,7 +7330,7 @@ async def enable_node_scheduling( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7412,7 +7417,7 @@ async def get_node_remote_login_settings( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7436,7 +7441,7 @@ async def upload_node_logs( self, pool_id: str, node_id: str, - content: _models.UploadBatchServiceLogsContent, + upload_options: _models.UploadBatchServiceLogsOptions, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, @@ -7455,8 +7460,8 @@ async def upload_node_logs( :param node_id: The ID of the Compute Node for which you want to get the Remote Desktop Protocol file. Required. :type node_id: str - :param content: The Azure Batch service log files upload options. Required. - :type content: ~azure.batch.models.UploadBatchServiceLogsContent + :param upload_options: The Azure Batch service log files upload options. Required. + :type upload_options: ~azure.batch.models.UploadBatchServiceLogsOptions :keyword 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. @@ -7486,7 +7491,7 @@ async def upload_node_logs( ) cls: ClsType[_models.UploadBatchServiceLogsResult] = kwargs.pop("cls", None) - _content = json.dumps(content, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(upload_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_batch_upload_node_logs_request( pool_id=pool_id, @@ -7518,7 +7523,7 @@ async def upload_node_logs( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7546,9 +7551,9 @@ def list_nodes( ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, filter: Optional[str] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchNode"]: + ) -> AsyncItemPaged["_models.BatchNode"]: """Lists the Compute Nodes in the specified Pool. Lists the Compute Nodes in the specified Pool. @@ -7580,7 +7585,7 @@ def list_nodes( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNode]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNode]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -7635,7 +7640,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNode], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNode], 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) @@ -7651,7 +7656,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -7667,7 +7672,7 @@ async def get_node_extension( *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any ) -> _models.BatchNodeVMExtension: """Gets information about the specified Compute Node Extension. @@ -7738,7 +7743,7 @@ async def get_node_extension( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -7766,9 +7771,9 @@ def list_node_extensions( timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, max_results: Optional[int] = None, - select: Optional[List[str]] = None, + select: Optional[list[str]] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchNodeVMExtension"]: + ) -> AsyncItemPaged["_models.BatchNodeVMExtension"]: """Lists the Compute Nodes Extensions in the specified Pool. Lists the Compute Nodes Extensions in the specified Pool. @@ -7797,7 +7802,7 @@ def list_node_extensions( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNodeVMExtension]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNodeVMExtension]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -7852,7 +7857,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNodeVMExtension], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNodeVMExtension], 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) @@ -7868,7 +7873,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response @@ -7953,7 +7958,7 @@ async def delete_node_file( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8056,7 +8061,7 @@ async def get_node_file( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize(_models.BatchError, response.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8080,8 +8085,6 @@ async def get_node_file( return deserialized # type: ignore - # manually renamed - # rename will be through typespec in next version @distributed_trace_async async def _get_node_file_properties_internal( self, @@ -8138,7 +8141,7 @@ async def _get_node_file_properties_internal( cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_batch_get_node_file_properties_request( + _request = build_batch_get_node_file_properties_internal_request( pool_id=pool_id, node_id=node_id, file_path=file_path, @@ -8164,7 +8167,7 @@ async def _get_node_file_properties_internal( 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) response_headers = {} @@ -8196,7 +8199,7 @@ def list_node_files( filter: Optional[str] = None, recursive: Optional[bool] = None, **kwargs: Any - ) -> AsyncIterable["_models.BatchNodeFile"]: + ) -> AsyncItemPaged["_models.BatchNodeFile"]: """Lists all of the files in Task directories on the specified Compute Node. Lists all of the files in Task directories on the specified Compute Node. @@ -8217,7 +8220,7 @@ def list_node_files( applications can be returned. Default value is None. :paramtype max_results: int :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-compute-node-files + `https://learn.microsoft.com/rest/api/batchservice/odata-filters-in-batch#list-compute-node-files `_. Default value is None. :paramtype filter: str @@ -8230,7 +8233,7 @@ def list_node_files( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.BatchNodeFile]] = kwargs.pop("cls", None) + cls: ClsType[list[_models.BatchNodeFile]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -8286,7 +8289,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.BatchNodeFile], deserialized["value"]) + list_of_elem = _deserialize(list[_models.BatchNodeFile], 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) @@ -8302,7 +8305,7 @@ async def get_next(next_link=None): 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.json()) + error = _failsafe_deserialize(_models.BatchError, response) raise HttpResponseError(response=response, model=error) return pipeline_response 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 b3c12ac94cfb..5f55431b36e0 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_operations/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_operations/_patch.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines, C4763 # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -10,40 +11,1152 @@ import datetime import collections import logging -from typing import Any, Deque, AsyncIterator, List, Iterable, Optional, Union +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.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, + DeleteCertificatePollingMethodAsync, + DeleteJobPollingMethodAsync, + DeleteJobSchedulePollingMethodAsync, + DeletePoolPollingMethodAsync, + DisableJobPollingMethodAsync, + EnableJobPollingMethodAsync, + RebootNodePollingMethodAsync, + ReimageNodePollingMethodAsync, + RemoveNodePollingMethodAsync, + ResizePoolPollingMethodAsync, + StartNodePollingMethodAsync, + StopPoolResizePollingMethodAsync, + TerminateJobPollingMethodAsync, + TerminateJobSchedulePollingMethodAsync, +) from ._operations import ( - BatchClientOperationsMixin as BatchClientOperationsMixinGenerated, + _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" + "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, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + # redundant but needed to fix pylint errors in the polling method code + 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, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_enable_job( + self, + job_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_delete_job_schedule( + self, + job_schedule_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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 + ) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_delete_pool( + self, + pool_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_delete_certificate( + self, + thumbprint_algorithm: str, + thumbprint: str, + *, + timeout: Optional[int] = None, + ocpdate: Optional[datetime.datetime] = None, + polling_interval: int = 5, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Deletes a Certificate from the specified Account with Long Running Operation support. + + You cannot delete a Certificate if a resource (Pool or Compute Node) is using + it. Before you can delete a Certificate, you must therefore make sure that the + Certificate is not associated with any existing Pools, the Certificate is not + installed on any Nodes (even if you remove a Certificate from a Pool, it is not + removed from existing Compute Nodes in that Pool until they restart), and no + running Tasks depend on the Certificate. If you try to delete a Certificate + that is in use, the deletion fails. The Certificate status changes to + deleteFailed. You can use Cancel Delete Certificate to set the status back to + active if you decide that you want to continue using the Certificate. + + :param thumbprint_algorithm: The algorithm used to derive the thumbprint parameter. This must + be sha1. Required. + :type thumbprint_algorithm: str + :param thumbprint: The thumbprint of the Certificate to be deleted. Required. + :type thumbprint: str + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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._delete_certificate_internal( + thumbprint_algorithm, + thumbprint, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = DeleteCertificatePollingMethodAsync( + self, pipeline_response, None, thumbprint_algorithm, thumbprint, 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.BatchNodeDeallocateOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeDeallocateOptions + :keyword 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 timeout: int + :keyword ocpdate: 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. + :keyword polling_interval: The interval in seconds between polling attempts. Default value is 5. + :paramtype polling_interval: int + :paramtype ocpdate: ~datetime.datetime + :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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = DeallocateNodePollingMethodAsync( + self, pipeline_response, None, pool_id, node_id, 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.BatchNodeRebootOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeRebootOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = RebootNodePollingMethodAsync(self, pipeline_response, None, pool_id, node_id, 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.BatchNodeReimageOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchNodeReimageOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = ReimageNodePollingMethodAsync( + self, pipeline_response, None, pool_id, node_id, 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, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + 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, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_start_node( + self, + pool_id: str, + node_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + cls=capture_pipeline_response, + **kwargs, + ), + ) + + polling_method = StartNodePollingMethodAsync(self, pipeline_response, None, pool_id, node_id, polling_interval) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_stop_pool_resize( + self, + pool_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_terminate_job( + self, + job_id: str, + options: Optional[_models.BatchJobTerminateOptions] = None, + *, + timeout: Optional[int] = None, + ocpdate: 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.BatchJobTerminateOptions + :keyword 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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) + return AsyncLROPoller(self, pipeline_response, lambda _: None, polling_method, **kwargs) + + @distributed_trace + async def begin_terminate_job_schedule( + self, + job_schedule_id: str, + *, + timeout: Optional[int] = None, + ocpdate: 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 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 timeout: int + :keyword ocpdate: 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 ocpdate: ~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, + timeout=timeout, + ocpdate=ocpdate, + 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 + ) + 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.BatchTaskCreateContent], + task_collection: List[_models.BatchTaskCreateOptions], concurrencies: int = 0, *, timeout: Optional[int] = None, ocpdate: Optional[datetime.datetime] = None, **kwargs: Any - ) -> _models.BatchTaskAddCollectionResult: + ) -> _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 @@ -65,10 +1178,10 @@ async def create_tasks( :type job_id: str :param task_collection: The Tasks to be added. Required. :type task_collection: ~azure.batch.models.BatchTaskAddCollectionResult - :param 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 - :type concurrency: int + :param concurrencies: 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 + :type concurrencies: int :keyword timeout: The maximum number of items to return in the response. A maximum of 1000 applications can be returned. Default value is None. :paramtype timeout: int @@ -76,29 +1189,22 @@ async def create_tasks( current system clock time; set it explicitly if you are calling the REST API directly. Default value is None. :paramtype ocpdate: ~datetime.datetime - :keyword content_type: Type of content. Default value is "application/json; - odata=minimalmetadata". - :paramtype content_type: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: BatchTaskAddCollectionResult. The BatchTaskAddCollectionResult is compatible with MutableMapping :rtype: ~azure.batch.models.BatchTaskAddCollectionResult - :raises ~azure.batch.custom.CreateTasksError + :raises ~azure.batch.custom.CreateTasksError: """ kwargs.update({"timeout": timeout, "ocpdate": ocpdate}) - results_queue: Deque[_models.BatchTaskAddResult] = collections.deque() - task_workflow_manager = _TaskWorkflowManager( - self, job_id=job_id, task_collection=task_collection, **kwargs - ) + results_queue: Deque[_models.BatchTaskCreateResult] = collections.deque() + task_workflow_manager = _TaskWorkflowManager(self, job_id=job_id, task_collection=task_collection, **kwargs) if concurrencies: if concurrencies < 0: raise ValueError("Concurrencies must be positive or 0") coroutines = [] - for i in range(concurrencies): + for _ in range(concurrencies): coroutines.append(task_workflow_manager.task_collection_handler(results_queue)) await asyncio.gather(*coroutines) else: @@ -111,9 +1217,8 @@ async def create_tasks( task_workflow_manager.failure_tasks, task_workflow_manager.errors, ) - else: - submitted_tasks = _handle_output(results_queue) - return _models.BatchTaskAddCollectionResult(value=submitted_tasks) + submitted_tasks = _handle_output(results_queue) + return _models.BatchCreateTaskCollectionResult(values_property=submitted_tasks) @distributed_trace async def get_node_file( @@ -158,8 +1263,6 @@ async def get_node_file( The format is bytes=startRange-endRange. Default value is None. :paramtype ocp_range: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: bytes :rtype: bytes :raises ~azure.core.exceptions.HttpResponseError: @@ -215,33 +1318,43 @@ async def get_node_file_properties( 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 bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: BatchFileProperties :rtype: ~azure.batch.models.BatchFileProperties :raises ~azure.core.exceptions.HttpResponseError: """ - cls = lambda pipeline_response, json_response, headers: _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"], + 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, - timeout=timeout, - ocpdate=ocpdate, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, + + # cls = lambda pipeline_response, json_response, headers: _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, + timeout=timeout, + ocpdate=ocpdate, + if_modified_since=if_modified_since, + if_unmodified_since=if_unmodified_since, cls=cls, - **kwargs) + **kwargs, + ) return get_response @@ -283,33 +1396,43 @@ async def get_task_file_properties( 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 bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: BatchFileProperties :rtype: ~azure.batch.models.BatchFileProperties :raises ~azure.core.exceptions.HttpResponseError: """ - cls = lambda pipeline_response, json_response, headers: _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"], + 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, - timeout=timeout, - ocpdate=ocpdate, - if_modified_since=if_modified_since, - if_unmodified_since=if_unmodified_since, + + # cls = lambda pipeline_response, json_response, headers: _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, + timeout=timeout, + ocpdate=ocpdate, + if_modified_since=if_modified_since, + if_unmodified_since=if_unmodified_since, cls=cls, - **kwargs) + **kwargs, + ) return get_response @@ -356,8 +1479,6 @@ async def get_task_file( The format is bytes=startRange-endRange. Default value is None. :paramtype ocp_range: str - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. :return: bytes :rtype: bytes :raises ~azure.core.exceptions.HttpResponseError: @@ -394,11 +1515,11 @@ def __init__( self, batch_client: BatchClientOperationsMixin, job_id: str, - task_collection: Iterable[_models.BatchTaskCreateContent], + task_collection: Iterable[_models.BatchTaskCreateOptions], **kwargs ): # List of tasks which failed to add due to a returned client error - self.failure_tasks: Deque[_models.BatchTaskAddResult] = collections.deque() + self.failure_tasks: Deque[_models.BatchTaskCreateResult] = collections.deque() # List of unknown exceptions which occurred during requests. self.errors: Deque[Any] = collections.deque() @@ -415,7 +1536,7 @@ def __init__( async def _bulk_add_tasks( self, results_queue: collections.deque, - chunk_tasks_to_add: List[_models.BatchTaskCreateContent], + chunk_tasks_to_add: List[_models.BatchTaskCreateOptions], ): """Adds a chunk of tasks to the job @@ -424,16 +1545,16 @@ async def _bulk_add_tasks( :param results_queue: Queue to place the return value of the request :type results_queue: collections.deque - :ivar chunk_tasks_to_add: Chunk of at most 100 tasks with retry details - :vartype chunk_tasks_to_add: list[~azure.batch.models.BatchTaskCreateContent] + :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.BatchTaskAddCollectionResult = ( + create_task_collection_response: _models.BatchCreateTaskCollectionResult = ( await self._batch_client.create_task_collection( job_id=self._job_id, - task_collection=_models.BatchTaskGroup(value=chunk_tasks_to_add), - **self._kwargs + task_collection=_models.BatchTaskGroup(values_property=chunk_tasks_to_add), + **self._kwargs, ) ) except HttpResponseError as e: @@ -449,7 +1570,7 @@ async def _bulk_add_tasks( 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 to add task with ID %s due to the body exceeding the maximum request size", failed_task.id, ) else: @@ -473,7 +1594,7 @@ async def _bulk_add_tasks( 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 + 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 @@ -486,16 +1607,15 @@ async def _bulk_add_tasks( # Unknown State - don't know if tasks failed to add or were successful self.errors.appendleft(e) else: - if create_task_collection_response.value: - for task_result in create_task_collection_response.value: + if create_task_collection_response.values_property: + for task_result in create_task_collection_response.values_property: 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") + 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) 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 new file mode 100644 index 000000000000..56d8fd0152cb --- /dev/null +++ b/sdk/batch/azure-batch/azure/batch/aio/_operations/_polling_async.py @@ -0,0 +1,1495 @@ +# 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 DeleteCertificatePollingMethodAsync(AsyncPollingMethod): + """Polling method for certificate delete operation. + + This class is used to poll the status of a certificate deletion operation. + It checks the status of the certificate until it is deleted or an error occurs. + """ + + def __init__( + self, + client: Any, + initial_response: PipelineResponse, + deserialization_callback: Optional[Callable], + thumbprint_algorithm: str, + thumbprint: str, + polling_interval: int = 5, + ): + """Initialize the DeleteCertificatePollingMethodAsync. + + Sets the initial status of this long-running operation, verifies that polling + is possible, and initializes all necessary components for polling the certificate + deletion status. + + :param client: An instance of the Batch client used to make API calls for + checking certificate status during polling. + :type client: Any + :param initial_response: The PipelineResponse returned from the initial + delete certificate 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 thumbprint_algorithm: The algorithm used to generate the certificate + thumbprint (e.g., "sha1"). + :type thumbprint_algorithm: str + :param thumbprint: The hexadecimal string representation of the certificate + thumbprint. + :type thumbprint: str + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type polling_interval: int + """ + self._client = client + self._initial_response = initial_response + self._deserialization_callback = deserialization_callback + self._thumbprint_algorithm = thumbprint_algorithm + self._thumbprint = thumbprint + 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: + certificate = await self._client.get_certificate(self._thumbprint_algorithm, self._thumbprint) + + # check certificate state is DELETING state (if not in deleting state then it's succeeded) + if certificate.state == _models.BatchCertificateState.DELETING: + self._status = "InProgress" + self._finished = False + else: + self._status = "Succeeded" + self._finished = True + + except ResourceNotFoundError: + # Certificate 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 + :param node_id: The unique identifier of the node to be deallocated. + :type node_id: str + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param node_id: The unique identifier of the node to be rebooted. + :type node_id: str + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param node_id: The unique identifier of the node to be reimaged. + :type node_id: str + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param node_id: The unique identifier of the node to be started. + :type node_id: str + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 + :param polling_interval: The time interval in seconds between polling + attempts. Defaults to 5 seconds. + :type 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 64a3f1262c22..4434e3c36878 100644 --- a/sdk/batch/azure-batch/azure/batch/aio/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/aio/_patch.py @@ -7,15 +7,13 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from ._client import BatchClient as GenerateBatchClient -from .._patch import BatchSharedKeyAuthPolicy -from azure.core.credentials import TokenCredential - +from typing import Union +from azure.core.credentials import TokenCredential from azure.core.credentials import AzureNamedKeyCredential - -from typing import Union +from ._client import BatchClient as GenerateBatchClient +from .._patch import BatchExceptionPolicy, BatchSharedKeyAuthPolicy __all__ = [ "BatchClient", @@ -38,11 +36,14 @@ class BatchClient(GenerateBatchClient): :paramtype api_version: str """ - def __init__(self, endpoint: str, credential: Union[AzureNamedKeyCredential, TokenCredential], **kwargs): + 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 + credential=credential, # type: ignore authentication_policy=kwargs.pop("authentication_policy", self._format_shared_key_credential(credential)), + per_call_policies=per_call_policies, **kwargs ) diff --git a/sdk/batch/azure-batch/azure/batch/models/__init__.py b/sdk/batch/azure-batch/azure/batch/models/__init__.py index c54aed6d5845..7ae0c54205f1 100644 --- a/sdk/batch/azure-batch/azure/batch/models/__init__.py +++ b/sdk/batch/azure-batch/azure/batch/models/__init__.py @@ -14,7 +14,6 @@ from ._models import ( # type: ignore - AffinityInfo, AuthenticationTokenSettings, AutoScaleRun, AutoScaleRunError, @@ -22,18 +21,24 @@ AutomaticOsUpgradePolicy, AzureBlobFileSystemConfiguration, AzureFileShareConfiguration, + BatchAffinityInfo, BatchApplication, BatchApplicationPackageReference, BatchAutoPoolSpecification, BatchCertificate, + BatchCertificateDeleteError, BatchCertificateReference, + BatchContainerConfiguration, + BatchCreateTaskCollectionResult, + BatchDiffDiskSettings, BatchError, BatchErrorDetail, BatchErrorMessage, + BatchInboundNatPool, BatchJob, BatchJobConstraints, - BatchJobCreateContent, - BatchJobDisableContent, + BatchJobCreateOptions, + BatchJobDisableOptions, BatchJobExecutionInfo, BatchJobManagerTask, BatchJobNetworkConfiguration, @@ -44,62 +49,64 @@ BatchJobReleaseTaskExecutionInfo, BatchJobSchedule, BatchJobScheduleConfiguration, - BatchJobScheduleCreateContent, + BatchJobScheduleCreateOptions, BatchJobScheduleExecutionInfo, BatchJobScheduleStatistics, - BatchJobScheduleUpdateContent, + BatchJobScheduleUpdateOptions, BatchJobSchedulingError, BatchJobSpecification, BatchJobStatistics, - BatchJobTerminateContent, - BatchJobUpdateContent, + BatchJobTerminateOptions, + BatchJobUpdateOptions, + BatchMetadataItem, BatchNode, BatchNodeAgentInfo, BatchNodeCounts, - BatchNodeDeallocateContent, - BatchNodeDisableSchedulingContent, + BatchNodeDeallocateOptions, + BatchNodeDisableSchedulingOptions, BatchNodeEndpointConfiguration, BatchNodeError, BatchNodeFile, BatchNodeIdentityReference, BatchNodeInfo, BatchNodePlacementConfiguration, - BatchNodeRebootContent, - BatchNodeReimageContent, + BatchNodeRebootOptions, + BatchNodeReimageOptions, BatchNodeRemoteLoginSettings, - BatchNodeRemoveContent, - BatchNodeUserCreateContent, - BatchNodeUserUpdateContent, + BatchNodeRemoveOptions, + BatchNodeUserCreateOptions, + BatchNodeUserUpdateOptions, BatchNodeVMExtension, + BatchOsDisk, BatchPool, - BatchPoolCreateContent, - BatchPoolEnableAutoScaleContent, + BatchPoolCreateOptions, + BatchPoolEnableAutoScaleOptions, BatchPoolEndpointConfiguration, - BatchPoolEvaluateAutoScaleContent, + BatchPoolEvaluateAutoScaleOptions, BatchPoolIdentity, BatchPoolInfo, BatchPoolNodeCounts, - BatchPoolReplaceContent, - BatchPoolResizeContent, + BatchPoolReplaceOptions, + BatchPoolResizeOptions, BatchPoolResourceStatistics, BatchPoolSpecification, BatchPoolStatistics, - BatchPoolUpdateContent, + BatchPoolUpdateOptions, BatchPoolUsageMetrics, BatchPoolUsageStatistics, + BatchPublicIpAddressConfiguration, BatchStartTask, BatchStartTaskInfo, BatchSubtask, BatchSupportedImage, BatchTask, - BatchTaskAddCollectionResult, - BatchTaskAddResult, BatchTaskConstraints, BatchTaskContainerExecutionInfo, BatchTaskContainerSettings, BatchTaskCounts, BatchTaskCountsResult, - BatchTaskCreateContent, + BatchTaskCreateOptions, + BatchTaskCreateResult, BatchTaskDependencies, BatchTaskExecutionInfo, BatchTaskFailureInfo, @@ -109,13 +116,14 @@ BatchTaskSchedulingPolicy, BatchTaskSlotCounts, BatchTaskStatistics, + BatchUefiSettings, + BatchUserAssignedIdentity, + BatchVmDiskSecurityProfile, + BatchVmImageReference, CifsMountConfiguration, - ContainerConfiguration, ContainerHostBatchBindMountEntry, ContainerRegistryReference, DataDisk, - DeleteBatchCertificateError, - DiffDiskSettings, DiskEncryptionConfiguration, EnvironmentSetting, ExitCodeMapping, @@ -123,41 +131,32 @@ ExitConditions, ExitOptions, FileProperties, - GetCertificateResponse, - HttpHeader, - ImageReference, InboundEndpoint, - InboundNatPool, InstanceViewStatus, LinuxUserConfiguration, ManagedDisk, - MetadataItem, MountConfiguration, MultiInstanceSettings, NameValuePair, NetworkConfiguration, NetworkSecurityGroupRule, NfsMountConfiguration, - OSDisk, OutputFile, OutputFileBlobContainerDestination, OutputFileDestination, OutputFileUploadConfig, - PublicIpAddressConfiguration, + OutputFileUploadHeader, RecentBatchJob, ResizeError, ResourceFile, RollingUpgradePolicy, SecurityProfile, ServiceArtifactReference, - UefiSettings, UpgradePolicy, - UploadBatchServiceLogsContent, + UploadBatchServiceLogsOptions, UploadBatchServiceLogsResult, UserAccount, - UserAssignedIdentity, UserIdentity, - VMDiskSecurityProfile, VMExtension, VMExtensionInstanceView, VirtualMachineConfiguration, @@ -167,14 +166,16 @@ ) from ._enums import ( # type: ignore - AccessScope, AllocationState, AutoUserScope, + BatchAccessScope, + BatchAllTasksCompleteMode, BatchCertificateFormat, BatchCertificateState, BatchCertificateStoreLocation, BatchCertificateVisibility, - BatchJobAction, + BatchErrorSourceCategory, + BatchJobActionKind, BatchJobPreparationTaskState, BatchJobReleaseTaskState, BatchJobScheduleState, @@ -185,7 +186,7 @@ BatchNodeDisableSchedulingOption, BatchNodeFillType, BatchNodePlacementPolicyType, - BatchNodeRebootOption, + BatchNodeRebootKind, BatchNodeReimageOption, BatchNodeState, BatchPoolIdentityType, @@ -195,6 +196,7 @@ BatchSubtaskState, BatchTaskAddStatus, BatchTaskExecutionResult, + BatchTaskFailureMode, BatchTaskState, CachingType, ContainerHostDataPath, @@ -206,15 +208,12 @@ DiskEncryptionTarget, DynamicVNetAssignmentScope, ElevationLevel, - ErrorCategory, ImageVerificationType, InboundEndpointProtocol, IpAddressProvisioningType, LoginMode, NetworkSecurityGroupRuleAccess, OSType, - OnAllBatchTasksComplete, - OnBatchTaskFailure, OutputFileUploadCondition, SchedulingState, SecurityEncryptionTypes, @@ -228,7 +227,6 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AffinityInfo", "AuthenticationTokenSettings", "AutoScaleRun", "AutoScaleRunError", @@ -236,18 +234,24 @@ "AutomaticOsUpgradePolicy", "AzureBlobFileSystemConfiguration", "AzureFileShareConfiguration", + "BatchAffinityInfo", "BatchApplication", "BatchApplicationPackageReference", "BatchAutoPoolSpecification", "BatchCertificate", + "BatchCertificateDeleteError", "BatchCertificateReference", + "BatchContainerConfiguration", + "BatchCreateTaskCollectionResult", + "BatchDiffDiskSettings", "BatchError", "BatchErrorDetail", "BatchErrorMessage", + "BatchInboundNatPool", "BatchJob", "BatchJobConstraints", - "BatchJobCreateContent", - "BatchJobDisableContent", + "BatchJobCreateOptions", + "BatchJobDisableOptions", "BatchJobExecutionInfo", "BatchJobManagerTask", "BatchJobNetworkConfiguration", @@ -258,62 +262,64 @@ "BatchJobReleaseTaskExecutionInfo", "BatchJobSchedule", "BatchJobScheduleConfiguration", - "BatchJobScheduleCreateContent", + "BatchJobScheduleCreateOptions", "BatchJobScheduleExecutionInfo", "BatchJobScheduleStatistics", - "BatchJobScheduleUpdateContent", + "BatchJobScheduleUpdateOptions", "BatchJobSchedulingError", "BatchJobSpecification", "BatchJobStatistics", - "BatchJobTerminateContent", - "BatchJobUpdateContent", + "BatchJobTerminateOptions", + "BatchJobUpdateOptions", + "BatchMetadataItem", "BatchNode", "BatchNodeAgentInfo", "BatchNodeCounts", - "BatchNodeDeallocateContent", - "BatchNodeDisableSchedulingContent", + "BatchNodeDeallocateOptions", + "BatchNodeDisableSchedulingOptions", "BatchNodeEndpointConfiguration", "BatchNodeError", "BatchNodeFile", "BatchNodeIdentityReference", "BatchNodeInfo", "BatchNodePlacementConfiguration", - "BatchNodeRebootContent", - "BatchNodeReimageContent", + "BatchNodeRebootOptions", + "BatchNodeReimageOptions", "BatchNodeRemoteLoginSettings", - "BatchNodeRemoveContent", - "BatchNodeUserCreateContent", - "BatchNodeUserUpdateContent", + "BatchNodeRemoveOptions", + "BatchNodeUserCreateOptions", + "BatchNodeUserUpdateOptions", "BatchNodeVMExtension", + "BatchOsDisk", "BatchPool", - "BatchPoolCreateContent", - "BatchPoolEnableAutoScaleContent", + "BatchPoolCreateOptions", + "BatchPoolEnableAutoScaleOptions", "BatchPoolEndpointConfiguration", - "BatchPoolEvaluateAutoScaleContent", + "BatchPoolEvaluateAutoScaleOptions", "BatchPoolIdentity", "BatchPoolInfo", "BatchPoolNodeCounts", - "BatchPoolReplaceContent", - "BatchPoolResizeContent", + "BatchPoolReplaceOptions", + "BatchPoolResizeOptions", "BatchPoolResourceStatistics", "BatchPoolSpecification", "BatchPoolStatistics", - "BatchPoolUpdateContent", + "BatchPoolUpdateOptions", "BatchPoolUsageMetrics", "BatchPoolUsageStatistics", + "BatchPublicIpAddressConfiguration", "BatchStartTask", "BatchStartTaskInfo", "BatchSubtask", "BatchSupportedImage", "BatchTask", - "BatchTaskAddCollectionResult", - "BatchTaskAddResult", "BatchTaskConstraints", "BatchTaskContainerExecutionInfo", "BatchTaskContainerSettings", "BatchTaskCounts", "BatchTaskCountsResult", - "BatchTaskCreateContent", + "BatchTaskCreateOptions", + "BatchTaskCreateResult", "BatchTaskDependencies", "BatchTaskExecutionInfo", "BatchTaskFailureInfo", @@ -323,13 +329,14 @@ "BatchTaskSchedulingPolicy", "BatchTaskSlotCounts", "BatchTaskStatistics", + "BatchUefiSettings", + "BatchUserAssignedIdentity", + "BatchVmDiskSecurityProfile", + "BatchVmImageReference", "CifsMountConfiguration", - "ContainerConfiguration", "ContainerHostBatchBindMountEntry", "ContainerRegistryReference", "DataDisk", - "DeleteBatchCertificateError", - "DiffDiskSettings", "DiskEncryptionConfiguration", "EnvironmentSetting", "ExitCodeMapping", @@ -337,55 +344,48 @@ "ExitConditions", "ExitOptions", "FileProperties", - "GetCertificateResponse", - "HttpHeader", - "ImageReference", "InboundEndpoint", - "InboundNatPool", "InstanceViewStatus", "LinuxUserConfiguration", "ManagedDisk", - "MetadataItem", "MountConfiguration", "MultiInstanceSettings", "NameValuePair", "NetworkConfiguration", "NetworkSecurityGroupRule", "NfsMountConfiguration", - "OSDisk", "OutputFile", "OutputFileBlobContainerDestination", "OutputFileDestination", "OutputFileUploadConfig", - "PublicIpAddressConfiguration", + "OutputFileUploadHeader", "RecentBatchJob", "ResizeError", "ResourceFile", "RollingUpgradePolicy", "SecurityProfile", "ServiceArtifactReference", - "UefiSettings", "UpgradePolicy", - "UploadBatchServiceLogsContent", + "UploadBatchServiceLogsOptions", "UploadBatchServiceLogsResult", "UserAccount", - "UserAssignedIdentity", "UserIdentity", - "VMDiskSecurityProfile", "VMExtension", "VMExtensionInstanceView", "VirtualMachineConfiguration", "VirtualMachineInfo", "WindowsConfiguration", "WindowsUserConfiguration", - "AccessScope", "AllocationState", "AutoUserScope", + "BatchAccessScope", + "BatchAllTasksCompleteMode", "BatchCertificateFormat", "BatchCertificateState", "BatchCertificateStoreLocation", "BatchCertificateVisibility", - "BatchJobAction", + "BatchErrorSourceCategory", + "BatchJobActionKind", "BatchJobPreparationTaskState", "BatchJobReleaseTaskState", "BatchJobScheduleState", @@ -396,7 +396,7 @@ "BatchNodeDisableSchedulingOption", "BatchNodeFillType", "BatchNodePlacementPolicyType", - "BatchNodeRebootOption", + "BatchNodeRebootKind", "BatchNodeReimageOption", "BatchNodeState", "BatchPoolIdentityType", @@ -406,6 +406,7 @@ "BatchSubtaskState", "BatchTaskAddStatus", "BatchTaskExecutionResult", + "BatchTaskFailureMode", "BatchTaskState", "CachingType", "ContainerHostDataPath", @@ -417,15 +418,12 @@ "DiskEncryptionTarget", "DynamicVNetAssignmentScope", "ElevationLevel", - "ErrorCategory", "ImageVerificationType", "InboundEndpointProtocol", "IpAddressProvisioningType", "LoginMode", "NetworkSecurityGroupRuleAccess", "OSType", - "OnAllBatchTasksComplete", - "OnBatchTaskFailure", "OutputFileUploadCondition", "SchedulingState", "SecurityEncryptionTypes", diff --git a/sdk/batch/azure-batch/azure/batch/models/_enums.py b/sdk/batch/azure-batch/azure/batch/models/_enums.py index c6adc7cc362d..58df1bbe6ab4 100644 --- a/sdk/batch/azure-batch/azure/batch/models/_enums.py +++ b/sdk/batch/azure-batch/azure/batch/models/_enums.py @@ -10,13 +10,6 @@ from azure.core import CaseInsensitiveEnumMeta -class AccessScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """AccessScope enums.""" - - JOB = "job" - """Grants access to perform all operations on the Job containing the Task.""" - - class AllocationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """AllocationState enums.""" @@ -41,6 +34,22 @@ class AutoUserScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): Node in a Pool.""" +class BatchAccessScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """BatchAccessScope enums.""" + + JOB = "job" + """Grants access to perform all operations on the Job containing the Task.""" + + +class BatchAllTasksCompleteMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The action the Batch service should take when all Tasks in the Job are in the completed state.""" + + NO_ACTION = "noaction" + """Do nothing. The Job remains active unless terminated or disabled by some other means.""" + TERMINATE_JOB = "terminatejob" + """Terminate the Job. The Job's terminationReason is set to 'AllTasksComplete'.""" + + class BatchCertificateFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): """BatchCertificateFormat enums.""" @@ -90,7 +99,16 @@ class BatchCertificateVisibility(str, Enum, metaclass=CaseInsensitiveEnumMeta): Compute Node.""" -class BatchJobAction(str, Enum, metaclass=CaseInsensitiveEnumMeta): +class BatchErrorSourceCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """BatchErrorSourceCategory enums.""" + + USER_ERROR = "usererror" + """The error is due to a user issue, such as misconfiguration.""" + SERVER_ERROR = "servererror" + """The error is due to an internal server issue.""" + + +class BatchJobActionKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """BatchJobAction enums.""" NONE = "none" @@ -198,9 +216,10 @@ class BatchNodeDeallocateOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Deallocate the Compute Node when all Tasks have completed.""" RETAINED_DATA = "retaineddata" - """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.""" + """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): @@ -216,9 +235,10 @@ class BatchNodeDeallocationOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Remove Compute Nodes when all Tasks have completed.""" RETAINED_DATA = "retaineddata" - """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.""" + """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): @@ -256,8 +276,8 @@ class BatchNodePlacementPolicyType(str, Enum, metaclass=CaseInsensitiveEnumMeta) balancing.""" -class BatchNodeRebootOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """BatchNodeRebootOption enums.""" +class BatchNodeRebootKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """BatchNodeRebootKind enums.""" REQUEUE = "requeue" """Terminate running Task processes and requeue the Tasks. The Tasks will run again when a Compute @@ -270,9 +290,10 @@ class BatchNodeRebootOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Restart the Compute Node when all Tasks have completed.""" RETAINED_DATA = "retaineddata" - """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.""" + """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): @@ -289,9 +310,10 @@ class BatchNodeReimageOption(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Allow currently running Tasks to complete. Schedule no new Tasks while waiting. Reimage the Compute Node when all Tasks have completed.""" RETAINED_DATA = "retaineddata" - """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.""" + """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): @@ -421,6 +443,15 @@ class BatchTaskExecutionResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): process was launched, while the Task process was executing, or after the Task process exited.""" +class BatchTaskFailureMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """TaskFailure enums.""" + + NO_ACTION = "noaction" + """Do nothing. The Job remains active unless terminated or disabled by some other means.""" + PERFORM_EXIT_OPTIONS_JOB_ACTION = "performexitoptionsjobaction" + """Terminate the Job. The Job's terminationReason is set to 'AllTasksComplete'.""" + + class BatchTaskState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """BatchTaskState enums.""" @@ -558,15 +589,6 @@ class ElevationLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The user is a user with elevated access and operates with full Administrator permissions.""" -class ErrorCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ErrorCategory enums.""" - - USER_ERROR = "usererror" - """The error is due to a user issue, such as misconfiguration.""" - SERVER_ERROR = "servererror" - """The error is due to an internal server issue.""" - - class ImageVerificationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ImageVerificationType enums.""" @@ -622,24 +644,6 @@ class NetworkSecurityGroupRuleAccess(str, Enum, metaclass=CaseInsensitiveEnumMet """Deny access.""" -class OnAllBatchTasksComplete(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The action the Batch service should take when all Tasks in the Job are in the completed state.""" - - NO_ACTION = "noaction" - """Do nothing. The Job remains active unless terminated or disabled by some other means.""" - TERMINATE_JOB = "terminatejob" - """Terminate the Job. The Job's terminationReason is set to 'AllTasksComplete'.""" - - -class OnBatchTaskFailure(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """OnTaskFailure enums.""" - - NO_ACTION = "noaction" - """Do nothing. The Job remains active unless terminated or disabled by some other means.""" - PERFORM_EXIT_OPTIONS_JOB_ACTION = "performexitoptionsjobaction" - """Terminate the Job. The Job's terminationReason is set to 'AllTasksComplete'.""" - - class OSType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """OSType enums.""" diff --git a/sdk/batch/azure-batch/azure/batch/models/_models.py b/sdk/batch/azure-batch/azure/batch/models/_models.py index 842decf5de5c..bb2b5c37e21e 100644 --- a/sdk/batch/azure-batch/azure/batch/models/_models.py +++ b/sdk/batch/azure-batch/azure/batch/models/_models.py @@ -9,52 +9,15 @@ # pylint: disable=useless-super-delegation import datetime -from typing import Any, Dict, List, Mapping, Optional, TYPE_CHECKING, Union, overload +from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload -from .. import _model_base -from .._model_base import rest_field +from .._utils.model_base import Model as _Model, rest_field if TYPE_CHECKING: from .. import models as _models -class AffinityInfo(_model_base.Model): - """A locality hint that can be used by the Batch service to select a Compute Node - on which to start a Task. - - :ivar affinity_id: An opaque string representing the location of a Compute Node or a Task that - has run previously. You can pass the affinityId of a Node to indicate that this Task needs to - run on that 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 scheduled - elsewhere. Required. - :vartype affinity_id: str - """ - - affinity_id: str = rest_field(name="affinityId", visibility=["read", "create", "update", "delete", "query"]) - """An opaque string representing the location of a Compute Node or a Task that has run previously. - You can pass the affinityId of a Node to indicate that this Task needs to run on that 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 scheduled elsewhere. Required.""" - - @overload - def __init__( - self, - *, - affinity_id: str, - ) -> 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 AuthenticationTokenSettings(_model_base.Model): +class AuthenticationTokenSettings(_Model): """The settings for an authentication token that the Task can use to perform Batch service operations. @@ -62,10 +25,10 @@ class AuthenticationTokenSettings(_model_base.Model): grants access to a limited set of Batch service operations. Currently the only supported value for the access property is 'job', which grants access to all operations related to the Job which contains the Task. - :vartype access: list[str or ~azure.batch.models.AccessScope] + :vartype access: list[str or ~azure.batch.models.BatchAccessScope] """ - access: Optional[List[Union[str, "_models.AccessScope"]]] = rest_field( + access: Optional[list[Union[str, "_models.BatchAccessScope"]]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """The Batch resources to which the token grants access. The authentication token grants access to @@ -77,7 +40,7 @@ class AuthenticationTokenSettings(_model_base.Model): def __init__( self, *, - access: Optional[List[Union[str, "_models.AccessScope"]]] = None, + access: Optional[list[Union[str, "_models.BatchAccessScope"]]] = None, ) -> None: ... @overload @@ -91,7 +54,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutomaticOsUpgradePolicy(_model_base.Model): +class AutomaticOsUpgradePolicy(_Model): """The configuration parameters used for performing automatic OS upgrade. :ivar disable_automatic_rollback: Whether OS image rollback feature should be disabled. @@ -154,7 +117,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutoScaleRun(_model_base.Model): +class AutoScaleRun(_Model): """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. @@ -202,7 +165,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutoScaleRunError(_model_base.Model): +class AutoScaleRunError(_Model): """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 @@ -221,7 +184,7 @@ class AutoScaleRunError(_model_base.Model): message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A message describing the autoscale error, intended to be suitable for display in a user interface.""" - values_property: Optional[List["_models.NameValuePair"]] = rest_field( + values_property: Optional[list["_models.NameValuePair"]] = rest_field( name="values", visibility=["read", "create", "update", "delete", "query"] ) """A list of additional error details related to the autoscale error.""" @@ -232,7 +195,7 @@ def __init__( *, code: Optional[str] = None, message: Optional[str] = None, - values_property: Optional[List["_models.NameValuePair"]] = None, + values_property: Optional[list["_models.NameValuePair"]] = None, ) -> None: ... @overload @@ -246,7 +209,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AutoUserSpecification(_model_base.Model): +class AutoUserSpecification(_Model): """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 @@ -293,7 +256,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureBlobFileSystemConfiguration(_model_base.Model): +class AzureBlobFileSystemConfiguration(_Model): """Information used to connect to an Azure Storage Container using Blobfuse. :ivar account_name: The Azure Storage Account name. Required. @@ -372,16 +335,16 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureFileShareConfiguration(_model_base.Model): +class AzureFileShareConfiguration(_Model): """Information used to connect to an Azure Fileshare. :ivar account_name: The Azure Storage account name. Required. :vartype account_name: str + :ivar account_key: The Azure Storage account key. Required. + :vartype account_key: str :ivar azure_file_url: The Azure Files URL. This is of the form 'https://{account}.file.core.windows.net/'. Required. :vartype azure_file_url: str - :ivar account_key: The Azure Storage account key. Required. - :vartype account_key: str :ivar relative_mount_path: The relative path on the compute node where the file system will be mounted. All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. @@ -393,10 +356,10 @@ class AzureFileShareConfiguration(_model_base.Model): account_name: str = rest_field(name="accountName", visibility=["read", "create", "update", "delete", "query"]) """The Azure Storage account name. Required.""" - azure_file_url: str = rest_field(name="azureFileUrl", visibility=["read", "create", "update", "delete", "query"]) - """The Azure Files URL. This is of the form 'https://{account}.file.core.windows.net/'. Required.""" account_key: str = rest_field(name="accountKey", visibility=["read", "create", "update", "delete", "query"]) """The Azure Storage account key. Required.""" + azure_file_url: str = rest_field(name="azureFileUrl", visibility=["read", "create", "update", "delete", "query"]) + """The Azure Files URL. This is of the form 'https://{account}.file.core.windows.net/'. Required.""" relative_mount_path: str = rest_field( name="relativeMountPath", visibility=["read", "create", "update", "delete", "query"] ) @@ -414,8 +377,8 @@ def __init__( self, *, account_name: str, - azure_file_url: str, account_key: str, + azure_file_url: str, relative_mount_path: str, mount_options: Optional[str] = None, ) -> None: ... @@ -431,7 +394,43 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchApplication(_model_base.Model): +class BatchAffinityInfo(_Model): + """A locality hint that can be used by the Batch service to select a Compute Node + on which to start a Task. + + :ivar affinity_id: An opaque string representing the location of a Compute Node or a Task that + has run previously. You can pass the affinityId of a Node to indicate that this Task needs to + run on that 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 scheduled + elsewhere. Required. + :vartype affinity_id: str + """ + + affinity_id: str = rest_field(name="affinityId", visibility=["read", "create", "update", "delete", "query"]) + """An opaque string representing the location of a Compute Node or a Task that has run previously. + You can pass the affinityId of a Node to indicate that this Task needs to run on that 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 scheduled elsewhere. Required.""" + + @overload + def __init__( + self, + *, + affinity_id: str, + ) -> 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 BatchApplication(_Model): """Contains information about an application in an Azure Batch Account. :ivar id: A string that uniquely identifies the application within the Account. Required. @@ -446,7 +445,7 @@ class BatchApplication(_model_base.Model): """A string that uniquely identifies the application within the Account. Required.""" display_name: str = rest_field(name="displayName", visibility=["read", "create", "update", "delete", "query"]) """The display name for the application. Required.""" - versions: List[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + versions: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The list of available versions of the application. Required.""" @overload @@ -455,7 +454,7 @@ def __init__( *, id: str, # pylint: disable=redefined-builtin display_name: str, - versions: List[str], + versions: list[str], ) -> None: ... @overload @@ -469,7 +468,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchApplicationPackageReference(_model_base.Model): +class BatchApplicationPackageReference(_Model): """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 @@ -516,7 +515,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchAutoPoolSpecification(_model_base.Model): +class BatchAutoPoolSpecification(_Model): """Specifies characteristics for a temporary 'auto pool'. The Batch service will create this auto Pool when the Job is submitted. @@ -583,7 +582,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchCertificate(_model_base.Model): +class BatchCertificate(_Model): """A Certificate that can be installed on Compute Nodes and can be used to authenticate operations on the machine. @@ -611,9 +610,9 @@ class BatchCertificate(_model_base.Model): :vartype public_data: str :ivar delete_certificate_error: The error that occurred on the last attempt to delete this Certificate. This property is set only if the Certificate is in the DeleteFailed state. - :vartype delete_certificate_error: ~azure.batch.models.DeleteBatchCertificateError + :vartype delete_certificate_error: ~azure.batch.models.BatchCertificateDeleteError :ivar data: The base64-encoded contents of the Certificate. The maximum size is 10KB. Required. - :vartype data: str + :vartype data: bytes :ivar certificate_format: The format of the Certificate data. Known values are: "pfx" and "cer". :vartype certificate_format: str or ~azure.batch.models.BatchCertificateFormat @@ -649,12 +648,12 @@ class BatchCertificate(_model_base.Model): Certificate is in its initial Active state.""" public_data: Optional[str] = rest_field(name="publicData", visibility=["read"]) """The public part of the Certificate as a base-64 encoded .cer file.""" - delete_certificate_error: Optional["_models.DeleteBatchCertificateError"] = rest_field( + delete_certificate_error: Optional["_models.BatchCertificateDeleteError"] = rest_field( name="deleteCertificateError", visibility=["read"] ) """The error that occurred on the last attempt to delete this Certificate. This property is set only if the Certificate is in the DeleteFailed state.""" - data: str = rest_field(visibility=["create"]) + data: bytes = rest_field(visibility=["create"], format="base64") """The base64-encoded contents of the Certificate. The maximum size is 10KB. Required.""" certificate_format: Optional[Union[str, "_models.BatchCertificateFormat"]] = rest_field( name="certificateFormat", visibility=["create"] @@ -670,7 +669,7 @@ def __init__( *, thumbprint: str, thumbprint_algorithm: str, - data: str, + data: bytes, certificate_format: Optional[Union[str, "_models.BatchCertificateFormat"]] = None, password: Optional[str] = None, ) -> None: ... @@ -686,7 +685,57 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchCertificateReference(_model_base.Model): +class BatchCertificateDeleteError(_Model): + """An error encountered by the Batch service when deleting a Certificate. + + :ivar code: An identifier for the Certificate deletion error. Codes are invariant and are + intended to be consumed programmatically. + :vartype code: str + :ivar message: A message describing the Certificate deletion error, intended to be suitable for + display in a user interface. + :vartype message: str + :ivar values_property: A list of additional error details related to the Certificate deletion + error. This list includes details such as the active Pools and Compute Nodes referencing this + Certificate. However, if a large number of resources reference the Certificate, the list + contains only about the first hundred. + :vartype values_property: list[~azure.batch.models.NameValuePair] + """ + + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An identifier for the Certificate deletion error. Codes are invariant and are intended to be + consumed programmatically.""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A message describing the Certificate deletion error, intended to be suitable for display in a + user interface.""" + values_property: Optional[list["_models.NameValuePair"]] = rest_field( + name="values", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of additional error details related to the Certificate deletion error. This list + includes details such as the active Pools and Compute Nodes referencing this Certificate. + However, if a large number of resources reference the Certificate, the list contains only about + the first hundred.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + message: Optional[str] = None, + values_property: Optional[list["_models.NameValuePair"]] = 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 BatchCertificateReference(_Model): """A reference to a Certificate to be installed on Compute Nodes in a Pool. Warning: This object is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ @@ -745,7 +794,7 @@ class BatchCertificateReference(_model_base.Model): Image reference). Common store names include: My, Root, CA, Trust, Disallowed, TrustedPeople, TrustedPublisher, AuthRoot, AddressBook, but any custom store name can also be used. The default value is My.""" - visibility: Optional[List[Union[str, "_models.BatchCertificateVisibility"]]] = rest_field( + visibility: Optional[list[Union[str, "_models.BatchCertificateVisibility"]]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """Which user Accounts on the Compute Node should have access to the private data of the @@ -760,7 +809,138 @@ def __init__( thumbprint_algorithm: str, store_location: Optional[Union[str, "_models.BatchCertificateStoreLocation"]] = None, store_name: Optional[str] = None, - visibility: Optional[List[Union[str, "_models.BatchCertificateVisibility"]]] = None, + visibility: Optional[list[Union[str, "_models.BatchCertificateVisibility"]]] = 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 BatchContainerConfiguration(_Model): + """The configuration for container-enabled Pools. + + :ivar type: The container technology to be used. Required. Known values are: "dockerCompatible" + and "criCompatible". + :vartype type: str or ~azure.batch.models.ContainerType + :ivar container_image_names: The collection of container Image names. This is the full Image + reference, as would be specified to "docker pull". An Image will be sourced from the default + Docker registry unless the Image is fully qualified with an alternative registry. + :vartype container_image_names: list[str] + :ivar container_registries: Additional private registries from which containers can be pulled. + If any Images must be downloaded from a private registry which requires credentials, then those + credentials must be provided here. + :vartype container_registries: list[~azure.batch.models.ContainerRegistryReference] + """ + + type: Union[str, "_models.ContainerType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The container technology to be used. Required. Known values are: \"dockerCompatible\" and + \"criCompatible\".""" + container_image_names: Optional[list[str]] = rest_field( + name="containerImageNames", visibility=["read", "create", "update", "delete", "query"] + ) + """The collection of container Image names. This is the full Image reference, as would be + specified to \"docker pull\". An Image will be sourced from the default Docker registry unless + the Image is fully qualified with an alternative registry.""" + container_registries: Optional[list["_models.ContainerRegistryReference"]] = rest_field( + name="containerRegistries", visibility=["read", "create", "update", "delete", "query"] + ) + """Additional private registries from which containers can be pulled. If any Images must be + downloaded from a private registry which requires credentials, then those credentials must be + provided here.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.ContainerType"], + container_image_names: Optional[list[str]] = None, + container_registries: Optional[list["_models.ContainerRegistryReference"]] = 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 BatchCreateTaskCollectionResult(_Model): + """The result of creating a collection of Tasks to a Job. + + :ivar values_property: The results of the create Task collection operation. + :vartype values_property: list[~azure.batch.models.BatchTaskCreateResult] + """ + + values_property: Optional[list["_models.BatchTaskCreateResult"]] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] + ) + """The results of the create Task collection operation.""" + + @overload + def __init__( + self, + *, + values_property: Optional[list["_models.BatchTaskCreateResult"]] = 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 BatchDiffDiskSettings(_Model): + """Specifies the ephemeral Disk Settings for the operating system disk used by the + compute node (VM). + + :ivar placement: Specifies the ephemeral disk placement for operating system disk for all VMs + in the pool. This property can be used by user in the request to choose the location e.g., + cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk + size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at + `https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements + `_ + and Linux VMs at + `https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements + `_. + "cachedisk" + :vartype placement: str or ~azure.batch.models.DiffDiskPlacement + """ + + placement: Optional[Union[str, "_models.DiffDiskPlacement"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the ephemeral disk placement for operating system disk for all VMs in the pool. This + property can be used by user in the request to choose the location e.g., cache disk space for + Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, + please refer to Ephemeral OS disk size requirements for Windows VMs at + `https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements + `_ + and Linux VMs at + `https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements + `_. + \"cachedisk\"""" + + @overload + def __init__( + self, + *, + placement: Optional[Union[str, "_models.DiffDiskPlacement"]] = None, ) -> None: ... @overload @@ -774,11 +954,11 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchError(_model_base.Model): +class BatchError(_Model): """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 - programmatically. Required. + programmatically. :vartype code: str :ivar message: A message describing the error, intended to be suitable for display in a user interface. @@ -788,14 +968,14 @@ class BatchError(_model_base.Model): :vartype values_property: list[~azure.batch.models.BatchErrorDetail] """ - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """An identifier for the error. Codes are invariant and are intended to be consumed - programmatically. Required.""" + programmatically.""" message: Optional["_models.BatchErrorMessage"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A message describing the error, intended to be suitable for display in a user interface.""" - values_property: Optional[List["_models.BatchErrorDetail"]] = rest_field( + values_property: Optional[list["_models.BatchErrorDetail"]] = rest_field( name="values", visibility=["read", "create", "update", "delete", "query"] ) """A collection of key-value pairs containing additional details about the error.""" @@ -804,9 +984,9 @@ class BatchError(_model_base.Model): def __init__( self, *, - code: str, + code: Optional[str] = None, message: Optional["_models.BatchErrorMessage"] = None, - values_property: Optional[List["_models.BatchErrorDetail"]] = None, + values_property: Optional[list["_models.BatchErrorDetail"]] = None, ) -> None: ... @overload @@ -820,7 +1000,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchErrorDetail(_model_base.Model): +class BatchErrorDetail(_Model): """An item of additional information included in an Azure Batch error response. :ivar key: An identifier specifying the meaning of the Value property. @@ -853,7 +1033,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchErrorMessage(_model_base.Model): +class BatchErrorMessage(_Model): """An error message received in an Azure Batch error response. :ivar lang: The language code of the error message. @@ -886,15 +1066,115 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJob(_model_base.Model): - """An Azure Batch Job. +class BatchInboundNatPool(_Model): + """A inbound NAT Pool that can be used to address specific ports on Compute Nodes + in a Batch Pool externally. - :ivar id: A string that uniquely identifies the Job within the Account. The ID is - case-preserving and case-insensitive (that is, you may not have two IDs within an Account that - differ only by case). - :vartype id: str - :ivar display_name: The display name for the Job. - :vartype display_name: str + :ivar name: The name of the endpoint. The name must be unique within a Batch Pool, can contain + letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, + must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid + values are provided the request fails with HTTP status code 400. Required. + :vartype name: str + :ivar protocol: The protocol of the endpoint. Required. Known values are: "tcp" and "udp". + :vartype protocol: str or ~azure.batch.models.InboundEndpointProtocol + :ivar backend_port: The port number on the Compute Node. This must be unique within a Batch + Pool. Acceptable values are between 1 and 65535 except for 29876 and 29877 as these are + reserved. If any reserved values are provided the request fails with HTTP status code 400. + Required. + :vartype backend_port: int + :ivar frontend_port_range_start: The first port number in the range of external ports that will + be used to provide inbound access to the backendPort on individual Compute Nodes. Acceptable + values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All + ranges within a Pool must be distinct and cannot overlap. Each range must contain at least 40 + ports. If any reserved or overlapping values are provided the request fails with HTTP status + code 400. Required. + :vartype frontend_port_range_start: int + :ivar frontend_port_range_end: The last port number in the range of external ports that will be + used to provide inbound access to the backendPort on individual Compute Nodes. Acceptable + values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the + Batch service. All ranges within a Pool must be distinct and cannot overlap. Each range must + contain at least 40 ports. If any reserved or overlapping values are provided the request fails + with HTTP status code 400. Required. + :vartype frontend_port_range_end: int + :ivar network_security_group_rules: A list of network security group rules that will be applied + to the endpoint. The maximum number of rules that can be specified across all the endpoints on + a Batch Pool is 25. If no network security group rules are specified, a default rule will be + created to allow inbound access to the specified backendPort. If the maximum number of network + security group rules is exceeded the request fails with HTTP status code 400. + :vartype network_security_group_rules: list[~azure.batch.models.NetworkSecurityGroupRule] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the endpoint. The name must be unique within a Batch Pool, can contain letters, + numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end + with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values + are provided the request fails with HTTP status code 400. Required.""" + protocol: Union[str, "_models.InboundEndpointProtocol"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The protocol of the endpoint. Required. Known values are: \"tcp\" and \"udp\".""" + backend_port: int = rest_field(name="backendPort", visibility=["read", "create", "update", "delete", "query"]) + """The port number on the Compute Node. This must be unique within a Batch Pool. Acceptable values + are between 1 and 65535 except for 29876 and 29877 as these are reserved. If any reserved + values are provided the request fails with HTTP status code 400. Required.""" + frontend_port_range_start: int = rest_field( + name="frontendPortRangeStart", visibility=["read", "create", "update", "delete", "query"] + ) + """The first port number in the range of external ports that will be used to provide inbound + access to the backendPort on individual Compute Nodes. Acceptable values range between 1 and + 65534 except ports from 50000 to 55000 which are reserved. All ranges within a Pool must be + distinct and cannot overlap. Each range must contain at least 40 ports. If any reserved or + overlapping values are provided the request fails with HTTP status code 400. Required.""" + frontend_port_range_end: int = rest_field( + name="frontendPortRangeEnd", visibility=["read", "create", "update", "delete", "query"] + ) + """The last port number in the range of external ports that will be used to provide inbound access + to the backendPort on individual Compute Nodes. Acceptable values range between 1 and 65534 + except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a + Pool must be distinct and cannot overlap. Each range must contain at least 40 ports. If any + reserved or overlapping values are provided the request fails with HTTP status code 400. + Required.""" + network_security_group_rules: Optional[list["_models.NetworkSecurityGroupRule"]] = rest_field( + name="networkSecurityGroupRules", visibility=["read", "create", "update", "delete", "query"] + ) + """A list of network security group rules that will be applied to the endpoint. The maximum number + of rules that can be specified across all the endpoints on a Batch Pool is 25. If no network + security group rules are specified, a default rule will be created to allow inbound access to + the specified backendPort. If the maximum number of network security group rules is exceeded + the request fails with HTTP status code 400.""" + + @overload + def __init__( + self, + *, + name: str, + protocol: Union[str, "_models.InboundEndpointProtocol"], + backend_port: int, + frontend_port_range_start: int, + frontend_port_range_end: int, + network_security_group_rules: Optional[list["_models.NetworkSecurityGroupRule"]] = 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 BatchJob(_Model): + """An Azure Batch Job. + + :ivar id: A string that uniquely identifies the Job within the Account. The ID is + case-preserving and case-insensitive (that is, you may not have two IDs within an Account that + differ only by case). + :vartype id: str + :ivar display_name: The display name for the Job. + :vartype display_name: str :ivar uses_task_dependencies: Whether Tasks in the Job can define dependencies on each other. The default is false. :vartype uses_task_dependencies: bool @@ -954,28 +1234,28 @@ class BatchJob(_model_base.Model): :vartype common_environment_settings: list[~azure.batch.models.EnvironmentSetting] :ivar pool_info: The Pool settings associated with the Job. Required. :vartype pool_info: ~azure.batch.models.BatchPoolInfo - :ivar on_all_tasks_complete: The action the Batch service should take when all Tasks in the Job - are in the completed state. The default is noaction. Known values are: "noaction" and + :ivar all_tasks_complete_mode: The action the Batch service should take when all Tasks in the + Job are in the completed state. The default is noaction. Known values are: "noaction" and "terminatejob". - :vartype on_all_tasks_complete: str or ~azure.batch.models.OnAllBatchTasksComplete - :ivar on_task_failure: The action the Batch service should take when any Task in the Job fails. - A Task is considered to have failed if has a failureInfo. A failureInfo is set if the Task - completes with a non-zero exit code after exhausting its retry count, or if there was an error - starting the Task, for example due to a resource file download error. The default is noaction. - Known values are: "noaction" and "performexitoptionsjobaction". - :vartype on_task_failure: str or ~azure.batch.models.OnBatchTaskFailure + :vartype all_tasks_complete_mode: str or ~azure.batch.models.BatchAllTasksCompleteMode + :ivar task_failure_mode: The action the Batch service should take when any Task in the Job + fails. A Task is considered to have failed if has a failureInfo. A failureInfo is set if the + Task completes with a non-zero exit code after exhausting its retry count, or if there was an + error starting the Task, for example due to a resource file download error. The default is + noaction. Known values are: "noaction" and "performexitoptionsjobaction". + :vartype task_failure_mode: str or ~azure.batch.models.BatchTaskFailureMode :ivar network_configuration: The network configuration for the Job. :vartype network_configuration: ~azure.batch.models.BatchJobNetworkConfiguration :ivar metadata: A list of name-value pairs associated with the Job as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] :ivar execution_info: The execution information for the Job. :vartype execution_info: ~azure.batch.models.BatchJobExecutionInfo - :ivar stats: Resource usage statistics for the entire lifetime of the Job. This property is - populated only if the BatchJob was retrieved with an expand clause including the 'stats' - attribute; otherwise it is null. The statistics may not be immediately available. The Batch - service performs periodic roll-up of statistics. The typical delay is about 30 minutes. - :vartype stats: ~azure.batch.models.BatchJobStatistics + :ivar job_statistics: Resource usage statistics for the entire lifetime of the Job. This + property is populated only if the BatchJob was retrieved with an expand clause including the + 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The + Batch service performs periodic roll-up of statistics. The typical delay is about 30 minutes. + :vartype job_statistics: ~azure.batch.models.BatchJobStatistics """ id: Optional[str] = rest_field(visibility=["read"]) @@ -1048,7 +1328,7 @@ class BatchJob(_model_base.Model): job_release_task: Optional["_models.BatchJobReleaseTask"] = rest_field(name="jobReleaseTask", visibility=["read"]) """The Job Release Task. The Job Release Task is a special Task run at the end of the Job on each Compute Node that has run any other Task of the Job.""" - common_environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + common_environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="commonEnvironmentSettings", visibility=["read"] ) """The list of common environment variable settings. These environment variables are set for all @@ -1059,12 +1339,12 @@ class BatchJob(_model_base.Model): name="poolInfo", visibility=["read", "create", "update", "delete", "query"] ) """The Pool settings associated with the Job. Required.""" - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = rest_field( + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = rest_field( name="onAllTasksComplete", visibility=["read", "create", "update", "delete", "query"] ) """The action the Batch service should take when all Tasks in the Job are in the completed state. The default is noaction. Known values are: \"noaction\" and \"terminatejob\".""" - on_task_failure: Optional[Union[str, "_models.OnBatchTaskFailure"]] = rest_field( + task_failure_mode: Optional[Union[str, "_models.BatchTaskFailureMode"]] = rest_field( name="onTaskFailure", visibility=["read"] ) """The action the Batch service should take when any Task in the Job fails. A Task is considered @@ -1076,14 +1356,14 @@ class BatchJob(_model_base.Model): name="networkConfiguration", visibility=["read"] ) """The network configuration for the Job.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Job as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code.""" execution_info: Optional["_models.BatchJobExecutionInfo"] = rest_field(name="executionInfo", visibility=["read"]) """The execution information for the Job.""" - stats: Optional["_models.BatchJobStatistics"] = rest_field(visibility=["read"]) + job_statistics: Optional["_models.BatchJobStatistics"] = rest_field(name="stats", visibility=["read"]) """Resource usage statistics for the entire lifetime of the Job. This property is populated only if the BatchJob was retrieved with an expand clause including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch service performs @@ -1098,8 +1378,8 @@ def __init__( # pylint: disable=too-many-locals allow_task_preemption: Optional[bool] = None, max_parallel_tasks: Optional[int] = None, constraints: Optional["_models.BatchJobConstraints"] = None, - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, ) -> None: ... @overload @@ -1113,7 +1393,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobConstraints(_model_base.Model): +class BatchJobConstraints(_Model): """The execution constraints for a Job. :ivar max_wall_clock_time: The maximum elapsed time that the Job may run, measured from the @@ -1169,7 +1449,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobCreateContent(_model_base.Model): +class BatchJobCreateOptions(_Model): """Parameters for creating an Azure Batch Job. :ivar id: A string that uniquely identifies the Job within the Account. The ID can contain any @@ -1228,25 +1508,25 @@ class BatchJobCreateContent(_model_base.Model): :vartype common_environment_settings: list[~azure.batch.models.EnvironmentSetting] :ivar pool_info: The Pool on which the Batch service runs the Job's Tasks. Required. :vartype pool_info: ~azure.batch.models.BatchPoolInfo - :ivar on_all_tasks_complete: The action the Batch service should take when all Tasks in the Job - are in the completed state. Note that if a Job contains no Tasks, then all Tasks are considered - complete. This option is therefore most commonly used with a Job Manager task; if you want to - use automatic Job termination without a Job Manager, you should initially set + :ivar all_tasks_complete_mode: The action the Batch service should take when all Tasks in the + Job are in the completed state. Note that if a Job contains no Tasks, then all Tasks are + considered complete. This option is therefore most commonly used with a Job Manager task; if + you want to use automatic Job termination without a Job Manager, you should initially set onAllTasksComplete to noaction and update the Job properties to set onAllTasksComplete to terminatejob once you have finished adding Tasks. The default is noaction. Known values are: "noaction" and "terminatejob". - :vartype on_all_tasks_complete: str or ~azure.batch.models.OnAllBatchTasksComplete - :ivar on_task_failure: The action the Batch service should take when any Task in the Job fails. - A Task is considered to have failed if has a failureInfo. A failureInfo is set if the Task - completes with a non-zero exit code after exhausting its retry count, or if there was an error - starting the Task, for example due to a resource file download error. The default is noaction. - Known values are: "noaction" and "performexitoptionsjobaction". - :vartype on_task_failure: str or ~azure.batch.models.OnBatchTaskFailure + :vartype all_tasks_complete_mode: str or ~azure.batch.models.BatchAllTasksCompleteMode + :ivar task_failure_mode: The action the Batch service should take when any Task in the Job + fails. A Task is considered to have failed if has a failureInfo. A failureInfo is set if the + Task completes with a non-zero exit code after exhausting its retry count, or if there was an + error starting the Task, for example due to a resource file download error. The default is + noaction. Known values are: "noaction" and "performexitoptionsjobaction". + :vartype task_failure_mode: str or ~azure.batch.models.BatchTaskFailureMode :ivar network_configuration: The network configuration for the Job. :vartype network_configuration: ~azure.batch.models.BatchJobNetworkConfiguration :ivar metadata: A list of name-value pairs associated with the Job as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] """ id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -1310,7 +1590,7 @@ class BatchJobCreateContent(_model_base.Model): have run the Job Preparation Task. The primary purpose of the Job Release Task is to undo changes to Compute Nodes made by the Job Preparation Task. Example activities include deleting local files, or shutting down services that were started as part of Job preparation.""" - common_environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + common_environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="commonEnvironmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """The list of common environment variable settings. These environment variables are set for all @@ -1321,7 +1601,7 @@ class BatchJobCreateContent(_model_base.Model): name="poolInfo", visibility=["read", "create", "update", "delete", "query"] ) """The Pool on which the Batch service runs the Job's Tasks. Required.""" - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = rest_field( + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = rest_field( name="onAllTasksComplete", visibility=["read", "create", "update", "delete", "query"] ) """The action the Batch service should take when all Tasks in the Job are in the completed state. @@ -1330,7 +1610,7 @@ class BatchJobCreateContent(_model_base.Model): termination without a Job Manager, you should initially set onAllTasksComplete to noaction and update the Job properties to set onAllTasksComplete to terminatejob once you have finished adding Tasks. The default is noaction. Known values are: \"noaction\" and \"terminatejob\".""" - on_task_failure: Optional[Union[str, "_models.OnBatchTaskFailure"]] = rest_field( + task_failure_mode: Optional[Union[str, "_models.BatchTaskFailureMode"]] = rest_field( name="onTaskFailure", visibility=["read", "create", "update", "delete", "query"] ) """The action the Batch service should take when any Task in the Job fails. A Task is considered @@ -1342,7 +1622,7 @@ class BatchJobCreateContent(_model_base.Model): name="networkConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The network configuration for the Job.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Job as metadata. The Batch service does not @@ -1363,11 +1643,11 @@ def __init__( job_manager_task: Optional["_models.BatchJobManagerTask"] = None, job_preparation_task: Optional["_models.BatchJobPreparationTask"] = None, job_release_task: Optional["_models.BatchJobReleaseTask"] = None, - common_environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = None, - on_task_failure: Optional[Union[str, "_models.OnBatchTaskFailure"]] = None, + common_environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = None, + task_failure_mode: Optional[Union[str, "_models.BatchTaskFailureMode"]] = None, network_configuration: Optional["_models.BatchJobNetworkConfiguration"] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, ) -> None: ... @overload @@ -1381,7 +1661,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobDisableContent(_model_base.Model): +class BatchJobDisableOptions(_Model): """Parameters for disabling an Azure Batch Job. :ivar disable_tasks: What to do with active Tasks associated with the Job. Required. Known @@ -1413,7 +1693,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobExecutionInfo(_model_base.Model): +class BatchJobExecutionInfo(_Model): """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. @@ -1500,7 +1780,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobManagerTask(_model_base.Model): +class BatchJobManagerTask(_Model): """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 @@ -1648,7 +1928,7 @@ class BatchJobManagerTask(_model_base.Model): are mapped into the container, and the Task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will not be able to access those files.""" - resource_files: Optional[List["_models.ResourceFile"]] = rest_field( + resource_files: Optional[list["_models.ResourceFile"]] = rest_field( name="resourceFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will download to the Compute Node before running the @@ -1657,13 +1937,13 @@ class BatchJobManagerTask(_model_base.Model): request will fail and the response error code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.""" - output_files: Optional[List["_models.OutputFile"]] = rest_field( + output_files: Optional[list["_models.OutputFile"]] = rest_field( name="outputFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will upload from the Compute Node after running the command line. For multi-instance Tasks, the files will only be uploaded from the Compute Node on which the primary Task is executed.""" - environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="environmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """A list of environment variable settings for the Job Manager Task.""" @@ -1703,7 +1983,7 @@ class BatchJobManagerTask(_model_base.Model): other Tasks can run simultaneously with the Job Manager on a Compute Node. The Job Manager Task counts normally against the Compute Node's concurrent Task limit, so this is only relevant if the Compute Node allows multiple concurrent Tasks. The default value is true.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read", "create", "update", "delete", "query"] ) """A list of Application Packages that the Batch service will deploy to the @@ -1738,15 +2018,15 @@ def __init__( command_line: str, display_name: Optional[str] = None, container_settings: Optional["_models.BatchTaskContainerSettings"] = None, - resource_files: Optional[List["_models.ResourceFile"]] = None, - output_files: Optional[List["_models.OutputFile"]] = None, - environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, + resource_files: Optional[list["_models.ResourceFile"]] = None, + output_files: Optional[list["_models.OutputFile"]] = None, + environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, constraints: Optional["_models.BatchTaskConstraints"] = None, required_slots: Optional[int] = None, kill_job_on_completion: Optional[bool] = None, user_identity: Optional["_models.UserIdentity"] = None, run_exclusive: Optional[bool] = None, - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = None, + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = None, authentication_token_settings: Optional["_models.AuthenticationTokenSettings"] = None, allow_low_priority_node: Optional[bool] = None, ) -> None: ... @@ -1762,7 +2042,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobNetworkConfiguration(_model_base.Model): +class BatchJobNetworkConfiguration(_Model): """The network configuration for the Job. :ivar subnet_id: The ARM resource identifier of the virtual network subnet which Compute Nodes @@ -1786,11 +2066,11 @@ class BatchJobNetworkConfiguration(_model_base.Model): `_. Required. :vartype subnet_id: str - :ivar skip_withdraw_from_v_net: Whether to withdraw Compute Nodes from the virtual network to + :ivar skip_withdraw_from_vnet: Whether to withdraw Compute Nodes from the virtual network to DNC when the job is terminated or deleted. If true, nodes will remain joined to the virtual network to DNC. If false, nodes will automatically withdraw when the job ends. Defaults to - false. Required. - :vartype skip_withdraw_from_v_net: bool + false. + :vartype skip_withdraw_from_vnet: bool """ subnet_id: str = rest_field(name="subnetId", visibility=["read", "create", "update", "delete", "query"]) @@ -1813,19 +2093,19 @@ class BatchJobNetworkConfiguration(_model_base.Model): `https://learn.microsoft.com/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration `_. Required.""" - skip_withdraw_from_v_net: bool = rest_field( + skip_withdraw_from_vnet: Optional[bool] = rest_field( name="skipWithdrawFromVNet", visibility=["read", "create", "update", "delete", "query"] ) """Whether to withdraw Compute Nodes from the virtual network to DNC when the job is terminated or deleted. If true, nodes will remain joined to the virtual network to DNC. If false, nodes will - automatically withdraw when the job ends. Defaults to false. Required.""" + automatically withdraw when the job ends. Defaults to false.""" @overload def __init__( self, *, subnet_id: str, - skip_withdraw_from_v_net: bool, + skip_withdraw_from_vnet: Optional[bool] = None, ) -> None: ... @overload @@ -1839,7 +2119,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobPreparationAndReleaseTaskStatus(_model_base.Model): +class BatchJobPreparationAndReleaseTaskStatus(_Model): """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. @@ -1896,7 +2176,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobPreparationTask(_model_base.Model): +class BatchJobPreparationTask(_Model): """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 @@ -2014,7 +2294,7 @@ class BatchJobPreparationTask(_model_base.Model): are mapped into the container, and the Task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will not be able to access those files.""" - resource_files: Optional[List["_models.ResourceFile"]] = rest_field( + resource_files: Optional[list["_models.ResourceFile"]] = rest_field( name="resourceFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will download to the Compute Node before running the @@ -2023,7 +2303,7 @@ class BatchJobPreparationTask(_model_base.Model): request will fail and the response error code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.""" - environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="environmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """A list of environment variable settings for the Job Preparation Task.""" @@ -2067,8 +2347,8 @@ def __init__( command_line: str, id: Optional[str] = None, # pylint: disable=redefined-builtin container_settings: Optional["_models.BatchTaskContainerSettings"] = None, - resource_files: Optional[List["_models.ResourceFile"]] = None, - environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, + resource_files: Optional[list["_models.ResourceFile"]] = None, + environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, constraints: Optional["_models.BatchTaskConstraints"] = None, wait_for_success: Optional[bool] = None, user_identity: Optional["_models.UserIdentity"] = None, @@ -2086,7 +2366,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobPreparationTaskExecutionInfo(_model_base.Model): +class BatchJobPreparationTaskExecutionInfo(_Model): """Contains information about the execution of a Job Preparation Task on a Compute Node. @@ -2228,7 +2508,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobReleaseTask(_model_base.Model): +class BatchJobReleaseTask(_Model): """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 @@ -2324,7 +2604,7 @@ class BatchJobReleaseTask(_model_base.Model): mapped into the container, and the Task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will not be able to access those files.""" - resource_files: Optional[List["_models.ResourceFile"]] = rest_field( + resource_files: Optional[list["_models.ResourceFile"]] = rest_field( name="resourceFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will download to the Compute Node before running the @@ -2333,7 +2613,7 @@ class BatchJobReleaseTask(_model_base.Model): this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers. Files listed under this element are located in the Task's working directory.""" - environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="environmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """A list of environment variable settings for the Job Release Task.""" @@ -2365,8 +2645,8 @@ def __init__( command_line: str, id: Optional[str] = None, # pylint: disable=redefined-builtin container_settings: Optional["_models.BatchTaskContainerSettings"] = None, - resource_files: Optional[List["_models.ResourceFile"]] = None, - environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, + resource_files: Optional[list["_models.ResourceFile"]] = None, + environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, max_wall_clock_time: Optional[datetime.timedelta] = None, retention_time: Optional[datetime.timedelta] = None, user_identity: Optional["_models.UserIdentity"] = None, @@ -2383,7 +2663,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobReleaseTaskExecutionInfo(_model_base.Model): +class BatchJobReleaseTaskExecutionInfo(_Model): """Contains information about the execution of a Job Release Task on a Compute Node. @@ -2494,7 +2774,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobSchedule(_model_base.Model): +class BatchJobSchedule(_Model): """A Job Schedule that allows recurring Jobs by specifying when to run Jobs and a specification used to create each Job. @@ -2537,11 +2817,11 @@ class BatchJobSchedule(_model_base.Model): :vartype execution_info: ~azure.batch.models.BatchJobScheduleExecutionInfo :ivar metadata: A list of name-value pairs associated with the schedule as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] - :ivar stats: The lifetime resource usage statistics for the Job Schedule. The statistics may - not be immediately available. The Batch service performs periodic roll-up of statistics. The - typical delay is about 30 minutes. - :vartype stats: ~azure.batch.models.BatchJobScheduleStatistics + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] + :ivar job_schedule_statistics: The lifetime resource usage statistics for the Job Schedule. The + statistics may not be immediately available. The Batch service performs periodic roll-up of + statistics. The typical delay is about 30 minutes. + :vartype job_schedule_statistics: ~azure.batch.models.BatchJobScheduleStatistics """ id: Optional[str] = rest_field(visibility=["read"]) @@ -2592,12 +2872,14 @@ class BatchJobSchedule(_model_base.Model): name="executionInfo", visibility=["read"] ) """Information about Jobs that have been and will be run under this schedule.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the schedule as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code.""" - stats: Optional["_models.BatchJobScheduleStatistics"] = rest_field(visibility=["read"]) + job_schedule_statistics: Optional["_models.BatchJobScheduleStatistics"] = rest_field( + name="stats", visibility=["read"] + ) """The lifetime resource usage statistics for the Job Schedule. The statistics may not be immediately available. The Batch service performs periodic roll-up of statistics. The typical delay is about 30 minutes.""" @@ -2608,7 +2890,7 @@ def __init__( *, job_specification: "_models.BatchJobSpecification", schedule: Optional["_models.BatchJobScheduleConfiguration"] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, ) -> None: ... @overload @@ -2622,7 +2904,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleConfiguration(_model_base.Model): +class BatchJobScheduleConfiguration(_Model): """The schedule according to which Jobs will be created. All times are fixed respective to UTC and are not impacted by daylight saving time. @@ -2726,7 +3008,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleCreateContent(_model_base.Model): +class BatchJobScheduleCreateOptions(_Model): """Parameters for creating an Azure Batch Job Schedule. :ivar id: A string that uniquely identifies the schedule within the Account. The ID can contain @@ -2744,7 +3026,7 @@ class BatchJobScheduleCreateContent(_model_base.Model): :vartype job_specification: ~azure.batch.models.BatchJobSpecification :ivar metadata: A list of name-value pairs associated with the schedule as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] """ id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -2766,7 +3048,7 @@ class BatchJobScheduleCreateContent(_model_base.Model): name="jobSpecification", visibility=["read", "create", "update", "delete", "query"] ) """The details of the Jobs to be created on this schedule. Required.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the schedule as metadata. The Batch service does not @@ -2780,7 +3062,7 @@ def __init__( schedule: "_models.BatchJobScheduleConfiguration", job_specification: "_models.BatchJobSpecification", display_name: Optional[str] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, ) -> None: ... @overload @@ -2794,7 +3076,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleExecutionInfo(_model_base.Model): +class BatchJobScheduleExecutionInfo(_Model): """Contains information about Jobs that have been and will be run under a Job Schedule. @@ -2849,7 +3131,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleStatistics(_model_base.Model): +class BatchJobScheduleStatistics(_Model): """Resource usage statistics for a Job Schedule. :ivar url: The URL of the statistics. Required. @@ -2871,29 +3153,29 @@ class BatchJobScheduleStatistics(_model_base.Model): had not finished by then). If a Task was retried, this includes the wall clock time of all the Task retries. Required. :vartype wall_clock_time: ~datetime.timedelta - :ivar read_i_ops: The total number of disk read operations made by all Tasks in all Jobs - created under the schedule. Required. - :vartype read_i_ops: int - :ivar write_i_ops: The total number of disk write operations made by all Tasks in all Jobs + :ivar read_iops: The total number of disk read operations made by all Tasks in all Jobs created + under the schedule. Required. + :vartype read_iops: int + :ivar write_iops: The total number of disk write operations made by all Tasks in all Jobs created under the schedule. Required. - :vartype write_i_ops: int + :vartype write_iops: int :ivar read_io_gi_b: The total gibibytes read from disk by all Tasks in all Jobs created under the schedule. Required. :vartype read_io_gi_b: float :ivar write_io_gi_b: The total gibibytes written to disk by all Tasks in all Jobs created under the schedule. Required. :vartype write_io_gi_b: float - :ivar num_succeeded_tasks: The total number of Tasks successfully completed during the given + :ivar succeeded_tasks_count: The total number of Tasks successfully completed during the given time range in Jobs created under the schedule. A Task completes successfully if it returns exit code 0. Required. - :vartype num_succeeded_tasks: int - :ivar num_failed_tasks: The total number of Tasks that failed during the given time range in + :vartype succeeded_tasks_count: int + :ivar failed_tasks_count: The total number of Tasks that failed during the given time range in Jobs created under the schedule. A Task fails if it exhausts its maximum retry count without returning exit code 0. Required. - :vartype num_failed_tasks: int - :ivar num_task_retries: The total number of retries during the given time range on all Tasks in - all Jobs created under the schedule. Required. - :vartype num_task_retries: int + :vartype failed_tasks_count: int + :ivar task_retries_count: The total number of retries during the given time range on all Tasks + in all Jobs created under the schedule. Required. + :vartype task_retries_count: int :ivar wait_time: The total wait time of all Tasks in all Jobs created under the schedule. The wait time for a Task is defined as the elapsed time between the creation of the Task and the start of Task execution. (If the Task is retried due to failures, the wait time is the time to @@ -2931,12 +3213,12 @@ class BatchJobScheduleStatistics(_model_base.Model): finished (or to the last time the statistics were updated, if the Task had not finished by then). If a Task was retried, this includes the wall clock time of all the Task retries. Required.""" - read_i_ops: int = rest_field( + read_iops: int = rest_field( name="readIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk read operations made by all Tasks in all Jobs created under the schedule. Required.""" - write_i_ops: int = rest_field( + write_iops: int = rest_field( name="writeIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk write operations made by all Tasks in all Jobs created under the @@ -2947,18 +3229,18 @@ class BatchJobScheduleStatistics(_model_base.Model): write_io_gi_b: float = rest_field(name="writeIOGiB", visibility=["read", "create", "update", "delete", "query"]) """The total gibibytes written to disk by all Tasks in all Jobs created under the schedule. Required.""" - num_succeeded_tasks: int = rest_field( + succeeded_tasks_count: int = rest_field( name="numSucceededTasks", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of Tasks successfully completed during the given time range in Jobs created under the schedule. A Task completes successfully if it returns exit code 0. Required.""" - num_failed_tasks: int = rest_field( + failed_tasks_count: int = rest_field( name="numFailedTasks", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of Tasks that failed during the given time range in Jobs created under the schedule. A Task fails if it exhausts its maximum retry count without returning exit code 0. Required.""" - num_task_retries: int = rest_field( + task_retries_count: int = rest_field( name="numTaskRetries", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of retries during the given time range on all Tasks in all Jobs created under @@ -2982,13 +3264,13 @@ def __init__( user_cpu_time: datetime.timedelta, kernel_cpu_time: datetime.timedelta, wall_clock_time: datetime.timedelta, - read_i_ops: int, - write_i_ops: int, + read_iops: int, + write_iops: int, read_io_gi_b: float, write_io_gi_b: float, - num_succeeded_tasks: int, - num_failed_tasks: int, - num_task_retries: int, + succeeded_tasks_count: int, + failed_tasks_count: int, + task_retries_count: int, wait_time: datetime.timedelta, ) -> None: ... @@ -3003,7 +3285,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobScheduleUpdateContent(_model_base.Model): +class BatchJobScheduleUpdateOptions(_Model): """Parameters for updating an Azure Batch Job Schedule. :ivar schedule: The schedule according to which Jobs will be created. All times are fixed @@ -3016,7 +3298,7 @@ class BatchJobScheduleUpdateContent(_model_base.Model): :vartype job_specification: ~azure.batch.models.BatchJobSpecification :ivar metadata: A list of name-value pairs associated with the Job Schedule as metadata. If you do not specify this element, existing metadata is left unchanged. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] """ schedule: Optional["_models.BatchJobScheduleConfiguration"] = rest_field( @@ -3031,7 +3313,7 @@ class BatchJobScheduleUpdateContent(_model_base.Model): """The details of the Jobs to be created on this schedule. Updates affect only Jobs that are started after the update has taken place. Any currently active Job continues with the older specification.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Job Schedule as metadata. If you do not specify @@ -3043,7 +3325,7 @@ def __init__( *, schedule: Optional["_models.BatchJobScheduleConfiguration"] = None, job_specification: Optional["_models.BatchJobSpecification"] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, ) -> None: ... @overload @@ -3057,12 +3339,12 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobSchedulingError(_model_base.Model): +class BatchJobSchedulingError(_Model): """An error encountered by the Batch service when scheduling a Job. :ivar category: The category of the Job scheduling error. Required. Known values are: "usererror" and "servererror". - :vartype category: str or ~azure.batch.models.ErrorCategory + :vartype category: str or ~azure.batch.models.BatchErrorSourceCategory :ivar code: An identifier for the Job scheduling error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str @@ -3073,7 +3355,7 @@ class BatchJobSchedulingError(_model_base.Model): :vartype details: list[~azure.batch.models.NameValuePair] """ - category: Union[str, "_models.ErrorCategory"] = rest_field( + category: Union[str, "_models.BatchErrorSourceCategory"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """The category of the Job scheduling error. Required. Known values are: \"usererror\" and @@ -3084,7 +3366,7 @@ class BatchJobSchedulingError(_model_base.Model): message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A message describing the Job scheduling error, intended to be suitable for display in a user interface.""" - details: Optional[List["_models.NameValuePair"]] = rest_field( + details: Optional[list["_models.NameValuePair"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of additional error details related to the scheduling error.""" @@ -3093,10 +3375,10 @@ class BatchJobSchedulingError(_model_base.Model): def __init__( self, *, - category: Union[str, "_models.ErrorCategory"], + category: Union[str, "_models.BatchErrorSourceCategory"], code: Optional[str] = None, message: Optional[str] = None, - details: Optional[List["_models.NameValuePair"]] = None, + details: Optional[list["_models.NameValuePair"]] = None, ) -> None: ... @overload @@ -3110,7 +3392,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobSpecification(_model_base.Model): +class BatchJobSpecification(_Model): """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 @@ -3136,21 +3418,21 @@ class BatchJobSpecification(_model_base.Model): :ivar uses_task_dependencies: Whether Tasks in the Job can define dependencies on each other. The default is false. :vartype uses_task_dependencies: bool - :ivar on_all_tasks_complete: The action the Batch service should take when all Tasks in a Job + :ivar all_tasks_complete_mode: The action the Batch service should take when all Tasks in a Job created under this schedule are in the completed state. Note that if a Job contains no Tasks, then all Tasks are considered complete. This option is therefore most commonly used with a Job Manager task; if you want to use automatic Job termination without a Job Manager, you should initially set onAllTasksComplete to noaction and update the Job properties to set onAllTasksComplete to terminatejob once you have finished adding Tasks. The default is noaction. Known values are: "noaction" and "terminatejob". - :vartype on_all_tasks_complete: str or ~azure.batch.models.OnAllBatchTasksComplete - :ivar on_task_failure: The action the Batch service should take when any Task fails in a Job + :vartype all_tasks_complete_mode: str or ~azure.batch.models.BatchAllTasksCompleteMode + :ivar task_failure_mode: The action the Batch service should take when any Task fails in a Job created under this schedule. A Task is considered to have failed if it have failed if has a failureInfo. A failureInfo is set if the Task completes with a non-zero exit code after exhausting its retry count, or if there was an error starting the Task, for example due to a resource file download error. The default is noaction. Known values are: "noaction" and "performexitoptionsjobaction". - :vartype on_task_failure: str or ~azure.batch.models.OnBatchTaskFailure + :vartype task_failure_mode: str or ~azure.batch.models.BatchTaskFailureMode :ivar network_configuration: The network configuration for the Job. :vartype network_configuration: ~azure.batch.models.BatchJobNetworkConfiguration :ivar constraints: The execution constraints for Jobs created under this schedule. @@ -3183,7 +3465,7 @@ class BatchJobSpecification(_model_base.Model): :ivar metadata: A list of name-value pairs associated with each Job created under this schedule as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] """ priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -3214,7 +3496,7 @@ class BatchJobSpecification(_model_base.Model): name="usesTaskDependencies", visibility=["read", "create", "update", "delete", "query"] ) """Whether Tasks in the Job can define dependencies on each other. The default is false.""" - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = rest_field( + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = rest_field( name="onAllTasksComplete", visibility=["read", "create", "update", "delete", "query"] ) """The action the Batch service should take when all Tasks in a Job created under this schedule @@ -3224,7 +3506,7 @@ class BatchJobSpecification(_model_base.Model): onAllTasksComplete to noaction and update the Job properties to set onAllTasksComplete to terminatejob once you have finished adding Tasks. The default is noaction. Known values are: \"noaction\" and \"terminatejob\".""" - on_task_failure: Optional[Union[str, "_models.OnBatchTaskFailure"]] = rest_field( + task_failure_mode: Optional[Union[str, "_models.BatchTaskFailureMode"]] = rest_field( name="onTaskFailure", visibility=["read", "create", "update", "delete", "query"] ) """The action the Batch service should take when any Task fails in a Job created under this @@ -3264,7 +3546,7 @@ class BatchJobSpecification(_model_base.Model): preparation. A Job Release Task cannot be specified without also specifying a Job Preparation Task for the Job. The Batch service runs the Job Release Task on the Compute Nodes that have run the Job Preparation Task.""" - common_environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + common_environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="commonEnvironmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """A list of common environment variable settings. These environment variables are set for all @@ -3276,7 +3558,7 @@ class BatchJobSpecification(_model_base.Model): ) """The Pool on which the Batch service runs the Tasks of Jobs created under this schedule. Required.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with each Job created under this schedule as metadata. @@ -3293,15 +3575,15 @@ def __init__( max_parallel_tasks: Optional[int] = None, display_name: Optional[str] = None, uses_task_dependencies: Optional[bool] = None, - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = None, - on_task_failure: Optional[Union[str, "_models.OnBatchTaskFailure"]] = None, + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = None, + task_failure_mode: Optional[Union[str, "_models.BatchTaskFailureMode"]] = None, network_configuration: Optional["_models.BatchJobNetworkConfiguration"] = None, constraints: Optional["_models.BatchJobConstraints"] = None, job_manager_task: Optional["_models.BatchJobManagerTask"] = None, job_preparation_task: Optional["_models.BatchJobPreparationTask"] = None, job_release_task: Optional["_models.BatchJobReleaseTask"] = None, - common_environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + common_environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, ) -> None: ... @overload @@ -3315,7 +3597,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobStatistics(_model_base.Model): +class BatchJobStatistics(_Model): """Resource usage statistics for a Job. :ivar url: The URL of the statistics. Required. @@ -3336,28 +3618,28 @@ class BatchJobStatistics(_model_base.Model): (or to the last time the statistics were updated, if the Task had not finished by then). If a Task was retried, this includes the wall clock time of all the Task retries. Required. :vartype wall_clock_time: ~datetime.timedelta - :ivar read_i_ops: The total number of disk read operations made by all Tasks in the Job. + :ivar read_iops: The total number of disk read operations made by all Tasks in the Job. Required. - :vartype read_i_ops: int - :ivar write_i_ops: The total number of disk write operations made by all Tasks in the Job. + :vartype read_iops: int + :ivar write_iops: The total number of disk write operations made by all Tasks in the Job. Required. - :vartype write_i_ops: int + :vartype write_iops: int :ivar read_io_gi_b: The total amount of data in GiB read from disk by all Tasks in the Job. Required. :vartype read_io_gi_b: float :ivar write_io_gi_b: The total amount of data in GiB written to disk by all Tasks in the Job. Required. :vartype write_io_gi_b: float - :ivar num_succeeded_tasks: The total number of Tasks successfully completed in the Job during + :ivar succeeded_tasks_count: The total number of Tasks successfully completed in the Job during the given time range. A Task completes successfully if it returns exit code 0. Required. - :vartype num_succeeded_tasks: int - :ivar num_failed_tasks: The total number of Tasks in the Job that failed during the given time - range. A Task fails if it exhausts its maximum retry count without returning exit code 0. + :vartype succeeded_tasks_count: int + :ivar failed_tasks_count: The total number of Tasks in the Job that failed during the given + time range. A Task fails if it exhausts its maximum retry count without returning exit code 0. Required. - :vartype num_failed_tasks: int - :ivar num_task_retries: The total number of retries on all the Tasks in the Job during the + :vartype failed_tasks_count: int + :ivar task_retries_count: The total number of retries on all the Tasks in the Job during the given time range. Required. - :vartype num_task_retries: int + :vartype task_retries_count: int :ivar wait_time: The total wait time of all Tasks in the Job. The wait time for a Task is defined as the elapsed time between the creation of the Task and the start of Task execution. (If the Task is retried due to failures, the wait time is the time to the most recent Task @@ -3394,11 +3676,11 @@ class BatchJobStatistics(_model_base.Model): from when the Task started running on a Compute Node to when it finished (or to the last time the statistics were updated, if the Task had not finished by then). If a Task was retried, this includes the wall clock time of all the Task retries. Required.""" - read_i_ops: int = rest_field( + read_iops: int = rest_field( name="readIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk read operations made by all Tasks in the Job. Required.""" - write_i_ops: int = rest_field( + write_iops: int = rest_field( name="writeIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk write operations made by all Tasks in the Job. Required.""" @@ -3406,17 +3688,17 @@ class BatchJobStatistics(_model_base.Model): """The total amount of data in GiB read from disk by all Tasks in the Job. Required.""" write_io_gi_b: float = rest_field(name="writeIOGiB", visibility=["read", "create", "update", "delete", "query"]) """The total amount of data in GiB written to disk by all Tasks in the Job. Required.""" - num_succeeded_tasks: int = rest_field( + succeeded_tasks_count: int = rest_field( name="numSucceededTasks", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of Tasks successfully completed in the Job during the given time range. A Task completes successfully if it returns exit code 0. Required.""" - num_failed_tasks: int = rest_field( + failed_tasks_count: int = rest_field( name="numFailedTasks", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of Tasks in the Job that failed during the given time range. A Task fails if it exhausts its maximum retry count without returning exit code 0. Required.""" - num_task_retries: int = rest_field( + task_retries_count: int = rest_field( name="numTaskRetries", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of retries on all the Tasks in the Job during the given time range. Required.""" @@ -3439,13 +3721,13 @@ def __init__( user_cpu_time: datetime.timedelta, kernel_cpu_time: datetime.timedelta, wall_clock_time: datetime.timedelta, - read_i_ops: int, - write_i_ops: int, + read_iops: int, + write_iops: int, read_io_gi_b: float, write_io_gi_b: float, - num_succeeded_tasks: int, - num_failed_tasks: int, - num_task_retries: int, + succeeded_tasks_count: int, + failed_tasks_count: int, + task_retries_count: int, wait_time: datetime.timedelta, ) -> None: ... @@ -3460,7 +3742,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobTerminateContent(_model_base.Model): +class BatchJobTerminateOptions(_Model): """Parameters for terminating an Azure Batch Job. :ivar termination_reason: The text you want to appear as the Job's TerminationReason. The @@ -3491,7 +3773,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchJobUpdateContent(_model_base.Model): +class BatchJobUpdateOptions(_Model): """Parameters for updating an Azure Batch Job. :ivar priority: The priority of the Job. Priority values can range from -1000 to 1000, with @@ -3519,16 +3801,16 @@ class BatchJobUpdateContent(_model_base.Model): only if the autoPoolSpecification has a poolLifetimeOption of Job (other job properties can be updated as normal). If omitted, the Job continues to run on its current Pool. :vartype pool_info: ~azure.batch.models.BatchPoolInfo - :ivar on_all_tasks_complete: The action the Batch service should take when all Tasks in the Job - are in the completed state. If omitted, the completion behavior is left unchanged. You may not - change the value from terminatejob to noaction - that is, once you have engaged automatic Job - termination, you cannot turn it off again. If you try to do this, the request fails with an + :ivar all_tasks_complete_mode: The action the Batch service should take when all Tasks in the + Job are in the completed state. If omitted, the completion behavior is left unchanged. You may + not change the value from terminatejob to noaction - that is, once you have engaged automatic + Job termination, you cannot turn it off again. If you try to do this, the request fails with an 'invalid property value' error response; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). Known values are: "noaction" and "terminatejob". - :vartype on_all_tasks_complete: str or ~azure.batch.models.OnAllBatchTasksComplete + :vartype all_tasks_complete_mode: str or ~azure.batch.models.BatchAllTasksCompleteMode :ivar metadata: A list of name-value pairs associated with the Job as metadata. If omitted, the existing Job metadata is left unchanged. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] :ivar network_configuration: The network configuration for the Job. :vartype network_configuration: ~azure.batch.models.BatchJobNetworkConfiguration """ @@ -3565,7 +3847,7 @@ class BatchJobUpdateContent(_model_base.Model): keepAlive property of the autoPoolSpecification can be updated, and then only if the autoPoolSpecification has a poolLifetimeOption of Job (other job properties can be updated as normal). If omitted, the Job continues to run on its current Pool.""" - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = rest_field( + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = rest_field( name="onAllTasksComplete", visibility=["read", "create", "update", "delete", "query"] ) """The action the Batch service should take when all Tasks in the Job are in the completed state. @@ -3574,7 +3856,7 @@ class BatchJobUpdateContent(_model_base.Model): turn it off again. If you try to do this, the request fails with an 'invalid property value' error response; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). Known values are: \"noaction\" and \"terminatejob\".""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Job as metadata. If omitted, the existing Job @@ -3593,8 +3875,8 @@ def __init__( max_parallel_tasks: Optional[int] = None, constraints: Optional["_models.BatchJobConstraints"] = None, pool_info: Optional["_models.BatchPoolInfo"] = None, - on_all_tasks_complete: Optional[Union[str, "_models.OnAllBatchTasksComplete"]] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + all_tasks_complete_mode: Optional[Union[str, "_models.BatchAllTasksCompleteMode"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, network_configuration: Optional["_models.BatchJobNetworkConfiguration"] = None, ) -> None: ... @@ -3609,7 +3891,41 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNode(_model_base.Model): +class BatchMetadataItem(_Model): + """The Batch service does not assign any meaning to this metadata; it is solely + for the use of user code. + + :ivar name: The name of the metadata item. Required. + :vartype name: str + :ivar value: The value of the metadata item. Required. + :vartype value: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the metadata item. Required.""" + value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The value of the metadata item. Required.""" + + @overload + def __init__( + self, + *, + name: str, + value: str, + ) -> 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 BatchNode(_Model): """A Compute Node in the Batch service. :ivar id: The ID of the Compute Node. Every Compute Node that is added to a Pool is assigned a @@ -3774,7 +4090,7 @@ class BatchNode(_model_base.Model): """The total number of Job Tasks which completed successfully (with exitCode 0) on the Compute Node. This includes Job Manager Tasks and normal Tasks, but not Job Preparation, Job Release or Start Tasks.""" - recent_tasks: Optional[List["_models.BatchTaskInfo"]] = rest_field( + recent_tasks: Optional[list["_models.BatchTaskInfo"]] = rest_field( name="recentTasks", visibility=["read", "create", "update", "delete", "query"] ) """A list of Tasks whose state has recently changed. This property is present only if at least one @@ -3787,7 +4103,7 @@ class BatchNode(_model_base.Model): name="startTaskInfo", visibility=["read", "create", "update", "delete", "query"] ) """Runtime information about the execution of the StartTask on the Compute Node.""" - certificate_references: Optional[List["_models.BatchCertificateReference"]] = rest_field( + certificate_references: Optional[list["_models.BatchCertificateReference"]] = rest_field( name="certificateReferences", visibility=["read", "create", "update", "delete", "query"] ) """For Windows Nodes, the Batch service installs the Certificates to the specified Certificate @@ -3800,7 +4116,7 @@ class BatchNode(_model_base.Model): Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ instead.""" - errors: Optional[List["_models.BatchNodeError"]] = rest_field( + errors: Optional[list["_models.BatchNodeError"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """The list of errors that are currently being encountered by the Compute Node.""" @@ -3841,11 +4157,11 @@ def __init__( running_tasks_count: Optional[int] = None, running_task_slots_count: Optional[int] = None, total_tasks_succeeded: Optional[int] = None, - recent_tasks: Optional[List["_models.BatchTaskInfo"]] = None, + recent_tasks: Optional[list["_models.BatchTaskInfo"]] = None, start_task: Optional["_models.BatchStartTask"] = None, start_task_info: Optional["_models.BatchStartTaskInfo"] = None, - certificate_references: Optional[List["_models.BatchCertificateReference"]] = None, - errors: Optional[List["_models.BatchNodeError"]] = None, + certificate_references: Optional[list["_models.BatchCertificateReference"]] = None, + errors: Optional[list["_models.BatchNodeError"]] = None, is_dedicated: Optional[bool] = None, endpoint_configuration: Optional["_models.BatchNodeEndpointConfiguration"] = None, node_agent_info: Optional["_models.BatchNodeAgentInfo"] = None, @@ -3863,7 +4179,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeAgentInfo(_model_base.Model): +class BatchNodeAgentInfo(_Model): """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. @@ -3908,7 +4224,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeCounts(_model_base.Model): +class BatchNodeCounts(_Model): """The number of Compute Nodes in each Compute Node state. :ivar creating: The number of Compute Nodes in the creating state. Required. @@ -4021,7 +4337,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeDeallocateContent(_model_base.Model): +class BatchNodeDeallocateOptions(_Model): """Options for deallocating a Compute Node. :ivar node_deallocate_option: When to deallocate the Compute Node and what to do with currently @@ -4055,7 +4371,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeDisableSchedulingContent(_model_base.Model): +class BatchNodeDisableSchedulingOptions(_Model): """Parameters for disabling scheduling on an Azure Batch Compute Node. :ivar node_disable_scheduling_option: What to do with currently running Tasks when disabling @@ -4089,7 +4405,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeEndpointConfiguration(_model_base.Model): +class BatchNodeEndpointConfiguration(_Model): """The endpoint configuration for the Compute Node. :ivar inbound_endpoints: The list of inbound endpoints that are accessible on the Compute Node. @@ -4097,7 +4413,7 @@ class BatchNodeEndpointConfiguration(_model_base.Model): :vartype inbound_endpoints: list[~azure.batch.models.InboundEndpoint] """ - inbound_endpoints: List["_models.InboundEndpoint"] = rest_field( + inbound_endpoints: list["_models.InboundEndpoint"] = rest_field( name="inboundEndpoints", visibility=["read", "create", "update", "delete", "query"] ) """The list of inbound endpoints that are accessible on the Compute Node. Required.""" @@ -4106,7 +4422,7 @@ class BatchNodeEndpointConfiguration(_model_base.Model): def __init__( self, *, - inbound_endpoints: List["_models.InboundEndpoint"], + inbound_endpoints: list["_models.InboundEndpoint"], ) -> None: ... @overload @@ -4120,7 +4436,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeError(_model_base.Model): +class BatchNodeError(_Model): """An error encountered by a Compute Node. :ivar code: An identifier for the Compute Node error. Codes are invariant and are intended to @@ -4139,7 +4455,7 @@ class BatchNodeError(_model_base.Model): message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A message describing the Compute Node error, intended to be suitable for display in a user interface.""" - error_details: Optional[List["_models.NameValuePair"]] = rest_field( + error_details: Optional[list["_models.NameValuePair"]] = rest_field( name="errorDetails", visibility=["read", "create", "update", "delete", "query"] ) """The list of additional error details related to the Compute Node error.""" @@ -4150,7 +4466,7 @@ def __init__( *, code: Optional[str] = None, message: Optional[str] = None, - error_details: Optional[List["_models.NameValuePair"]] = None, + error_details: Optional[list["_models.NameValuePair"]] = None, ) -> None: ... @overload @@ -4164,7 +4480,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeFile(_model_base.Model): +class BatchNodeFile(_Model): """Information about a file or directory on a Compute Node. :ivar name: The file path. @@ -4211,7 +4527,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeIdentityReference(_model_base.Model): +class BatchNodeIdentityReference(_Model): """The reference to a user assigned identity associated with the Batch pool which a compute node will use. @@ -4242,7 +4558,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeInfo(_model_base.Model): +class BatchNodeInfo(_Model): """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 @@ -4303,7 +4619,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodePlacementConfiguration(_model_base.Model): +class BatchNodePlacementConfiguration(_Model): """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. @@ -4339,16 +4655,16 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeRebootContent(_model_base.Model): +class BatchNodeRebootOptions(_Model): """Parameters for rebooting an Azure Batch Compute Node. - :ivar node_reboot_option: When to reboot the Compute Node and what to do with currently running + :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". - :vartype node_reboot_option: str or ~azure.batch.models.BatchNodeRebootOption + :vartype node_reboot_kind: str or ~azure.batch.models.BatchNodeRebootKind """ - node_reboot_option: Optional[Union[str, "_models.BatchNodeRebootOption"]] = 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 @@ -4359,7 +4675,7 @@ class BatchNodeRebootContent(_model_base.Model): def __init__( self, *, - node_reboot_option: Optional[Union[str, "_models.BatchNodeRebootOption"]] = None, + node_reboot_kind: Optional[Union[str, "_models.BatchNodeRebootKind"]] = None, ) -> None: ... @overload @@ -4373,7 +4689,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeReimageContent(_model_base.Model): +class BatchNodeReimageOptions(_Model): """Parameters for reimaging an Azure Batch Compute Node. :ivar node_reimage_option: When to reimage the Compute Node and what to do with currently @@ -4407,7 +4723,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeRemoteLoginSettings(_model_base.Model): +class BatchNodeRemoteLoginSettings(_Model): """The remote login settings for a Compute Node. :ivar remote_login_ip_address: The IP address used for remote login to the Compute Node. @@ -4445,12 +4761,12 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeRemoveContent(_model_base.Model): +class BatchNodeRemoveOptions(_Model): """Parameters for removing nodes from an Azure Batch Pool. - :ivar node_list: A list containing the IDs of the Compute Nodes to be removed from the - specified Pool. A maximum of 100 nodes may be removed per request. Required. - :vartype node_list: list[str] + :ivar node_ids: A list containing the IDs of the Compute Nodes to be removed from the specified + Pool. A maximum of 100 nodes may be removed per request. Required. + :vartype node_ids: list[str] :ivar resize_timeout: The timeout for removal of Compute Nodes to the Pool. The default value is 15 minutes. The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code @@ -4462,7 +4778,7 @@ class BatchNodeRemoveContent(_model_base.Model): :vartype node_deallocation_option: str or ~azure.batch.models.BatchNodeDeallocationOption """ - node_list: List[str] = rest_field(name="nodeList", visibility=["read", "create", "update", "delete", "query"]) + node_ids: list[str] = rest_field(name="nodeList", visibility=["read", "create", "update", "delete", "query"]) """A list containing the IDs of the Compute Nodes to be removed from the specified Pool. A maximum of 100 nodes may be removed per request. Required.""" resize_timeout: Optional[datetime.timedelta] = rest_field( @@ -4483,7 +4799,7 @@ class BatchNodeRemoveContent(_model_base.Model): def __init__( self, *, - node_list: List[str], + node_ids: list[str], resize_timeout: Optional[datetime.timedelta] = None, node_deallocation_option: Optional[Union[str, "_models.BatchNodeDeallocationOption"]] = None, ) -> None: ... @@ -4499,7 +4815,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeUserCreateContent(_model_base.Model): +class BatchNodeUserCreateOptions(_Model): """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. @@ -4565,7 +4881,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeUserUpdateContent(_model_base.Model): +class BatchNodeUserUpdateOptions(_Model): """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 @@ -4622,7 +4938,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchNodeVMExtension(_model_base.Model): +class BatchNodeVMExtension(_Model): """The configuration for virtual machine extension instance view. :ivar provisioning_state: The provisioning state of the virtual machine extension. @@ -4666,7 +4982,72 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPool(_model_base.Model): +class BatchOsDisk(_Model): + """Settings for the operating system disk of the compute node (VM). + + :ivar ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating + system disk used by the compute node (VM). + :vartype ephemeral_os_disk_settings: ~azure.batch.models.BatchDiffDiskSettings + :ivar caching: Specifies the caching requirements. Possible values are: None, ReadOnly, + ReadWrite. The default values are: None for Standard storage. ReadOnly for Premium storage. + Known values are: "none", "readonly", and "readwrite". + :vartype caching: str or ~azure.batch.models.CachingType + :ivar disk_size_gb: The initial disk size in GB when creating new OS disk. + :vartype disk_size_gb: int + :ivar managed_disk: The managed disk parameters. + :vartype managed_disk: ~azure.batch.models.ManagedDisk + :ivar write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or + disabled on the disk. + :vartype write_accelerator_enabled: bool + """ + + ephemeral_os_disk_settings: Optional["_models.BatchDiffDiskSettings"] = rest_field( + name="ephemeralOSDiskSettings", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the ephemeral Disk Settings for the operating system disk used by the compute node + (VM).""" + caching: Optional[Union[str, "_models.CachingType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default + values are: None for Standard storage. ReadOnly for Premium storage. Known values are: + \"none\", \"readonly\", and \"readwrite\".""" + disk_size_gb: Optional[int] = rest_field( + name="diskSizeGB", visibility=["read", "create", "update", "delete", "query"] + ) + """The initial disk size in GB when creating new OS disk.""" + managed_disk: Optional["_models.ManagedDisk"] = rest_field( + name="managedDisk", visibility=["read", "create", "update", "delete", "query"] + ) + """The managed disk parameters.""" + write_accelerator_enabled: Optional[bool] = rest_field( + name="writeAcceleratorEnabled", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies whether writeAccelerator should be enabled or disabled on the disk.""" + + @overload + def __init__( + self, + *, + ephemeral_os_disk_settings: Optional["_models.BatchDiffDiskSettings"] = None, + caching: Optional[Union[str, "_models.CachingType"]] = None, + disk_size_gb: Optional[int] = None, + managed_disk: Optional["_models.ManagedDisk"] = None, + write_accelerator_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 BatchPool(_Model): """A Pool in the Azure Batch service. :ivar id: A string that uniquely identifies the Pool within the Account. The ID can contain any @@ -4784,13 +5165,13 @@ class BatchPool(_model_base.Model): :ivar user_accounts: The list of user Accounts to be created on each Compute Node in the Pool. :vartype user_accounts: list[~azure.batch.models.UserAccount] :ivar metadata: A list of name-value pairs associated with the Pool as metadata. - :vartype metadata: list[~azure.batch.models.MetadataItem] - :ivar stats: Utilization and resource usage statistics for the entire lifetime of the Pool. - This property is populated only if the BatchPool was retrieved with an expand clause including - the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. - The Batch service performs periodic roll-up of statistics. The typical delay is about 30 - minutes. - :vartype stats: ~azure.batch.models.BatchPoolStatistics + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] + :ivar pool_statistics: Utilization and resource usage statistics for the entire lifetime of the + Pool. This property is populated only if the BatchPool was retrieved with an expand clause + including the 'stats' attribute; otherwise it is null. The statistics may not be immediately + available. The Batch service performs periodic roll-up of statistics. The typical delay is + about 30 minutes. + :vartype pool_statistics: ~azure.batch.models.BatchPoolStatistics :ivar mount_configuration: A list of file systems to mount on each node in the pool. This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. :vartype mount_configuration: list[~azure.batch.models.MountConfiguration] @@ -4861,11 +5242,11 @@ class BatchPool(_model_base.Model): """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.""" - resize_errors: Optional[List["_models.ResizeError"]] = rest_field(name="resizeErrors", visibility=["read"]) + resize_errors: Optional[list["_models.ResizeError"]] = rest_field(name="resizeErrors", visibility=["read"]) """A list of errors encountered while performing the last resize on the Pool. This property is set only if one or more errors occurred during the last Pool resize, and only when the Pool allocationState is Steady.""" - resource_tags: Optional[Dict[str, str]] = rest_field(name="resourceTags", visibility=["read"]) + resource_tags: Optional[dict[str, str]] = rest_field(name="resourceTags", visibility=["read"]) """The user-specified tags associated with the pool. The user-defined tags to be associated with the Azure Batch Pool. When specified, these tags are propagated to the backing Azure resources associated with the pool. This property can only be specified when the Batch account was @@ -4910,7 +5291,7 @@ class BatchPool(_model_base.Model): name="startTask", visibility=["read", "create", "update", "delete", "query"] ) """A Task specified to run on each Compute Node as it joins the Pool.""" - certificate_references: Optional[List["_models.BatchCertificateReference"]] = rest_field( + certificate_references: Optional[list["_models.BatchCertificateReference"]] = rest_field( name="certificateReferences", visibility=["read"] ) """For Windows Nodes, the Batch service installs the Certificates to the specified Certificate @@ -4923,7 +5304,7 @@ class BatchPool(_model_base.Model): Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ instead.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read"] ) """The list of Packages to be installed on each Compute Node in the Pool. Changes to Package @@ -4939,16 +5320,16 @@ class BatchPool(_model_base.Model): ) """How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread.""" - user_accounts: Optional[List["_models.UserAccount"]] = rest_field(name="userAccounts", visibility=["read"]) + user_accounts: Optional[list["_models.UserAccount"]] = rest_field(name="userAccounts", visibility=["read"]) """The list of user Accounts to be created on each Compute Node in the Pool.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field(visibility=["read"]) + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field(visibility=["read"]) """A list of name-value pairs associated with the Pool as metadata.""" - stats: Optional["_models.BatchPoolStatistics"] = rest_field(visibility=["read"]) + pool_statistics: Optional["_models.BatchPoolStatistics"] = rest_field(name="stats", visibility=["read"]) """Utilization and resource usage statistics for the entire lifetime of the Pool. This property is populated only if the BatchPool was retrieved with an expand clause including the 'stats' attribute; otherwise it is null. The statistics may not be immediately available. The Batch service performs periodic roll-up of statistics. The typical delay is about 30 minutes.""" - mount_configuration: Optional[List["_models.MountConfiguration"]] = rest_field( + mount_configuration: Optional[list["_models.MountConfiguration"]] = rest_field( name="mountConfiguration", visibility=["read"] ) """A list of file systems to mount on each node in the pool. This supports Azure Files, NFS, @@ -4992,7 +5373,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolCreateContent(_model_base.Model): +class BatchPoolCreateOptions(_Model): """Parameters for creating an Azure Batch Pool. :ivar id: A string that uniquely identifies the Pool within the Account. The ID can contain any @@ -5094,7 +5475,7 @@ class BatchPoolCreateContent(_model_base.Model): :vartype user_accounts: list[~azure.batch.models.UserAccount] :ivar metadata: A list of name-value pairs associated with the Pool as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] :ivar mount_configuration: Mount storage using specified file system for the entire lifetime of the pool. Mount the storage using Azure fileshare, NFS, CIFS or Blobfuse based file system. :vartype mount_configuration: list[~azure.batch.models.MountConfiguration] @@ -5137,7 +5518,7 @@ class BatchPoolCreateContent(_model_base.Model): The minimum value is 5 minutes. If you specify a value less than 5 minutes, the Batch service returns an error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request).""" - resource_tags: Optional[Dict[str, str]] = rest_field( + resource_tags: Optional[dict[str, str]] = rest_field( name="resourceTags", visibility=["read", "create", "update", "delete", "query"] ) """The user-specified tags associated with the pool. The user-defined tags to be associated with @@ -5197,7 +5578,7 @@ class BatchPoolCreateContent(_model_base.Model): ) """A Task specified to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when the Compute Node is restarted.""" - certificate_references: Optional[List["_models.BatchCertificateReference"]] = rest_field( + certificate_references: Optional[list["_models.BatchCertificateReference"]] = rest_field( name="certificateReferences", visibility=["read", "create", "update", "delete", "query"] ) """For Windows Nodes, the Batch service installs the Certificates to the specified Certificate @@ -5210,7 +5591,7 @@ class BatchPoolCreateContent(_model_base.Model): Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ instead.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read", "create", "update", "delete", "query"] ) """The list of Packages to be installed on each Compute Node in the Pool. When creating a pool, @@ -5230,16 +5611,16 @@ class BatchPoolCreateContent(_model_base.Model): ) """How Tasks are distributed across Compute Nodes in a Pool. If not specified, the default is spread.""" - user_accounts: Optional[List["_models.UserAccount"]] = rest_field( + user_accounts: Optional[list["_models.UserAccount"]] = rest_field( name="userAccounts", visibility=["read", "create", "update", "delete", "query"] ) """The list of user Accounts to be created on each Compute Node in the Pool.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Pool as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code.""" - mount_configuration: Optional[List["_models.MountConfiguration"]] = rest_field( + mount_configuration: Optional[list["_models.MountConfiguration"]] = rest_field( name="mountConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """Mount storage using specified file system for the entire lifetime of the pool. Mount the @@ -5263,7 +5644,7 @@ def __init__( display_name: Optional[str] = None, virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, resize_timeout: Optional[datetime.timedelta] = None, - resource_tags: Optional[Dict[str, str]] = None, + resource_tags: Optional[dict[str, str]] = None, target_dedicated_nodes: Optional[int] = None, target_low_priority_nodes: Optional[int] = None, enable_auto_scale: Optional[bool] = None, @@ -5272,13 +5653,13 @@ def __init__( enable_inter_node_communication: Optional[bool] = None, network_configuration: Optional["_models.NetworkConfiguration"] = None, start_task: Optional["_models.BatchStartTask"] = None, - certificate_references: Optional[List["_models.BatchCertificateReference"]] = None, - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = None, + certificate_references: Optional[list["_models.BatchCertificateReference"]] = None, + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = None, task_slots_per_node: Optional[int] = None, task_scheduling_policy: Optional["_models.BatchTaskSchedulingPolicy"] = None, - user_accounts: Optional[List["_models.UserAccount"]] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, - mount_configuration: Optional[List["_models.MountConfiguration"]] = None, + user_accounts: Optional[list["_models.UserAccount"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, + mount_configuration: Optional[list["_models.MountConfiguration"]] = None, target_node_communication_mode: Optional[Union[str, "_models.BatchNodeCommunicationMode"]] = None, upgrade_policy: Optional["_models.UpgradePolicy"] = None, ) -> None: ... @@ -5294,7 +5675,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolEnableAutoScaleContent(_model_base.Model): +class BatchPoolEnableAutoScaleOptions(_Model): """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 @@ -5356,7 +5737,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolEndpointConfiguration(_model_base.Model): +class BatchPoolEndpointConfiguration(_Model): """The endpoint configuration for a Pool. :ivar inbound_nat_pools: A list of inbound NAT Pools that can be used to address specific ports @@ -5364,10 +5745,10 @@ class BatchPoolEndpointConfiguration(_model_base.Model): Pool is 5. If the maximum number of inbound NAT Pools is exceeded the request fails with HTTP status code 400. This cannot be specified if the IPAddressProvisioningType is NoPublicIPAddresses. Required. - :vartype inbound_nat_pools: list[~azure.batch.models.InboundNatPool] + :vartype inbound_nat_pools: list[~azure.batch.models.BatchInboundNatPool] """ - inbound_nat_pools: List["_models.InboundNatPool"] = rest_field( + inbound_nat_pools: list["_models.BatchInboundNatPool"] = rest_field( name="inboundNATPools", visibility=["read", "create", "update", "delete", "query"] ) """A list of inbound NAT Pools that can be used to address specific ports on an individual Compute @@ -5379,7 +5760,7 @@ class BatchPoolEndpointConfiguration(_model_base.Model): def __init__( self, *, - inbound_nat_pools: List["_models.InboundNatPool"], + inbound_nat_pools: list["_models.BatchInboundNatPool"], ) -> None: ... @overload @@ -5393,7 +5774,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolEvaluateAutoScaleContent(_model_base.Model): +class BatchPoolEvaluateAutoScaleOptions(_Model): """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 @@ -5433,7 +5814,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolIdentity(_model_base.Model): +class BatchPoolIdentity(_Model): """The identity of the Batch pool, if configured. :ivar type: The identity of the Batch pool, if configured. The list of user identities @@ -5445,7 +5826,7 @@ class BatchPoolIdentity(_model_base.Model): :ivar user_assigned_identities: The list of user identities associated with the Batch account. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. - :vartype user_assigned_identities: list[~azure.batch.models.UserAssignedIdentity] + :vartype user_assigned_identities: list[~azure.batch.models.BatchUserAssignedIdentity] """ type: Union[str, "_models.BatchPoolIdentityType"] = rest_field( @@ -5455,7 +5836,7 @@ class BatchPoolIdentity(_model_base.Model): Batch pool. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'. Required. Known values are: \"UserAssigned\" and \"None\".""" - user_assigned_identities: Optional[List["_models.UserAssignedIdentity"]] = rest_field( + user_assigned_identities: Optional[list["_models.BatchUserAssignedIdentity"]] = rest_field( name="userAssignedIdentities", visibility=["read", "create", "update", "delete", "query"] ) """The list of user identities associated with the Batch account. The user identity dictionary key @@ -5467,7 +5848,7 @@ def __init__( self, *, type: Union[str, "_models.BatchPoolIdentityType"], - user_assigned_identities: Optional[List["_models.UserAssignedIdentity"]] = None, + user_assigned_identities: Optional[list["_models.BatchUserAssignedIdentity"]] = None, ) -> None: ... @overload @@ -5481,7 +5862,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolInfo(_model_base.Model): +class BatchPoolInfo(_Model): """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 @@ -5538,7 +5919,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolNodeCounts(_model_base.Model): +class BatchPoolNodeCounts(_Model): """The number of Compute Nodes in each state for a Pool. :ivar pool_id: The ID of the Pool. Required. @@ -5580,7 +5961,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolReplaceContent(_model_base.Model): +class BatchPoolReplaceOptions(_Model): """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 @@ -5617,7 +5998,7 @@ class BatchPoolReplaceContent(_model_base.Model): :ivar metadata: A list of name-value pairs associated with the Pool as metadata. This list replaces any existing metadata configured on the Pool. If omitted, or if you specify an empty collection, any existing metadata is removed from the Pool. Required. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] :ivar target_node_communication_mode: The desired node communication mode for the pool. This setting replaces any existing targetNodeCommunication setting on the Pool. If omitted, the existing setting is default. Known values are: "default", "classic", and "simplified". @@ -5630,7 +6011,7 @@ class BatchPoolReplaceContent(_model_base.Model): """A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when the Compute Node is restarted. If this element is present, it overwrites any existing StartTask. If omitted, any existing StartTask is removed from the Pool.""" - certificate_references: List["_models.BatchCertificateReference"] = rest_field( + certificate_references: list["_models.BatchCertificateReference"] = rest_field( name="certificateReferences", visibility=["read", "create", "update", "delete", "query"] ) """This list replaces any existing Certificate references configured on the Pool. @@ -5647,7 +6028,7 @@ class BatchPoolReplaceContent(_model_base.Model): `Azure KeyVault Extension `_ instead. Required.""" - application_package_references: List["_models.BatchApplicationPackageReference"] = rest_field( + application_package_references: list["_models.BatchApplicationPackageReference"] = rest_field( name="applicationPackageReferences", visibility=["read", "create", "update", "delete", "query"] ) """The list of Application Packages to be installed on each Compute Node in the Pool. The list @@ -5657,7 +6038,7 @@ class BatchPoolReplaceContent(_model_base.Model): 10 Application Package references on any given Pool. If omitted, or if you specify an empty collection, any existing Application Packages references are removed from the Pool. A maximum of 10 references may be specified on a given Pool. Required.""" - metadata: List["_models.MetadataItem"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + metadata: list["_models.BatchMetadataItem"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A list of name-value pairs associated with the Pool as metadata. This list replaces any existing metadata configured on the Pool. If omitted, or if you specify an empty collection, any existing metadata is removed from the Pool. Required.""" @@ -5672,9 +6053,9 @@ class BatchPoolReplaceContent(_model_base.Model): def __init__( self, *, - certificate_references: List["_models.BatchCertificateReference"], - application_package_references: List["_models.BatchApplicationPackageReference"], - metadata: List["_models.MetadataItem"], + certificate_references: list["_models.BatchCertificateReference"], + application_package_references: list["_models.BatchApplicationPackageReference"], + metadata: list["_models.BatchMetadataItem"], start_task: Optional["_models.BatchStartTask"] = None, target_node_communication_mode: Optional[Union[str, "_models.BatchNodeCommunicationMode"]] = None, ) -> None: ... @@ -5690,7 +6071,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolResizeContent(_model_base.Model): +class BatchPoolResizeOptions(_Model): """Parameters for changing the size of an Azure Batch Pool. :ivar target_dedicated_nodes: The desired number of dedicated Compute Nodes in the Pool. @@ -5752,7 +6133,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolResourceStatistics(_model_base.Model): +class BatchPoolResourceStatistics(_Model): """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. @@ -5775,12 +6156,12 @@ class BatchPoolResourceStatistics(_model_base.Model): :ivar peak_disk_gi_b: The peak used disk space in GiB across all Compute Nodes in the Pool. Required. :vartype peak_disk_gi_b: float - :ivar disk_read_i_ops: The total number of disk read operations across all Compute Nodes in the + :ivar disk_read_iops: The total number of disk read operations across all Compute Nodes in the Pool. Required. - :vartype disk_read_i_ops: int - :ivar disk_write_i_ops: The total number of disk write operations across all Compute Nodes in + :vartype disk_read_iops: int + :ivar disk_write_iops: The total number of disk write operations across all Compute Nodes in the Pool. Required. - :vartype disk_write_i_ops: int + :vartype disk_write_iops: int :ivar disk_read_gi_b: The total amount of data in GiB of disk reads across all Compute Nodes in the Pool. Required. :vartype disk_read_gi_b: float @@ -5818,11 +6199,11 @@ class BatchPoolResourceStatistics(_model_base.Model): """The average used disk space in GiB across all Compute Nodes in the Pool. Required.""" peak_disk_gi_b: 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_i_ops: int = rest_field( + disk_read_iops: int = rest_field( name="diskReadIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk read operations across all Compute Nodes in the Pool. Required.""" - disk_write_i_ops: int = rest_field( + disk_write_iops: int = rest_field( name="diskWriteIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk write operations across all Compute Nodes in the Pool. Required.""" @@ -5852,8 +6233,8 @@ def __init__( peak_memory_gi_b: float, avg_disk_gi_b: float, peak_disk_gi_b: float, - disk_read_i_ops: int, - disk_write_i_ops: int, + disk_read_iops: int, + disk_write_iops: int, disk_read_gi_b: float, disk_write_gi_b: float, network_read_gi_b: float, @@ -5871,7 +6252,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolSpecification(_model_base.Model): +class BatchPoolSpecification(_Model): """Specification for creating a new Pool. :ivar display_name: The display name for the Pool. The display name need not be unique and can @@ -5963,7 +6344,7 @@ class BatchPoolSpecification(_model_base.Model): :vartype user_accounts: list[~azure.batch.models.UserAccount] :ivar metadata: A list of name-value pairs associated with the Pool as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] :ivar mount_configuration: A list of file systems to mount on each node in the pool. This supports Azure Files, NFS, CIFS/SMB, and Blobfuse. :vartype mount_configuration: list[~azure.batch.models.MountConfiguration] @@ -6067,7 +6448,7 @@ class BatchPoolSpecification(_model_base.Model): ) """A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when the Compute Node is restarted.""" - certificate_references: Optional[List["_models.BatchCertificateReference"]] = rest_field( + certificate_references: Optional[list["_models.BatchCertificateReference"]] = rest_field( name="certificateReferences", visibility=["read", "create", "update", "delete", "query"] ) """For Windows Nodes, the Batch service installs the Certificates to the specified Certificate @@ -6079,7 +6460,7 @@ class BatchPoolSpecification(_model_base.Model): Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ instead.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read", "create", "update", "delete", "query"] ) """The list of Packages to be installed on each Compute Node in the Pool. When creating a pool, @@ -6088,16 +6469,16 @@ class BatchPoolSpecification(_model_base.Model): Changes to Package references affect all new Nodes joining the Pool, but do not affect Compute Nodes that are already in the Pool until they are rebooted or reimaged. There is a maximum of 10 Package references on any given Pool.""" - user_accounts: Optional[List["_models.UserAccount"]] = rest_field( + user_accounts: Optional[list["_models.UserAccount"]] = rest_field( name="userAccounts", visibility=["read", "create", "update", "delete", "query"] ) """The list of user Accounts to be created on each Compute Node in the Pool.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Pool as metadata. The Batch service does not assign any meaning to metadata; it is solely for the use of user code.""" - mount_configuration: Optional[List["_models.MountConfiguration"]] = rest_field( + mount_configuration: Optional[list["_models.MountConfiguration"]] = rest_field( name="mountConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """A list of file systems to mount on each node in the pool. This supports Azure Files, NFS, @@ -6131,11 +6512,11 @@ def __init__( enable_inter_node_communication: Optional[bool] = None, network_configuration: Optional["_models.NetworkConfiguration"] = None, start_task: Optional["_models.BatchStartTask"] = None, - certificate_references: Optional[List["_models.BatchCertificateReference"]] = None, - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = None, - user_accounts: Optional[List["_models.UserAccount"]] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, - mount_configuration: Optional[List["_models.MountConfiguration"]] = None, + certificate_references: Optional[list["_models.BatchCertificateReference"]] = None, + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = None, + user_accounts: Optional[list["_models.UserAccount"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, + mount_configuration: Optional[list["_models.MountConfiguration"]] = None, target_node_communication_mode: Optional[Union[str, "_models.BatchNodeCommunicationMode"]] = None, upgrade_policy: Optional["_models.UpgradePolicy"] = None, ) -> None: ... @@ -6151,7 +6532,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolStatistics(_model_base.Model): +class BatchPoolStatistics(_Model): """Contains utilization and resource usage statistics for the lifetime of a Pool. :ivar url: The URL for the statistics. Required. @@ -6161,10 +6542,11 @@ class BatchPoolStatistics(_model_base.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_stats: Statistics related to Pool usage, such as the amount of core-time used. - :vartype usage_stats: ~azure.batch.models.BatchPoolUsageStatistics - :ivar resource_stats: Statistics related to resource consumption by Compute Nodes in the Pool. - :vartype resource_stats: ~azure.batch.models.BatchPoolResourceStatistics + :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 """ url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -6178,11 +6560,11 @@ class BatchPoolStatistics(_model_base.Model): ) """The time at which the statistics were last updated. All statistics are limited to the range between startTime and lastUpdateTime. Required.""" - usage_stats: Optional["_models.BatchPoolUsageStatistics"] = rest_field( + 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_stats: Optional["_models.BatchPoolResourceStatistics"] = rest_field( + resource_statistics: Optional["_models.BatchPoolResourceStatistics"] = rest_field( name="resourceStats", visibility=["read", "create", "update", "delete", "query"] ) """Statistics related to resource consumption by Compute Nodes in the Pool.""" @@ -6194,8 +6576,8 @@ def __init__( url: str, start_time: datetime.datetime, last_update_time: datetime.datetime, - usage_stats: Optional["_models.BatchPoolUsageStatistics"] = None, - resource_stats: Optional["_models.BatchPoolResourceStatistics"] = None, + usage_statistics: Optional["_models.BatchPoolUsageStatistics"] = None, + resource_statistics: Optional["_models.BatchPoolResourceStatistics"] = None, ) -> None: ... @overload @@ -6209,7 +6591,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolUpdateContent(_model_base.Model): +class BatchPoolUpdateOptions(_Model): """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 @@ -6259,7 +6641,7 @@ class BatchPoolUpdateContent(_model_base.Model): element is present, it replaces any existing metadata configured on the Pool. If you specify an empty collection, any metadata is removed from the Pool. If omitted, any existing metadata is left unchanged. - :vartype metadata: list[~azure.batch.models.MetadataItem] + :vartype metadata: list[~azure.batch.models.BatchMetadataItem] :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 @@ -6323,7 +6705,7 @@ class BatchPoolUpdateContent(_model_base.Model): """A Task to run on each Compute Node as it joins the Pool. The Task runs when the Compute Node is added to the Pool or when the Compute Node is restarted. If this element is present, it overwrites any existing StartTask. If omitted, any existing StartTask is left unchanged.""" - certificate_references: Optional[List["_models.BatchCertificateReference"]] = rest_field( + certificate_references: Optional[list["_models.BatchCertificateReference"]] = rest_field( name="certificateReferences", visibility=["read", "create", "update", "delete", "query"] ) """If this element is present, it replaces any existing Certificate references configured on the @@ -6339,7 +6721,7 @@ class BatchPoolUpdateContent(_model_base.Model): Warning: This property is deprecated and will be removed after February, 2024. Please use the `Azure KeyVault Extension `_ instead.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read", "create", "update", "delete", "query"] ) """A list of Packages to be installed on each Compute Node in the Pool. Changes to Package @@ -6348,7 +6730,7 @@ class BatchPoolUpdateContent(_model_base.Model): replaces any existing Package references. If you specify an empty collection, then all Package references are removed from the Pool. If omitted, any existing Package references are left unchanged.""" - metadata: Optional[List["_models.MetadataItem"]] = rest_field( + metadata: Optional[list["_models.BatchMetadataItem"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs associated with the Pool as metadata. If this element is present, it @@ -6381,7 +6763,7 @@ class BatchPoolUpdateContent(_model_base.Model): name="networkConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The network configuration for the Pool. This field can be updated only when the pool is empty.""" - resource_tags: Optional[Dict[str, str]] = rest_field( + resource_tags: Optional[dict[str, str]] = rest_field( name="resourceTags", visibility=["read", "create", "update", "delete", "query"] ) """The user-specified tags associated with the pool. The user-defined tags to be associated with @@ -6389,12 +6771,12 @@ class BatchPoolUpdateContent(_model_base.Model): associated with the pool. This property can only be specified when the Batch account was created with the poolAllocationMode property set to 'UserSubscription'.

This field can be updated only when the pool is empty.""" - user_accounts: Optional[List["_models.UserAccount"]] = rest_field( + user_accounts: Optional[list["_models.UserAccount"]] = rest_field( name="userAccounts", visibility=["read", "create", "update", "delete", "query"] ) """The list of user Accounts to be created on each Compute Node in the Pool. This field can be updated only when the pool is empty.""" - mount_configuration: Optional[List["_models.MountConfiguration"]] = rest_field( + mount_configuration: Optional[list["_models.MountConfiguration"]] = rest_field( name="mountConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """Mount storage using specified file system for the entire lifetime of the pool. Mount the @@ -6414,17 +6796,17 @@ def __init__( vm_size: Optional[str] = None, enable_inter_node_communication: Optional[bool] = None, start_task: Optional["_models.BatchStartTask"] = None, - certificate_references: Optional[List["_models.BatchCertificateReference"]] = None, - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = None, - metadata: Optional[List["_models.MetadataItem"]] = None, + certificate_references: Optional[list["_models.BatchCertificateReference"]] = None, + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = None, + metadata: Optional[list["_models.BatchMetadataItem"]] = None, virtual_machine_configuration: Optional["_models.VirtualMachineConfiguration"] = None, target_node_communication_mode: Optional[Union[str, "_models.BatchNodeCommunicationMode"]] = None, task_slots_per_node: Optional[int] = None, task_scheduling_policy: Optional["_models.BatchTaskSchedulingPolicy"] = None, network_configuration: Optional["_models.NetworkConfiguration"] = None, - resource_tags: Optional[Dict[str, str]] = None, - user_accounts: Optional[List["_models.UserAccount"]] = None, - mount_configuration: Optional[List["_models.MountConfiguration"]] = None, + resource_tags: Optional[dict[str, str]] = None, + user_accounts: Optional[list["_models.UserAccount"]] = None, + mount_configuration: Optional[list["_models.MountConfiguration"]] = None, upgrade_policy: Optional["_models.UpgradePolicy"] = None, ) -> None: ... @@ -6439,7 +6821,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolUsageMetrics(_model_base.Model): +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. @@ -6501,7 +6883,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchPoolUsageStatistics(_model_base.Model): +class BatchPoolUsageStatistics(_Model): """Statistics related to Pool usage information. :ivar start_time: The start time of the time range covered by the statistics. Required. @@ -6549,7 +6931,57 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchStartTask(_model_base.Model): +class BatchPublicIpAddressConfiguration(_Model): + """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. + The default value is BatchManaged. Known values are: "batchmanaged", "usermanaged", and + "nopublicipaddresses". + :vartype ip_address_provisioning_type: str or ~azure.batch.models.IpAddressProvisioningType + :ivar ip_address_ids: The list of public IPs which the Batch service will use when provisioning + Compute Nodes. The number of IPs specified here limits the maximum size of the Pool - 100 + dedicated nodes or 100 Spot/Low-priority nodes can be allocated for each public IP. For + example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each + element of this collection is of the form: + /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. + :vartype ip_address_ids: list[str] + """ + + ip_address_provisioning_type: Optional[Union[str, "_models.IpAddressProvisioningType"]] = rest_field( + name="provision", visibility=["read", "create", "update", "delete", "query"] + ) + """The provisioning type for Public IP Addresses for the Pool. The default value is BatchManaged. + Known values are: \"batchmanaged\", \"usermanaged\", and \"nopublicipaddresses\".""" + ip_address_ids: Optional[list[str]] = rest_field( + name="ipAddressIds", visibility=["read", "create", "update", "delete", "query"] + ) + """The list of public IPs which the Batch service will use when provisioning Compute Nodes. The + number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 + Spot/Low-priority nodes can be allocated for each public IP. For example, a pool needing 250 + dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of + the form: + /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}.""" + + @overload + def __init__( + self, + *, + ip_address_provisioning_type: Optional[Union[str, "_models.IpAddressProvisioningType"]] = None, + ip_address_ids: Optional[list[str]] = 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 BatchStartTask(_Model): """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. @@ -6635,7 +7067,7 @@ class BatchStartTask(_model_base.Model): container, and the Task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will not be able to access those files.""" - resource_files: Optional[List["_models.ResourceFile"]] = rest_field( + resource_files: Optional[list["_models.ResourceFile"]] = rest_field( name="resourceFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will download to the Compute Node before running the @@ -6644,7 +7076,7 @@ class BatchStartTask(_model_base.Model): this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers. Files listed under this element are located in the Task's working directory.""" - environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="environmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """A list of environment variable settings for the StartTask.""" @@ -6682,8 +7114,8 @@ def __init__( *, command_line: str, container_settings: Optional["_models.BatchTaskContainerSettings"] = None, - resource_files: Optional[List["_models.ResourceFile"]] = None, - environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, + resource_files: Optional[list["_models.ResourceFile"]] = None, + environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, user_identity: Optional["_models.UserIdentity"] = None, max_task_retry_count: Optional[int] = None, wait_for_success: Optional[bool] = None, @@ -6700,7 +7132,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchStartTaskInfo(_model_base.Model): +class BatchStartTaskInfo(_Model): """Information about a StartTask running on a Compute Node. :ivar state: The state of the StartTask on the Compute Node. Required. Known values are: @@ -6825,7 +7257,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchSubtask(_model_base.Model): +class BatchSubtask(_Model): """Information about an Azure Batch subtask. :ivar id: The ID of the subtask. @@ -6957,7 +7389,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchSupportedImage(_model_base.Model): +class BatchSupportedImage(_Model): """A reference to the Azure Virtual Machines Marketplace Image and additional information about the Image. @@ -6966,7 +7398,7 @@ class BatchSupportedImage(_model_base.Model): :vartype node_agent_sku_id: str :ivar image_reference: The reference to the Azure Virtual Machine's Marketplace Image. Required. - :vartype image_reference: ~azure.batch.models.ImageReference + :vartype image_reference: ~azure.batch.models.BatchVmImageReference :ivar os_type: The type of operating system (e.g. Windows or Linux) of the Image. Required. Known values are: "linux" and "windows". :vartype os_type: str or ~azure.batch.models.OSType @@ -6987,7 +7419,7 @@ class BatchSupportedImage(_model_base.Model): name="nodeAgentSKUId", visibility=["read", "create", "update", "delete", "query"] ) """The ID of the Compute Node agent SKU which the Image supports. Required.""" - image_reference: "_models.ImageReference" = rest_field( + image_reference: "_models.BatchVmImageReference" = rest_field( name="imageReference", visibility=["read", "create", "update", "delete", "query"] ) """The reference to the Azure Virtual Machine's Marketplace Image. Required.""" @@ -6996,7 +7428,7 @@ class BatchSupportedImage(_model_base.Model): ) """The type of operating system (e.g. Windows or Linux) of the Image. Required. Known values are: \"linux\" and \"windows\".""" - capabilities: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + capabilities: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The capabilities or features which the Image supports. Not every capability of the Image is listed. Capabilities in this list are considered of special interest and are generally related to integration with other features in the Azure Batch service.""" @@ -7015,10 +7447,10 @@ def __init__( self, *, node_agent_sku_id: str, - image_reference: "_models.ImageReference", + image_reference: "_models.BatchVmImageReference", os_type: Union[str, "_models.OSType"], verification_type: Union[str, "_models.ImageVerificationType"], - capabilities: Optional[List[str]] = None, + capabilities: Optional[list[str]] = None, batch_support_end_of_life: Optional[datetime.datetime] = None, ) -> None: ... @@ -7033,7 +7465,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTask(_model_base.Model): +class BatchTask(_Model): """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. @@ -7113,7 +7545,7 @@ class BatchTask(_model_base.Model): :vartype environment_settings: list[~azure.batch.models.EnvironmentSetting] :ivar affinity_info: A locality hint that can be used by the Batch service to select a Compute Node on which to start the new Task. - :vartype affinity_info: ~azure.batch.models.AffinityInfo + :vartype affinity_info: ~azure.batch.models.BatchAffinityInfo :ivar constraints: The execution constraints that apply to this Task. :vartype constraints: ~azure.batch.models.BatchTaskConstraints :ivar required_slots: The number of scheduling slots that the Task requires to run. The default @@ -7130,8 +7562,8 @@ class BatchTask(_model_base.Model): :ivar multi_instance_settings: An object that indicates that the Task is a multi-instance Task, and contains information about how to run the multi-instance Task. :vartype multi_instance_settings: ~azure.batch.models.MultiInstanceSettings - :ivar stats: Resource usage statistics for the Task. - :vartype stats: ~azure.batch.models.BatchTaskStatistics + :ivar task_statistics: Resource usage statistics for the Task. + :vartype task_statistics: ~azure.batch.models.BatchTaskStatistics :ivar depends_on: The Tasks that this Task depends on. This Task will not be scheduled until all Tasks that it depends on have completed successfully. If any of those Tasks fail and exhaust their retry counts, this Task will never be scheduled. @@ -7214,7 +7646,7 @@ class BatchTask(_model_base.Model): container, and the Task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will not be able to access those files.""" - resource_files: Optional[List["_models.ResourceFile"]] = rest_field(name="resourceFiles", visibility=["read"]) + resource_files: Optional[list["_models.ResourceFile"]] = rest_field(name="resourceFiles", visibility=["read"]) """A list of files that the Batch service will download to the Compute Node before running the command line. For multi-instance Tasks, the resource files will only be downloaded to the Compute Node on which the primary Task is executed. There is a maximum size for the list of @@ -7222,15 +7654,15 @@ class BatchTask(_model_base.Model): code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.""" - output_files: Optional[List["_models.OutputFile"]] = rest_field(name="outputFiles", visibility=["read"]) + output_files: Optional[list["_models.OutputFile"]] = rest_field(name="outputFiles", visibility=["read"]) """A list of files that the Batch service will upload from the Compute Node after running the command line. For multi-instance Tasks, the files will only be uploaded from the Compute Node on which the primary Task is executed.""" - environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="environmentSettings", visibility=["read"] ) """A list of environment variable settings for the Task.""" - affinity_info: Optional["_models.AffinityInfo"] = rest_field(name="affinityInfo", visibility=["read"]) + affinity_info: Optional["_models.BatchAffinityInfo"] = rest_field(name="affinityInfo", visibility=["read"]) """A locality hint that can be used by the Batch service to select a Compute Node on which to start the new Task.""" constraints: Optional["_models.BatchTaskConstraints"] = rest_field( @@ -7253,13 +7685,13 @@ class BatchTask(_model_base.Model): ) """An object that indicates that the Task is a multi-instance Task, and contains information about how to run the multi-instance Task.""" - stats: Optional["_models.BatchTaskStatistics"] = rest_field(visibility=["read"]) + task_statistics: Optional["_models.BatchTaskStatistics"] = rest_field(name="stats", visibility=["read"]) """Resource usage statistics for the Task.""" depends_on: Optional["_models.BatchTaskDependencies"] = rest_field(name="dependsOn", visibility=["read"]) """The Tasks that this Task depends on. This Task will not be scheduled until all Tasks that it depends on have completed successfully. If any of those Tasks fail and exhaust their retry counts, this Task will never be scheduled.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read"] ) """A list of Packages that the Batch service will deploy to the Compute Node before running the @@ -7297,103 +7729,8 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskAddCollectionResult(_model_base.Model): - """The result of adding a collection of Tasks to a Job. - - :ivar value: The results of the add Task collection operation. - :vartype value: list[~azure.batch.models.BatchTaskAddResult] - """ - - value: Optional[List["_models.BatchTaskAddResult"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The results of the add Task collection operation.""" - - @overload - def __init__( - self, - *, - value: Optional[List["_models.BatchTaskAddResult"]] = 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 BatchTaskAddResult(_model_base.Model): - """Result for a single Task added as part of an add Task collection operation. - - :ivar status: The status of the add Task request. Required. Known values are: "success", - "clienterror", and "servererror". - :vartype status: str or ~azure.batch.models.BatchTaskAddStatus - :ivar task_id: The ID of the Task for which this is the result. Required. - :vartype task_id: str - :ivar e_tag: The ETag of the Task, if the Task was successfully added. You can use this to - detect whether the Task has changed between requests. In particular, you can be pass the ETag - with an Update Task request to specify that your changes should take effect only if nobody else - has modified the Job in the meantime. - :vartype e_tag: str - :ivar last_modified: The last modified time of the Task. - :vartype last_modified: ~datetime.datetime - :ivar location: The URL of the Task, if the Task was successfully added. - :vartype location: str - :ivar error: The error encountered while attempting to add the Task. - :vartype error: ~azure.batch.models.BatchError - """ - - status: Union[str, "_models.BatchTaskAddStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the add Task request. Required. Known values are: \"success\", \"clienterror\", - and \"servererror\".""" - task_id: str = rest_field(name="taskId", visibility=["read", "create", "update", "delete", "query"]) - """The ID of the Task for which this is the result. Required.""" - e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) - """The ETag of the Task, if the Task was successfully added. You can use this to detect whether - the Task has changed between requests. In particular, you can be pass the ETag with an Update - Task request to specify that your changes should take effect only if nobody else has modified - the Job in the meantime.""" - last_modified: Optional[datetime.datetime] = rest_field( - name="lastModified", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """The last modified time of the Task.""" - location: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the Task, if the Task was successfully added.""" - error: Optional["_models.BatchError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The error encountered while attempting to add the Task.""" - - @overload - def __init__( - self, - *, - status: Union[str, "_models.BatchTaskAddStatus"], - task_id: str, - e_tag: Optional[str] = None, - last_modified: Optional[datetime.datetime] = None, - location: Optional[str] = None, - error: Optional["_models.BatchError"] = 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 BatchTaskConstraints(_model_base.Model): - """Execution constraints to apply to a Task. +class BatchTaskConstraints(_Model): + """Execution constraints to apply to a Task. :ivar max_wall_clock_time: The maximum elapsed time that the Task may run, measured from the time the Task starts. If the Task does not complete within the time limit, the Batch service @@ -7460,7 +7797,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskContainerExecutionInfo(_model_base.Model): +class BatchTaskContainerExecutionInfo(_Model): """Contains information about the container which a Task is executing. :ivar container_id: The ID of the container. @@ -7506,7 +7843,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskContainerSettings(_model_base.Model): +class BatchTaskContainerSettings(_Model): """The container settings for a Task. :ivar container_run_options: Additional options to the container create command. These @@ -7551,7 +7888,7 @@ class BatchTaskContainerSettings(_model_base.Model): ) """The location of the container Task working directory. The default is 'taskWorkingDirectory'. Known values are: \"taskWorkingDirectory\" and \"containerImageDefault\".""" - container_host_batch_bind_mounts: Optional[List["_models.ContainerHostBatchBindMountEntry"]] = rest_field( + container_host_batch_bind_mounts: Optional[list["_models.ContainerHostBatchBindMountEntry"]] = rest_field( name="containerHostBatchBindMounts", visibility=["read", "create", "update", "delete", "query"] ) """The paths you want to mounted to container task. If this array is null or be not present, @@ -7566,7 +7903,7 @@ def __init__( container_run_options: Optional[str] = None, registry: Optional["_models.ContainerRegistryReference"] = None, working_directory: Optional[Union[str, "_models.ContainerWorkingDirectory"]] = None, - container_host_batch_bind_mounts: Optional[List["_models.ContainerHostBatchBindMountEntry"]] = None, + container_host_batch_bind_mounts: Optional[list["_models.ContainerHostBatchBindMountEntry"]] = None, ) -> None: ... @overload @@ -7580,7 +7917,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCounts(_model_base.Model): +class BatchTaskCounts(_Model): """The Task counts for a Job. :ivar active: The number of Tasks in the active state. Required. @@ -7632,7 +7969,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCountsResult(_model_base.Model): +class BatchTaskCountsResult(_Model): """The Task and TaskSlot counts for a Job. :ivar task_counts: The number of Tasks per state. Required. @@ -7669,7 +8006,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskCreateContent(_model_base.Model): +class BatchTaskCreateOptions(_Model): """Parameters for creating an Azure Batch Task. :ivar id: A string that uniquely identifies the Task within the Job. The ID can contain any @@ -7720,7 +8057,7 @@ class BatchTaskCreateContent(_model_base.Model): :vartype environment_settings: list[~azure.batch.models.EnvironmentSetting] :ivar affinity_info: A locality hint that can be used by the Batch service to select a Compute Node on which to start the new Task. - :vartype affinity_info: ~azure.batch.models.AffinityInfo + :vartype affinity_info: ~azure.batch.models.BatchAffinityInfo :ivar constraints: The execution constraints that apply to this Task. If you do not specify constraints, the maxTaskRetryCount is the maxTaskRetryCount specified for the Job, the maxWallClockTime is infinite, and the retentionTime is 7 days. @@ -7797,7 +8134,7 @@ class BatchTaskCreateContent(_model_base.Model): container, and the Task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR might not be reflected to the host disk, meaning that Batch file APIs will not be able to access those files.""" - resource_files: Optional[List["_models.ResourceFile"]] = rest_field( + resource_files: Optional[list["_models.ResourceFile"]] = rest_field( name="resourceFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will download to the Compute Node before running the @@ -7807,17 +8144,17 @@ class BatchTaskCreateContent(_model_base.Model): code will be RequestEntityTooLarge. If this occurs, the collection of ResourceFiles must be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers.""" - output_files: Optional[List["_models.OutputFile"]] = rest_field( + output_files: Optional[list["_models.OutputFile"]] = rest_field( name="outputFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will upload from the Compute Node after running the command line. For multi-instance Tasks, the files will only be uploaded from the Compute Node on which the primary Task is executed.""" - environment_settings: Optional[List["_models.EnvironmentSetting"]] = rest_field( + environment_settings: Optional[list["_models.EnvironmentSetting"]] = rest_field( name="environmentSettings", visibility=["read", "create", "update", "delete", "query"] ) """A list of environment variable settings for the Task.""" - affinity_info: Optional["_models.AffinityInfo"] = rest_field( + affinity_info: Optional["_models.BatchAffinityInfo"] = rest_field( name="affinityInfo", visibility=["read", "create", "update", "delete", "query"] ) """A locality hint that can be used by the Batch service to select a Compute Node on which to @@ -7852,7 +8189,7 @@ class BatchTaskCreateContent(_model_base.Model): counts, this Task will never be scheduled. If the Job does not have usesTaskDependencies set to true, and this element is present, the request fails with error code TaskDependenciesNotSpecifiedOnJob.""" - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = rest_field( + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = rest_field( name="applicationPackageReferences", visibility=["read", "create", "update", "delete", "query"] ) """A list of Packages that the Batch service will deploy to the Compute Node before running the @@ -7881,16 +8218,16 @@ def __init__( display_name: Optional[str] = None, exit_conditions: Optional["_models.ExitConditions"] = None, container_settings: Optional["_models.BatchTaskContainerSettings"] = None, - resource_files: Optional[List["_models.ResourceFile"]] = None, - output_files: Optional[List["_models.OutputFile"]] = None, - environment_settings: Optional[List["_models.EnvironmentSetting"]] = None, - affinity_info: Optional["_models.AffinityInfo"] = None, + resource_files: Optional[list["_models.ResourceFile"]] = None, + output_files: Optional[list["_models.OutputFile"]] = None, + environment_settings: Optional[list["_models.EnvironmentSetting"]] = None, + affinity_info: Optional["_models.BatchAffinityInfo"] = None, constraints: Optional["_models.BatchTaskConstraints"] = None, required_slots: Optional[int] = None, user_identity: Optional["_models.UserIdentity"] = None, multi_instance_settings: Optional["_models.MultiInstanceSettings"] = None, depends_on: Optional["_models.BatchTaskDependencies"] = None, - application_package_references: Optional[List["_models.BatchApplicationPackageReference"]] = None, + application_package_references: Optional[list["_models.BatchApplicationPackageReference"]] = None, authentication_token_settings: Optional["_models.AuthenticationTokenSettings"] = None, ) -> None: ... @@ -7905,7 +8242,72 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskDependencies(_model_base.Model): +class BatchTaskCreateResult(_Model): + """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", + "clienterror", and "servererror". + :vartype status: str or ~azure.batch.models.BatchTaskAddStatus + :ivar task_id: The ID of the Task for which this is the result. Required. + :vartype task_id: str + :ivar e_tag: The ETag of the Task, if the Task was successfully added. You can use this to + detect whether the Task has changed between requests. In particular, you can be pass the ETag + with an Update Task request to specify that your changes should take effect only if nobody else + has modified the Job in the meantime. + :vartype e_tag: str + :ivar last_modified: The last modified time of the Task. + :vartype last_modified: ~datetime.datetime + :ivar location: The URL of the Task, if the Task was successfully added. + :vartype location: str + :ivar error: The error encountered while attempting to add the Task. + :vartype error: ~azure.batch.models.BatchError + """ + + status: Union[str, "_models.BatchTaskAddStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The status of the add Task request. Required. Known values are: \"success\", \"clienterror\", + and \"servererror\".""" + task_id: str = rest_field(name="taskId", visibility=["read", "create", "update", "delete", "query"]) + """The ID of the Task for which this is the result. Required.""" + e_tag: Optional[str] = rest_field(name="eTag", visibility=["read", "create", "update", "delete", "query"]) + """The ETag of the Task, if the Task was successfully added. You can use this to detect whether + the Task has changed between requests. In particular, you can be pass the ETag with an Update + Task request to specify that your changes should take effect only if nobody else has modified + the Job in the meantime.""" + last_modified: Optional[datetime.datetime] = rest_field( + name="lastModified", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The last modified time of the Task.""" + location: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URL of the Task, if the Task was successfully added.""" + error: Optional["_models.BatchError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The error encountered while attempting to add the Task.""" + + @overload + def __init__( + self, + *, + status: Union[str, "_models.BatchTaskAddStatus"], + task_id: str, + e_tag: Optional[str] = None, + last_modified: Optional[datetime.datetime] = None, + location: Optional[str] = None, + error: Optional["_models.BatchError"] = 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 BatchTaskDependencies(_Model): """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. @@ -7921,7 +8323,7 @@ class BatchTaskDependencies(_model_base.Model): :vartype task_id_ranges: list[~azure.batch.models.BatchTaskIdRange] """ - task_ids: Optional[List[str]] = rest_field( + task_ids: Optional[list[str]] = rest_field( name="taskIds", visibility=["read", "create", "update", "delete", "query"] ) """The list of Task IDs that this Task depends on. All Tasks in this list must complete @@ -7929,7 +8331,7 @@ class BatchTaskDependencies(_model_base.Model): 64000 characters total (i.e. the combined length of all Task IDs). If the taskIds collection exceeds the maximum length, the Add Task request fails with error code TaskDependencyListTooLong. In this case consider using Task ID ranges instead.""" - task_id_ranges: Optional[List["_models.BatchTaskIdRange"]] = rest_field( + task_id_ranges: Optional[list["_models.BatchTaskIdRange"]] = rest_field( name="taskIdRanges", visibility=["read", "create", "update", "delete", "query"] ) """The list of Task ID ranges that this Task depends on. All Tasks in all ranges must complete @@ -7939,8 +8341,8 @@ class BatchTaskDependencies(_model_base.Model): def __init__( self, *, - task_ids: Optional[List[str]] = None, - task_id_ranges: Optional[List["_models.BatchTaskIdRange"]] = None, + task_ids: Optional[list[str]] = None, + task_id_ranges: Optional[list["_models.BatchTaskIdRange"]] = None, ) -> None: ... @overload @@ -7954,7 +8356,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskExecutionInfo(_model_base.Model): +class BatchTaskExecutionInfo(_Model): """Information about the execution of a Task. :ivar start_time: The time at which the Task started running. 'Running' corresponds to the @@ -8094,12 +8496,12 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskFailureInfo(_model_base.Model): +class BatchTaskFailureInfo(_Model): """Information about a Task failure. :ivar category: The category of the Task error. Required. Known values are: "usererror" and "servererror". - :vartype category: str or ~azure.batch.models.ErrorCategory + :vartype category: str or ~azure.batch.models.BatchErrorSourceCategory :ivar code: An identifier for the Task error. Codes are invariant and are intended to be consumed programmatically. :vartype code: str @@ -8110,7 +8512,7 @@ class BatchTaskFailureInfo(_model_base.Model): :vartype details: list[~azure.batch.models.NameValuePair] """ - category: Union[str, "_models.ErrorCategory"] = rest_field( + category: Union[str, "_models.BatchErrorSourceCategory"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """The category of the Task error. Required. Known values are: \"usererror\" and \"servererror\".""" @@ -8119,7 +8521,7 @@ class BatchTaskFailureInfo(_model_base.Model): programmatically.""" message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A message describing the Task error, intended to be suitable for display in a user interface.""" - details: Optional[List["_models.NameValuePair"]] = rest_field( + details: Optional[list["_models.NameValuePair"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """A list of additional details related to the error.""" @@ -8128,10 +8530,10 @@ class BatchTaskFailureInfo(_model_base.Model): def __init__( self, *, - category: Union[str, "_models.ErrorCategory"], + category: Union[str, "_models.BatchErrorSourceCategory"], code: Optional[str] = None, message: Optional[str] = None, - details: Optional[List["_models.NameValuePair"]] = None, + details: Optional[list["_models.NameValuePair"]] = None, ) -> None: ... @overload @@ -8145,18 +8547,18 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskGroup(_model_base.Model): +class BatchTaskGroup(_Model): """A collection of Azure Batch Tasks to add. - :ivar value: The collection of Tasks to add. The maximum count of Tasks is 100. The total - serialized size of this collection must be less than 1MB. If it is greater than 1MB (for + :ivar values_property: The collection of Tasks to add. The maximum count of Tasks is 100. The + total serialized size of this collection must be less than 1MB. If it is greater than 1MB (for example if each Task has 100's of resource files or environment variables), the request will fail with code 'RequestBodyTooLarge' and should be retried again with fewer Tasks. Required. - :vartype value: list[~azure.batch.models.BatchTaskCreateContent] + :vartype values_property: list[~azure.batch.models.BatchTaskCreateOptions] """ - value: List["_models.BatchTaskCreateContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + values_property: list["_models.BatchTaskCreateOptions"] = rest_field( + name="value", visibility=["read", "create", "update", "delete", "query"] ) """The collection of Tasks to add. The maximum count of Tasks is 100. The total serialized size of this collection must be less than 1MB. If it is greater than 1MB (for example if each Task has @@ -8167,7 +8569,7 @@ class BatchTaskGroup(_model_base.Model): def __init__( self, *, - value: List["_models.BatchTaskCreateContent"], + values_property: list["_models.BatchTaskCreateOptions"], ) -> None: ... @overload @@ -8181,7 +8583,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskIdRange(_model_base.Model): +class BatchTaskIdRange(_Model): """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'. @@ -8215,7 +8617,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskInfo(_model_base.Model): +class BatchTaskInfo(_Model): """Information about a Task running on a Compute Node. :ivar task_url: The URL of the Task. @@ -8274,7 +8676,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskSchedulingPolicy(_model_base.Model): +class BatchTaskSchedulingPolicy(_Model): """Specifies how Tasks should be distributed across Compute Nodes. :ivar node_fill_type: How Tasks are distributed across Compute Nodes in a Pool. If not @@ -8306,7 +8708,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskSlotCounts(_model_base.Model): +class BatchTaskSlotCounts(_Model): """The TaskSlot counts for a Job. :ivar active: The number of TaskSlots for active Tasks. Required. @@ -8354,7 +8756,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class BatchTaskStatistics(_model_base.Model): +class BatchTaskStatistics(_Model): """Resource usage statistics for a Task. :ivar url: The URL of the statistics. Required. @@ -8375,10 +8777,10 @@ class BatchTaskStatistics(_model_base.Model): the last time the statistics were updated, if the Task had not finished by then). If the Task was retried, this includes the wall clock time of all the Task retries. Required. :vartype wall_clock_time: ~datetime.timedelta - :ivar read_i_ops: The total number of disk read operations made by the Task. Required. - :vartype read_i_ops: int - :ivar write_i_ops: The total number of disk write operations made by the Task. Required. - :vartype write_i_ops: int + :ivar read_iops: The total number of disk read operations made by the Task. Required. + :vartype read_iops: int + :ivar write_iops: The total number of disk write operations made by the Task. Required. + :vartype write_iops: int :ivar read_io_gi_b: The total gibibytes read from disk by the Task. Required. :vartype read_io_gi_b: float :ivar write_io_gi_b: The total gibibytes written to disk by the Task. Required. @@ -8418,11 +8820,11 @@ class BatchTaskStatistics(_model_base.Model): Task started running on a Compute Node to when it finished (or to the last time the statistics were updated, if the Task had not finished by then). If the Task was retried, this includes the wall clock time of all the Task retries. Required.""" - read_i_ops: int = rest_field( + read_iops: int = rest_field( name="readIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk read operations made by the Task. Required.""" - write_i_ops: int = rest_field( + write_iops: int = rest_field( name="writeIOps", visibility=["read", "create", "update", "delete", "query"], format="str" ) """The total number of disk write operations made by the Task. Required.""" @@ -8447,8 +8849,8 @@ def __init__( user_cpu_time: datetime.timedelta, kernel_cpu_time: datetime.timedelta, wall_clock_time: datetime.timedelta, - read_i_ops: int, - write_i_ops: int, + read_iops: int, + write_iops: int, read_io_gi_b: float, write_io_gi_b: float, wait_time: datetime.timedelta, @@ -8465,51 +8867,32 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CifsMountConfiguration(_model_base.Model): - """Information used to connect to a CIFS file system. +class BatchUefiSettings(_Model): + """Specifies the security settings like secure boot and vTPM used while creating the virtual + machine. - :ivar username: The user to use for authentication against the CIFS file system. Required. - :vartype username: str - :ivar source: The URI of the file system to mount. Required. - :vartype source: str - :ivar relative_mount_path: The relative path on the compute node where the file system will be - mounted. All file systems are mounted relative to the Batch mounts directory, accessible via - the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. - :vartype relative_mount_path: str - :ivar mount_options: Additional command line options to pass to the mount command. These are - 'net use' options in Windows and 'mount' options in Linux. - :vartype mount_options: str - :ivar password: The password to use for authentication against the CIFS file system. Required. - :vartype password: str + :ivar secure_boot_enabled: Specifies whether secure boot should be enabled on the virtual + machine. + :vartype secure_boot_enabled: bool + :ivar v_tpm_enabled: Specifies whether vTPM should be enabled on the virtual machine. + :vartype v_tpm_enabled: bool """ - username: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The user to use for authentication against the CIFS file system. Required.""" - source: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URI of the file system to mount. Required.""" - relative_mount_path: str = rest_field( - name="relativeMountPath", visibility=["read", "create", "update", "delete", "query"] + secure_boot_enabled: Optional[bool] = rest_field( + name="secureBootEnabled", visibility=["read", "create", "update", "delete", "query"] ) - """The relative path on the compute node where the file system will be mounted. All file systems - are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR - environment variable. Required.""" - mount_options: Optional[str] = rest_field( - name="mountOptions", visibility=["read", "create", "update", "delete", "query"] + """Specifies whether secure boot should be enabled on the virtual machine.""" + v_tpm_enabled: Optional[bool] = rest_field( + name="vTpmEnabled", visibility=["read", "create", "update", "delete", "query"] ) - """Additional command line options to pass to the mount command. These are 'net use' options in - Windows and 'mount' options in Linux.""" - password: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The password to use for authentication against the CIFS file system. Required.""" + """Specifies whether vTPM should be enabled on the virtual machine.""" @overload def __init__( self, *, - username: str, - source: str, - relative_mount_path: str, - password: str, - mount_options: Optional[str] = None, + secure_boot_enabled: Optional[bool] = None, + v_tpm_enabled: Optional[bool] = None, ) -> None: ... @overload @@ -8523,45 +8906,29 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ContainerConfiguration(_model_base.Model): - """The configuration for container-enabled Pools. +class BatchUserAssignedIdentity(_Model): + """The user assigned Identity. - :ivar type: The container technology to be used. Required. Known values are: "dockerCompatible" - and "criCompatible". - :vartype type: str or ~azure.batch.models.ContainerType - :ivar container_image_names: The collection of container Image names. This is the full Image - reference, as would be specified to "docker pull". An Image will be sourced from the default - Docker registry unless the Image is fully qualified with an alternative registry. - :vartype container_image_names: list[str] - :ivar container_registries: Additional private registries from which containers can be pulled. - If any Images must be downloaded from a private registry which requires credentials, then those - credentials must be provided here. - :vartype container_registries: list[~azure.batch.models.ContainerRegistryReference] + :ivar resource_id: The ARM resource id of the user assigned identity. Required. + :vartype resource_id: str + :ivar client_id: The client id of the user assigned identity. + :vartype client_id: str + :ivar principal_id: The principal id of the user assigned identity. + :vartype principal_id: str """ - type: Union[str, "_models.ContainerType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The container technology to be used. Required. Known values are: \"dockerCompatible\" and - \"criCompatible\".""" - container_image_names: Optional[List[str]] = rest_field( - name="containerImageNames", visibility=["read", "create", "update", "delete", "query"] - ) - """The collection of container Image names. This is the full Image reference, as would be - specified to \"docker pull\". An Image will be sourced from the default Docker registry unless - the Image is fully qualified with an alternative registry.""" - container_registries: Optional[List["_models.ContainerRegistryReference"]] = rest_field( - name="containerRegistries", visibility=["read", "create", "update", "delete", "query"] - ) - """Additional private registries from which containers can be pulled. If any Images must be - downloaded from a private registry which requires credentials, then those credentials must be - provided here.""" + resource_id: str = rest_field(name="resourceId", visibility=["read", "create", "update", "delete", "query"]) + """The ARM resource id of the user assigned identity. Required.""" + client_id: Optional[str] = rest_field(name="clientId", visibility=["read"]) + """The client id of the user assigned identity.""" + principal_id: Optional[str] = rest_field(name="principalId", visibility=["read"]) + """The principal id of the user assigned identity.""" @overload def __init__( self, *, - type: Union[str, "_models.ContainerType"], - container_image_names: Optional[List[str]] = None, - container_registries: Optional[List["_models.ContainerRegistryReference"]] = None, + resource_id: str, ) -> None: ... @overload @@ -8575,23 +8942,228 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ContainerHostBatchBindMountEntry(_model_base.Model): - """The entry of path and mount mode you want to mount into task container. +class BatchVmDiskSecurityProfile(_Model): + """Specifies the security profile settings for the managed disk. **Note**: It can only be set for + Confidential VMs and required when using Confidential VMs. - :ivar source: The path which be mounted to container customer can select. Known values are: - "Shared", "Startup", "VfsMounts", "Task", "JobPrep", and "Applications". - :vartype source: str or ~azure.batch.models.ContainerHostDataPath - :ivar is_read_only: Mount this source path as read-only mode or not. Default value is false - (read/write mode). For Linux, if you mount this path as a read/write mode, this does not mean - that all users in container have the read/write access for the path, it depends on the access - in host VM. If this path is mounted read-only, all users within the container will not be able - to modify the path. - :vartype is_read_only: bool + :ivar security_encryption_type: Specifies the EncryptionType of the managed disk. It is set to + VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not + persisting firmware state in the VMGuestState blob. **Note**: It can be set for only + Confidential VMs and is required when using Confidential VMs. Known values are: + "NonPersistedTPM" and "VMGuestStateOnly". + :vartype security_encryption_type: str or ~azure.batch.models.SecurityEncryptionTypes """ - source: Optional[Union[str, "_models.ContainerHostDataPath"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) + security_encryption_type: Optional[Union[str, "_models.SecurityEncryptionTypes"]] = rest_field( + name="securityEncryptionType", visibility=["read", "create", "update", "delete", "query"] + ) + """Specifies the EncryptionType of the managed disk. It is set to VMGuestStateOnly for encryption + of just the VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the + VMGuestState blob. **Note**: It can be set for only Confidential VMs and is required when using + Confidential VMs. Known values are: \"NonPersistedTPM\" and \"VMGuestStateOnly\".""" + + @overload + def __init__( + self, + *, + security_encryption_type: Optional[Union[str, "_models.SecurityEncryptionTypes"]] = 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 BatchVmImageReference(_Model): + """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. + + :ivar publisher: The publisher of the Azure Virtual Machines Marketplace Image. For example, + Canonical or MicrosoftWindowsServer. + :vartype publisher: str + :ivar offer: The offer type of the Azure Virtual Machines Marketplace Image. For example, + UbuntuServer or WindowsServer. + :vartype offer: str + :ivar sku: The SKU of the Azure Virtual Machines Marketplace Image. For example, 18.04-LTS or + 2019-Datacenter. + :vartype sku: str + :ivar version: The version of the Azure Virtual Machines Marketplace Image. A value of 'latest' + can be specified to select the latest version of an Image. If omitted, the default is 'latest'. + :vartype version: str + :ivar virtual_machine_image_id: The ARM resource identifier of the Azure Compute Gallery Image. + Compute Nodes in the Pool will be created using this Image Id. This is of the form + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{VersionId} + or + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName} + for always defaulting to the latest image version. This property is mutually exclusive with + other ImageReference properties. The Azure Compute Gallery Image must have replicas in the same + region and must be in the same subscription as the Azure Batch account. If the image version is + not specified in the imageId, the latest version will be used. For information about the + firewall settings for the Batch Compute Node agent to communicate with the Batch service see + `https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration + `_. + :vartype virtual_machine_image_id: str + :ivar exact_version: The specific version of the platform image or marketplace image used to + create the node. This read-only field differs from 'version' only if the value specified for + 'version' when the pool was created was 'latest'. + :vartype exact_version: str + :ivar shared_gallery_image_id: The shared gallery image unique identifier. This property is + mutually exclusive with other properties and can be fetched from shared gallery image GET call. + :vartype shared_gallery_image_id: str + :ivar community_gallery_image_id: The community gallery image unique identifier. This property + is mutually exclusive with other properties and can be fetched from community gallery image GET + call. + :vartype community_gallery_image_id: str + """ + + publisher: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The publisher of the Azure Virtual Machines Marketplace Image. For example, Canonical or + MicrosoftWindowsServer.""" + offer: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The offer type of the Azure Virtual Machines Marketplace Image. For example, UbuntuServer or + WindowsServer.""" + sku: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The SKU of the Azure Virtual Machines Marketplace Image. For example, 18.04-LTS or + 2019-Datacenter.""" + version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The version of the Azure Virtual Machines Marketplace Image. A value of 'latest' can be + specified to select the latest version of an Image. If omitted, the default is 'latest'.""" + virtual_machine_image_id: Optional[str] = rest_field( + name="virtualMachineImageId", visibility=["read", "create", "update", "delete", "query"] + ) + """The ARM resource identifier of the Azure Compute Gallery Image. Compute Nodes in the Pool will + be created using this Image Id. This is of the form + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{VersionId} + or + /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName} + for always defaulting to the latest image version. This property is mutually exclusive with + other ImageReference properties. The Azure Compute Gallery Image must have replicas in the same + region and must be in the same subscription as the Azure Batch account. If the image version is + not specified in the imageId, the latest version will be used. For information about the + firewall settings for the Batch Compute Node agent to communicate with the Batch service see + `https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration + `_.""" + exact_version: Optional[str] = rest_field(name="exactVersion", visibility=["read"]) + """The specific version of the platform image or marketplace image used to create the node. This + read-only field differs from 'version' only if the value specified for 'version' when the pool + was created was 'latest'.""" + shared_gallery_image_id: Optional[str] = rest_field( + name="sharedGalleryImageId", visibility=["read", "create", "update", "delete", "query"] + ) + """The shared gallery image unique identifier. This property is mutually exclusive with other + properties and can be fetched from shared gallery image GET call.""" + community_gallery_image_id: Optional[str] = rest_field( + name="communityGalleryImageId", visibility=["read", "create", "update", "delete", "query"] + ) + """The community gallery image unique identifier. This property is mutually exclusive with other + properties and can be fetched from community gallery image GET call.""" + + @overload + def __init__( + self, + *, + publisher: Optional[str] = None, + offer: Optional[str] = None, + sku: Optional[str] = None, + version: Optional[str] = None, + virtual_machine_image_id: Optional[str] = None, + shared_gallery_image_id: Optional[str] = None, + community_gallery_image_id: Optional[str] = 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 CifsMountConfiguration(_Model): + """Information used to connect to a CIFS file system. + + :ivar username: The user to use for authentication against the CIFS file system. Required. + :vartype username: str + :ivar source: The URI of the file system to mount. Required. + :vartype source: str + :ivar relative_mount_path: The relative path on the compute node where the file system will be + mounted. All file systems are mounted relative to the Batch mounts directory, accessible via + the AZ_BATCH_NODE_MOUNTS_DIR environment variable. Required. + :vartype relative_mount_path: str + :ivar mount_options: Additional command line options to pass to the mount command. These are + 'net use' options in Windows and 'mount' options in Linux. + :vartype mount_options: str + :ivar password: The password to use for authentication against the CIFS file system. Required. + :vartype password: str + """ + + username: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The user to use for authentication against the CIFS file system. Required.""" + source: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URI of the file system to mount. Required.""" + relative_mount_path: str = rest_field( + name="relativeMountPath", visibility=["read", "create", "update", "delete", "query"] + ) + """The relative path on the compute node where the file system will be mounted. All file systems + are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR + environment variable. Required.""" + mount_options: Optional[str] = rest_field( + name="mountOptions", visibility=["read", "create", "update", "delete", "query"] + ) + """Additional command line options to pass to the mount command. These are 'net use' options in + Windows and 'mount' options in Linux.""" + password: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The password to use for authentication against the CIFS file system. Required.""" + + @overload + def __init__( + self, + *, + username: str, + source: str, + relative_mount_path: str, + password: str, + mount_options: Optional[str] = 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 ContainerHostBatchBindMountEntry(_Model): + """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: + "Shared", "Startup", "VfsMounts", "Task", "JobPrep", and "Applications". + :vartype source: str or ~azure.batch.models.ContainerHostDataPath + :ivar is_read_only: Mount this source path as read-only mode or not. Default value is false + (read/write mode). For Linux, if you mount this path as a read/write mode, this does not mean + that all users in container have the read/write access for the path, it depends on the access + in host VM. If this path is mounted read-only, all users within the container will not be able + to modify the path. + :vartype is_read_only: bool + """ + + source: Optional[Union[str, "_models.ContainerHostDataPath"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """The path which be mounted to container customer can select. Known values are: \"Shared\", \"Startup\", \"VfsMounts\", \"Task\", \"JobPrep\", and \"Applications\".""" is_read_only: Optional[bool] = rest_field( @@ -8621,7 +9193,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ContainerRegistryReference(_model_base.Model): +class ContainerRegistryReference(_Model): """A private container registry. :ivar username: The user name to log into the registry server. @@ -8670,7 +9242,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DataDisk(_model_base.Model): +class DataDisk(_Model): """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. @@ -8734,43 +9306,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DeleteBatchCertificateError(_model_base.Model): - """An error encountered by the Batch service when deleting a Certificate. +class DiskEncryptionConfiguration(_Model): + """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. - :ivar code: An identifier for the Certificate deletion error. Codes are invariant and are - intended to be consumed programmatically. - :vartype code: str - :ivar message: A message describing the Certificate deletion error, intended to be suitable for - display in a user interface. - :vartype message: str - :ivar values_property: A list of additional error details related to the Certificate deletion - error. This list includes details such as the active Pools and Compute Nodes referencing this - Certificate. However, if a large number of resources reference the Certificate, the list - contains only about the first hundred. - :vartype values_property: list[~azure.batch.models.NameValuePair] + :ivar targets: The list of disk targets Batch Service will encrypt on the compute node. The + list of disk targets Batch Service will encrypt on the compute node. + :vartype targets: list[str or ~azure.batch.models.DiskEncryptionTarget] """ - code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier for the Certificate deletion error. Codes are invariant and are intended to be - consumed programmatically.""" - message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A message describing the Certificate deletion error, intended to be suitable for display in a - user interface.""" - values_property: Optional[List["_models.NameValuePair"]] = rest_field( - name="values", visibility=["read", "create", "update", "delete", "query"] + targets: Optional[list[Union[str, "_models.DiskEncryptionTarget"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] ) - """A list of additional error details related to the Certificate deletion error. This list - includes details such as the active Pools and Compute Nodes referencing this Certificate. - However, if a large number of resources reference the Certificate, the list contains only about - the first hundred.""" + """The list of disk targets Batch Service will encrypt on the compute node. The list of disk + targets Batch Service will encrypt on the compute node.""" @overload def __init__( self, *, - code: Optional[str] = None, - message: Optional[str] = None, - values_property: Optional[List["_models.NameValuePair"]] = None, + targets: Optional[list[Union[str, "_models.DiskEncryptionTarget"]]] = None, ) -> None: ... @overload @@ -8784,91 +9340,8 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DiffDiskSettings(_model_base.Model): - """Specifies the ephemeral Disk Settings for the operating system disk used by the - compute node (VM). - - :ivar placement: Specifies the ephemeral disk placement for operating system disk for all VMs - in the pool. This property can be used by user in the request to choose the location e.g., - cache disk space for Ephemeral OS disk provisioning. For more information on Ephemeral OS disk - size requirements, please refer to Ephemeral OS disk size requirements for Windows VMs at - `https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements - `_ - and Linux VMs at - `https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements - `_. - "cachedisk" - :vartype placement: str or ~azure.batch.models.DiffDiskPlacement - """ - - placement: Optional[Union[str, "_models.DiffDiskPlacement"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies the ephemeral disk placement for operating system disk for all VMs in the pool. This - property can be used by user in the request to choose the location e.g., cache disk space for - Ephemeral OS disk provisioning. For more information on Ephemeral OS disk size requirements, - please refer to Ephemeral OS disk size requirements for Windows VMs at - `https://learn.microsoft.com/azure/virtual-machines/windows/ephemeral-os-disks#size-requirements - `_ - and Linux VMs at - `https://learn.microsoft.com/azure/virtual-machines/linux/ephemeral-os-disks#size-requirements - `_. - \"cachedisk\"""" - - @overload - def __init__( - self, - *, - placement: Optional[Union[str, "_models.DiffDiskPlacement"]] = 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 DiskEncryptionConfiguration(_model_base.Model): - """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. - - :ivar targets: The list of disk targets Batch Service will encrypt on the compute node. The - list of disk targets Batch Service will encrypt on the compute node. - :vartype targets: list[str or ~azure.batch.models.DiskEncryptionTarget] - """ - - targets: Optional[List[Union[str, "_models.DiskEncryptionTarget"]]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The list of disk targets Batch Service will encrypt on the compute node. The list of disk - targets Batch Service will encrypt on the compute node.""" - - @overload - def __init__( - self, - *, - targets: Optional[List[Union[str, "_models.DiskEncryptionTarget"]]] = 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 EnvironmentSetting(_model_base.Model): - """An environment variable to be set on a Task process. +class EnvironmentSetting(_Model): + """An environment variable to be set on a Task process. :ivar name: The name of the environment variable. Required. :vartype name: str @@ -8900,7 +9373,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitCodeMapping(_model_base.Model): +class ExitCodeMapping(_Model): """How the Batch service should respond if a Task exits with a particular exit code. @@ -8937,7 +9410,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitCodeRangeMapping(_model_base.Model): +class ExitCodeRangeMapping(_Model): """A range of exit codes and how the Batch service should respond to exit codes within that range. @@ -8980,7 +9453,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitConditions(_model_base.Model): +class ExitConditions(_Model): """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 @@ -9005,11 +9478,11 @@ class ExitConditions(_model_base.Model): :vartype default: ~azure.batch.models.ExitOptions """ - exit_codes: Optional[List["_models.ExitCodeMapping"]] = rest_field( + exit_codes: Optional[list["_models.ExitCodeMapping"]] = rest_field( name="exitCodes", visibility=["read", "create", "update", "delete", "query"] ) """A list of individual Task exit codes and how the Batch service should respond to them.""" - exit_code_ranges: Optional[List["_models.ExitCodeRangeMapping"]] = rest_field( + exit_code_ranges: Optional[list["_models.ExitCodeRangeMapping"]] = rest_field( name="exitCodeRanges", visibility=["read", "create", "update", "delete", "query"] ) """A list of Task exit code ranges and how the Batch service should respond to them.""" @@ -9035,8 +9508,8 @@ class ExitConditions(_model_base.Model): def __init__( self, *, - exit_codes: Optional[List["_models.ExitCodeMapping"]] = None, - exit_code_ranges: Optional[List["_models.ExitCodeRangeMapping"]] = None, + exit_codes: Optional[list["_models.ExitCodeMapping"]] = None, + exit_code_ranges: Optional[list["_models.ExitCodeRangeMapping"]] = None, pre_processing_error: Optional["_models.ExitOptions"] = None, file_upload_error: Optional["_models.ExitOptions"] = None, default: Optional["_models.ExitOptions"] = None, @@ -9053,7 +9526,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExitOptions(_model_base.Model): +class ExitOptions(_Model): """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 @@ -9063,7 +9536,7 @@ class ExitOptions(_model_base.Model): Task request fails with an invalid property value error; if you are calling the REST API directly, the HTTP status code is 400 (Bad Request). Known values are: "none", "disable", and "terminate". - :vartype job_action: str or ~azure.batch.models.BatchJobAction + :vartype job_action: str or ~azure.batch.models.BatchJobActionKind :ivar dependency_action: An action that the Batch service performs on Tasks that depend on this Task. Possible values are 'satisfy' (allowing dependent tasks to progress) and 'block' (dependent tasks continue to wait). Batch does not yet support cancellation of dependent tasks. @@ -9071,7 +9544,7 @@ class ExitOptions(_model_base.Model): :vartype dependency_action: str or ~azure.batch.models.DependencyAction """ - job_action: Optional[Union[str, "_models.BatchJobAction"]] = rest_field( + job_action: Optional[Union[str, "_models.BatchJobActionKind"]] = rest_field( name="jobAction", visibility=["read", "create", "update", "delete", "query"] ) """An action to take on the Job containing the Task, if the Task completes with the given exit @@ -9092,7 +9565,7 @@ class ExitOptions(_model_base.Model): def __init__( self, *, - job_action: Optional[Union[str, "_models.BatchJobAction"]] = None, + job_action: Optional[Union[str, "_models.BatchJobActionKind"]] = None, dependency_action: Optional[Union[str, "_models.DependencyAction"]] = None, ) -> None: ... @@ -9107,7 +9580,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class FileProperties(_model_base.Model): +class FileProperties(_Model): """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 @@ -9166,232 +9639,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class GetCertificateResponse(_model_base.Model): - """GetCertificateResponse. - - :ivar thumbprint: The X.509 thumbprint of the Certificate. This is a sequence of up to 40 hex - digits (it may include spaces but these are removed). Required. - :vartype thumbprint: str - :ivar thumbprint_algorithm: The algorithm used to derive the thumbprint. This must be sha1. - Required. - :vartype thumbprint_algorithm: str - :ivar url: The URL of the Certificate. - :vartype url: str - :ivar state: The state of the Certificate. Known values are: "active", "deleting", and - "deletefailed". - :vartype state: str or ~azure.batch.models.BatchCertificateState - :ivar state_transition_time: The time at which the Certificate entered its current state. - :vartype state_transition_time: ~datetime.datetime - :ivar previous_state: The previous state of the Certificate. This property is not set if the - Certificate is in its initial active state. Known values are: "active", "deleting", and - "deletefailed". - :vartype previous_state: str or ~azure.batch.models.BatchCertificateState - :ivar previous_state_transition_time: The time at which the Certificate entered its previous - state. This property is not set if the Certificate is in its initial Active state. - :vartype previous_state_transition_time: ~datetime.datetime - :ivar public_data: The public part of the Certificate as a base-64 encoded .cer file. - :vartype public_data: str - :ivar delete_certificate_error: The error that occurred on the last attempt to delete this - Certificate. This property is set only if the Certificate is in the DeleteFailed state. - :vartype delete_certificate_error: ~azure.batch.models.DeleteBatchCertificateError - """ - - thumbprint: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The X.509 thumbprint of the Certificate. This is a sequence of up to 40 hex digits (it may - include spaces but these are removed). Required.""" - thumbprint_algorithm: str = rest_field( - name="thumbprintAlgorithm", visibility=["read", "create", "update", "delete", "query"] - ) - """The algorithm used to derive the thumbprint. This must be sha1. Required.""" - url: Optional[str] = rest_field(visibility=["read"]) - """The URL of the Certificate.""" - state: Optional[Union[str, "_models.BatchCertificateState"]] = rest_field(visibility=["read"]) - """The state of the Certificate. Known values are: \"active\", \"deleting\", and \"deletefailed\".""" - state_transition_time: Optional[datetime.datetime] = rest_field( - name="stateTransitionTime", visibility=["read"], format="rfc3339" - ) - """The time at which the Certificate entered its current state.""" - previous_state: Optional[Union[str, "_models.BatchCertificateState"]] = rest_field( - name="previousState", visibility=["read"] - ) - """The previous state of the Certificate. This property is not set if the Certificate is in its - initial active state. Known values are: \"active\", \"deleting\", and \"deletefailed\".""" - previous_state_transition_time: Optional[datetime.datetime] = rest_field( - name="previousStateTransitionTime", visibility=["read"], format="rfc3339" - ) - """The time at which the Certificate entered its previous state. This property is not set if the - Certificate is in its initial Active state.""" - public_data: Optional[str] = rest_field(name="publicData", visibility=["read"]) - """The public part of the Certificate as a base-64 encoded .cer file.""" - delete_certificate_error: Optional["_models.DeleteBatchCertificateError"] = rest_field( - name="deleteCertificateError", visibility=["read"] - ) - """The error that occurred on the last attempt to delete this Certificate. This property is set - only if the Certificate is in the DeleteFailed state.""" - - @overload - def __init__( - self, - *, - thumbprint: str, - thumbprint_algorithm: str, - ) -> 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 HttpHeader(_model_base.Model): - """An HTTP header name-value pair. - - :ivar name: The case-insensitive name of the header to be used while uploading output files. - Required. - :vartype name: str - :ivar value: The value of the header to be used while uploading output files. - :vartype value: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The case-insensitive name of the header to be used while uploading output files. Required.""" - value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The value of the header to be used while uploading output files.""" - - @overload - def __init__( - self, - *, - name: str, - value: Optional[str] = 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 ImageReference(_model_base.Model): - """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. - - :ivar publisher: The publisher of the Azure Virtual Machines Marketplace Image. For example, - Canonical or MicrosoftWindowsServer. - :vartype publisher: str - :ivar offer: The offer type of the Azure Virtual Machines Marketplace Image. For example, - UbuntuServer or WindowsServer. - :vartype offer: str - :ivar sku: The SKU of the Azure Virtual Machines Marketplace Image. For example, 18.04-LTS or - 2019-Datacenter. - :vartype sku: str - :ivar version: The version of the Azure Virtual Machines Marketplace Image. A value of 'latest' - can be specified to select the latest version of an Image. If omitted, the default is 'latest'. - :vartype version: str - :ivar virtual_machine_image_id: The ARM resource identifier of the Azure Compute Gallery Image. - Compute Nodes in the Pool will be created using this Image Id. This is of the form - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{VersionId} - or - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName} - for always defaulting to the latest image version. This property is mutually exclusive with - other ImageReference properties. The Azure Compute Gallery Image must have replicas in the same - region and must be in the same subscription as the Azure Batch account. If the image version is - not specified in the imageId, the latest version will be used. For information about the - firewall settings for the Batch Compute Node agent to communicate with the Batch service see - `https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration - `_. - :vartype virtual_machine_image_id: str - :ivar exact_version: The specific version of the platform image or marketplace image used to - create the node. This read-only field differs from 'version' only if the value specified for - 'version' when the pool was created was 'latest'. - :vartype exact_version: str - :ivar shared_gallery_image_id: The shared gallery image unique identifier. This property is - mutually exclusive with other properties and can be fetched from shared gallery image GET call. - :vartype shared_gallery_image_id: str - :ivar community_gallery_image_id: The community gallery image unique identifier. This property - is mutually exclusive with other properties and can be fetched from community gallery image GET - call. - :vartype community_gallery_image_id: str - """ - - publisher: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The publisher of the Azure Virtual Machines Marketplace Image. For example, Canonical or - MicrosoftWindowsServer.""" - offer: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The offer type of the Azure Virtual Machines Marketplace Image. For example, UbuntuServer or - WindowsServer.""" - sku: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The SKU of the Azure Virtual Machines Marketplace Image. For example, 18.04-LTS or - 2019-Datacenter.""" - version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The version of the Azure Virtual Machines Marketplace Image. A value of 'latest' can be - specified to select the latest version of an Image. If omitted, the default is 'latest'.""" - virtual_machine_image_id: Optional[str] = rest_field( - name="virtualMachineImageId", visibility=["read", "create", "update", "delete", "query"] - ) - """The ARM resource identifier of the Azure Compute Gallery Image. Compute Nodes in the Pool will - be created using this Image Id. This is of the form - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName}/versions/{VersionId} - or - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/galleries/{galleryName}/images/{imageDefinitionName} - for always defaulting to the latest image version. This property is mutually exclusive with - other ImageReference properties. The Azure Compute Gallery Image must have replicas in the same - region and must be in the same subscription as the Azure Batch account. If the image version is - not specified in the imageId, the latest version will be used. For information about the - firewall settings for the Batch Compute Node agent to communicate with the Batch service see - `https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration - `_.""" - exact_version: Optional[str] = rest_field(name="exactVersion", visibility=["read"]) - """The specific version of the platform image or marketplace image used to create the node. This - read-only field differs from 'version' only if the value specified for 'version' when the pool - was created was 'latest'.""" - shared_gallery_image_id: Optional[str] = rest_field( - name="sharedGalleryImageId", visibility=["read", "create", "update", "delete", "query"] - ) - """The shared gallery image unique identifier. This property is mutually exclusive with other - properties and can be fetched from shared gallery image GET call.""" - community_gallery_image_id: Optional[str] = rest_field( - name="communityGalleryImageId", visibility=["read", "create", "update", "delete", "query"] - ) - """The community gallery image unique identifier. This property is mutually exclusive with other - properties and can be fetched from community gallery image GET call.""" - - @overload - def __init__( - self, - *, - publisher: Optional[str] = None, - offer: Optional[str] = None, - sku: Optional[str] = None, - version: Optional[str] = None, - virtual_machine_image_id: Optional[str] = None, - shared_gallery_image_id: Optional[str] = None, - community_gallery_image_id: Optional[str] = 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 InboundEndpoint(_model_base.Model): +class InboundEndpoint(_Model): """An inbound endpoint on a Compute Node. :ivar name: The name of the endpoint. Required. @@ -9420,110 +9668,10 @@ class InboundEndpoint(_model_base.Model): """The public IP address of the Compute Node. Required.""" public_fqdn: str = rest_field(name="publicFQDN", visibility=["read", "create", "update", "delete", "query"]) """The public fully qualified domain name for the Compute Node. Required.""" - frontend_port: int = rest_field(name="frontendPort", visibility=["read", "create", "update", "delete", "query"]) - """The public port number of the endpoint. Required.""" - backend_port: int = rest_field(name="backendPort", visibility=["read", "create", "update", "delete", "query"]) - """The backend port number of the endpoint. Required.""" - - @overload - def __init__( - self, - *, - name: str, - protocol: Union[str, "_models.InboundEndpointProtocol"], - public_ip_address: str, - public_fqdn: str, - frontend_port: int, - backend_port: int, - ) -> 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 InboundNatPool(_model_base.Model): - """A inbound NAT Pool that can be used to address specific ports on Compute Nodes - in a Batch Pool externally. - - :ivar name: The name of the endpoint. The name must be unique within a Batch Pool, can contain - letters, numbers, underscores, periods, and hyphens. Names must start with a letter or number, - must end with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid - values are provided the request fails with HTTP status code 400. Required. - :vartype name: str - :ivar protocol: The protocol of the endpoint. Required. Known values are: "tcp" and "udp". - :vartype protocol: str or ~azure.batch.models.InboundEndpointProtocol - :ivar backend_port: The port number on the Compute Node. This must be unique within a Batch - Pool. Acceptable values are between 1 and 65535 except for 29876 and 29877 as these are - reserved. If any reserved values are provided the request fails with HTTP status code 400. - Required. - :vartype backend_port: int - :ivar frontend_port_range_start: The first port number in the range of external ports that will - be used to provide inbound access to the backendPort on individual Compute Nodes. Acceptable - values range between 1 and 65534 except ports from 50000 to 55000 which are reserved. All - ranges within a Pool must be distinct and cannot overlap. Each range must contain at least 40 - ports. If any reserved or overlapping values are provided the request fails with HTTP status - code 400. Required. - :vartype frontend_port_range_start: int - :ivar frontend_port_range_end: The last port number in the range of external ports that will be - used to provide inbound access to the backendPort on individual Compute Nodes. Acceptable - values range between 1 and 65534 except ports from 50000 to 55000 which are reserved by the - Batch service. All ranges within a Pool must be distinct and cannot overlap. Each range must - contain at least 40 ports. If any reserved or overlapping values are provided the request fails - with HTTP status code 400. Required. - :vartype frontend_port_range_end: int - :ivar network_security_group_rules: A list of network security group rules that will be applied - to the endpoint. The maximum number of rules that can be specified across all the endpoints on - a Batch Pool is 25. If no network security group rules are specified, a default rule will be - created to allow inbound access to the specified backendPort. If the maximum number of network - security group rules is exceeded the request fails with HTTP status code 400. - :vartype network_security_group_rules: list[~azure.batch.models.NetworkSecurityGroupRule] - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the endpoint. The name must be unique within a Batch Pool, can contain letters, - numbers, underscores, periods, and hyphens. Names must start with a letter or number, must end - with a letter, number, or underscore, and cannot exceed 77 characters. If any invalid values - are provided the request fails with HTTP status code 400. Required.""" - protocol: Union[str, "_models.InboundEndpointProtocol"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The protocol of the endpoint. Required. Known values are: \"tcp\" and \"udp\".""" - backend_port: int = rest_field(name="backendPort", visibility=["read", "create", "update", "delete", "query"]) - """The port number on the Compute Node. This must be unique within a Batch Pool. Acceptable values - are between 1 and 65535 except for 29876 and 29877 as these are reserved. If any reserved - values are provided the request fails with HTTP status code 400. Required.""" - frontend_port_range_start: int = rest_field( - name="frontendPortRangeStart", visibility=["read", "create", "update", "delete", "query"] - ) - """The first port number in the range of external ports that will be used to provide inbound - access to the backendPort on individual Compute Nodes. Acceptable values range between 1 and - 65534 except ports from 50000 to 55000 which are reserved. All ranges within a Pool must be - distinct and cannot overlap. Each range must contain at least 40 ports. If any reserved or - overlapping values are provided the request fails with HTTP status code 400. Required.""" - frontend_port_range_end: int = rest_field( - name="frontendPortRangeEnd", visibility=["read", "create", "update", "delete", "query"] - ) - """The last port number in the range of external ports that will be used to provide inbound access - to the backendPort on individual Compute Nodes. Acceptable values range between 1 and 65534 - except ports from 50000 to 55000 which are reserved by the Batch service. All ranges within a - Pool must be distinct and cannot overlap. Each range must contain at least 40 ports. If any - reserved or overlapping values are provided the request fails with HTTP status code 400. - Required.""" - network_security_group_rules: Optional[List["_models.NetworkSecurityGroupRule"]] = rest_field( - name="networkSecurityGroupRules", visibility=["read", "create", "update", "delete", "query"] - ) - """A list of network security group rules that will be applied to the endpoint. The maximum number - of rules that can be specified across all the endpoints on a Batch Pool is 25. If no network - security group rules are specified, a default rule will be created to allow inbound access to - the specified backendPort. If the maximum number of network security group rules is exceeded - the request fails with HTTP status code 400.""" + frontend_port: int = rest_field(name="frontendPort", visibility=["read", "create", "update", "delete", "query"]) + """The public port number of the endpoint. Required.""" + backend_port: int = rest_field(name="backendPort", visibility=["read", "create", "update", "delete", "query"]) + """The backend port number of the endpoint. Required.""" @overload def __init__( @@ -9531,10 +9679,10 @@ def __init__( *, name: str, protocol: Union[str, "_models.InboundEndpointProtocol"], + public_ip_address: str, + public_fqdn: str, + frontend_port: int, backend_port: int, - frontend_port_range_start: int, - frontend_port_range_end: int, - network_security_group_rules: Optional[List["_models.NetworkSecurityGroupRule"]] = None, ) -> None: ... @overload @@ -9548,7 +9696,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class InstanceViewStatus(_model_base.Model): +class InstanceViewStatus(_Model): """The instance view status. :ivar code: The status code. @@ -9602,7 +9750,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class LinuxUserConfiguration(_model_base.Model): +class LinuxUserConfiguration(_Model): """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 @@ -9657,14 +9805,14 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ManagedDisk(_model_base.Model): +class ManagedDisk(_Model): """The managed disk parameters. :ivar storage_account_type: The storage account type for managed disk. Known values are: "standard_lrs", "premium_lrs", and "standardssd_lrs". :vartype storage_account_type: str or ~azure.batch.models.StorageAccountType :ivar security_profile: Specifies the security profile settings for the managed disk. - :vartype security_profile: ~azure.batch.models.VMDiskSecurityProfile + :vartype security_profile: ~azure.batch.models.BatchVmDiskSecurityProfile """ storage_account_type: Optional[Union[str, "_models.StorageAccountType"]] = rest_field( @@ -9672,7 +9820,7 @@ class ManagedDisk(_model_base.Model): ) """The storage account type for managed disk. Known values are: \"standard_lrs\", \"premium_lrs\", and \"standardssd_lrs\".""" - security_profile: Optional["_models.VMDiskSecurityProfile"] = rest_field( + security_profile: Optional["_models.BatchVmDiskSecurityProfile"] = rest_field( name="securityProfile", visibility=["read", "create", "update", "delete", "query"] ) """Specifies the security profile settings for the managed disk.""" @@ -9682,41 +9830,7 @@ def __init__( self, *, storage_account_type: Optional[Union[str, "_models.StorageAccountType"]] = None, - security_profile: Optional["_models.VMDiskSecurityProfile"] = 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 MetadataItem(_model_base.Model): - """The Batch service does not assign any meaning to this metadata; it is solely - for the use of user code. - - :ivar name: The name of the metadata item. Required. - :vartype name: str - :ivar value: The value of the metadata item. Required. - :vartype value: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the metadata item. Required.""" - value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The value of the metadata item. Required.""" - - @overload - def __init__( - self, - *, - name: str, - value: str, + security_profile: Optional["_models.BatchVmDiskSecurityProfile"] = None, ) -> None: ... @overload @@ -9730,7 +9844,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MountConfiguration(_model_base.Model): +class MountConfiguration(_Model): """The file system to mount on each node. :ivar azure_blob_file_system_configuration: The Azure Storage Container to mount using blob @@ -9790,7 +9904,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MultiInstanceSettings(_model_base.Model): +class MultiInstanceSettings(_Model): """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 @@ -9827,7 +9941,7 @@ class MultiInstanceSettings(_model_base.Model): """The command line to run on all the Compute Nodes to enable them to coordinate when the primary runs the main Task command. A typical coordination command line launches a background service and verifies that the service is ready to process inter-node messages. Required.""" - common_resource_files: Optional[List["_models.ResourceFile"]] = rest_field( + common_resource_files: Optional[list["_models.ResourceFile"]] = rest_field( name="commonResourceFiles", visibility=["read", "create", "update", "delete", "query"] ) """A list of files that the Batch service will download before running the coordination command @@ -9846,7 +9960,7 @@ def __init__( *, coordination_command_line: str, number_of_instances: Optional[int] = None, - common_resource_files: Optional[List["_models.ResourceFile"]] = None, + common_resource_files: Optional[list["_models.ResourceFile"]] = None, ) -> None: ... @overload @@ -9860,7 +9974,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NameValuePair(_model_base.Model): +class NameValuePair(_Model): """Represents a name-value pair. :ivar name: The name in the name-value pair. @@ -9893,7 +10007,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NetworkConfiguration(_model_base.Model): +class NetworkConfiguration(_Model): """The network configuration for a Pool. :ivar subnet_id: The ARM resource identifier of the virtual network subnet which the Compute @@ -9915,15 +10029,15 @@ class NetworkConfiguration(_model_base.Model): `https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration `_. :vartype subnet_id: str - :ivar dynamic_v_net_assignment_scope: The scope of dynamic vnet assignment. Known values are: + :ivar dynamic_vnet_assignment_scope: The scope of dynamic vnet assignment. Known values are: "none" and "job". - :vartype dynamic_v_net_assignment_scope: str or ~azure.batch.models.DynamicVNetAssignmentScope + :vartype dynamic_vnet_assignment_scope: str or ~azure.batch.models.DynamicVNetAssignmentScope :ivar endpoint_configuration: The configuration for endpoints on Compute Nodes in the Batch Pool. :vartype endpoint_configuration: ~azure.batch.models.BatchPoolEndpointConfiguration :ivar public_ip_address_configuration: The Public IPAddress configuration for Compute Nodes in the Batch Pool. - :vartype public_ip_address_configuration: ~azure.batch.models.PublicIpAddressConfiguration + :vartype public_ip_address_configuration: ~azure.batch.models.BatchPublicIpAddressConfiguration :ivar enable_accelerated_networking: Whether this pool should enable accelerated networking. Accelerated networking enables single root I/O virtualization (SR-IOV) to a VM, which may lead to improved networking performance. For more details, see: @@ -9951,7 +10065,7 @@ class NetworkConfiguration(_model_base.Model): 29877. Also enable outbound connections to Azure Storage on port 443. For more details see: `https://learn.microsoft.com/azure/batch/nodes-and-pools#virtual-network-vnet-and-firewall-configuration `_.""" - dynamic_v_net_assignment_scope: Optional[Union[str, "_models.DynamicVNetAssignmentScope"]] = rest_field( + dynamic_vnet_assignment_scope: Optional[Union[str, "_models.DynamicVNetAssignmentScope"]] = rest_field( name="dynamicVNetAssignmentScope", visibility=["read", "create", "update", "delete", "query"] ) """The scope of dynamic vnet assignment. Known values are: \"none\" and \"job\".""" @@ -9959,7 +10073,7 @@ class NetworkConfiguration(_model_base.Model): name="endpointConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The configuration for endpoints on Compute Nodes in the Batch Pool.""" - public_ip_address_configuration: Optional["_models.PublicIpAddressConfiguration"] = rest_field( + public_ip_address_configuration: Optional["_models.BatchPublicIpAddressConfiguration"] = rest_field( name="publicIPAddressConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The Public IPAddress configuration for Compute Nodes in the Batch Pool.""" @@ -9977,9 +10091,9 @@ def __init__( self, *, subnet_id: Optional[str] = None, - dynamic_v_net_assignment_scope: Optional[Union[str, "_models.DynamicVNetAssignmentScope"]] = None, + dynamic_vnet_assignment_scope: Optional[Union[str, "_models.DynamicVNetAssignmentScope"]] = None, endpoint_configuration: Optional["_models.BatchPoolEndpointConfiguration"] = None, - public_ip_address_configuration: Optional["_models.PublicIpAddressConfiguration"] = None, + public_ip_address_configuration: Optional["_models.BatchPublicIpAddressConfiguration"] = None, enable_accelerated_networking: Optional[bool] = None, ) -> None: ... @@ -9994,7 +10108,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NetworkSecurityGroupRule(_model_base.Model): +class NetworkSecurityGroupRule(_Model): """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 @@ -10038,7 +10152,7 @@ class NetworkSecurityGroupRule(_model_base.Model): """The source address prefix or tag to match for the rule. Valid values are a single IP address (i.e. 10.10.10.10), IP subnet (i.e. 192.168.1.0/24), default tag, or * (for all addresses). If any other values are provided the request fails with HTTP status code 400. Required.""" - source_port_ranges: Optional[List[str]] = rest_field( + source_port_ranges: Optional[list[str]] = rest_field( name="sourcePortRanges", visibility=["read", "create", "update", "delete", "query"] ) """The source port ranges to match for the rule. Valid values are '*' (for all ports 0 - 65535), a @@ -10054,7 +10168,7 @@ def __init__( priority: int, access: Union[str, "_models.NetworkSecurityGroupRuleAccess"], source_address_prefix: str, - source_port_ranges: Optional[List[str]] = None, + source_port_ranges: Optional[list[str]] = None, ) -> None: ... @overload @@ -10068,7 +10182,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class NfsMountConfiguration(_model_base.Model): +class NfsMountConfiguration(_Model): """Information used to connect to an NFS file system. :ivar source: The URI of the file system to mount. Required. @@ -10116,72 +10230,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OSDisk(_model_base.Model): - """Settings for the operating system disk of the compute node (VM). - - :ivar ephemeral_os_disk_settings: Specifies the ephemeral Disk Settings for the operating - system disk used by the compute node (VM). - :vartype ephemeral_os_disk_settings: ~azure.batch.models.DiffDiskSettings - :ivar caching: Specifies the caching requirements. Possible values are: None, ReadOnly, - ReadWrite. The default values are: None for Standard storage. ReadOnly for Premium storage. - Known values are: "none", "readonly", and "readwrite". - :vartype caching: str or ~azure.batch.models.CachingType - :ivar disk_size_gb: The initial disk size in GB when creating new OS disk. - :vartype disk_size_gb: int - :ivar managed_disk: The managed disk parameters. - :vartype managed_disk: ~azure.batch.models.ManagedDisk - :ivar write_accelerator_enabled: Specifies whether writeAccelerator should be enabled or - disabled on the disk. - :vartype write_accelerator_enabled: bool - """ - - ephemeral_os_disk_settings: Optional["_models.DiffDiskSettings"] = rest_field( - name="ephemeralOSDiskSettings", visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies the ephemeral Disk Settings for the operating system disk used by the compute node - (VM).""" - caching: Optional[Union[str, "_models.CachingType"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies the caching requirements. Possible values are: None, ReadOnly, ReadWrite. The default - values are: None for Standard storage. ReadOnly for Premium storage. Known values are: - \"none\", \"readonly\", and \"readwrite\".""" - disk_size_gb: Optional[int] = rest_field( - name="diskSizeGB", visibility=["read", "create", "update", "delete", "query"] - ) - """The initial disk size in GB when creating new OS disk.""" - managed_disk: Optional["_models.ManagedDisk"] = rest_field( - name="managedDisk", visibility=["read", "create", "update", "delete", "query"] - ) - """The managed disk parameters.""" - write_accelerator_enabled: Optional[bool] = rest_field( - name="writeAcceleratorEnabled", visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies whether writeAccelerator should be enabled or disabled on the disk.""" - - @overload - def __init__( - self, - *, - ephemeral_os_disk_settings: Optional["_models.DiffDiskSettings"] = None, - caching: Optional[Union[str, "_models.CachingType"]] = None, - disk_size_gb: Optional[int] = None, - managed_disk: Optional["_models.ManagedDisk"] = None, - write_accelerator_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 OutputFile(_model_base.Model): +class OutputFile(_Model): """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. @@ -10189,14 +10238,14 @@ class OutputFile(_model_base.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. @@ -10212,14 +10261,14 @@ class OutputFile(_model_base.Model): """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 + \\*\\* 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 + \\*\\*\\\\*.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 + 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( @@ -10252,7 +10301,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileBlobContainerDestination(_model_base.Model): +class OutputFileBlobContainerDestination(_Model): """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 @@ -10275,7 +10324,7 @@ class OutputFileBlobContainerDestination(_model_base.Model): on allowed headers when uploading blobs: `https://learn.microsoft.com/rest/api/storageservices/put-blob#request-headers-all-blob-types `_. - :vartype upload_headers: list[~azure.batch.models.HttpHeader] + :vartype upload_headers: list[~azure.batch.models.OutputFileUploadHeader] """ path: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -10294,7 +10343,7 @@ class OutputFileBlobContainerDestination(_model_base.Model): ) """The reference to the user assigned identity to use to access Azure Blob Storage specified by containerUrl. The identity must have write access to the Azure Blob Storage container.""" - upload_headers: Optional[List["_models.HttpHeader"]] = rest_field( + upload_headers: Optional[list["_models.OutputFileUploadHeader"]] = rest_field( name="uploadHeaders", visibility=["read", "create", "update", "delete", "query"] ) """A list of name-value pairs for headers to be used in uploading output files. These headers will @@ -10310,7 +10359,7 @@ def __init__( container_url: str, path: Optional[str] = None, identity_reference: Optional["_models.BatchNodeIdentityReference"] = None, - upload_headers: Optional[List["_models.HttpHeader"]] = None, + upload_headers: Optional[list["_models.OutputFileUploadHeader"]] = None, ) -> None: ... @overload @@ -10324,7 +10373,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileDestination(_model_base.Model): +class OutputFileDestination(_Model): """The destination to which a file should be uploaded. :ivar container: A location in Azure blob storage to which files are uploaded. @@ -10354,7 +10403,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OutputFileUploadConfig(_model_base.Model): +class OutputFileUploadConfig(_Model): """Options for an output file upload operation, including under what conditions to perform the upload. @@ -10389,43 +10438,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class PublicIpAddressConfiguration(_model_base.Model): - """The public IP Address configuration of the networking configuration of a Pool. +class OutputFileUploadHeader(_Model): + """An HTTP header name-value pair. - :ivar ip_address_provisioning_type: The provisioning type for Public IP Addresses for the Pool. - The default value is BatchManaged. Known values are: "batchmanaged", "usermanaged", and - "nopublicipaddresses". - :vartype ip_address_provisioning_type: str or ~azure.batch.models.IpAddressProvisioningType - :ivar ip_address_ids: The list of public IPs which the Batch service will use when provisioning - Compute Nodes. The number of IPs specified here limits the maximum size of the Pool - 100 - dedicated nodes or 100 Spot/Low-priority nodes can be allocated for each public IP. For - example, a pool needing 250 dedicated VMs would need at least 3 public IPs specified. Each - element of this collection is of the form: - /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}. - :vartype ip_address_ids: list[str] + :ivar name: The case-insensitive name of the header to be used while uploading output files. + Required. + :vartype name: str + :ivar value: The value of the header to be used while uploading output files. + :vartype value: str """ - ip_address_provisioning_type: Optional[Union[str, "_models.IpAddressProvisioningType"]] = rest_field( - name="provision", visibility=["read", "create", "update", "delete", "query"] - ) - """The provisioning type for Public IP Addresses for the Pool. The default value is BatchManaged. - Known values are: \"batchmanaged\", \"usermanaged\", and \"nopublicipaddresses\".""" - ip_address_ids: Optional[List[str]] = rest_field( - name="ipAddressIds", visibility=["read", "create", "update", "delete", "query"] - ) - """The list of public IPs which the Batch service will use when provisioning Compute Nodes. The - number of IPs specified here limits the maximum size of the Pool - 100 dedicated nodes or 100 - Spot/Low-priority nodes can be allocated for each public IP. For example, a pool needing 250 - dedicated VMs would need at least 3 public IPs specified. Each element of this collection is of - the form: - /subscriptions/{subscription}/resourceGroups/{group}/providers/Microsoft.Network/publicIPAddresses/{ip}.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The case-insensitive name of the header to be used while uploading output files. Required.""" + value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The value of the header to be used while uploading output files.""" @overload def __init__( self, *, - ip_address_provisioning_type: Optional[Union[str, "_models.IpAddressProvisioningType"]] = None, - ip_address_ids: Optional[List[str]] = None, + name: str, + value: Optional[str] = None, ) -> None: ... @overload @@ -10439,7 +10472,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RecentBatchJob(_model_base.Model): +class RecentBatchJob(_Model): """Information about the most recent Job to run under the Job Schedule. :ivar id: The ID of the Job. @@ -10472,7 +10505,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResizeError(_model_base.Model): +class ResizeError(_Model): """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 @@ -10491,7 +10524,7 @@ class ResizeError(_model_base.Model): message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A message describing the Pool resize error, intended to be suitable for display in a user interface.""" - values_property: Optional[List["_models.NameValuePair"]] = rest_field( + values_property: Optional[list["_models.NameValuePair"]] = rest_field( name="values", visibility=["read", "create", "update", "delete", "query"] ) """A list of additional error details related to the Pool resize error.""" @@ -10502,7 +10535,7 @@ def __init__( *, code: Optional[str] = None, message: Optional[str] = None, - values_property: Optional[List["_models.NameValuePair"]] = None, + values_property: Optional[list["_models.NameValuePair"]] = None, ) -> None: ... @overload @@ -10516,7 +10549,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResourceFile(_model_base.Model): +class ResourceFile(_Model): """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 @@ -10636,7 +10669,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RollingUpgradePolicy(_model_base.Model): +class RollingUpgradePolicy(_Model): """The configuration parameters used while performing a rolling upgrade. :ivar enable_cross_zone_upgrade: Allow VMSS to ignore AZ boundaries when constructing upgrade @@ -10747,7 +10780,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class SecurityProfile(_model_base.Model): +class SecurityProfile(_Model): """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 @@ -10756,19 +10789,17 @@ class SecurityProfile(_model_base.Model): on encryption at host requirements, please refer to `https://learn.microsoft.com/azure/virtual-machines/disk-encryption#supported-vm-sizes `_. - Required. :vartype encryption_at_host: bool :ivar security_type: Specifies the SecurityType of the virtual machine. It has to be set to any - specified value to enable UefiSettings. Required. Known values are: "trustedLaunch" and - "confidentialVM". + specified value to enable UefiSettings. Known values are: "trustedLaunch" and "confidentialVM". :vartype security_type: str or ~azure.batch.models.SecurityTypes :ivar uefi_settings: Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Specifies the security settings like secure boot and vTPM used - while creating the virtual machine. Required. - :vartype uefi_settings: ~azure.batch.models.UefiSettings + while creating the virtual machine. + :vartype uefi_settings: ~azure.batch.models.BatchUefiSettings """ - encryption_at_host: bool = rest_field( + encryption_at_host: Optional[bool] = rest_field( name="encryptionAtHost", visibility=["read", "create", "update", "delete", "query"] ) """This property can be used by user in the request to enable or disable the Host Encryption for @@ -10776,27 +10807,26 @@ class SecurityProfile(_model_base.Model): disks including Resource/Temp disk at host itself. For more information on encryption at host requirements, please refer to `https://learn.microsoft.com/azure/virtual-machines/disk-encryption#supported-vm-sizes - `_. - Required.""" - security_type: Union[str, "_models.SecurityTypes"] = rest_field( + `_.""" + security_type: Optional[Union[str, "_models.SecurityTypes"]] = rest_field( name="securityType", visibility=["read", "create", "update", "delete", "query"] ) """Specifies the SecurityType of the virtual machine. It has to be set to any specified value to - enable UefiSettings. Required. Known values are: \"trustedLaunch\" and \"confidentialVM\".""" - uefi_settings: "_models.UefiSettings" = rest_field( + enable UefiSettings. Known values are: \"trustedLaunch\" and \"confidentialVM\".""" + uefi_settings: Optional["_models.BatchUefiSettings"] = rest_field( name="uefiSettings", visibility=["read", "create", "update", "delete", "query"] ) """Specifies the security settings like secure boot and vTPM used while creating the virtual machine. Specifies the security settings like secure boot and vTPM used while creating the - virtual machine. Required.""" + virtual machine.""" @overload def __init__( self, *, - encryption_at_host: bool, - security_type: Union[str, "_models.SecurityTypes"], - uefi_settings: "_models.UefiSettings", + encryption_at_host: Optional[bool] = None, + security_type: Optional[Union[str, "_models.SecurityTypes"]] = None, + uefi_settings: Optional["_models.BatchUefiSettings"] = None, ) -> None: ... @overload @@ -10810,7 +10840,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ServiceArtifactReference(_model_base.Model): +class ServiceArtifactReference(_Model): """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. @@ -10845,46 +10875,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UefiSettings(_model_base.Model): - """Specifies the security settings like secure boot and vTPM used while creating the virtual - machine. - - :ivar secure_boot_enabled: Specifies whether secure boot should be enabled on the virtual - machine. - :vartype secure_boot_enabled: bool - :ivar v_tpm_enabled: Specifies whether vTPM should be enabled on the virtual machine. - :vartype v_tpm_enabled: bool - """ - - secure_boot_enabled: Optional[bool] = rest_field( - name="secureBootEnabled", visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies whether secure boot should be enabled on the virtual machine.""" - v_tpm_enabled: Optional[bool] = rest_field( - name="vTpmEnabled", visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies whether vTPM should be enabled on the virtual machine.""" - - @overload - def __init__( - self, - *, - secure_boot_enabled: Optional[bool] = None, - v_tpm_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 UpgradePolicy(_model_base.Model): +class UpgradePolicy(_Model): """Describes an upgrade policy - automatic, manual, or rolling. :ivar mode: Specifies the mode of an upgrade to virtual machines in the scale set.

@@ -10939,7 +10930,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UploadBatchServiceLogsContent(_model_base.Model): +class UploadBatchServiceLogsOptions(_Model): """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 @@ -11013,7 +11004,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UploadBatchServiceLogsResult(_model_base.Model): +class UploadBatchServiceLogsResult(_Model): """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 @@ -11055,7 +11046,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UserAccount(_model_base.Model): +class UserAccount(_Model): """Properties used to create a user used to execute Tasks on an Azure Batch Compute Node. @@ -11121,43 +11112,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UserAssignedIdentity(_model_base.Model): - """The user assigned Identity. - - :ivar resource_id: The ARM resource id of the user assigned identity. Required. - :vartype resource_id: str - :ivar client_id: The client id of the user assigned identity. - :vartype client_id: str - :ivar principal_id: The principal id of the user assigned identity. - :vartype principal_id: str - """ - - resource_id: str = rest_field(name="resourceId", visibility=["read", "create", "update", "delete", "query"]) - """The ARM resource id of the user assigned identity. Required.""" - client_id: Optional[str] = rest_field(name="clientId", visibility=["read"]) - """The client id of the user assigned identity.""" - principal_id: Optional[str] = rest_field(name="principalId", visibility=["read"]) - """The principal id of the user assigned identity.""" - - @overload - def __init__( - self, - *, - resource_id: str, - ) -> 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 UserIdentity(_model_base.Model): +class UserIdentity(_Model): """The definition of the user identity under which the Task is run. Specify either the userName or autoUser property, but not both. @@ -11197,13 +11152,13 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VirtualMachineConfiguration(_model_base.Model): +class VirtualMachineConfiguration(_Model): """The configuration for Compute Nodes in a Pool based on the Azure Virtual Machines infrastructure. :ivar image_reference: A reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image to use. Required. - :vartype image_reference: ~azure.batch.models.ImageReference + :vartype image_reference: ~azure.batch.models.BatchVmImageReference :ivar node_agent_sku_id: The SKU of the Batch Compute Node agent to be provisioned on Compute Nodes in the Pool. The Batch Compute Node agent is a program that runs on each Compute Node in the Pool, and provides the command-and-control interface between the Compute Node and the Batch @@ -11233,16 +11188,15 @@ class VirtualMachineConfiguration(_model_base.Model): 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. - Windows_Client - The on-premises license is for Windows Client. + + 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 Tasks and Job manager Tasks run on this Pool must specify the containerSettings property, and all other Tasks may specify it. - :vartype container_configuration: ~azure.batch.models.ContainerConfiguration + :vartype container_configuration: ~azure.batch.models.BatchContainerConfiguration :ivar disk_encryption_configuration: The disk encryption configuration for the pool. If specified, encryption is performed on each node in the pool during node provisioning. :vartype disk_encryption_configuration: ~azure.batch.models.DiskEncryptionConfiguration @@ -11253,7 +11207,7 @@ class VirtualMachineConfiguration(_model_base.Model): mentioned in this configuration will be installed on each node. :vartype extensions: list[~azure.batch.models.VMExtension] :ivar os_disk: Settings for the operating system disk of the Virtual Machine. - :vartype os_disk: ~azure.batch.models.OSDisk + :vartype os_disk: ~azure.batch.models.BatchOsDisk :ivar security_profile: Specifies the security profile settings for the virtual machine or virtual machine scale set. :vartype security_profile: ~azure.batch.models.SecurityProfile @@ -11264,7 +11218,7 @@ class VirtualMachineConfiguration(_model_base.Model): :vartype service_artifact_reference: ~azure.batch.models.ServiceArtifactReference """ - image_reference: "_models.ImageReference" = rest_field( + image_reference: "_models.BatchVmImageReference" = rest_field( name="imageReference", visibility=["read", "create", "update", "delete", "query"] ) """A reference to the Azure Virtual Machines Marketplace Image or the custom Virtual Machine Image @@ -11284,7 +11238,7 @@ class VirtualMachineConfiguration(_model_base.Model): ) """Windows operating system settings on the virtual machine. This property must not be specified if the imageReference property specifies a Linux OS Image.""" - data_disks: Optional[List["_models.DataDisk"]] = rest_field( + data_disks: Optional[list["_models.DataDisk"]] = rest_field( name="dataDisks", visibility=["read", "create", "update", "delete", "query"] ) """The configuration for data disks attached to the Compute Nodes in the Pool. This property must @@ -11306,10 +11260,9 @@ class VirtualMachineConfiguration(_model_base.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.ContainerConfiguration"] = rest_field( + 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( name="containerConfiguration", visibility=["read", "create", "update", "delete", "query"] ) """The container configuration for the Pool. If specified, setup is performed on each Compute Node @@ -11325,12 +11278,12 @@ class VirtualMachineConfiguration(_model_base.Model): ) """The node placement configuration for the pool. This configuration will specify rules on how nodes in the pool will be physically allocated.""" - extensions: Optional[List["_models.VMExtension"]] = rest_field( + extensions: Optional[list["_models.VMExtension"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """The virtual machine extension for the pool. If specified, the extensions mentioned in this configuration will be installed on each node.""" - os_disk: Optional["_models.OSDisk"] = rest_field( + os_disk: Optional["_models.BatchOsDisk"] = rest_field( name="osDisk", visibility=["read", "create", "update", "delete", "query"] ) """Settings for the operating system disk of the Virtual Machine.""" @@ -11350,16 +11303,16 @@ class VirtualMachineConfiguration(_model_base.Model): def __init__( self, *, - image_reference: "_models.ImageReference", + image_reference: "_models.BatchVmImageReference", node_agent_sku_id: str, windows_configuration: Optional["_models.WindowsConfiguration"] = None, - data_disks: Optional[List["_models.DataDisk"]] = None, + data_disks: Optional[list["_models.DataDisk"]] = None, license_type: Optional[str] = None, - container_configuration: Optional["_models.ContainerConfiguration"] = None, + container_configuration: Optional["_models.BatchContainerConfiguration"] = None, disk_encryption_configuration: Optional["_models.DiskEncryptionConfiguration"] = None, node_placement_configuration: Optional["_models.BatchNodePlacementConfiguration"] = None, - extensions: Optional[List["_models.VMExtension"]] = None, - os_disk: Optional["_models.OSDisk"] = None, + extensions: Optional[list["_models.VMExtension"]] = None, + os_disk: Optional["_models.BatchOsDisk"] = None, security_profile: Optional["_models.SecurityProfile"] = None, service_artifact_reference: Optional["_models.ServiceArtifactReference"] = None, ) -> None: ... @@ -11375,18 +11328,18 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VirtualMachineInfo(_model_base.Model): +class VirtualMachineInfo(_Model): """Info about the current state of the virtual machine. :ivar image_reference: The reference to the Azure Virtual Machine's Marketplace Image. - :vartype image_reference: ~azure.batch.models.ImageReference + :vartype image_reference: ~azure.batch.models.BatchVmImageReference :ivar scale_set_vm_resource_id: The resource ID of the Compute Node's current Virtual Machine Scale Set VM. Only defined if the Batch Account was created with its poolAllocationMode property set to 'UserSubscription'. :vartype scale_set_vm_resource_id: str """ - image_reference: Optional["_models.ImageReference"] = rest_field( + image_reference: Optional["_models.BatchVmImageReference"] = rest_field( name="imageReference", visibility=["read", "create", "update", "delete", "query"] ) """The reference to the Azure Virtual Machine's Marketplace Image.""" @@ -11400,7 +11353,7 @@ class VirtualMachineInfo(_model_base.Model): def __init__( self, *, - image_reference: Optional["_models.ImageReference"] = None, + image_reference: Optional["_models.BatchVmImageReference"] = None, scale_set_vm_resource_id: Optional[str] = None, ) -> None: ... @@ -11415,45 +11368,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VMDiskSecurityProfile(_model_base.Model): - """Specifies the security profile settings for the managed disk. **Note**: It can only be set for - Confidential VMs and required when using Confidential VMs. - - :ivar security_encryption_type: Specifies the EncryptionType of the managed disk. It is set to - VMGuestStateOnly for encryption of just the VMGuestState blob, and NonPersistedTPM for not - persisting firmware state in the VMGuestState blob. **Note**: It can be set for only - Confidential VMs and is required when using Confidential VMs. Known values are: - "NonPersistedTPM" and "VMGuestStateOnly". - :vartype security_encryption_type: str or ~azure.batch.models.SecurityEncryptionTypes - """ - - security_encryption_type: Optional[Union[str, "_models.SecurityEncryptionTypes"]] = rest_field( - name="securityEncryptionType", visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies the EncryptionType of the managed disk. It is set to VMGuestStateOnly for encryption - of just the VMGuestState blob, and NonPersistedTPM for not persisting firmware state in the - VMGuestState blob. **Note**: It can be set for only Confidential VMs and is required when using - Confidential VMs. Known values are: \"NonPersistedTPM\" and \"VMGuestStateOnly\".""" - - @overload - def __init__( - self, - *, - security_encryption_type: Optional[Union[str, "_models.SecurityEncryptionTypes"]] = 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_base.Model): +class VMExtension(_Model): """The configuration for virtual machine extensions. :ivar name: The name of the virtual machine extension. Required. @@ -11502,14 +11417,14 @@ class VMExtension(_model_base.Model): ) """Indicates whether the extension should be automatically upgraded by the platform if there is a newer version of the extension available.""" - settings: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + settings: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """JSON formatted public settings for the extension.""" - protected_settings: Optional[Dict[str, str]] = rest_field( + protected_settings: Optional[dict[str, str]] = rest_field( name="protectedSettings", visibility=["read", "create", "update", "delete", "query"] ) """The extension can contain either protectedSettings or protectedSettingsFromKeyVault or no protected settings at all.""" - provision_after_extensions: Optional[List[str]] = rest_field( + provision_after_extensions: Optional[list[str]] = rest_field( name="provisionAfterExtensions", visibility=["read", "create", "update", "delete", "query"] ) """The collection of extension names. Collection of extension names after which this extension @@ -11525,9 +11440,9 @@ def __init__( type_handler_version: Optional[str] = None, auto_upgrade_minor_version: Optional[bool] = None, enable_automatic_upgrade: Optional[bool] = None, - settings: Optional[Dict[str, str]] = None, - protected_settings: Optional[Dict[str, str]] = None, - provision_after_extensions: Optional[List[str]] = None, + settings: Optional[dict[str, str]] = None, + protected_settings: Optional[dict[str, str]] = None, + provision_after_extensions: Optional[list[str]] = None, ) -> None: ... @overload @@ -11541,7 +11456,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class VMExtensionInstanceView(_model_base.Model): +class VMExtensionInstanceView(_Model): """The vm extension instance view. :ivar name: The name of the vm extension instance view. @@ -11554,11 +11469,11 @@ class VMExtensionInstanceView(_model_base.Model): name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The name of the vm extension instance view.""" - statuses: Optional[List["_models.InstanceViewStatus"]] = rest_field( + statuses: Optional[list["_models.InstanceViewStatus"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """The resource status information.""" - sub_statuses: Optional[List["_models.InstanceViewStatus"]] = rest_field( + sub_statuses: Optional[list["_models.InstanceViewStatus"]] = rest_field( name="subStatuses", visibility=["read", "create", "update", "delete", "query"] ) """The resource status information.""" @@ -11568,8 +11483,8 @@ def __init__( self, *, name: Optional[str] = None, - statuses: Optional[List["_models.InstanceViewStatus"]] = None, - sub_statuses: Optional[List["_models.InstanceViewStatus"]] = None, + statuses: Optional[list["_models.InstanceViewStatus"]] = None, + sub_statuses: Optional[list["_models.InstanceViewStatus"]] = None, ) -> None: ... @overload @@ -11583,7 +11498,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class WindowsConfiguration(_model_base.Model): +class WindowsConfiguration(_Model): """Windows operating system settings to apply to the virtual machine. :ivar enable_automatic_updates: Whether automatic updates are enabled on the virtual machine. @@ -11615,7 +11530,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class WindowsUserConfiguration(_model_base.Model): +class WindowsUserConfiguration(_Model): """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: diff --git a/sdk/batch/azure-batch/azure/batch/models/_patch.py b/sdk/batch/azure-batch/azure/batch/models/_patch.py index 6435ce16c022..cae277a3313c 100644 --- a/sdk/batch/azure-batch/azure/batch/models/_patch.py +++ b/sdk/batch/azure-batch/azure/batch/models/_patch.py @@ -7,18 +7,17 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ import datetime -from typing import List, Any, Optional +from typing import List, Optional from azure.core.exceptions import HttpResponseError -from ._models import BatchPoolReplaceContent as BatchPoolReplaceContentGenerated -from .._model_base import rest_field __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. @@ -28,7 +27,13 @@ class CreateTasksError(HttpResponseError): :param [~Exception] errors: List of unknown errors forcing early termination """ - def __init__(self, pending_tasks=[], failure_tasks=[], errors=[]): + 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 @@ -62,8 +67,8 @@ def __init__(self, pending_tasks=[], failure_tasks=[], errors=[]): ) super(CreateTasksError, self).__init__(self.message) -class BatchFileProperties: +class BatchFileProperties: """Information about a file or directory on a Compute Node with additional properties. :ivar url: The URL of the file. @@ -71,7 +76,7 @@ class BatchFileProperties: :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. + 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 @@ -84,7 +89,7 @@ class BatchFileProperties: :vartype file_mode: str """ - url: Optional[str] + url: Optional[str] """The URL of the file.""" is_directory: Optional[bool] """Whether the object represents a directory.""" @@ -119,6 +124,7 @@ def __init__( self.content_type = content_type self.file_mode = file_mode + def patch_sdk(): """Do not remove from this file. diff --git a/sdk/batch/azure-batch/dev_requirements.txt b/sdk/batch/azure-batch/dev_requirements.txt index a14271b5a0a3..06a838c51c92 100644 --- a/sdk/batch/azure-batch/dev_requirements.txt +++ b/sdk/batch/azure-batch/dev_requirements.txt @@ -1,6 +1,6 @@ -e ../../../eng/tools/azure-sdk-tools -e ../azure-mgmt-batch --e ../../core/azure-core +../../core/azure-core # -e ../../identity/azure-identity azure-identity==1.17.0 azure-mgmt-resource<=21.1.0 diff --git a/sdk/batch/azure-batch/migration_guide.md b/sdk/batch/azure-batch/migration_guide.md new file mode 100644 index 000000000000..7f0ddfd550d2 --- /dev/null +++ b/sdk/batch/azure-batch/migration_guide.md @@ -0,0 +1,35 @@ +# (WIP) Azure Batch Data Plane Migration Guide from <= v14.x to v15.x + +This guide assists you in the migration from [azure-batch](https://pypi.org/project/azure-batch/) v14.x to [azure-batch](https://pypi.org/project/azure-batch/15.0.0b1/) v15.x. Side-by-side comparisons are provided for similar operations between the two packages. + +Familiarity with the `azure-batch` v14.x package is assumed. If you're new to the Azure Batch client library for Python, see the [README for `azure-batch`](https://learn.microsoft.com/python/api/overview/azure/batch?view=azure-python) and samples instead of this guide. + +## Table of Contents + +- [Overview](#overview) + - [Migration Benefits](#migration-benefits) + - [Package Differences](#package-differences) +- [Additional Samples](#additional-samples) + +## Overview + +### Migration Benefits + +> Note: `azure-batch` `<= v14.x` have been deprecated. Please upgrade to `azure-batch` `v15.x` for continued support. + +A natural question to ask when considering whether to adopt a new version or library is what the benefits of doing so would be. As Azure has matured and been embraced by a more diverse group of developers, we've focused on learning the patterns and practices to best support developer productivity and to understand the gaps that the Python client libraries have. + +Several areas of consistent feedback were expressed across the Azure client library ecosystem. One of the most important is that the client libraries for different Azure services haven't had a consistent approach to organization, naming, and API structure. Additionally, many developers have felt that the learning curve was too steep. The APIs didn't offer an approachable and consistent onboarding story for those learning Azure or exploring a specific Azure service. + +To improve the development experience across Azure services, a set of uniform [design guidelines](https://azure.github.io/azure-sdk/general_introduction.html) was created for all languages to drive a consistent experience with established API patterns for all services. A set of [Python-specific guidelines](https://azure.github.io/azure-sdk/python/guidelines/index.html) was also introduced to ensure that Python clients have a natural and idiomatic feel with respect to the Python ecosystem. Further details are available in the guidelines. + +The new Batch version `v15.x` provides the ability to share in some of the cross-service improvements made to the Azure development experience, such as using the new Azure.Identity library to share a single authentication between clients and a unified diagnostics pipeline offering a common view of the activities across each of the client libraries. + +We strongly encourage moving to `azure-batch` `v15.x`. It is important to be aware that any version `<= v14.x` is officially deprecated. Though they will continue to be supported with critical security and bug fixes, they are no longer under active development and will not receive new features or minor fixes. There is no guarantee of feature parity between versions below `v14.x` and `v15.x`. + +### Package Differences + + +## Additional Samples + +For more samples, see \ No newline at end of file diff --git a/sdk/batch/azure-batch/pyproject.toml b/sdk/batch/azure-batch/pyproject.toml index 69e5a2854bc3..215a6a124a0a 100644 --- a/sdk/batch/azure-batch/pyproject.toml +++ b/sdk/batch/azure-batch/pyproject.toml @@ -1,7 +1,67 @@ +# -------------------------------------------------------------------------- +# 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"] +build-backend = "setuptools.build_meta" + +[project] +name = "azure-batch" +authors = [ + { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, +] +description = "Microsoft Corporation Azure Batch Client Library for Python" +license = "MIT" +classifiers = [ + "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", +] +requires-python = ">=3.9" +keywords = ["azure", "azure sdk"] + +dependencies = [ + "isodate>=0.6.1", + "azure-core>=1.35.0", + "typing-extensions>=4.6.0", +] +dynamic = [ +"version", "readme" +] + +[project.urls] +homepage = "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.packages.find] +exclude = [ + "tests*", + "samples*", + "doc*", + "azure", +] + +[tool.setuptools.package-data] +pytyped = ["py.typed"] + [tool.azure-sdk-build] -pylint = false -pyright = false +pylint = true +pyright = true mypy = true -verifytypes = false -sphinx = false -whl_no_aio= false +verifytypes = true +ci_enabled = true +sphinx = true +whl_no_aio = false 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 d56f69c799c6..386d6a0e8012 100644 --- a/sdk/batch/azure-batch/samples/batch_samples_hello_world.py +++ b/sdk/batch/azure-batch/samples/batch_samples_hello_world.py @@ -30,7 +30,7 @@ def create_pool(self, client: BatchClient, pool_id: str): # set up virtual machine configuration vm_configuration = models.VirtualMachineConfiguration( - image_reference=models.ImageReference( + image_reference=models.BatchVmImageReference( publisher="MicrosoftWindowsServer", offer="WindowsServer", sku="2016-Datacenter-smalldisk", @@ -39,7 +39,7 @@ def create_pool(self, client: BatchClient, pool_id: str): ) # set up parameters for a batch pool - pool_content = models.BatchPoolCreateContent( + pool_content = models.BatchPoolCreateOptions( id=pool_id, vm_size="standard_d2_v2", target_dedicated_nodes=1, @@ -55,7 +55,7 @@ def create_pool(self, client: BatchClient, pool_id: str): def create_job_and_submit_task(self, client: BatchClient, pool_id: str, job_id: str): # set up parameters for a batch job - job_content = models.BatchJobCreateContent( + job_content = models.BatchJobCreateOptions( id=job_id, pool_info=models.BatchPoolInfo(pool_id=pool_id), ) @@ -67,7 +67,7 @@ def create_job_and_submit_task(self, client: BatchClient, pool_id: str, job_id: print(e) # set up parameters for a batch task - task_content = models.BatchTaskCreateContent( + task_content = models.BatchTaskCreateOptions( id="my_task", command_line='cmd /c "echo hello world"', ) @@ -80,9 +80,9 @@ def create_job_and_submit_task(self, client: BatchClient, pool_id: str, job_id: def cleanup(self, client: BatchClient, pool_id: str, job_id: str): # deleting the job - client.delete_job(job_id=job_id) + client.begin_delete_job(job_id=job_id) # deleting the pool - client.delete_pool(pool_id=pool_id) + client.begin_delete_pool(pool_id=pool_id) if __name__ == "__main__": diff --git a/sdk/batch/azure-batch/setup.py b/sdk/batch/azure-batch/setup.py deleted file mode 100644 index c8218eb0bece..000000000000 --- a/sdk/batch/azure-batch/setup.py +++ /dev/null @@ -1,70 +0,0 @@ -# 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. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 - -import os -import re -from setuptools import setup, find_packages - - -PACKAGE_NAME = "azure-batch" -PACKAGE_PPRINT_NAME = "Azure Batch" - -# a-b-c => a/b/c -package_folder_path = PACKAGE_NAME.replace("-", "/") - -# Version extraction inspired from 'requests' -with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: - version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) - -if not version: - raise RuntimeError("Cannot find version information") - - -setup( - name=PACKAGE_NAME, - version=version, - description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), - long_description=open("README.md", "r").read(), - long_description_content_type="text/markdown", - license="MIT License", - author="Microsoft Corporation", - author_email="azpysdkhelp@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", - keywords="azure, azure sdk", - classifiers=[ - "Development Status :: 4 - Beta", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "License :: OSI Approved :: MIT License", - ], - zip_safe=False, - packages=find_packages( - exclude=[ - "tests", - # Exclude packages that will be covered by PEP420 or nspkg - "azure", - ] - ), - include_package_data=True, - package_data={ - "azure.batch": ["py.typed"], - }, - install_requires=[ - "isodate>=0.6.1", - "azure-core>=1.30.0", - "typing-extensions>=4.6.0", - ], - python_requires=">=3.8", -) diff --git a/sdk/batch/azure-batch/tests/batch_preparers.py b/sdk/batch/azure-batch/tests/batch_preparers.py index 38e90eb7a217..89937550b65f 100644 --- a/sdk/batch/azure-batch/tests/batch_preparers.py +++ b/sdk/batch/azure-batch/tests/batch_preparers.py @@ -197,9 +197,9 @@ def create_resource(self, name, **kwargs): deployment = models.DeploymentConfiguration( virtual_machine_configuration=models.VirtualMachineConfiguration( image_reference=models.ImageReference( - publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS" + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" ), - node_agent_sku_id="batch.node.ubuntu 18.04", + node_agent_sku_id="batch.node.ubuntu 22.04", ) ) inboundpool_config = models.InboundNatPool( @@ -229,7 +229,6 @@ def create_resource(self, name, **kwargs): ): time.sleep(10) self.resource = self.client.pool.get(group.name, batch_account.name, name) - # add_general_regex_sanitizer(regex=name, value=self.moniker) else: self.resource = FakeResource(name=name, id=name) return { @@ -292,14 +291,14 @@ def _get_batch_pool_id(self, **kwargs): return azure.batch.models.BatchPoolInfo(pool_id=pool_id) except KeyError: auto_pool = azure.batch.models.BatchAutoPoolSpecification( - pool_lifetime_option=azure.batch.models.BatchPoolLifetimeOption.job, + pool_lifetime_option=azure.batch.models.BatchPoolLifetimeOption.JOB, pool=azure.batch.models.BatchPoolSpecification( vm_size="standard_d2_v2", virtual_machine_configuration=azure.batch.models.VirtualMachineConfiguration( - image_reference=azure.batch.models.ImageReference( - publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS" + image_reference=azure.batch.models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" ), - node_agent_sku_id="batch.node.ubuntu 18.04", + node_agent_sku_id="batch.node.ubuntu 22.04", ), ), ) @@ -309,7 +308,7 @@ def create_resource(self, name, **kwargs): if self.is_live: self.client = self._get_batch_client(**kwargs) pool = self._get_batch_pool_id(**kwargs) - self.resource = azure.batch.models.BatchJobCreateContent(id=name, pool_info=pool, **self.extra_args) + self.resource = azure.batch.models.BatchJobCreateOptions(id=name, pool_info=pool, **self.extra_args) try: self.client.create_job(self.resource) except azure.core.exceptions.HttpResponseError as e: @@ -326,4 +325,4 @@ def create_resource(self, name, **kwargs): def remove_resource(self, name, **kwargs): if self.is_live: - self.client.delete_job(name) + self.client.begin_delete_job(name).result() diff --git a/sdk/batch/azure-batch/tests/test_batch.py b/sdk/batch/azure-batch/tests/test_batch.py index 51e33cb2465b..386c8abac65e 100644 --- a/sdk/batch/azure-batch/tests/test_batch.py +++ b/sdk/batch/azure-batch/tests/test_batch.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=too-many-lines,line-too-long,useless-suppression # coding: utf-8 # ------------------------------------------------------------------------- @@ -79,53 +79,11 @@ async def assertCreateTasksError(self, code, func, *args, **kwargs): try: batch_error = err.errors.pop() if code: - # self.assertEqual(batch_error.error.code, code) assert batch_error.error.code == code except IndexError: pytest.fail("Inner BatchErrorException expected but not exist") except Exception as err: pytest.fail("Expected CreateTasksError, instead got: {!r}".format(err)) - - @CachedResourceGroupPreparer(location=AZURE_LOCATION) - @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) - @pytest.mark.parametrize("BatchClient", [SyncBatchClient, AsyncBatchClient], ids=["sync", "async"]) - @client_setup - @recorded_by_proxy_async - async def test_batch_certificates(self, client: BatchClient, **kwargs): - # Test Add Certificate - certificate = models.BatchCertificate( - thumbprint="cff2ab63c8c955aaf71989efa641b906558d9fb7", - thumbprint_algorithm="sha1", - data="MIIGMQIBAzCCBe0GCSqGSIb3DQEHAaCCBd4EggXaMIIF1jCCA8AGCSqGSIb3DQEHAaCCA7EEggOtMIIDqTCCA6UGCyqGSIb3DQEMCgECoIICtjCCArIwHAYKKoZIhvcNAQwBAzAOBAhyd3xCtln3iQICB9AEggKQhe5P10V9iV1BsDlwWT561Yu2hVq3JT8ae/ebx1ZR/gMApVereDKkS9Zg4vFyssusHebbK5pDpU8vfAqle0TM4m7wGsRj453ZorSPUfMpHvQnAOn+2pEpWdMThU7xvZ6DVpwhDOQk9166z+KnKdHGuJKh4haMT7Rw/6xZ1rsBt2423cwTrQVMQyACrEkianpuujubKltN99qRoFAxhQcnYE2KlYKw7lRcExq6mDSYAyk5xJZ1ZFdLj6MAryZroQit/0g5eyhoNEKwWbi8px5j71pRTf7yjN+deMGQKwbGl+3OgaL1UZ5fCjypbVL60kpIBxLZwIJ7p3jJ+q9pbq9zSdzshPYor5lxyUfXqaso/0/91ayNoBzg4hQGh618PhFI6RMGjwkzhB9xk74iweJ9HQyIHf8yx2RCSI22JuCMitPMWSGvOszhbNx3AEDLuiiAOHg391mprEtKZguOIr9LrJwem/YmcHbwyz5YAbZmiseKPkllfC7dafFfCFEkj6R2oegIsZo0pEKYisAXBqT0g+6/jGwuhlZcBo0f7UIZm88iA3MrJCjlXEgV5OcQdoWj+hq0lKEdnhtCKr03AIfukN6+4vjjarZeW1bs0swq0l3XFf5RHa11otshMS4mpewshB9iO9MuKWpRxuxeng4PlKZ/zuBqmPeUrjJ9454oK35Pq+dghfemt7AUpBH/KycDNIZgfdEWUZrRKBGnc519C+RTqxyt5hWL18nJk4LvSd3QKlJ1iyJxClhhb/NWEzPqNdyA5cxen+2T9bd/EqJ2KzRv5/BPVwTQkHH9W/TZElFyvFfOFIW2+03RKbVGw72Mr/0xKZ+awAnEfoU+SL/2Gj2m6PHkqFX2sOCi/tN9EA4xgdswEwYJKoZIhvcNAQkVMQYEBAEAAAAwXQYJKwYBBAGCNxEBMVAeTgBNAGkAYwByAG8AcwBvAGYAdAAgAFMAdAByAG8AbgBnACAAQwByAHkAcAB0AG8AZwByAGEAcABoAGkAYwAgAFAAcgBvAHYAaQBkAGUAcjBlBgkqhkiG9w0BCRQxWB5WAFAAdgBrAFQAbQBwADoANABjAGUANgAwADQAZABhAC0AMAA2ADgAMQAtADQANAAxADUALQBhADIAYwBhAC0ANQA3ADcAMwAwADgAZQA2AGQAOQBhAGMwggIOBgkqhkiG9w0BBwGgggH/BIIB+zCCAfcwggHzBgsqhkiG9w0BDAoBA6CCAcswggHHBgoqhkiG9w0BCRYBoIIBtwSCAbMwggGvMIIBXaADAgECAhAdka3aTQsIsUphgIXGUmeRMAkGBSsOAwIdBQAwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3kwHhcNMTYwMTAxMDcwMDAwWhcNMTgwMTAxMDcwMDAwWjASMRAwDgYDVQQDEwdub2Rlc2RrMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC5fhcxbJHxxBEIDzVOMc56s04U6k4GPY7yMR1m+rBGVRiAyV4RjY6U936dqXHCVD36ps2Q0Z+OeEgyCInkIyVeB1EwXcToOcyeS2YcUb0vRWZDouC3tuFdHwiK1Ed5iW/LksmXDotyV7kpqzaPhOFiMtBuMEwNJcPge9k17hRgRQIDAQABo0swSTBHBgNVHQEEQDA+gBAS5AktBh0dTwCNYSHcFmRjoRgwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3mCEAY3bACqAGSKEc+41KpcNfQwCQYFKw4DAh0FAANBAHl2M97QbpzdnwO5HoRBsiEExOcLTNg+GKCr7HUsbzfvrUivw+JLL7qjHAIc5phnK+F5bQ8HKe0L9YXBSKl+fvwxFTATBgkqhkiG9w0BCRUxBgQEAQAAADA7MB8wBwYFKw4DAhoEFGVtyGMqiBd32fGpzlGZQoRM6UQwBBTI0YHFFqTS4Go8CoLgswn29EiuUQICB9A=", - certificate_format=models.BatchCertificateFormat.PFX, - password="nodesdk", - ) - - response = await wrap_result(client.create_certificate(certificate)) - assert response is None - - # Test List Certificates - certs = await wrap_list_result(client.list_certificates()) - test_cert = [c for c in certs if c.thumbprint == "cff2ab63c8c955aaf71989efa641b906558d9fb7"] - assert len(test_cert) == 1 - - # Test Get Certificate - cert = await wrap_result(client.get_certificate("sha1", "cff2ab63c8c955aaf71989efa641b906558d9fb7")) - assert cert.thumbprint == "cff2ab63c8c955aaf71989efa641b906558d9fb7" - assert cert.thumbprint_algorithm == "sha1" - assert cert.delete_certificate_error is None - - # Test Cancel Certificate Delete - await self.assertBatchError( - "CertificateStateActive", - client.cancel_certificate_deletion, - "sha1", - "cff2ab63c8c955aaf71989efa641b906558d9fb7", - ) - - # Test Delete Certificate - response = await wrap_result(client.delete_certificate("sha1", "cff2ab63c8c955aaf71989efa641b906558d9fb7")) - assert response is None @CachedResourceGroupPreparer(location=AZURE_LOCATION) @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) @@ -142,11 +100,11 @@ async def test_batch_create_pools(self, client: BatchClient, **kwargs): elevation_level=models.ElevationLevel.ADMIN, ), ] - test_iaas_pool = models.BatchPoolCreateContent( + test_iaas_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_iaas_"), vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference( + image_reference=models.BatchVmImageReference( publisher="MicrosoftWindowsServer", offer="WindowsServer", sku="2016-Datacenter-smalldisk", @@ -181,13 +139,15 @@ async def test_batch_create_pools(self, client: BatchClient, **kwargs): "/virtualNetworks/vnet1" "/subnets/subnet1" ) - test_network_pool = models.BatchPoolCreateContent( + test_network_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_network_"), vm_size=DEFAULT_VM_SIZE, network_configuration=network_config, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference(publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS"), - node_agent_sku_id="batch.node.ubuntu 18.04", + image_reference=models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" + ), + node_agent_sku_id="batch.node.ubuntu 22.04", ), ) await self.assertBatchError( @@ -197,11 +157,11 @@ async def test_batch_create_pools(self, client: BatchClient, **kwargs): timeout=45, ) - test_image_pool = models.BatchPoolCreateContent( + test_image_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_image_"), vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference( + image_reference=models.BatchVmImageReference( virtual_machine_image_id="/subscriptions/00000000-0000-0000-0000-000000000000" "/resourceGroups/test" "/providers/Microsoft.Compute" @@ -209,19 +169,21 @@ async def test_batch_create_pools(self, client: BatchClient, **kwargs): "/images/FakeImage" "/versions/version" ), - node_agent_sku_id="batch.node.ubuntu 18.04", + node_agent_sku_id="batch.node.ubuntu 22.04", ), ) await self.assertBatchError("InvalidPropertyValue", client.create_pool, pool=test_image_pool, timeout=45) # Test Create Pool with Data Disk data_disk = models.DataDisk(logical_unit_number=1, disk_size_gb=50) - test_disk_pool = models.BatchPoolCreateContent( + test_disk_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_disk_"), vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference(publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS"), - node_agent_sku_id="batch.node.ubuntu 18.04", + image_reference=models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" + ), + node_agent_sku_id="batch.node.ubuntu 22.04", data_disks=[data_disk], ), target_node_communication_mode=models.BatchNodeCommunicationMode.CLASSIC, @@ -236,15 +198,17 @@ async def test_batch_create_pools(self, client: BatchClient, **kwargs): assert disk_pool.target_node_communication_mode == models.BatchNodeCommunicationMode.CLASSIC # Test Create Pool with Azure Disk Encryption - test_ade_pool = models.BatchPoolCreateContent( + test_ade_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_ade_"), vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference(publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS"), + image_reference=models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" + ), disk_encryption_configuration=models.DiskEncryptionConfiguration( targets=[models.DiskEncryptionTarget.TEMPORARY_DISK] ), - node_agent_sku_id="batch.node.ubuntu 18.04", + node_agent_sku_id="batch.node.ubuntu 22.04", ), ) response = await wrap_result(client.create_pool(test_ade_pool)) @@ -283,11 +247,11 @@ async def test_batch_create_pools(self, client: BatchClient, **kwargs): @recorded_by_proxy_async async def test_batch_create_pool_with_blobfuse_mount(self, client: BatchClient, **kwargs): # Test Create Iaas Pool - test_iaas_pool = models.BatchPoolCreateContent( + test_iaas_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_iaas_"), vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference( + image_reference=models.BatchVmImageReference( publisher="MicrosoftWindowsServer", offer="WindowsServer", sku="2016-Datacenter-smalldisk", @@ -322,12 +286,14 @@ async def test_batch_create_pool_with_blobfuse_mount(self, client: BatchClient, @client_setup @recorded_by_proxy_async async def test_batch_update_pools(self, client: BatchClient, **kwargs): - test_paas_pool = models.BatchPoolCreateContent( + test_paas_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_paas_"), vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - node_agent_sku_id="batch.node.ubuntu 18.04", - image_reference=models.ImageReference(publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS"), + node_agent_sku_id="batch.node.ubuntu 22.04", + image_reference=models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" + ), ), start_task=models.BatchStartTask( command_line='cmd.exe /c "echo hello world"', @@ -342,17 +308,17 @@ async def test_batch_update_pools(self, client: BatchClient, **kwargs): assert response is None # Test Update Pool Options - params = models.BatchPoolReplaceContent( + params = models.BatchPoolReplaceOptions( certificate_references=[], application_package_references=[], - metadata=[models.MetadataItem(name="foo", value="bar")], + metadata=[models.BatchMetadataItem(name="foo", value="bar")], target_node_communication_mode=models.BatchNodeCommunicationMode.CLASSIC, ) response = await wrap_result(client.replace_pool_properties(test_paas_pool.id, params)) assert response is None # Test Patch Pool Options - params = models.BatchPoolUpdateContent(metadata=[models.MetadataItem(name="foo2", value="bar2")]) + params = models.BatchPoolUpdateOptions(metadata=[models.BatchMetadataItem(name="foo2", value="bar2")]) response = await wrap_result(client.update_pool(test_paas_pool.id, params)) assert response is None @@ -366,7 +332,6 @@ async def test_batch_update_pools(self, client: BatchClient, **kwargs): assert pool.id == test_paas_pool.id assert pool.state == models.BatchPoolState.ACTIVE assert pool.allocation_state == models.AllocationState.STEADY - # assert pool.vm_configuration.node_agent_sku_id == "batch.node.ubuntu 18.04" assert pool.vm_size == DEFAULT_VM_SIZE assert pool.start_task is None assert pool.metadata is not None @@ -382,9 +347,16 @@ async def test_batch_update_pools(self, client: BatchClient, **kwargs): assert pool.allocation_state is None assert pool.vm_size is None - # Test Delete Pool - response = await wrap_result(client.delete_pool(test_paas_pool.id)) - assert response is None + poller = await wrap_result(client.begin_delete_pool(pool_id=test_paas_pool.id, polling_interval=5)) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" @CachedResourceGroupPreparer(location=AZURE_LOCATION) @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) @@ -399,7 +371,7 @@ async def test_batch_scale_pools(self, client: BatchClient, **kwargs): response = await wrap_result( client.enable_pool_auto_scale( batch_pool.name, - models.BatchPoolEnableAutoScaleContent( + models.BatchPoolEnableAutoScaleOptions( auto_scale_formula="$TargetDedicatedNodes=2", auto_scale_evaluation_interval=interval, ), @@ -412,7 +384,7 @@ async def test_batch_scale_pools(self, client: BatchClient, **kwargs): result = await wrap_result( client.evaluate_pool_auto_scale( batch_pool.name, - models.BatchPoolEvaluateAutoScaleContent(auto_scale_formula="$TargetDedicatedNodes=3"), + models.BatchPoolEvaluateAutoScaleOptions(auto_scale_formula="$TargetDedicatedNodes=3"), ) ) assert isinstance(result, models.AutoScaleRun) @@ -431,13 +403,24 @@ async def test_batch_scale_pools(self, client: BatchClient, **kwargs): while self.is_live and pool.allocation_state != models.AllocationState.STEADY: time.sleep(5) pool = await wrap_result(client.get_pool(batch_pool.name)) - params = models.BatchPoolResizeContent(target_dedicated_nodes=0, target_low_priority_nodes=2) - response = await wrap_result(client.resize_pool(batch_pool.name, params)) - assert response is None + params = models.BatchPoolResizeOptions(target_dedicated_nodes=0, target_low_priority_nodes=2) + + # LRO for resizing + poller = await wrap_result(client.begin_resize_pool(batch_pool.name, params, polling_interval=5)) + assert poller is not None + + poller = await wrap_result(client.begin_stop_pool_resize(batch_pool.name, polling_interval=5)) + assert poller is not None + + # Wait for LRO completion + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" - # Test Stop Pool Resize - response = await wrap_result(client.stop_pool_resize(batch_pool.name)) - assert response is None pool = await wrap_result(client.get_pool(batch_pool.name)) while self.is_live and pool.allocation_state != models.AllocationState.STEADY: time.sleep(5) @@ -454,13 +437,13 @@ async def test_batch_job_schedules(self, client: BatchClient, **kwargs): job_spec = models.BatchJobSpecification( pool_info=models.BatchPoolInfo(pool_id="pool_id"), constraints=models.BatchJobConstraints(max_task_retry_count=2), - on_all_tasks_complete=models.OnAllBatchTasksComplete.TERMINATE_JOB, + all_tasks_complete_mode=models.BatchAllTasksCompleteMode.TERMINATE_JOB, ) schedule = models.BatchJobScheduleConfiguration( start_window=datetime.timedelta(hours=1), recurrence_interval=datetime.timedelta(days=1), ) - params = models.BatchJobScheduleCreateContent(id=schedule_id, schedule=schedule, job_specification=job_spec) + params = models.BatchJobScheduleCreateOptions(id=schedule_id, schedule=schedule, job_specification=job_spec) response = await wrap_result(client.create_job_schedule(params)) assert response is None @@ -499,17 +482,33 @@ async def test_batch_job_schedules(self, client: BatchClient, **kwargs): # Test Patch Job Schedule schedule = models.BatchJobScheduleConfiguration(recurrence_interval=datetime.timedelta(hours=5)) - params = models.BatchJobScheduleUpdateContent(schedule=schedule) + params = models.BatchJobScheduleUpdateOptions(schedule=schedule) response = await wrap_result(client.update_job_schedule(schedule_id, params)) assert response is None - # Test Terminate Job Schedule - response = await wrap_result(client.terminate_job_schedule(schedule_id)) - assert response is None - - # Test Delete Job Schedule - response = await wrap_result(client.delete_job_schedule(schedule_id)) - assert response is None + # Test Terminate Job Schedule using LRO + poller = await wrap_result(client.begin_terminate_job_schedule(job_schedule_id=schedule_id, polling_interval=5)) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" + + # Test Delete Job using LRO + poller = await wrap_result(client.begin_delete_job_schedule(job_schedule_id=schedule_id, polling_interval=5)) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" @CachedResourceGroupPreparer(location=AZURE_LOCATION) @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) @@ -521,7 +520,7 @@ async def test_batch_network_configuration(self, client: BatchClient, **kwargs): network_config = models.NetworkConfiguration( endpoint_configuration=models.BatchPoolEndpointConfiguration( inbound_nat_pools=[ - models.InboundNatPool( + models.BatchInboundNatPool( name="TestEndpointConfig", protocol=models.InboundEndpointProtocol.UDP, backend_port=64444, @@ -539,10 +538,12 @@ async def test_batch_network_configuration(self, client: BatchClient, **kwargs): ) ) virtual_machine_config = models.VirtualMachineConfiguration( - node_agent_sku_id="batch.node.ubuntu 18.04", - image_reference=models.ImageReference(publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS"), + node_agent_sku_id="batch.node.ubuntu 22.04", + image_reference=models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" + ), ) - pool = models.BatchPoolCreateContent( + pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_network_"), target_dedicated_nodes=1, vm_size=DEFAULT_VM_SIZE, @@ -590,7 +591,7 @@ async def test_batch_compute_nodes(self, client: BatchClient, **kwargs): assert node.node_agent_info.version is not None # Test Upload Log - config = models.UploadBatchServiceLogsContent( + config = models.UploadBatchServiceLogsOptions( container_url="https://computecontainer.blob.core.windows.net/", start_time=datetime.datetime.utcnow() - datetime.timedelta(minutes=6), ) @@ -609,8 +610,8 @@ async def test_batch_compute_nodes(self, client: BatchClient, **kwargs): client.disable_node_scheduling( batch_pool.name, nodes[0].id, - models.BatchNodeDisableSchedulingContent( - node_disable_scheduling_option=models.BatchNodeDisableSchedulingOption.terminate + models.BatchNodeDisableSchedulingOptions( + node_disable_scheduling_option=models.BatchNodeDisableSchedulingOption.TERMINATE ), ) ) @@ -620,15 +621,24 @@ async def test_batch_compute_nodes(self, client: BatchClient, **kwargs): response = await wrap_result(client.enable_node_scheduling(batch_pool.name, nodes[0].id)) assert response is None - # Test Reboot Node - response = await wrap_result( - client.reboot_node( + # Test LRO reboot node + poller = await wrap_result( + client.begin_reboot_node( batch_pool.name, nodes[0].id, - models.BatchNodeRebootContent(node_reboot_option=models.BatchNodeRebootOption.TERMINATE), + models.BatchNodeRebootOptions(node_reboot_kind=models.BatchNodeRebootKind.TERMINATE), + polling_interval=5, ) ) - assert response is None + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" # Test Reimage Node # TODO: check to see if reimage is removed from service @@ -637,13 +647,21 @@ async def test_batch_compute_nodes(self, client: BatchClient, **kwargs): # client.reimage_node, # batch_pool.name, # nodes[1].id, - # models.BatchNodeReimageParameters(node_reimage_option=models.BatchNodeReimageOption.terminate), + # models.BatchNodeReimageOptions(node_reimage_option=models.BatchNodeReimageOption.TERMINATE), # ) # Test Remove Nodes - options = models.BatchNodeRemoveContent(node_list=[n.id for n in nodes]) - response = await wrap_result(client.remove_nodes(batch_pool.name, options)) - assert response is None + options = models.BatchNodeRemoveOptions(node_ids=[n.id for n in nodes]) + poller = await wrap_result(client.begin_remove_nodes(batch_pool.name, options)) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" @CachedResourceGroupPreparer(location=AZURE_LOCATION) @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) @@ -655,7 +673,7 @@ async def test_batch_compute_node_extensions(self, client: BatchClient, **kwargs network_config = models.NetworkConfiguration( endpoint_configuration=models.BatchPoolEndpointConfiguration( inbound_nat_pools=[ - models.InboundNatPool( + models.BatchInboundNatPool( name="TestEndpointConfig", protocol=models.InboundEndpointProtocol.UDP, backend_port=64444, @@ -680,11 +698,13 @@ async def test_batch_compute_node_extensions(self, client: BatchClient, **kwargs auto_upgrade_minor_version=True, ) virtual_machine_config = models.VirtualMachineConfiguration( - node_agent_sku_id="batch.node.ubuntu 18.04", + node_agent_sku_id="batch.node.ubuntu 22.04", extensions=[extension], - image_reference=models.ImageReference(publisher="Canonical", offer="UbuntuServer", sku="18.04-LTS"), + image_reference=models.BatchVmImageReference( + publisher="Canonical", offer="0001-com-ubuntu-server-jammy", sku="22_04-lts" + ), ) - batch_pool = models.BatchPoolCreateContent( + batch_pool = models.BatchPoolCreateOptions( id=self.get_resource_name("batch_network_"), target_dedicated_nodes=1, vm_size=DEFAULT_VM_SIZE, @@ -731,12 +751,13 @@ async def test_batch_compute_node_user(self, client: BatchClient, **kwargs): # Test Add User user_name = "BatchPythonSDKUser" nodes = list(await wrap_list_result(client.list_nodes(batch_pool.name))) - user = models.BatchNodeUserCreateContent(name=user_name, password="secret", is_admin=False) + user = models.BatchNodeUserCreateOptions(name=user_name, password="secret", is_admin=False) + assert nodes[0].id is not None # TODO: typespec fix for id possibly None response = await wrap_result(client.create_node_user(batch_pool.name, nodes[0].id, user)) assert response is None # Test Update User - user = models.BatchNodeUserUpdateContent(password="liilef#$DdRGSa_ewkjh") + user = models.BatchNodeUserUpdateOptions(password="liilef#$DdRGSa_ewkjh") response = await wrap_result(client.replace_node_user(batch_pool.name, nodes[0].id, user_name, user)) assert response is None @@ -795,7 +816,7 @@ async def test_batch_files(self, client: BatchClient, **kwargs): node = nodes[0].id assert node is not None task_id = "test_task" - task_param = models.BatchTaskCreateContent(id=task_id, command_line='cmd /c "echo hello world"') + task_param = models.BatchTaskCreateOptions(id=task_id, command_line='cmd /c "echo hello world"') response = await wrap_result(client.create_task(batch_job.id, task_param)) assert response is None task = await wrap_result(client.get_task(batch_job.id, task_id)) @@ -814,7 +835,7 @@ async def test_batch_files(self, client: BatchClient, **kwargs): else: raise ValueError("File path is None") assert props.content_length is not None - # assert props.content_type is not None # add content-type to typespec + # assert props.content_type is not None # TODO: add content-type to typespec # Test Get File from Batch Node file_length = 0 @@ -827,7 +848,7 @@ async def test_batch_files(self, client: BatchClient, **kwargs): # Test Delete File from Batch Node response = await wrap_result( client.delete_node_file(batch_pool.name, node, only_files[1].name) - ) # TODO: maybe delete stderr to use in the next test for content_length (against "hello world") + ) # TODO: delete stderr to use in test for content_length (against "hello world") assert response is None # Test List Files from Task @@ -843,7 +864,7 @@ async def test_batch_files(self, client: BatchClient, **kwargs): else: raise ValueError("File path is None") assert props.content_length is not None - # assert props.content_type is not None # add content-type to typespec + # assert props.content_type is not None # TODO: add content-type to typespec # Test Get File from Task file_length = 0 @@ -859,7 +880,7 @@ async def test_batch_files(self, client: BatchClient, **kwargs): @CachedResourceGroupPreparer(location=AZURE_LOCATION) @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) - @JobPreparer(on_task_failure=models.OnBatchTaskFailure.PERFORM_EXIT_OPTIONS_JOB_ACTION) + @JobPreparer(task_failure_mode=models.BatchTaskFailureMode.PERFORM_EXIT_OPTIONS_JOB_ACTION) @pytest.mark.parametrize("BatchClient", [SyncBatchClient, AsyncBatchClient], ids=["sync", "async"]) @client_setup @recorded_by_proxy_async @@ -870,19 +891,19 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): exit_codes=[ models.ExitCodeMapping( code=1, - exit_options=models.ExitOptions(job_action=models.BatchJobAction.TERMINATE), + exit_options=models.ExitOptions(job_action=models.BatchJobActionKind.TERMINATE), ) ], exit_code_ranges=[ models.ExitCodeRangeMapping( start=2, end=4, - exit_options=models.ExitOptions(job_action=models.BatchJobAction.DISABLE), + exit_options=models.ExitOptions(job_action=models.BatchJobActionKind.DISABLE), ) ], - default=models.ExitOptions(job_action=models.BatchJobAction.NONE), + default=models.ExitOptions(job_action=models.BatchJobActionKind.NONE), ) - task_param = models.BatchTaskCreateContent( + task_param = models.BatchTaskCreateOptions( id=self.get_resource_name("batch_task1_"), command_line='cmd /c "echo hello world"', exit_conditions=exit_conditions, @@ -898,10 +919,10 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): assert isinstance(task, models.BatchTask) assert task.exit_conditions is not None assert task.exit_conditions.default is not None - assert task.exit_conditions.default.job_action == models.BatchJobAction.NONE + assert task.exit_conditions.default.job_action == models.BatchJobActionKind.NONE assert task.exit_conditions.exit_codes is not None assert task.exit_conditions.exit_codes[0].code == 1 - assert task.exit_conditions.exit_codes[0].exit_options.job_action == models.BatchJobAction.TERMINATE + assert task.exit_conditions.exit_codes[0].exit_options.job_action == models.BatchJobActionKind.TERMINATE # Test Create Task with Output Files container_url = "https://test.blob.core.windows.net:443/test-container" @@ -929,7 +950,7 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): ), ), ] - task_param = models.BatchTaskCreateContent( + task_param = models.BatchTaskCreateOptions( id=self.get_resource_name("batch_task2_"), command_line='cmd /c "echo hello world"', output_files=outputs, @@ -943,7 +964,7 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): auto_user = models.AutoUserSpecification( scope=models.AutoUserScope.TASK, elevation_level=models.ElevationLevel.ADMIN ) - task_param = models.BatchTaskCreateContent( + task_param = models.BatchTaskCreateOptions( id=self.get_resource_name("batch_task3_"), command_line='cmd /c "echo hello world"', user_identity=models.UserIdentity(auto_user=auto_user), @@ -955,7 +976,7 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): assert task.user_identity.auto_user.elevation_level == models.ElevationLevel.ADMIN # Test Create Task with Container Settings - task_param = models.BatchTaskCreateContent( + task_param = models.BatchTaskCreateOptions( id=self.get_resource_name("batch_task5_"), command_line='cmd /c "echo hello world"', container_settings=models.BatchTaskContainerSettings( @@ -970,7 +991,7 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): assert task.container_settings.registry.username == "username" # Test Create Task with Run-As-User - task_param = models.BatchTaskCreateContent( + task_param = models.BatchTaskCreateOptions( id=self.get_resource_name("batch_task6_"), command_line='cmd /c "echo hello world"', user_identity=models.UserIdentity(username="task-user"), @@ -984,15 +1005,16 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): tasks = [] for i in range(7, 10): tasks.append( - models.BatchTaskCreateContent( + models.BatchTaskCreateOptions( id=self.get_resource_name("batch_task{}_".format(i)), command_line='cmd /c "echo hello world"', ) ) result = await wrap_result(client.create_tasks(batch_job.id, task_collection=tasks)) - assert isinstance(result, models.BatchTaskAddCollectionResult) - assert len(result.value) == 3 - assert result.value[0].status.lower() == models.BatchTaskAddStatus.SUCCESS + assert isinstance(result, models.BatchCreateTaskCollectionResult) + assert result.values_property is not None + assert len(result.values_property) == 3 + assert result.values_property[0].status.lower() == models.BatchTaskAddStatus.SUCCESS # Test List Tasks tasks = list(await wrap_list_result(client.list_tasks(batch_job.id))) @@ -1045,7 +1067,7 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): file_path="resourceFile{}".format(str(i)), ) resource_files.append(resource_file) - task = models.BatchTaskCreateContent(id=task_id, command_line="sleep 1", resource_files=resource_files) + task = models.BatchTaskCreateOptions(id=task_id, command_line="sleep 1", resource_files=resource_files) tasks_to_add.append(task) await self.assertCreateTasksError( "RequestBodyTooLarge", @@ -1072,17 +1094,18 @@ async def test_batch_tasks(self, client: BatchClient, **kwargs): ) resource_files.append(resource_file) for i in range(733): - task = models.BatchTaskCreateContent( + task = models.BatchTaskCreateOptions( id=task_id + str(i), command_line="sleep 1", resource_files=resource_files, ) tasks_to_add.append(task) result = await wrap_result(client.create_tasks(batch_job.id, tasks_to_add)) - assert isinstance(result, models.BatchTaskAddCollectionResult) - assert len(result.value) == 733 - assert result.value[0].status.lower() == models.BatchTaskAddStatus.SUCCESS - assert all(t.status.lower() == models.BatchTaskAddStatus.SUCCESS for t in result.value) + assert isinstance(result, models.BatchCreateTaskCollectionResult) + assert result.values_property is not None + assert len(result.values_property) == 733 + assert result.values_property[0].status.lower() == models.BatchTaskAddStatus.SUCCESS + assert all(t.status.lower() == models.BatchTaskAddStatus.SUCCESS for t in result.values_property) @CachedResourceGroupPreparer(location=AZURE_LOCATION) @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) @@ -1096,19 +1119,19 @@ async def test_batch_jobs(self, client: BatchClient, **kwargs): pool=models.BatchPoolSpecification( vm_size=DEFAULT_VM_SIZE, virtual_machine_configuration=models.VirtualMachineConfiguration( - image_reference=models.ImageReference( + image_reference=models.BatchVmImageReference( publisher="Canonical", - offer="UbuntuServer", - sku="18.04-LTS", + offer="0001-com-ubuntu-server-jammy", + sku="22_04-lts", version="latest", ), - node_agent_sku_id="batch.node.ubuntu 18.04", + node_agent_sku_id="batch.node.ubuntu 22.04", ), ), ) job_prep = models.BatchJobPreparationTask(command_line='cmd /c "echo hello world"') job_release = models.BatchJobReleaseTask(command_line='cmd /c "echo goodbye world"') - job_param = models.BatchJobCreateContent( + job_param = models.BatchJobCreateOptions( id=self.get_resource_name("batch_job1_"), pool_info=models.BatchPoolInfo(auto_pool_specification=auto_pool), job_preparation_task=job_prep, @@ -1131,7 +1154,7 @@ async def test_batch_jobs(self, client: BatchClient, **kwargs): assert response is None # Test Patch Job - options = models.BatchJobUpdateContent(priority=900) + options = models.BatchJobUpdateOptions(priority=900) response = await wrap_result(client.update_job(job_param.id, options)) assert response is None @@ -1142,46 +1165,147 @@ async def test_batch_jobs(self, client: BatchClient, **kwargs): assert job.priority == 900 # Test Create Job with Auto Complete - job_auto_param = models.BatchJobCreateContent( + job_auto_param = models.BatchJobCreateOptions( id=self.get_resource_name("batch_job2_"), - on_all_tasks_complete=models.OnAllBatchTasksComplete.TERMINATE_JOB, - on_task_failure=models.OnBatchTaskFailure.PERFORM_EXIT_OPTIONS_JOB_ACTION, + all_tasks_complete_mode=models.BatchAllTasksCompleteMode.TERMINATE_JOB, + task_failure_mode=models.BatchTaskFailureMode.PERFORM_EXIT_OPTIONS_JOB_ACTION, pool_info=models.BatchPoolInfo(auto_pool_specification=auto_pool), ) response = await wrap_result(client.create_job(job_auto_param)) assert response is None job = await wrap_result(client.get_job(job_auto_param.id)) assert isinstance(job, models.BatchJob) - assert job.on_all_tasks_complete == models.OnAllBatchTasksComplete.TERMINATE_JOB - assert job.on_task_failure == models.OnBatchTaskFailure.PERFORM_EXIT_OPTIONS_JOB_ACTION + assert job.all_tasks_complete_mode == models.BatchAllTasksCompleteMode.TERMINATE_JOB + assert job.task_failure_mode == models.BatchTaskFailureMode.PERFORM_EXIT_OPTIONS_JOB_ACTION # Test List Jobs jobs = await wrap_list_result(client.list_jobs()) assert isinstance(jobs, Iterable) assert len(list(jobs)) == 2 - # Test Disable Job - response = await wrap_result( - client.disable_job( + # Test LRO disable job + poller = await wrap_result( + client.begin_disable_job( job_id=job_param.id, - content=models.BatchJobDisableContent(disable_tasks="requeue"), + disable_options=models.BatchJobDisableOptions(disable_tasks="requeue"), + polling_interval=5, ) ) - assert response is None + assert poller is not None - # Test Enable Job - response = await wrap_result(client.enable_job(job_param.id)) - assert response is None + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" + + # Test LRO enable job + poller = await wrap_result(client.begin_enable_job(job_id=job_param.id, polling_interval=5)) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" # Prep and release task status task_status = await wrap_list_result(client.list_job_preparation_and_release_task_status(job_param.id)) assert isinstance(task_status, Iterable) assert list(task_status) == [] - # Test Terminate Job - response = await wrap_result(client.terminate_job(job_param.id)) - assert response is None + # Test Terminate Job using LRO + # TODO: default for termination_reason wasn't set so manually adding it. check on why default isn't working + poller = await wrap_result( + client.begin_terminate_job( + job_id=job_param.id, + options=models.BatchJobTerminateOptions(termination_reason='UserTerminate'), + polling_interval=5 + ) + ) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + # waiting for completion + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" + + # Test Delete Job using LRO + poller = await wrap_result(client.begin_delete_job(job_id=job_auto_param.id, polling_interval=5)) + assert poller is not None + + result = poller.result() + if hasattr(result, "__await__"): + # Async poller + result = await result + assert result is None + assert poller.done() + assert poller.status() == "Succeeded" - # Test Delete Job - response = await wrap_result(client.delete_job(job_auto_param.id)) - assert response is None + @CachedResourceGroupPreparer(location=AZURE_LOCATION) + @AccountPreparer(location=AZURE_LOCATION, batch_environment=BATCH_ENVIRONMENT) + @pytest.mark.parametrize("BatchClient", [SyncBatchClient, AsyncBatchClient], ids=["sync", "async"]) + @client_setup + @recorded_by_proxy_async + async def test_batch_exception_policy(self, client: BatchClient, **kwargs): + # Test Resource Not Found Error (404) + try: + await wrap_result(client.get_pool("non-existent-pool-id")) + self.fail("Expected ResourceNotFoundError but no exception was raised") + except azure.core.exceptions.ResourceNotFoundError as e: + assert e.response is not None + assert hasattr(e, "model") + assert "(PoolNotFound) The specified pool does not exist." in str(e) + if hasattr(e, "error") and hasattr(e.error, "code"): + assert e.error.code in ["PoolNotFound"] + + # Test Resource Exists Error (409) + job_id = self.get_resource_name("batch_test_job_") + auto_pool = models.BatchAutoPoolSpecification( + pool_lifetime_option=models.BatchPoolLifetimeOption.JOB, + pool=models.BatchPoolSpecification( + vm_size=DEFAULT_VM_SIZE, + virtual_machine_configuration=models.VirtualMachineConfiguration( + image_reference=models.BatchVmImageReference( + publisher="Canonical", + offer="0001-com-ubuntu-server-jammy", + sku="22_04-lts", + version="latest", + ), + node_agent_sku_id="batch.node.ubuntu 22.04", + ), + ), + ) + + job_param = models.BatchJobCreateOptions( + id=job_id, + pool_info=models.BatchPoolInfo(auto_pool_specification=auto_pool), + ) + + # creating the job for the first time + await wrap_result(client.create_job(job_param)) + + try: + # trying to create the same job again but should fail + await wrap_result(client.create_job(job_param)) + self.fail("Expected ResourceExistsError but no exception was raised") + except azure.core.exceptions.ResourceExistsError as e: + assert e.response is not None + assert hasattr(e, "model") + assert "(JobExists) The specified job already exists." in str(e) + if hasattr(e, "error") and hasattr(e.error, "code"): + assert e.error.code in ["JobExists"] + finally: + try: + await wrap_result(client.delete_job(job_id)) + except: + pass diff --git a/sdk/batch/azure-batch/tests/test_response_handlers.py b/sdk/batch/azure-batch/tests/test_response_handlers.py new file mode 100644 index 000000000000..94cb74fe25c2 --- /dev/null +++ b/sdk/batch/azure-batch/tests/test_response_handlers.py @@ -0,0 +1,188 @@ +import unittest +from unittest.mock import Mock, MagicMock + +from azure.core.exceptions import ( + HttpResponseError, + ClientAuthenticationError, + ResourceNotFoundError, + ResourceExistsError, + ResourceModifiedError, +) +from azure.batch._patch import BatchExceptionPolicy, BatchErrorFormat + + +class TestBatchErrorFormat(unittest.TestCase): + def test_batch_error_format_with_values(self): + odata_error = { + "code": 401, + "message": {"lang": "en-us", "value": "Property value is invalid"}, + "values": [ + {"key": "property1", "value": "error_details"}, + {"key": "property2", "value": "more_error_details"}, + ], + } + + batch_error = BatchErrorFormat(odata_error) + self.assertEqual(batch_error.details[0].code, "property1") + self.assertEqual(batch_error.details[1].code, "property2") + + def test_batch_error_format_without_values(self): + odata_error = { + "error": {"code": "InvalidProperty", "message": {"lang": "en-us", "value": "Property value is invalid"}} + } + batch_error = BatchErrorFormat(odata_error) + self.assertFalse(hasattr(batch_error, "values")) + + def test_invalid_odata_error(self): + odata_error = {"code": "InvalidProperty", "message": "This is not an object"} + + with self.assertRaises(TypeError): + BatchErrorFormat(odata_error) + + +class TestResponseHandler(unittest.TestCase): + def test_client_authentication_error(self): + mock_http_response = Mock() + mock_http_response.status_code = 401 + mock_http_response.json.return_value = { + "code": 401, + "message": "Authentication failed", + } + + mock_request_headers = Mock() + mock_request_headers.get.return_value = None + mock_http_request = Mock() + mock_http_request.headers = mock_request_headers + + mock_response = Mock() + mock_response.http_response = mock_http_response + mock_request = Mock() + mock_request.http_request = mock_http_request + + policy = BatchExceptionPolicy() + + with self.assertRaises(ClientAuthenticationError): + policy.on_response(mock_request, mock_response) + + def test_resource_not_found_error(self): + mock_http_response = Mock() + mock_http_response.status_code = 404 + mock_http_response.json.return_value = { + "code": 404, + "message": "Resource not found", + } + + mock_request_headers = Mock() + mock_request_headers.get.return_value = None + mock_http_request = Mock() + mock_http_request.headers = mock_request_headers + + mock_response = Mock() + mock_response.http_response = mock_http_response + mock_request = Mock() + mock_request.http_request = mock_http_request + + policy = BatchExceptionPolicy() + + with self.assertRaises(ResourceNotFoundError): + policy.on_response(mock_request, mock_response) + + def test_if_match_resource_not_found(self): + mock_http_response = Mock() + mock_http_response.status_code = 500 + mock_http_response.json.return_value = { + "code": 500, + "message": "Server error", + } + + mock_request_headers = Mock() + mock_request_headers.get.side_effect = lambda header: "*" if header == "If-Match" else None + mock_http_request = Mock() + mock_http_request.headers = mock_request_headers + + mock_response = Mock() + mock_response.http_response = mock_http_response + mock_request = Mock() + mock_request.http_request = mock_http_request + + policy = BatchExceptionPolicy() + + with self.assertRaises(ResourceNotFoundError): + policy.on_response(mock_request, mock_response) + + def test_if_none_match_resource_not_found(self): + mock_http_response = Mock() + mock_http_response.status_code = 500 + mock_http_response.json.return_value = { + "code": 500, + "message": "Server error", + } + + mock_request_headers = Mock() + mock_request_headers.get.side_effect = lambda header: "*" if header == "If-None-Match" else None + mock_http_request = Mock() + mock_http_request.headers = mock_request_headers + + mock_response = Mock() + mock_response.http_response = mock_http_response + mock_request = Mock() + mock_request.http_request = mock_http_request + + policy = BatchExceptionPolicy() + + with self.assertRaises(ResourceNotFoundError): + policy.on_response(mock_request, mock_response) + + def test_if_match_takes_precedence_over_if_none_match(self): + mock_http_response = Mock() + mock_http_response.status_code = 400 + mock_http_response.json.return_value = { + "code": 400, + "message": "Bad request", + } + + mock_request_headers = Mock() + + def get_header(header): + if header == "If-Match": + return "foobar" + elif header == "If-None-Match": + return "*" + return None + + mock_request_headers.get.side_effect = get_header + mock_http_request = Mock() + mock_http_request.headers = mock_request_headers + + mock_response = Mock() + mock_response.http_response = mock_http_response + mock_request = Mock() + mock_request.http_request = mock_http_request + + policy = BatchExceptionPolicy() + + with self.assertRaises(ResourceModifiedError): + policy.on_response(mock_request, mock_response) + + def test_header_takes_precedence_over_status_code(self): + mock_http_response = Mock() + mock_http_response.status_code = 401 + mock_http_response.json.return_value = { + "code": 401, + "message": "Authentication failed", + } + + mock_request_headers = Mock() + mock_request_headers.get.side_effect = lambda header: "*" if header == "If-Match" else None + mock_http_request = Mock() + mock_http_request.headers = mock_request_headers + + mock_response = Mock() + mock_response.http_response = mock_http_response + mock_request = Mock() + mock_request.http_request = mock_http_request + + policy = BatchExceptionPolicy() + + with self.assertRaises(ResourceNotFoundError): + policy.on_response(mock_request, mock_response) diff --git a/sdk/batch/azure-batch/tsp-location.yaml b/sdk/batch/azure-batch/tsp-location.yaml index 96f30af8578f..0726949a61ea 100644 --- a/sdk/batch/azure-batch/tsp-location.yaml +++ b/sdk/batch/azure-batch/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/batch/Azure.Batch -commit: e7ed63002df7e9cc1d3e4cd139d76c4d7040acd3 +commit: 4d45f0386a8d29556eac8028a3b7180e0e82eb0e repo: Azure/azure-rest-api-specs additionalDirectories: