-
Notifications
You must be signed in to change notification settings - Fork 44
/
google_v2_base.py
1634 lines (1364 loc) · 58.3 KB
/
google_v2_base.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
# Lint as: python3
# Copyright 2018 Verily Life Sciences Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Provider for running jobs on Google Cloud Platform.
This module serves as the base class for the google-v2 and google-cls-v2
providers. The APIs they are based on are very similar and can benefit from
sharing code.
"""
import ast
import json
import math
import operator
import os
import re
import sys
import textwrap
from . import base
from . import google_base
from . import google_v2_operations
from . import google_v2_pipelines
from . import google_v2_versions
from ..lib import dsub_util
from ..lib import job_model
from ..lib import param_util
from ..lib import providers_util
# Create file provider whitelist.
_SUPPORTED_FILE_PROVIDERS = frozenset([job_model.P_GCS])
_SUPPORTED_LOGGING_PROVIDERS = _SUPPORTED_FILE_PROVIDERS
_SUPPORTED_INPUT_PROVIDERS = _SUPPORTED_FILE_PROVIDERS
_SUPPORTED_OUTPUT_PROVIDERS = _SUPPORTED_FILE_PROVIDERS
# Action steps that interact with GCS need gsutil and Python.
# Use the 'slim' variant of the cloud-sdk image as it is much smaller.
_CLOUD_SDK_IMAGE = 'gcr.io/google.com/cloudsdktool/cloud-sdk:294.0.0-slim'
# This image is for an optional ssh container.
_SSH_IMAGE = 'gcr.io/cloud-genomics-pipelines/tools'
_DEFAULT_SSH_PORT = 22
# This image is for an optional mount on a bucket using GCS Fuse
_GCSFUSE_IMAGE = 'gcr.io/cloud-genomics-pipelines/gcsfuse:latest'
# Name of the data disk
_DATA_DISK_NAME = 'datadisk'
# Define a bash function for "echo" that includes timestamps
_LOG_MSG_FN = textwrap.dedent("""\
function get_datestamp() {
date "+%Y-%m-%d %H:%M:%S"
}
function log_info() {
echo "$(get_datestamp) INFO: $@"
}
function log_warning() {
1>&2 echo "$(get_datestamp) WARNING: $@"
}
function log_error() {
1>&2 echo "$(get_datestamp) ERROR: $@"
}
""")
# Define a bash function for "gsutil cp" to be used by the logging,
# localization, and delocalization actions.
_GSUTIL_CP_FN = textwrap.dedent("""\
function gsutil_cp() {
local src="${1}"
local dst="${2}"
local content_type="${3}"
local user_project_name="${4}"
local headers=""
if [[ -n "${content_type}" ]]; then
headers="-h Content-Type:${content_type}"
fi
local user_project_flag=""
if [[ -n "${user_project_name}" ]]; then
user_project_flag="-u ${user_project_name}"
fi
local attempt
for ((attempt = 0; attempt < 4; attempt++)); do
log_info "gsutil ${headers} ${user_project_flag} -mq cp \"${src}\" \"${dst}\""
if gsutil ${headers} ${user_project_flag} -mq cp "${src}" "${dst}"; then
return
fi
if (( attempt < 3 )); then
log_warning "Sleeping 10s before the next attempt of failed gsutil command"
log_warning "gsutil ${headers} ${user_project_flag} -mq cp \"${src}\" \"${dst}\""
sleep 10s
fi
done
log_error "gsutil ${headers} ${user_project_flag} -mq cp \"${src}\" \"${dst}\""
exit 1
}
function log_cp() {
local src="${1}"
local dst="${2}"
local tmp="${3}"
local check_src="${4}"
local user_project_name="${5}"
if [[ "${check_src}" == "true" ]] && [[ ! -e "${src}" ]]; then
return
fi
# Copy the log files to a local temporary location so that our "gsutil cp" is never
# executed on a file that is changing.
local tmp_path="${tmp}/$(basename ${src})"
cp "${src}" "${tmp_path}"
gsutil_cp "${tmp_path}" "${dst}" "text/plain" "${user_project_name}"
}
""")
# Define a bash function for "gsutil rsync" to be used by the logging,
# localization, and delocalization actions.
_GSUTIL_RSYNC_FN = textwrap.dedent("""\
function gsutil_rsync() {
local src="${1}"
local dst="${2}"
local user_project_name="${3}"
local user_project_flag=""
if [[ -n "${user_project_name}" ]]; then
user_project_flag="-u ${user_project_name}"
fi
local attempt
for ((attempt = 0; attempt < 4; attempt++)); do
log_info "gsutil ${user_project_flag} -mq rsync -r \"${src}\" \"${dst}\""
if gsutil ${user_project_flag} -mq rsync -r "${src}" "${dst}"; then
return
fi
if (( attempt < 3 )); then
log_warning "Sleeping 10s before the next attempt of failed gsutil command"
log_warning "gsutil ${user_project_flag} -mq rsync -r \"${src}\" \"${dst}\""
sleep 10s
fi
done
log_error "gsutil ${user_project_flag} -mq rsync -r \"${src}\" \"${dst}\""
exit 1
}
""")
# The logging in v2alpha1 is different than in v1alpha2.
# v1alpha2 would provide:
# [your_path].log: Logging of the on-instance "controller" code that the
# Google Pipelines API ran.
# [your_path]-stdout.log: stdout logging for the user command
# [your_path]-stderr.log: stderr logging for the user command
#
# v2alpha1 allows provides:
# /google/logs/output: <all container output>
# /google/logs/action/<action-number>/stdout: stdout logging of the action
# /google/logs/action/<action-number>/stderr: stderr logging of the action
#
# We explicitly copy off the logs, simulating v1alpha2 behavior.
# If the logging commands fail, there is currently no useful information in
# the operation to indicate why it failed.
_LOG_CP_CMD = textwrap.dedent("""\
mkdir -p /tmp/{logging_action}
log_cp /google/logs/action/{user_action}/stdout "${{STDOUT_PATH}}" /tmp/{logging_action} "true" "${{USER_PROJECT}}" &
STDOUT_PID=$!
log_cp /google/logs/action/{user_action}/stderr "${{STDERR_PATH}}" /tmp/{logging_action} "true" "${{USER_PROJECT}}" &
STDERR_PID=$!
log_cp /google/logs/output "${{LOGGING_PATH}}" /tmp/{logging_action} "false" "${{USER_PROJECT}}" &
LOG_PID=$!
wait "${{STDOUT_PID}}"
wait "${{STDERR_PID}}"
wait "${{LOG_PID}}"
""")
_LOGGING_CMD = textwrap.dedent("""\
set -o errexit
set -o nounset
set -o pipefail
{log_msg_fn}
{log_cp_fn}
{log_cp_cmd}
""")
# Keep logging until the final logging action starts
_CONTINUOUS_LOGGING_CMD = textwrap.dedent("""\
set -o errexit
set -o nounset
set -o pipefail
{log_msg_fn}
{log_cp_fn}
while [[ ! -d /google/logs/action/{final_logging_action} ]]; do
{log_cp_cmd}
sleep {log_interval}
done
""")
_LOCALIZATION_LOOP = textwrap.dedent("""\
set -o errexit
set -o nounset
set -o pipefail
for ((i=0; i < INPUT_COUNT; i++)); do
INPUT_VAR="INPUT_${i}"
INPUT_RECURSIVE="INPUT_RECURSIVE_${i}"
INPUT_SRC="INPUT_SRC_${i}"
INPUT_DST="INPUT_DST_${i}"
log_info "Localizing ${!INPUT_VAR}"
if [[ "${!INPUT_RECURSIVE}" -eq "1" ]]; then
gsutil_rsync "${!INPUT_SRC}" "${!INPUT_DST}" "${USER_PROJECT}"
else
gsutil_cp "${!INPUT_SRC}" "${!INPUT_DST}" "" "${USER_PROJECT}"
fi
done
""")
_DELOCALIZATION_LOOP = textwrap.dedent("""\
set -o errexit
set -o nounset
set -o pipefail
for ((i=0; i < OUTPUT_COUNT; i++)); do
OUTPUT_VAR="OUTPUT_${i}"
OUTPUT_RECURSIVE="OUTPUT_RECURSIVE_${i}"
OUTPUT_SRC="OUTPUT_SRC_${i}"
OUTPUT_DST="OUTPUT_DST_${i}"
log_info "Delocalizing ${!OUTPUT_VAR}"
if [[ "${!OUTPUT_RECURSIVE}" -eq "1" ]]; then
gsutil_rsync "${!OUTPUT_SRC}" "${!OUTPUT_DST}" "${USER_PROJECT}"
else
gsutil_cp "${!OUTPUT_SRC}" "${!OUTPUT_DST}" "" "${USER_PROJECT}"
fi
done
""")
_LOCALIZATION_CMD = textwrap.dedent("""\
{log_msg_fn}
{recursive_cp_fn}
{cp_fn}
{cp_loop}
""")
# Command to create the directories for the dsub user environment
_MK_RUNTIME_DIRS_CMD = '\n'.join('mkdir -m 777 -p "%s" ' % dir for dir in [
providers_util.SCRIPT_DIR, providers_util.TMP_DIR,
providers_util.WORKING_DIR
])
# The user's script or command is made available to the container in
# /mnt/data/script/<script-name>
#
# To get it there, it is passed in through the environment in the "prepare"
# action and "echo"-ed to a file.
#
# Pipelines v2alpha1 uses Docker environment files which do not support
# multi-line environment variables, so we encode the script using Python's
# repr() function and then decoded it using ast.literal_eval().
# This has the advantage over other encoding schemes (such as base64) of being
# user-readable in the Genomics "operation" object.
_SCRIPT_VARNAME = '_SCRIPT_REPR'
_META_YAML_VARNAME = '_META_YAML_REPR'
_PYTHON_DECODE_SCRIPT = textwrap.dedent("""\
import ast
import sys
sys.stdout.write(ast.literal_eval(sys.stdin.read()))
""")
_MK_IO_DIRS = textwrap.dedent("""\
for ((i=0; i < DIR_COUNT; i++)); do
DIR_VAR="DIR_${i}"
log_info "mkdir -m 777 -p \"${!DIR_VAR}\""
mkdir -m 777 -p "${!DIR_VAR}"
done
""")
_PREPARE_CMD = textwrap.dedent("""\
#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
{log_msg_fn}
{mk_runtime_dirs}
echo "${{{script_var}}}" \
| python -c '{python_decode_script}' \
> "{script_path}"
chmod a+x "{script_path}"
{mk_io_dirs}
""")
_USER_CMD = textwrap.dedent("""\
export TMPDIR="{tmp_dir}"
cd {working_dir}
"{user_script}"
""")
_ACTION_LOGGING = 'logging'
_ACTION_PREPARE = 'prepare'
_ACTION_LOCALIZATION = 'localization'
_ACTION_USER_COMMAND = 'user-command'
_ACTION_DELOCALIZATION = 'delocalization'
_ACTION_FINAL_LOGGING = 'final_logging'
_FILTER_ACTIONS = [_ACTION_LOGGING, _ACTION_PREPARE, _ACTION_FINAL_LOGGING]
_FILTERED_EVENT_REGEXES = [
re.compile('^Started running "({})"$'.format('|'.join(_FILTER_ACTIONS))),
re.compile('Stopped pulling'),
re.compile('Stopped running'),
# An error causes two events, one we capture and one is filtered out.
re.compile('Execution failed: action 4: unexpected exit status [\\d]{1,4}')
]
_ABORT_REGEX = re.compile('The operation was cancelled')
_FAIL_REGEX = re.compile(
'^Unexpected exit status [\\d]{1,4} while running "user-command"$')
_EVENT_REGEX_MAP = {
'start': re.compile('^Worker ".*" assigned in ".*".*$'),
'pulling-image': re.compile('^Started pulling "(.*)"$'),
'localizing-files': re.compile('^Started running "localization"$'),
'running-docker': re.compile('^Started running "user-command"$'),
'delocalizing-files': re.compile('^Started running "delocalization"$'),
'ok': re.compile('^Worker released$'),
'fail': _FAIL_REGEX,
'canceled': _ABORT_REGEX,
}
class GoogleV2EventMap(object):
"""Helper for extracing a set of normalized, filtered operation events."""
def __init__(self, op):
self._op = op
def get_filtered_normalized_events(self):
"""Filter the granular v2 events down to events of interest.
Filter through the large number of granular events returned by the
pipelines API, and extract only those that are interesting to a user. This
is implemented by filtering out events which are known to be uninteresting
(i.e. the default actions run for every job) and by explicitly matching
specific events which are interesting and mapping those to v1 style naming.
Events which are not whitelisted or blacklisted will still be output,
meaning any events which are added in the future won't be masked.
We don't want to suppress display of events that we don't recognize.
They may be important.
Returns:
A list of maps containing the normalized, filtered events.
"""
# Need the user-image to look for the right "pulling image" event
user_image = google_v2_operations.get_action_image(self._op,
_ACTION_USER_COMMAND)
# Only create an "ok" event for operations with SUCCESS status.
need_ok = google_v2_operations.is_success(self._op)
# Events are keyed by name for easier deletion.
events = {}
# Events are assumed to be ordered by timestamp (newest to oldest).
for event in google_v2_operations.get_events(self._op):
if self._filter(event):
continue
mapped, match = self._map(event)
name = mapped['name']
if name == 'ok':
# If we want the "ok" event, we grab the first (most recent).
if not need_ok or 'ok' in events:
continue
if name == 'pulling-image':
if match and match.group(1) != user_image:
continue
events[name] = mapped
return sorted(list(events.values()), key=operator.itemgetter('start-time'))
def _map(self, event):
"""Extract elements from an operation event and map to a named event."""
description = event.get('description', '')
start_time = google_base.parse_rfc3339_utc_string(
event.get('timestamp', ''))
for name, regex in _EVENT_REGEX_MAP.items():
match = regex.match(description)
if match:
return {'name': name, 'start-time': start_time}, match
return {'name': description, 'start-time': start_time}, None
def _filter(self, event):
for regex in _FILTERED_EVENT_REGEXES:
if regex.match(event.get('description', '')):
return True
return False
class GoogleV2BatchHandler(object):
"""Implement the HttpBatch interface to enable simple serial batches."""
# The v2alpha1 batch endpoint is not currently implemented.
# When it is, this can be replaced by service.new_batch_http_request.
def __init__(self, callback):
self._cancel_list = []
self._response_handler = callback
def add(self, cancel_fn, request_id):
self._cancel_list.append((request_id, cancel_fn))
def execute(self):
for (request_id, cancel_fn) in self._cancel_list:
response = None
exception = None
try:
response = cancel_fn.execute()
except: # pylint: disable=bare-except
exception = sys.exc_info()[1]
self._response_handler(request_id, response, exception)
class GoogleV2JobProviderBase(base.JobProvider):
"""dsub provider implementation managing Jobs on Google Cloud."""
def __init__(self, provider_name, api_version, credentials, project, dry_run):
google_v2_pipelines.set_api_version(api_version)
google_v2_operations.set_api_version(api_version)
service = google_base.setup_service(
google_v2_versions.get_api_name(api_version), api_version, credentials)
storage_service = dsub_util.get_storage_service(credentials=credentials)
self._provider_name = provider_name
self._service = service
self._project = project
self._dry_run = dry_run
self._storage_service = storage_service
def _get_pipeline_regions(self, regions, zones):
"""Returns the list of regions to use for a pipeline request."""
raise NotImplementedError('Derived class must implement this function')
def _pipelines_run_api(self, request):
"""Executes the provider-specific pipelines.run() API."""
raise NotImplementedError('Derived class must implement this function')
def _operations_list_api(self, ops_filter, page_token, page_size):
"""Executes the provider-specific operaitons.list() API."""
raise NotImplementedError('Derived class must implement this function')
def _operations_cancel_api_def(self):
"""Returns a function object for the provider-specific cancel API."""
raise NotImplementedError('Derived class must implement this function')
def _batch_handler_def(self):
"""Returns a function object for the provider-specific batch handler."""
raise NotImplementedError('Derived class must implement this function')
def prepare_job_metadata(self, script, job_name, user_id):
"""Returns a dictionary of metadata fields for the job."""
return providers_util.prepare_job_metadata(script, job_name, user_id)
def _get_logging_env(self, logging_uri, user_project):
"""Returns the environment for actions that copy logging files."""
if not logging_uri.endswith('.log'):
raise ValueError('Logging URI must end in ".log": {}'.format(logging_uri))
logging_prefix = logging_uri[:-len('.log')]
return {
'LOGGING_PATH': '{}.log'.format(logging_prefix),
'STDOUT_PATH': '{}-stdout.log'.format(logging_prefix),
'STDERR_PATH': '{}-stderr.log'.format(logging_prefix),
'USER_PROJECT': user_project,
}
def _get_prepare_env(self, script, job_descriptor, inputs, outputs, mounts):
"""Return a dict with variables for the 'prepare' action."""
# Add the _SCRIPT_REPR with the repr(script) contents
# Add the _META_YAML_REPR with the repr(meta) contents
# Add variables for directories that need to be created, for example:
# DIR_COUNT: 2
# DIR_0: /mnt/data/input/gs/bucket/path1/
# DIR_1: /mnt/data/output/gs/bucket/path2
# List the directories in sorted order so that they are created in that
# order. This is primarily to ensure that permissions are set as we create
# each directory.
# For example:
# mkdir -m 777 -p /root/first/second
# mkdir -m 777 -p /root/first
# *may* not actually set 777 on /root/first
docker_paths = sorted([
var.docker_path if var.recursive else os.path.dirname(var.docker_path)
for var in inputs | outputs | mounts
if var.value
])
env = {
_SCRIPT_VARNAME: repr(script.value),
_META_YAML_VARNAME: repr(job_descriptor.to_yaml()),
'DIR_COUNT': str(len(docker_paths))
}
for idx, path in enumerate(docker_paths):
env['DIR_{}'.format(idx)] = os.path.join(providers_util.DATA_MOUNT_POINT,
path)
return env
def _get_localization_env(self, inputs, user_project):
"""Return a dict with variables for the 'localization' action."""
# Add variables for paths that need to be localized, for example:
# INPUT_COUNT: 1
# INPUT_0: MY_INPUT_FILE
# INPUT_RECURSIVE_0: 0
# INPUT_SRC_0: gs://mybucket/mypath/myfile
# INPUT_DST_0: /mnt/data/inputs/mybucket/mypath/myfile
non_empty_inputs = [var for var in inputs if var.value]
env = {'INPUT_COUNT': str(len(non_empty_inputs))}
for idx, var in enumerate(non_empty_inputs):
env['INPUT_{}'.format(idx)] = var.name
env['INPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive))
env['INPUT_SRC_{}'.format(idx)] = var.value
# For wildcard paths, the destination must be a directory
dst = os.path.join(providers_util.DATA_MOUNT_POINT, var.docker_path)
path, filename = os.path.split(dst)
if '*' in filename:
dst = '{}/'.format(path)
env['INPUT_DST_{}'.format(idx)] = dst
env['USER_PROJECT'] = user_project
return env
def _get_delocalization_env(self, outputs, user_project):
"""Return a dict with variables for the 'delocalization' action."""
# Add variables for paths that need to be delocalized, for example:
# OUTPUT_COUNT: 1
# OUTPUT_0: MY_OUTPUT_FILE
# OUTPUT_RECURSIVE_0: 0
# OUTPUT_SRC_0: gs://mybucket/mypath/myfile
# OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile
non_empty_outputs = [var for var in outputs if var.value]
env = {'OUTPUT_COUNT': str(len(non_empty_outputs))}
for idx, var in enumerate(non_empty_outputs):
env['OUTPUT_{}'.format(idx)] = var.name
env['OUTPUT_RECURSIVE_{}'.format(idx)] = str(int(var.recursive))
env['OUTPUT_SRC_{}'.format(idx)] = os.path.join(
providers_util.DATA_MOUNT_POINT, var.docker_path)
# For wildcard paths, the destination must be a directory
if '*' in var.uri.basename:
dst = var.uri.path
else:
dst = var.uri
env['OUTPUT_DST_{}'.format(idx)] = dst
env['USER_PROJECT'] = user_project
return env
def _build_user_environment(self, envs, inputs, outputs, mounts):
"""Returns a dictionary of for the user container environment."""
envs = {env.name: env.value for env in envs}
envs.update(providers_util.get_file_environment_variables(inputs))
envs.update(providers_util.get_file_environment_variables(outputs))
envs.update(providers_util.get_file_environment_variables(mounts))
return envs
def _get_mount_actions(self, mounts, mnt_datadisk):
"""Returns a list of two actions per gcs bucket to mount."""
actions_to_add = []
for mount in mounts:
bucket = mount.value[len('gs://'):]
mount_path = mount.docker_path
actions_to_add.extend([
google_v2_pipelines.build_action(
name='mount-{}'.format(bucket),
enable_fuse=True,
run_in_background=True,
image_uri=_GCSFUSE_IMAGE,
mounts=[mnt_datadisk],
commands=[
'--implicit-dirs', '--foreground', '-o ro', bucket,
os.path.join(providers_util.DATA_MOUNT_POINT, mount_path)
]),
google_v2_pipelines.build_action(
name='mount-wait-{}'.format(bucket),
enable_fuse=True,
image_uri=_GCSFUSE_IMAGE,
mounts=[mnt_datadisk],
commands=[
'wait',
os.path.join(providers_util.DATA_MOUNT_POINT, mount_path)
])
])
return actions_to_add
def _build_pipeline_request(self, task_view):
"""Returns a Pipeline objects for the task."""
job_metadata = task_view.job_metadata
job_params = task_view.job_params
job_resources = task_view.job_resources
task_metadata = task_view.task_descriptors[0].task_metadata
task_params = task_view.task_descriptors[0].task_params
task_resources = task_view.task_descriptors[0].task_resources
# Set up VM-specific variables
mnt_datadisk = google_v2_pipelines.build_mount(
disk=_DATA_DISK_NAME,
path=providers_util.DATA_MOUNT_POINT,
read_only=False)
scopes = job_resources.scopes or google_base.DEFAULT_SCOPES
# Set up the task labels
labels = {
label.name: label.value if label.value else '' for label in
google_base.build_pipeline_labels(job_metadata, task_metadata)
| job_params['labels'] | task_params['labels']
}
# Set local variables for the core pipeline values
script = task_view.job_metadata['script']
user_project = task_view.job_metadata['user-project'] or ''
envs = job_params['envs'] | task_params['envs']
inputs = job_params['inputs'] | task_params['inputs']
outputs = job_params['outputs'] | task_params['outputs']
mounts = job_params['mounts']
gcs_mounts = param_util.get_gcs_mounts(mounts)
persistent_disk_mount_params = param_util.get_persistent_disk_mounts(mounts)
# pylint: disable=g-complex-comprehension
persistent_disks = [
google_v2_pipelines.build_disk(
name=disk.name.replace('_', '-'), # Underscores not allowed
size_gb=disk.disk_size or job_model.DEFAULT_MOUNTED_DISK_SIZE,
source_image=disk.value,
disk_type=disk.disk_type or job_model.DEFAULT_DISK_TYPE)
for disk in persistent_disk_mount_params
]
persistent_disk_mounts = [
google_v2_pipelines.build_mount(
disk=persistent_disk.get('name'),
path=os.path.join(providers_util.DATA_MOUNT_POINT,
persistent_disk_mount_param.docker_path),
read_only=True)
for persistent_disk, persistent_disk_mount_param in zip(
persistent_disks, persistent_disk_mount_params)
]
# pylint: enable=g-complex-comprehension
# The list of "actions" (1-based) will be:
# 1- continuous copy of log files off to Cloud Storage
# 2- prepare the shared mount point (write the user script)
# 3- localize objects from Cloud Storage to block storage
# 4- execute user command
# 5- delocalize objects from block storage to Cloud Storage
# 6- final copy of log files off to Cloud Storage
#
# If the user has requested an SSH server be started, it will be inserted
# after logging is started, and all subsequent action numbers above will be
# incremented by 1.
# If the user has requested to mount one or more buckets, two actions per
# bucket will be inserted after the prepare step, and all subsequent action
# numbers will be incremented by the number of actions added.
#
# We need to track the action numbers specifically for the user action and
# the final logging action.
optional_actions = 0
if job_resources.ssh:
optional_actions += 1
mount_actions = self._get_mount_actions(gcs_mounts, mnt_datadisk)
optional_actions += len(mount_actions)
user_action = 4 + optional_actions
final_logging_action = 6 + optional_actions
# Set up the commands and environment for the logging actions
logging_cmd = _LOGGING_CMD.format(
log_msg_fn=_LOG_MSG_FN,
log_cp_fn=_GSUTIL_CP_FN,
log_cp_cmd=_LOG_CP_CMD.format(
user_action=user_action, logging_action='logging_action'))
continuous_logging_cmd = _CONTINUOUS_LOGGING_CMD.format(
log_msg_fn=_LOG_MSG_FN,
log_cp_fn=_GSUTIL_CP_FN,
log_cp_cmd=_LOG_CP_CMD.format(
user_action=user_action,
logging_action='continuous_logging_action'),
final_logging_action=final_logging_action,
log_interval=job_resources.log_interval or '60s')
logging_env = self._get_logging_env(task_resources.logging_path.uri,
user_project)
# Set up command and environments for the prepare, localization, user,
# and de-localization actions
script_path = os.path.join(providers_util.SCRIPT_DIR, script.name)
prepare_command = _PREPARE_CMD.format(
log_msg_fn=_LOG_MSG_FN,
mk_runtime_dirs=_MK_RUNTIME_DIRS_CMD,
script_var=_SCRIPT_VARNAME,
python_decode_script=_PYTHON_DECODE_SCRIPT,
script_path=script_path,
mk_io_dirs=_MK_IO_DIRS)
prepare_env = self._get_prepare_env(script, task_view, inputs, outputs,
mounts)
localization_env = self._get_localization_env(inputs, user_project)
user_environment = self._build_user_environment(envs, inputs, outputs,
mounts)
delocalization_env = self._get_delocalization_env(outputs, user_project)
# When --ssh is enabled, run all actions in the same process ID namespace
pid_namespace = 'shared' if job_resources.ssh else None
# Build the list of actions
actions = []
actions.append(
google_v2_pipelines.build_action(
name='logging',
pid_namespace=pid_namespace,
run_in_background=True,
image_uri=_CLOUD_SDK_IMAGE,
environment=logging_env,
entrypoint='/bin/bash',
commands=['-c', continuous_logging_cmd]))
if job_resources.ssh:
actions.append(
google_v2_pipelines.build_action(
name='ssh',
pid_namespace=pid_namespace,
image_uri=_SSH_IMAGE,
mounts=[mnt_datadisk],
entrypoint='ssh-server',
port_mappings={_DEFAULT_SSH_PORT: _DEFAULT_SSH_PORT},
run_in_background=True))
actions.append(
google_v2_pipelines.build_action(
name='prepare',
pid_namespace=pid_namespace,
image_uri=_CLOUD_SDK_IMAGE,
mounts=[mnt_datadisk],
environment=prepare_env,
entrypoint='/bin/bash',
commands=['-c', prepare_command]),)
actions.extend(mount_actions)
actions.extend([
google_v2_pipelines.build_action(
name='localization',
pid_namespace=pid_namespace,
image_uri=_CLOUD_SDK_IMAGE,
mounts=[mnt_datadisk],
environment=localization_env,
entrypoint='/bin/bash',
commands=[
'-c',
_LOCALIZATION_CMD.format(
log_msg_fn=_LOG_MSG_FN,
recursive_cp_fn=_GSUTIL_RSYNC_FN,
cp_fn=_GSUTIL_CP_FN,
cp_loop=_LOCALIZATION_LOOP)
]),
google_v2_pipelines.build_action(
name='user-command',
pid_namespace=pid_namespace,
block_external_network=job_resources.block_external_network,
image_uri=job_resources.image,
mounts=[mnt_datadisk] + persistent_disk_mounts,
environment=user_environment,
entrypoint='/usr/bin/env',
commands=[
'bash', '-c',
_USER_CMD.format(
tmp_dir=providers_util.TMP_DIR,
working_dir=providers_util.WORKING_DIR,
user_script=script_path)
]),
google_v2_pipelines.build_action(
name='delocalization',
pid_namespace=pid_namespace,
image_uri=_CLOUD_SDK_IMAGE,
mounts=[mnt_datadisk],
environment=delocalization_env,
entrypoint='/bin/bash',
commands=[
'-c',
_LOCALIZATION_CMD.format(
log_msg_fn=_LOG_MSG_FN,
recursive_cp_fn=_GSUTIL_RSYNC_FN,
cp_fn=_GSUTIL_CP_FN,
cp_loop=_DELOCALIZATION_LOOP)
]),
google_v2_pipelines.build_action(
name='final_logging',
pid_namespace=pid_namespace,
always_run=True,
image_uri=_CLOUD_SDK_IMAGE,
environment=logging_env,
entrypoint='/bin/bash',
commands=['-c', logging_cmd]),
])
assert len(actions) - 2 == user_action
assert len(actions) == final_logging_action
# Prepare the VM (resources) configuration
disks = [
google_v2_pipelines.build_disk(
_DATA_DISK_NAME,
job_resources.disk_size,
source_image=None,
disk_type=job_resources.disk_type or job_model.DEFAULT_DISK_TYPE)
]
disks.extend(persistent_disks)
network = google_v2_pipelines.build_network(
job_resources.network, job_resources.subnetwork,
job_resources.use_private_address)
if job_resources.machine_type:
machine_type = job_resources.machine_type
elif job_resources.min_cores or job_resources.min_ram:
machine_type = GoogleV2CustomMachine.build_machine_type(
job_resources.min_cores, job_resources.min_ram)
else:
machine_type = job_model.DEFAULT_MACHINE_TYPE
accelerators = None
if job_resources.accelerator_type:
accelerators = [
google_v2_pipelines.build_accelerator(job_resources.accelerator_type,
job_resources.accelerator_count)
]
service_account = google_v2_pipelines.build_service_account(
job_resources.service_account or 'default', scopes)
resources = google_v2_pipelines.build_resources(
self._project,
self._get_pipeline_regions(job_resources.regions, job_resources.zones),
google_base.get_zones(job_resources.zones),
google_v2_pipelines.build_machine(
network=network,
machine_type=machine_type,
# Preemptible comes from task_resources because it may change
# on retry attempts
preemptible=task_resources.preemptible,
service_account=service_account,
boot_disk_size_gb=job_resources.boot_disk_size,
disks=disks,
accelerators=accelerators,
nvidia_driver_version=job_resources.nvidia_driver_version,
labels=labels,
cpu_platform=job_resources.cpu_platform,
enable_stackdriver_monitoring=job_resources
.enable_stackdriver_monitoring),
)
# Build the pipeline request
pipeline = google_v2_pipelines.build_pipeline(actions, resources, None,
job_resources.timeout)
return {'pipeline': pipeline, 'labels': labels}
def _submit_pipeline(self, request):
google_base_api = google_base.Api()
operation = google_base_api.execute(self._pipelines_run_api(request))
print('Provider internal-id (operation): {}'.format(operation['name']))
return GoogleOperation(self._provider_name, operation).get_field('task-id')
def submit_job(self, job_descriptor, skip_if_output_present):
"""Submit the job (or tasks) to be executed.
Args:
job_descriptor: all parameters needed to launch all job tasks
skip_if_output_present: (boolean) if true, skip tasks whose output
is present (see --skip flag for more explanation).
Returns:
A dictionary containing the 'user-id', 'job-id', and 'task-id' list.
For jobs that are not task array jobs, the task-id list should be empty.
Raises:
ValueError: if job resources or task data contain illegal values.
"""
# Validate task data and resources.
param_util.validate_submit_args_or_fail(
job_descriptor,
provider_name=self._provider_name,
input_providers=_SUPPORTED_INPUT_PROVIDERS,
output_providers=_SUPPORTED_OUTPUT_PROVIDERS,
logging_providers=_SUPPORTED_LOGGING_PROVIDERS)
# Prepare and submit jobs.
launched_tasks = []
requests = []
for task_view in job_model.task_view_generator(job_descriptor):
job_params = task_view.job_params
task_params = task_view.task_descriptors[0].task_params
outputs = job_params['outputs'] | task_params['outputs']
if skip_if_output_present:
# check whether the output's already there
if dsub_util.outputs_are_present(outputs, self._storage_service):
print('Skipping task because its outputs are present')
continue
request = self._build_pipeline_request(task_view)
if self._dry_run:
requests.append(request)
else:
task_id = self._submit_pipeline(request)
launched_tasks.append(task_id)
# If this is a dry-run, emit all the pipeline request objects
if self._dry_run:
print(
json.dumps(
requests, indent=2, sort_keys=True, separators=(',', ': ')))
if not requests and not launched_tasks:
return {'job-id': dsub_util.NO_JOB}
return {
'job-id': job_descriptor.job_metadata['job-id'],
'user-id': job_descriptor.job_metadata['user-id'],
'task-id': [task_id for task_id in launched_tasks if task_id],
}
def get_tasks_completion_messages(self, tasks):
completion_messages = []
for task in tasks:
completion_messages.append(task.error_message())
return completion_messages
def _get_status_filters(self, statuses):
if not statuses or statuses == {'*'}:
return None