-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.py
2013 lines (1794 loc) · 66.2 KB
/
commands.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Azure commands to work with batch and associated storage
# Heavily borrowed from azure batch samples in python
import configparser
import datetime
import io
import logging
import os
import shutil
import sys
import math
import time
import azure.batch as batch
import azure.batch.batch_auth as batchauth
import azure.batch.models as batchmodels
from azure.batch import BatchServiceClient
from azure.core.exceptions import ResourceExistsError
from azure.storage import blob
from azure.storage.blob import (
BlobSasPermissions,
BlobServiceClient,
ContainerSasPermissions,
generate_account_sas,
generate_blob_sas,
generate_container_sas,
)
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def generate_blank_config(config_file: str):
"""
Generate blank config. Replace the angle '<>' brackets and the text within
them with the appropriate values
Parameters
----------
config_file : str
config filename
Raises
------
Exception if config file already exists. Move it out of the way or generate with another name
"""
if os.path.exists(config_file):
raise f"Config file: {config_file} exists! Please delete or move out of the way to generate"
with open(config_file, "w") as fh:
fh.write(
"""# Update the Batch and Storage account credential strings below with the values
# unique to your accounts. These are used when constructing connection strings
# for the Batch and Storage client objects.
# Replace the <xxxxxx> with actual values from your account
[DEFAULT]
_BATCH_ACCOUNT_NAME = <batch_account_name>
_BATCH_ACCOUNT_KEY = <batch_account_key>
_BATCH_ACCOUNT_URL = https://<batch_account_name>.<location>.batch.azure.com
_STORAGE_ACCOUNT_NAME = <storage_account_name>
_STORAGE_ACCOUNT_KEY = <storage_account_key>
_STORAGE_ACCOUNT_DOMAIN = blob.core.windows.net
"""
)
def load_config(config_file: str):
"""
Loads config file with a 'DEFAULT' section. See configparser
Config file contains a default section. To generate an empty one use the
generate_blank_config(config_file) method
Parameters
----------
config_file : str
Filename
Returns
-------
config: dict
configuration name value pairs
"""
parser = configparser.ConfigParser()
parser.optionxform = str
parser.read(config_file)
config = dict(parser["DEFAULT"].items())
return config
def create_batch_client(config_file: str):
"""
Create a batch client
Parameters
----------
config_file : str
filename
Returns
-------
AzureBatch
a configured instance of the class for working with the batch account
"""
config = load_config(config_file)
# Create a Batch service client. We'll now be interacting with the Batch
return AzureBatch(
config["_BATCH_ACCOUNT_NAME"],
config["_BATCH_ACCOUNT_KEY"],
config["_BATCH_ACCOUNT_URL"],
)
def create_blob_client(config_file: str):
"""
Create a blob client
Parameters
----------
config_file : str
filename
Returns
-------
AzureBlob
a configured instance for working with the storage 'blob' account
"""
config = load_config(config_file)
# Create the blob client, for use in obtaining references to
# blob storage containers and uploading files to containers.
return AzureBlob(
config["_STORAGE_ACCOUNT_NAME"],
config["_STORAGE_ACCOUNT_KEY"],
config["_STORAGE_ACCOUNT_DOMAIN"],
)
class AzureBatch:
"""
AzureBatch manages batch pools, jobs and task submissions. This class encapsulates some sensible defaults for typical
cpu intensive tasks
Management of batch accounts, application packages are either done manually or separately by other scripts
The config file with the needed values are defined in a config file use :py:func:`generate_blank_config`
"""
_STANDARD_OUT_FILE_NAME = "stdout.txt"
_STANDARD_ERROR_FILE_NAME = "stderr.txt"
def __init__(
self, batch_account_name: str, batch_account_key: str, batch_account_url: str
):
"""
Initializes the batch account client
Parameters
----------
batch_account_name : str
batch account name
batch_account_key : str
batch account key
batch_account_url : str
batch accont url
"""
self.credentials = batchauth.SharedKeyCredentials(
batch_account_name, batch_account_key
)
self.batch_client = BatchServiceClient(
self.credentials, batch_url=batch_account_url
)
def create_pool_if_not_exist(self, pool: batchmodels.PoolAddParameter) -> bool:
"""
Creates the pool if it doesn't exist. Otherwise throws an exception that is caught and returned as a bool
Parameters
----------
pool : batchmodels.PoolAddParameter
pool to add
-------
Returns
bool
True if created else False
"""
try:
logger.info("Attempting to create pool:", pool.id)
self.batch_client.pool.add(pool)
logger.info("Created pool:", pool.id)
return True
except batchmodels.BatchErrorException as e:
if e.error.code != "PoolExists":
raise
else:
logger.info("Pool {!r} already exists".format(pool.id))
return False
def resize_pool(
self, pool_id: str, pool_size: int, node_deallocation_option="taskCompletion"
):
"""
Resize pool with pool_id to pool_size. This method starts the resizing but that could take a couple of minutes
to finish. See :py:func:`wait_for_pool_nodes`
Parameters
----------
pool_id : str
pool_size : int
node_deallocation_option : str, optional
by default 'taskCompletion' so that pool nodes are shutdown only after current tasks on it run to completion
"""
pool_resize_param = batchmodels.PoolResizeParameter(
target_dedicated_nodes=pool_size,
node_deallocation_option=node_deallocation_option,
) # scale it down to zero
self.batch_client.pool.resize(pool_id, pool_resize_param)
def wait_for_pool_nodes(self, pool_id: str):
"""
wait for pool nodes to get to a stable state ( could be idle or unusable )
Typically you want to do this if you want nodes available before tasks are assigned to the pool
Parameters
----------
pool_id : str
pool name
Raises
------
RuntimeError
if something goes wrong
"""
nodes = self.wait_for_all_nodes_state(
pool_id,
frozenset(
(
batchmodels.ComputeNodeState.start_task_failed,
batchmodels.ComputeNodeState.unusable,
batchmodels.ComputeNodeState.idle,
)
),
)
# ensure all node are idle
if any(node.state != batchmodels.ComputeNodeState.idle for node in nodes):
raise RuntimeError("node(s) of pool {} not in idle state".format(pool_id))
def create_pool(
self,
pool_id: str,
pool_size: int,
vm_size="standard_f2s_v2",
tasks_per_vm=2,
os_image_data=(
"microsoftwindowsserver",
"windowsserver",
"2019-datacenter-core",
),
os_image_reference=None,
app_packages=[],
start_task_cmd="cmd /c set",
start_task_admin=False,
resource_files=None,
elevation_level=batchmodels.ElevationLevel.admin,
enable_inter_node_communication=False,
wait_for_success=True,
):
"""
Create or if exists then resize pool to desired pool_size
The vm_size should be selected based on the kind of workload. For cpu intensive tasks, the F or D series work well.
These `benchmarks<https://docs.microsoft.com/en-us/azure/virtual-machines/windows/compute-benchmark-scores>`_ are useful in determining
the ones with the fastest CPU
This has to be combined with the temporary space available in different VMs otherwise disk storage has to be separately mounted and paid for
The pricing and storage is available by browsing `these pages<https://azure.microsoft.com/en-us/pricing/details/virtual-machines/windows/>`_
Parameters
----------
pool_id : str
the name of the pool
pool_size : int
the size of the pool, i.e. number of nodes (machines) in the pool. These are of the on-demand pricing type
vm_size : str, optional
the name of the vm type, by default 'standard_f2s_v2'. See `this<https://docs.microsoft.com/en-us/azure/virtual-machines/sizes>`_
tasks_per_vm : int, optional
This is the number of tasks that can be run simultaneously. one can under or oversubscribe this relative to the cpus available in the vm_size, by default 2
os_image_data : tuple, optional
The `os image list <https://docs.microsoft.com/en-us/azure/batch/batch-pool-vm-sizes#supported-vm-images>`_, by default ('microsoftwindowsserver', 'windowsserver', '2019-datacenter-core')
app_packages : list, optional
list of tuples of (app name, app version), by default []
start_task_cmd : str, optional
command to be run on start of node, by default "cmd /c set"
start_task_admin : bool, optional
whether task should be run as admin, by default False
resource_files : list of ResourceFile, optional
input file spec list. See :py:func:create_input_file_spec, by default None
elevation_level : admin or non_admin, optional
admin or non_admin, by default batchmodels.ElevationLevel.admin
enable_inter_node_communication : bool, optional
if the task needs high bandwidth (Infiniband) connected nodes, by default False
wait_for_success : bool, optional
wait for pool to be created, by default False
Returns
-------
bool
True if pool is created, False otherwise
"""
vm_count = pool_size
# choosing windows machine here (just the core windows, it has no other apps on it including explorer)
if os_image_reference == None:
sku_to_use, image_ref_to_use = (
self.select_latest_verified_vm_image_with_node_agent_sku(*os_image_data)
)
else:
sku_to_use, image_ref_to_use = os_image_reference
vmconfig = batchmodels.VirtualMachineConfiguration(
image_reference=image_ref_to_use, node_agent_sku_id=sku_to_use
)
# applications needed here
app_references = [
batchmodels.ApplicationPackageReference(
application_id=app[0], version=app[1]
)
for app in app_packages
]
if start_task_admin:
user_identity = batchmodels.UserIdentity(
auto_user=batchmodels.AutoUserSpecification(
scope=batchmodels.AutoUserScope.pool,
elevation_level=elevation_level,
)
)
else:
user_identity = batchmodels.UserIdentity()
pool = batchmodels.PoolAddParameter(
id=pool_id,
virtual_machine_configuration=vmconfig,
vm_size=vm_size,
target_dedicated_nodes=vm_count,
# not understood but carried from an example maybe outdated ?
# max_tasks_per_node=1 if enable_inter_node_communication else tasks_per_vm,
task_slots_per_node=1 if enable_inter_node_communication else tasks_per_vm,
resize_timeout=datetime.timedelta(minutes=15),
enable_inter_node_communication=enable_inter_node_communication,
application_package_references=app_references,
start_task=(
batchmodels.StartTask(
command_line=start_task_cmd,
user_identity=user_identity,
wait_for_success=wait_for_success,
resource_files=resource_files,
)
if start_task_cmd
else None
),
)
pool_created = self.create_pool_if_not_exist(pool)
return pool_created
def create_or_resize_pool(
self,
pool_id,
pool_size,
vm_size="standard_f4s_v2",
tasks_per_vm=2,
os_image_data=(
"microsoftwindowsserver",
"windowsserver",
"2019-datacenter-core",
),
os_image_reference=None,
app_packages=[],
start_task_cmd="cmd /c set",
start_task_admin=False,
resource_files=None,
elevation_level=batchmodels.ElevationLevel.admin,
enable_inter_node_communication=False,
wait_for_success=False,
):
"""Create or if exists then resize pool to desired pool_size
Args:
pool_id (str): pool id
pool_size (int): pool size in number of vms (cores per vm may depend on machine type here)
vm_size: name of vm, default standard_f4s_v2
tasks_per_vm (default 4): this is tied to the number of cores on the vm_size above. if your task needs 1 cpu per task set this to number of cores
"""
pool_created = self.create_pool(
pool_id,
pool_size,
vm_size,
tasks_per_vm,
os_image_data,
os_image_reference,
app_packages,
start_task_cmd,
start_task_admin,
resource_files,
elevation_level,
enable_inter_node_communication,
wait_for_success,
)
if not pool_created:
self.resize_pool(pool_id, pool_size)
def exists_pool(self, pool_id: str) -> bool:
"""
checks if pool exists
Parameters
----------
pool_id : str
name of pool
Returns
-------
bool
True if pool exists
"""
return self.batch_client.pool.exists(pool_id)
def delete_pool(self, pool_id: str):
"""
asks pool to be deleted. The pool delete will take some time as the nodes have to be shutdown, etc.
Parameters
----------
pool_id : str
name of pool
Returns
-------
"""
return self.batch_client.pool.delete(pool_id)
def wait_for_pool_delete(self, pool_id: str, polling_interval_secs=10):
"""
wait for pool to be deleted. Polls with :py:func:`exists_pool` every polling_interval_secs (10 is default)
Parameters
----------
pool_id : str
name of pool
polling_interval_secs : int, optional
polling interval by default 10
"""
while self.exists_pool(pool_id):
time.sleep(polling_interval_secs)
def create_job(
self,
job_id: str,
pool_id: str,
prep_task: batchmodels.JobPreparationTask = None,
max_task_retry_count=0,
):
"""
Creates a job with the specified ID, associated with the specified pool.
Parameters
----------
job_id : str
name of job
pool_id : str
name of pool
prep_task : batchmodels.JobPreparationTask, optional
a preperation task to be run before any tasks, by default None
"""
logger.info("Creating job [{}]...".format(job_id))
job = batch.models.JobAddParameter(
id=job_id,
job_preparation_task=prep_task,
pool_info=batch.models.PoolInformation(pool_id=pool_id),
constraints=batch.models.JobConstraints(
max_task_retry_count=max_task_retry_count
),
)
self.batch_client.job.add(job)
def mark_job_termination_on_task_completion(self, job_id: str):
"""
Mark job for termination on all tasks completion
"""
self.batch_client.job.patch(
job_id=job_id,
job_patch_parameter=batchmodels.JobPatchParameter(
on_all_tasks_complete=batchmodels.OnAllTasksComplete.terminate_job
),
)
def get_job(self, job_id: str) -> batchmodels.CloudJob:
"""
get job with matching id
Parameters
----------
job_id : str
job id
Returns
-------
batchmodels.CloudJob
"""
return self.batch_client.job.get(job_id)
def delete_job(self, job_id: str):
"""
deletes the job
Parameters
----------
job_id : str
job id
"""
self.batch_client.job.delete(job_id)
def wait_for_job_under_job_schedule(
self,
job_schedule_id: str,
timeout: datetime.timedelta,
polling_interval_secs: int = 10,
) -> batchmodels.CloudJob:
"""
Waits for a job schedule to run
Parameters
----------
job_schedule_id : str
job schedule id
timeout : datetime.timedelta
how long to wait
polling_interval_secs: int
how often to poll
Returns
-------
[type]
[description]
Raises
------
TimeoutError
[description]
"""
time_to_timeout_at = datetime.datetime.now() + timeout
while datetime.datetime.now() < time_to_timeout_at:
cloud_job_schedule = self.batch_client.job_schedule.get(
job_schedule_id=job_schedule_id
)
logger.info("Checking if job exists...")
if (cloud_job_schedule.execution_info.recent_job) and (
cloud_job_schedule.execution_info.recent_job.id is not None
):
return cloud_job_schedule.execution_info.recent_job.id
time.sleep(polling_interval_secs)
raise TimeoutError("Timed out waiting for tasks to complete")
def wait_for_job_schedule_to_complete(
self,
job_schedule_id: str,
timeout: datetime.timedelta,
polling_interval_secs: int = 10,
):
"""
Waits for a job schedule to complete.
Parameters
----------
job_schedule_id : str
timeout : datetime.timedelta
how long to wait
polling_interval_secs : int, optional
how often to poll
"""
while datetime.datetime.now() < timeout:
cloud_job_schedule = self.batch_client.job_schedule.get(
job_schedule_id=job_schedule_id
)
logger.info("Checking if job schedule is complete...")
state = cloud_job_schedule.state
if state == batchmodels.JobScheduleState.completed:
return
time.sleep(polling_interval_secs)
return
def create_input_file_spec(
self,
container_name: str,
blob_prefix: str,
file_path: str = ".",
container_name_is_sas_url: bool = False,
) -> batchmodels.ResourceFile:
"""
input file specs are information for the batch task to download these files
to the task before starting the task.
Parameters
----------
container_name : str
name of container
blob_prefix : str
path to blob
file_path : str, optional
where to place the contents of the blob_prefix; appends this value to the blob_prefix, by default '.'
Returns
-------
ResourceFile
:py:func:`batch.models.ResourceFile`
"""
if container_name_is_sas_url:
return batchmodels.ResourceFile(
http_url=container_name, file_path=file_path
)
else:
return batchmodels.ResourceFile(
auto_storage_container_name=container_name,
blob_prefix=blob_prefix,
file_path=file_path,
)
def create_output_file_spec(
self,
file_pattern: str,
output_container_sas_url: str,
blob_path: str = None,
upload_condition=batchmodels.OutputFileUploadCondition.task_completion,
) -> batchmodels.OutputFile:
"""
create an output file spec that is information for uploading the output of the task matching the file_pattern to be
uploaded to the container as defined by the output_container_sas_url and the blob_path
Parameters
----------
file_pattern : str
Matching patterns to upload, e.g. ../std*.txt or **/output
output_container_sas_url : str
The container sas url to which to upload the matching file patterns. See :py:func:`AzureBlob.get_container_sas_url`
blob_path : str, optional
the blob_path within the output container where to place the matching files, by default '.'
Returns
-------
batchmodels.OutputFile
[description]
"""
return batchmodels.OutputFile(
file_pattern=file_pattern,
destination=batchmodels.OutputFileDestination(
container=batchmodels.OutputFileBlobContainerDestination(
container_url=output_container_sas_url, path=blob_path
)
),
upload_options=batchmodels.OutputFileUploadOptions(
upload_condition=upload_condition
),
)
def create_prep_task(
self,
task_name: str,
commands: str,
resource_files: list = None,
ostype: str = "windows",
elevation_level=batchmodels.ElevationLevel.admin,
) -> batchmodels.JobPreparationTask:
"""
Creates a task to run on a node before any tasks for a job are run. This creates the the task that is then
used to create a job with this prep task specified. See :py:func:`create_job`
Parameters
----------
task_name : str
Name of task
commands : str
commands to run. See :py:func:`wrap_commands_in_shell`
resource_files : list, optional
list of :py:func:'batchmodels.ResourceFile`, by default None
ostype : str, optional
name of os, either 'windows' or 'linux', by default 'windows'
Returns
-------
batchmodels.JobPreparationTask
"""
cmdline = self.wrap_commands_in_shell(commands, ostype)
prep_task = batchmodels.JobPreparationTask(
id=task_name,
command_line=cmdline,
resource_files=resource_files,
wait_for_success=True,
user_identity=batchmodels.UserIdentity(
auto_user=batchmodels.AutoUserSpecification(
scope=batchmodels.AutoUserScope.pool,
elevation_level=elevation_level,
)
),
)
return prep_task
def create_task_copy_file_to_shared_dir(
self,
container: str,
blob_path: str,
file_path: str,
shared_dir: str = "AZ_BATCH_NODE_SHARED_DIR",
ostype: str = "windows",
container_is_sas_url=False,
) -> batchmodels.JobPreparationTask:
"""
A special job prep task for the common use case of copying file from container blob to shared directory on node.
This is designed to be run as preperation task for a job to have this shared file available to the tasks that will subsequently run
on the node
Parameters
----------
container : str
Name of container in storage associate with the batch account
blob_path : str
Path to the blob within the container
file_path : str
Path to file on node
shared_dir : str, optional
share directory on node, by default 'AZ_BATCH_NODE_SHARED_DIR'
ostype : str, optional
'windows' or 'linux', by default 'windows'
Returns
-------
batchmodels.JobPreparationTask
the preperation task
"""
if container_is_sas_url:
input_file = batchmodels.ResourceFile(
http_url=container, file_path=file_path
)
else:
input_file = batchmodels.ResourceFile(
auto_storage_container_name=container,
blob_prefix=blob_path,
file_path=file_path,
)
cmdline = ""
if ostype == "windows":
cmdline = f"move {file_path}\\{blob_path}* %AZ_BATCH_NODE_SHARED_DIR%"
else:
cmdline = f"mv {file_path}/{blob_path}*" + " ${AZ_BATCH_NODE_SHARED_DIR}"
prep_task = self.create_prep_task(
"copy_file_task", [cmdline], resource_files=[input_file], ostype=ostype
)
return prep_task
def create_task(
self,
task_id: str,
command: str,
resource_files: list = None,
output_files: list = None,
env_settings: dict = None,
elevation_level: str = None,
num_instances: int = 1,
coordination_cmdline: str = None,
coordination_files: list = None,
container_settings: batchmodels.TaskContainerSettings = None,
depends_on: list = None,
):
"""
Create a task for the given input_file, command, output file specs and environment settings.
You need to add :py:func:'submit_task' to send it to batch service to run.
To build a command line, use :py:func:`wrap_commands_in_shell`
To build resource_files or coordination_files (batchmodels.ResourceFile) use :py:func:`create_input_file_spec`
To build output_files use :py:func:`create_output_file_spec`
Parameters
----------
task_id : str
The ID of the task to be added.
command : str
command line for the application.
resource_files : list, optional
list of input files to be downloaded before running task. batchmodels.ResourceFile
output_files : list, optional
patterns of output files and containers to upload to defined as batchmodels.OutputFileSpecs, default None
env_settings : dict, optional
environment variables as key (name) and values (value), by default None
elevation_level : str, optional
either 'admin' or 'non_admin'
num_instances : int, optional
The number of instances of this task (usually = 1 ), unless using MPI
coordination_cmdline : str, optional
coordination command line, usually for MP tasks
coordination_files : list, optional
list of common_files as batchmodels.ResourceFile, by default None
Returns
-------
batchmodels.TaskAddParameter
The task definition
"""
environment_settings = (
None
if env_settings is None
else [
batch.models.EnvironmentSetting(name=key, value=env_settings[key])
for key in env_settings
]
)
multi_instance_settings = None
if coordination_cmdline or (num_instances and num_instances > 1):
multi_instance_settings = batchmodels.MultiInstanceSettings(
number_of_instances=num_instances,
coordination_command_line=coordination_cmdline,
common_resource_files=coordination_files,
)
user = batchmodels.AutoUserSpecification(
scope=batchmodels.AutoUserScope.pool, elevation_level=elevation_level
)
return batchmodels.TaskAddParameter(
id=task_id,
command_line=command,
user_identity=batchmodels.UserIdentity(auto_user=user),
resource_files=resource_files,
environment_settings=environment_settings,
output_files=output_files,
multi_instance_settings=multi_instance_settings,
container_settings=container_settings,
depends_on=depends_on,
)
def submit_tasks(
self, job_id: str, tasks: list, tasks_per_request: int = 100, auto_complete=True
):
"""
submit tasks as a list.
There are limitations on size of request and also timeout. For this reason this task
submits tasks upto task_per_request
Parameters
----------
job_id : str
job id
tasks : list
list of batchmodels.TaskAddParameter. See :py:func:`create_task`
tasks_per_request : int, optional
tasks per request (grouped requests), by default 100
"""
for i in range(0, math.ceil(len(tasks) / tasks_per_request)):
try:
self.batch_client.task.add_collection(
job_id,
list(
tasks[
i * tasks_per_request : i * tasks_per_request
+ tasks_per_request
]
),
)
except batch.custom.custom_errors.CreateTasksErrorException as err:
self.print_task_exception(err)
raise err
except batchmodels.BatchErrorException as err:
self.print_batch_exception(err)
raise err
if auto_complete:
self.mark_job_termination_on_task_completion(job_id)
def submit_tasks_and_wait(
self,
job_id: str,
tasks: list,
tasks_per_request: int = 100,
timeout: datetime.timedelta = datetime.timedelta(minutes=30),
polling_interval_secs: int = 10,
):
"""
submit tasks as a list.
There are limitations on size of request and also timeout. For this reason this task
submits tasks upto task_per_request
Parameters
----------
job_id : str
job id
tasks : list
list of batchmodels.TaskAddParameter. See :py:func:`create_task`
tasks_per_request : int, optional
tasks per request (grouped requests), by default 100
timeout : datetime.timedelta,
how long to wait in minutes, by default 30 minutes
polling_interval_secs:
how often to check, by default 10 seconds
"""
try:
self.submit_tasks(self.batch_client, job_id, tasks)
# Pause execution until tasks reach Completed state.
self.wait_for_tasks_to_complete(
job_id, timeout, polling_interval_secs=polling_interval_secs
)
logger.info(
"Success! All tasks completed within the timeout period:", timeout
)
except batchmodels.BatchErrorException as err:
self.print_batch_exception(err)
raise
def delete_task(self, job_name: str, task_name: str):
"""
deletes tasks
Parameters
----------
job_name : str
job name
task_name : str
task name
"""
self.batch_client.task.delete(job_name, task_name)
def wait_for_subtasks_to_complete(
self,
job_id: str,
task_id: str,
timeout: datetime.timedelta,
polling_interval_secs: int = 10,
):
"""
Returns when all subtasks in the specified task reach the Completed state.
Parameters
----------
job_id : str
job id
task_id : str
task id
timeout : datetime.timedelta
how long to wait
polling_interval_secs : int, optional
how often to check, by default 10 secs
Raises
------
RuntimeError
If couldn't complete in timeout interval
"""
timeout_expiration = datetime.datetime.now() + timeout
logger.debug(
"Monitoring all tasks for 'Completed' state, timeout in {}...".format(
timeout
),
end="",
)
while datetime.datetime.now() < timeout_expiration:
subtasks = self.batch_client.task.list_subtasks(job_id, task_id)
incomplete_subtasks = [
subtask
for subtask in subtasks.value
if subtask.state != batchmodels.TaskState.completed
]
if not incomplete_subtasks:
return True
else:
time.sleep(polling_interval_secs)
raise RuntimeError(
"ERROR: Subtasks did not reach 'Completed' state within "
"timeout period of " + str(timeout)
)
def wait_for_tasks_to_complete(
self,
job_id: str,
timeout: datetime.timedelta = datetime.timedelta(minutes=10),
polling_interval_secs: int = 10,
):
"""
Returns when all tasks in the specified job reach the Completed state.
Parameters
----------
job_id : str
job id
timeout : datetime.timedelta, optional
how long to wait, by default datetime.timedelta(minutes=10)
polling_interval_secs : int, optional
how often to check, by default 10