/
io.py
3064 lines (2595 loc) · 106 KB
/
io.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
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
""" Set of interfaces that allow interaction with data. Currently
available interfaces are:
DataSource: Generic nifti to named Nifti interface
DataSink: Generic named output from interfaces to data store
XNATSource: preliminary interface to XNAT
To come :
XNATSink
"""
import glob
import fnmatch
import string
import json
import os
import os.path as op
import shutil
import subprocess
import re
import copy
import tempfile
from os.path import join, dirname
from warnings import warn
from .. import config, logging
from ..utils.filemanip import (
copyfile,
simplify_list,
ensure_list,
get_related_files,
split_filename,
)
from ..utils.misc import human_order_sorted, str2bool
from .base import (
TraitedSpec,
traits,
Str,
File,
Directory,
BaseInterface,
InputMultiPath,
isdefined,
OutputMultiPath,
DynamicTraitedSpec,
Undefined,
BaseInterfaceInputSpec,
LibraryBaseInterface,
SimpleInterface,
)
iflogger = logging.getLogger("nipype.interface")
def copytree(src, dst, use_hardlink=False):
"""Recursively copy a directory tree using
nipype.utils.filemanip.copyfile()
This is not a thread-safe routine. However, in the case of creating new
directories, it checks to see if a particular directory has already been
created by another process.
"""
names = os.listdir(src)
try:
os.makedirs(dst)
except OSError as why:
if "File exists" in why.strerror:
pass
else:
raise why
errors = []
for name in names:
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if os.path.isdir(srcname):
copytree(srcname, dstname, use_hardlink)
else:
copyfile(
srcname,
dstname,
True,
hashmethod="content",
use_hardlink=use_hardlink,
)
except (IOError, os.error) as why:
errors.append((srcname, dstname, str(why)))
# catch the Error from the recursive copytree so that we can
# continue with other files
except Exception as err:
errors.extend(err.args[0])
if errors:
raise Exception(errors)
def add_traits(base, names, trait_type=None):
"""Add traits to a traited class.
All traits are set to Undefined by default
"""
if trait_type is None:
trait_type = traits.Any
undefined_traits = {}
for key in names:
base.add_trait(key, trait_type)
undefined_traits[key] = Undefined
base.trait_set(trait_change_notify=False, **undefined_traits)
# access each trait
for key in names:
_ = getattr(base, key)
return base
def _get_head_bucket(s3_resource, bucket_name):
"""Try to get the header info of a bucket, in order to
check if it exists and its permissions
"""
import botocore
# Try fetch the bucket with the name argument
try:
s3_resource.meta.client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as exc:
error_code = int(exc.response["Error"]["Code"])
if error_code == 403:
err_msg = "Access to bucket: %s is denied; check credentials" % bucket_name
raise Exception(err_msg)
elif error_code == 404:
err_msg = (
"Bucket: %s does not exist; check spelling and try "
"again" % bucket_name
)
raise Exception(err_msg)
else:
err_msg = "Unable to connect to bucket: %s. Error message:\n%s" % (
bucket_name,
exc,
)
except Exception as exc:
err_msg = "Unable to connect to bucket: %s. Error message:\n%s" % (
bucket_name,
exc,
)
raise Exception(err_msg)
class IOBase(BaseInterface):
def _run_interface(self, runtime):
return runtime
def _list_outputs(self):
raise NotImplementedError
def _outputs(self):
return self._add_output_traits(super(IOBase, self)._outputs())
def _add_output_traits(self, base):
return base
# Class to track percentage of S3 file upload
class ProgressPercentage(object):
"""
Callable class instsance (via __call__ method) that displays
upload percentage of a file to S3
"""
def __init__(self, filename):
""" """
# Import packages
import threading
# Initialize data attributes
self._filename = filename
self._size = float(os.path.getsize(filename))
self._seen_so_far = 0
self._lock = threading.Lock()
def __call__(self, bytes_amount):
""" """
# Import packages
import sys
# With the lock on, print upload status
with self._lock:
self._seen_so_far += bytes_amount
if self._size != 0:
percentage = (self._seen_so_far // self._size) * 100
else:
percentage = 0
progress_str = "%d / %d (%.2f%%)\r" % (
self._seen_so_far,
self._size,
percentage,
)
# Write to stdout
sys.stdout.write(progress_str)
sys.stdout.flush()
# DataSink inputs
class DataSinkInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec):
""" """
# Init inputspec data attributes
base_directory = Str(desc="Path to the base directory for storing data.")
container = Str(desc="Folder within base directory in which to store output")
parameterization = traits.Bool(
True, usedefault=True, desc="store output in parametrized structure"
)
strip_dir = Str(desc="path to strip out of filename")
substitutions = InputMultiPath(
traits.Tuple(Str, Str),
desc=(
"List of 2-tuples reflecting string "
"to substitute and string to replace "
"it with"
),
)
regexp_substitutions = InputMultiPath(
traits.Tuple(Str, Str),
desc=(
"List of 2-tuples reflecting a pair of a "
"Python regexp pattern and a replacement "
"string. Invoked after string `substitutions`"
),
)
_outputs = traits.Dict(Str, value={}, usedefault=True)
remove_dest_dir = traits.Bool(
False, usedefault=True, desc="remove dest directory when copying dirs"
)
# AWS S3 data attributes
creds_path = Str(
desc="Filepath to AWS credentials file for S3 bucket "
"access; if not specified, the credentials will "
"be taken from the AWS_ACCESS_KEY_ID and "
"AWS_SECRET_ACCESS_KEY environment variables"
)
encrypt_bucket_keys = traits.Bool(
desc="Flag indicating whether to use S3 " "server-side AES-256 encryption"
)
# Set this if user wishes to override the bucket with their own
bucket = traits.Any(desc="Boto3 S3 bucket for manual override of bucket")
# Set this if user wishes to have local copy of files as well
local_copy = Str(desc="Copy files locally as well as to S3 bucket")
# Set call-able inputs attributes
def __setattr__(self, key, value):
if key not in self.copyable_trait_names():
if not isdefined(value):
super(DataSinkInputSpec, self).__setattr__(key, value)
self._outputs[key] = value
else:
if key in self._outputs:
self._outputs[key] = value
super(DataSinkInputSpec, self).__setattr__(key, value)
# DataSink outputs
class DataSinkOutputSpec(TraitedSpec):
# Init out file
out_file = traits.Any(desc="datasink output")
# Custom DataSink class
class DataSink(IOBase):
"""
Generic datasink module to store structured outputs.
Primarily for use within a workflow. This interface allows arbitrary
creation of input attributes. The names of these attributes define the
directory structure to create for storage of the files or directories.
The attributes take the following form::
string[[.[@]]string[[.[@]]string]] ...
where parts between ``[]`` are optional.
An attribute such as contrasts.@con will create a 'contrasts' directory
to store the results linked to the attribute. If the ``@`` is left out, such
as in 'contrasts.con', a subdirectory 'con' will be created under
'contrasts'.
The general form of the output is::
'base_directory/container/parameterization/destloc/filename'
``destloc = string[[.[@]]string[[.[@]]string]]`` and
``filename`` come from the input to the connect statement.
.. warning::
This is not a thread-safe node because it can write to a common
shared location. It will not complain when it overwrites a file.
.. note::
If both substitutions and regexp_substitutions are used, then
substitutions are applied first followed by regexp_substitutions.
This interface **cannot** be used in a MapNode as the inputs are
defined only when the connect statement is executed.
Examples
--------
>>> ds = DataSink()
>>> ds.inputs.base_directory = 'results_dir'
>>> ds.inputs.container = 'subject'
>>> ds.inputs.structural = 'structural.nii'
>>> setattr(ds.inputs, 'contrasts.@con', ['cont1.nii', 'cont2.nii'])
>>> setattr(ds.inputs, 'contrasts.alt', ['cont1a.nii', 'cont2a.nii'])
>>> ds.run() # doctest: +SKIP
To use DataSink in a MapNode, its inputs have to be defined at the
time the interface is created.
>>> ds = DataSink(infields=['contasts.@con'])
>>> ds.inputs.base_directory = 'results_dir'
>>> ds.inputs.container = 'subject'
>>> ds.inputs.structural = 'structural.nii'
>>> setattr(ds.inputs, 'contrasts.@con', ['cont1.nii', 'cont2.nii'])
>>> setattr(ds.inputs, 'contrasts.alt', ['cont1a.nii', 'cont2a.nii'])
>>> ds.run() # doctest: +SKIP
"""
# Give obj .inputs and .outputs
input_spec = DataSinkInputSpec
output_spec = DataSinkOutputSpec
# Initialization method to set up datasink
def __init__(self, infields=None, force_run=True, **kwargs):
"""
Parameters
----------
infields : list of str
Indicates the input fields to be dynamically created
"""
super(DataSink, self).__init__(**kwargs)
undefined_traits = {}
# used for mandatory inputs check
self._infields = infields
if infields:
for key in infields:
self.inputs.add_trait(key, traits.Any)
self.inputs._outputs[key] = Undefined
undefined_traits[key] = Undefined
self.inputs.trait_set(trait_change_notify=False, **undefined_traits)
if force_run:
self._always_run = True
# Get destination paths
def _get_dst(self, src):
# If path is directory with trailing os.path.sep,
# then remove that for a more robust behavior
src = src.rstrip(os.path.sep)
path, fname = os.path.split(src)
if self.inputs.parameterization:
dst = path
if isdefined(self.inputs.strip_dir):
dst = dst.replace(self.inputs.strip_dir, "")
folders = [
folder for folder in dst.split(os.path.sep) if folder.startswith("_")
]
dst = os.path.sep.join(folders)
if fname:
dst = os.path.join(dst, fname)
else:
if fname:
dst = fname
else:
dst = path.split(os.path.sep)[-1]
if dst[0] == os.path.sep:
dst = dst[1:]
return dst
# Substitute paths in substitutions dictionary parameter
def _substitute(self, pathstr):
pathstr_ = pathstr
if isdefined(self.inputs.substitutions):
for key, val in self.inputs.substitutions:
oldpathstr = pathstr
pathstr = pathstr.replace(key, val)
if pathstr != oldpathstr:
iflogger.debug(
"sub.str: %s -> %s using %r -> %r",
oldpathstr,
pathstr,
key,
val,
)
if isdefined(self.inputs.regexp_substitutions):
for key, val in self.inputs.regexp_substitutions:
oldpathstr = pathstr
pathstr, _ = re.subn(key, val, pathstr)
if pathstr != oldpathstr:
iflogger.debug(
"sub.regexp: %s -> %s using %r -> %r",
oldpathstr,
pathstr,
key,
val,
)
if pathstr_ != pathstr:
iflogger.info("sub: %s -> %s", pathstr_, pathstr)
return pathstr
# Check for s3 in base directory
def _check_s3_base_dir(self):
"""
Method to see if the datasink's base directory specifies an
S3 bucket path; if it does, it parses the path for the bucket
name in the form 's3://bucket_name/...' and returns it
Parameters
----------
Returns
-------
s3_flag : boolean
flag indicating whether the base_directory contained an
S3 bucket path
bucket_name : string
name of the S3 bucket to connect to; if the base directory
is not a valid S3 path, defaults to '<N/A>'
"""
s3_str = "s3://"
bucket_name = "<N/A>"
base_directory = self.inputs.base_directory
if not isdefined(base_directory):
s3_flag = False
return s3_flag, bucket_name
s3_flag = base_directory.lower().startswith(s3_str)
if s3_flag:
bucket_name = base_directory[len(s3_str) :].partition("/")[0]
return s3_flag, bucket_name
# Function to return AWS secure environment variables
def _return_aws_keys(self):
"""
Method to return AWS access key id and secret access key using
credentials found in a local file.
Parameters
----------
self : nipype.interfaces.io.DataSink
self for instance method
Returns
-------
aws_access_key_id : string
string of the AWS access key ID
aws_secret_access_key : string
string of the AWS secret access key
"""
# Import packages
import os
# Init variables
creds_path = self.inputs.creds_path
# Check if creds exist
if creds_path and os.path.exists(creds_path):
with open(creds_path, "r") as creds_in:
# Grab csv rows
row1 = creds_in.readline()
row2 = creds_in.readline()
# Are they root or user keys
if "User Name" in row1:
# And split out for keys
aws_access_key_id = row2.split(",")[1]
aws_secret_access_key = row2.split(",")[2]
elif "AWSAccessKeyId" in row1:
# And split out for keys
aws_access_key_id = row1.split("=")[1]
aws_secret_access_key = row2.split("=")[1]
else:
err_msg = "Credentials file not recognized, check file is correct"
raise Exception(err_msg)
# Strip any carriage return/line feeds
aws_access_key_id = aws_access_key_id.replace("\r", "").replace("\n", "")
aws_secret_access_key = aws_secret_access_key.replace("\r", "").replace(
"\n", ""
)
else:
aws_access_key_id = os.getenv("AWS_ACCESS_KEY_ID")
aws_secret_access_key = os.getenv("AWS_SECRET_ACCESS_KEY")
# Return keys
return aws_access_key_id, aws_secret_access_key
# Fetch bucket object
def _fetch_bucket(self, bucket_name):
"""
Method to return a bucket object which can be used to interact
with an AWS S3 bucket using credentials found in a local file.
Parameters
----------
self : nipype.interfaces.io.DataSink
self for instance method
bucket_name : string
string corresponding to the name of the bucket on S3
Returns
-------
bucket : boto3.resources.factory.s3.Bucket
boto3 s3 Bucket object which is used to interact with files
in an S3 bucket on AWS
"""
# Import packages
try:
import boto3
import botocore
except ImportError as exc:
err_msg = "Boto3 package is not installed - install boto3 and " "try again."
raise Exception(err_msg)
# Init variables
creds_path = self.inputs.creds_path
# Get AWS credentials
try:
aws_access_key_id, aws_secret_access_key = self._return_aws_keys()
except Exception as exc:
err_msg = (
"There was a problem extracting the AWS credentials "
"from the credentials file provided: %s. Error:\n%s" % (creds_path, exc)
)
raise Exception(err_msg)
# Try and get AWS credentials if a creds_path is specified
if aws_access_key_id and aws_secret_access_key:
# Init connection
iflogger.info(
"Connecting to S3 bucket: %s with credentials...", bucket_name
)
# Use individual session for each instance of DataSink
# Better when datasinks are being used in multi-threading, see:
# http://boto3.readthedocs.org/en/latest/guide/resources.html#multithreading
session = boto3.session.Session(
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
)
else:
iflogger.info("Connecting to S3 bucket: %s with IAM role...", bucket_name)
# Lean on AWS environment / IAM role authentication and authorization
session = boto3.session.Session()
s3_resource = session.resource("s3", use_ssl=True)
# And try fetch the bucket with the name argument
try:
_get_head_bucket(s3_resource, bucket_name)
except Exception as exc:
# Try to connect anonymously
s3_resource.meta.client.meta.events.register(
"choose-signer.s3.*", botocore.handlers.disable_signing
)
iflogger.info("Connecting to AWS: %s anonymously...", bucket_name)
_get_head_bucket(s3_resource, bucket_name)
# Explicitly declare a secure SSL connection for bucket object
bucket = s3_resource.Bucket(bucket_name)
# Return the bucket
return bucket
# Send up to S3 method
def _upload_to_s3(self, bucket, src, dst):
"""
Method to upload outputs to S3 bucket instead of on local disk
"""
# Import packages
import hashlib
import os
from botocore.exceptions import ClientError
s3_str = "s3://"
s3_prefix = s3_str + bucket.name
# Explicitly lower-case the "s3"
if dst.lower().startswith(s3_str):
dst = s3_str + dst[len(s3_str) :]
# If src is a directory, collect files (this assumes dst is a dir too)
if os.path.isdir(src):
src_files = []
for root, dirs, files in os.walk(src):
src_files.extend([os.path.join(root, fil) for fil in files])
# Make the dst files have the dst folder as base dir
dst_files = [os.path.join(dst, src_f.split(src)[1]) for src_f in src_files]
else:
src_files = [src]
dst_files = [dst]
# Iterate over src and copy to dst
for src_idx, src_f in enumerate(src_files):
# Get destination filename/keyname
dst_f = dst_files[src_idx]
dst_k = dst_f.replace(s3_prefix, "").lstrip("/")
# See if same file is already up there
try:
dst_obj = bucket.Object(key=dst_k)
dst_md5 = dst_obj.e_tag.strip('"')
# See if same file is already there
src_read = open(src_f, "rb").read()
src_md5 = hashlib.md5(src_read).hexdigest()
# Move to next loop iteration
if dst_md5 == src_md5:
iflogger.info("File %s already exists on S3, skipping...", dst_f)
continue
else:
iflogger.info("Overwriting previous S3 file...")
except ClientError:
iflogger.info("New file to S3")
# Copy file up to S3 (either encrypted or not)
iflogger.info(
"Uploading %s to S3 bucket, %s, as %s...", src_f, bucket.name, dst_f
)
if self.inputs.encrypt_bucket_keys:
extra_args = {"ServerSideEncryption": "AES256"}
else:
extra_args = {}
bucket.upload_file(
src_f, dst_k, ExtraArgs=extra_args, Callback=ProgressPercentage(src_f)
)
# List outputs, main run routine
def _list_outputs(self):
"""Execute this module."""
# Init variables
outputs = self.output_spec().get()
out_files = []
# Use hardlink
use_hardlink = str2bool(config.get("execution", "try_hard_link_datasink"))
# Set local output directory if specified
if isdefined(self.inputs.local_copy):
outdir = self.inputs.local_copy
else:
outdir = self.inputs.base_directory
# If base directory isn't given, assume current directory
if not isdefined(outdir):
outdir = "."
# Check if base directory reflects S3 bucket upload
s3_flag, bucket_name = self._check_s3_base_dir()
if s3_flag:
s3dir = self.inputs.base_directory
# If user overrides bucket object, use that
if self.inputs.bucket:
bucket = self.inputs.bucket
# Otherwise fetch bucket object using name
else:
try:
bucket = self._fetch_bucket(bucket_name)
# If encountering an exception during bucket access, set output
# base directory to a local folder
except Exception as exc:
s3dir = "<N/A>"
if not isdefined(self.inputs.local_copy):
local_out_exception = os.path.join(
os.path.expanduser("~"), "s3_datasink_" + bucket_name
)
outdir = local_out_exception
# Log local copying directory
iflogger.info(
"Access to S3 failed! Storing outputs locally at: "
"%s\nError: %s",
outdir,
exc,
)
else:
s3dir = "<N/A>"
# If container input is given, append that to outdir
if isdefined(self.inputs.container):
outdir = os.path.join(outdir, self.inputs.container)
s3dir = os.path.join(s3dir, self.inputs.container)
# If sinking to local folder
if outdir != s3dir:
outdir = os.path.abspath(outdir)
# Create the directory if it doesn't exist
if not os.path.exists(outdir):
try:
os.makedirs(outdir)
except OSError as inst:
if "File exists" in inst.strerror:
pass
else:
raise (inst)
# Iterate through outputs attributes {key : path(s)}
for key, files in list(self.inputs._outputs.items()):
if not isdefined(files):
continue
iflogger.debug("key: %s files: %s", key, str(files))
files = ensure_list(files)
tempoutdir = outdir
if s3_flag:
s3tempoutdir = s3dir
for d in key.split("."):
if d[0] == "@":
continue
tempoutdir = os.path.join(tempoutdir, d)
if s3_flag:
s3tempoutdir = os.path.join(s3tempoutdir, d)
# flattening list
if isinstance(files, list):
if isinstance(files[0], list):
files = [item for sublist in files for item in sublist]
# Iterate through passed-in source files
for src in ensure_list(files):
# Format src and dst files
src = os.path.abspath(src)
if not os.path.isfile(src):
src = os.path.join(src, "")
dst = self._get_dst(src)
if s3_flag:
s3dst = os.path.join(s3tempoutdir, dst)
s3dst = self._substitute(s3dst)
dst = os.path.join(tempoutdir, dst)
dst = self._substitute(dst)
path, _ = os.path.split(dst)
# If we're uploading to S3
if s3_flag:
self._upload_to_s3(bucket, src, s3dst)
out_files.append(s3dst)
# Otherwise, copy locally src -> dst
if not s3_flag or isdefined(self.inputs.local_copy):
# Create output directory if it doesn't exist
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as inst:
if "File exists" in inst.strerror:
pass
else:
raise (inst)
# If src is a file, copy it to dst
if os.path.isfile(src):
iflogger.debug("copyfile: %s %s", src, dst)
copyfile(
src,
dst,
copy=True,
hashmethod="content",
use_hardlink=use_hardlink,
)
out_files.append(dst)
# If src is a directory, copy entire contents to dst dir
elif os.path.isdir(src):
if os.path.exists(dst) and self.inputs.remove_dest_dir:
iflogger.debug("removing: %s", dst)
shutil.rmtree(dst)
iflogger.debug("copydir: %s %s", src, dst)
copytree(src, dst)
out_files.append(dst)
# Return outputs dictionary
outputs["out_file"] = out_files
return outputs
class S3DataGrabberInputSpec(DynamicTraitedSpec, BaseInterfaceInputSpec):
anon = traits.Bool(
False,
usedefault=True,
desc="Use anonymous connection to s3. If this is set to True, boto may print"
" a urlopen error, but this does not prevent data from being downloaded.",
)
region = Str("us-east-1", usedefault=True, desc="Region of s3 bucket")
bucket = Str(mandatory=True, desc="Amazon S3 bucket where your data is stored")
bucket_path = Str(
"", usedefault=True, desc="Location within your bucket for subject data."
)
local_directory = Directory(
exists=True,
desc="Path to the local directory for subject data to be downloaded "
"and accessed. Should be on HDFS for Spark jobs.",
)
raise_on_empty = traits.Bool(
True,
usedefault=True,
desc="Generate exception if list is empty for a given field",
)
sort_filelist = traits.Bool(
mandatory=True, desc="Sort the filelist that matches the template"
)
template = Str(
mandatory=True,
desc="Layout used to get files. Relative to bucket_path if defined."
"Uses regex rather than glob style formatting.",
)
template_args = traits.Dict(
key_trait=Str,
value_trait=traits.List(traits.List),
desc="Information to plug into template",
)
class S3DataGrabber(LibraryBaseInterface, IOBase):
"""
Pull data from an Amazon S3 Bucket.
Generic datagrabber module that wraps around glob in an
intelligent way for neuroimaging tasks to grab files from
Amazon S3
Works exactly like DataGrabber, except, you must specify an
S3 "bucket" and "bucket_path" to search for your data and a
"local_directory" to store the data. "local_directory"
should be a location on HDFS for Spark jobs. Additionally,
"template" uses regex style formatting, rather than the
glob-style found in the original DataGrabber.
Examples
--------
>>> s3grab = S3DataGrabber(infields=['subj_id'], outfields=["func", "anat"])
>>> s3grab.inputs.bucket = 'openneuro'
>>> s3grab.inputs.sort_filelist = True
>>> s3grab.inputs.template = '*'
>>> s3grab.inputs.anon = True
>>> s3grab.inputs.bucket_path = 'ds000101/ds000101_R2.0.0/uncompressed/'
>>> s3grab.inputs.local_directory = '/tmp'
>>> s3grab.inputs.field_template = {'anat': '%s/anat/%s_T1w.nii.gz',
... 'func': '%s/func/%s_task-simon_run-1_bold.nii.gz'}
>>> s3grab.inputs.template_args = {'anat': [['subj_id', 'subj_id']],
... 'func': [['subj_id', 'subj_id']]}
>>> s3grab.inputs.subj_id = 'sub-01'
>>> s3grab.run() # doctest: +SKIP
"""
input_spec = S3DataGrabberInputSpec
output_spec = DynamicTraitedSpec
_always_run = True
_pkg = "boto"
def __init__(self, infields=None, outfields=None, **kwargs):
"""
Parameters
----------
infields : list of str
Indicates the input fields to be dynamically created
outfields: list of str
Indicates output fields to be dynamically created
See class examples for usage
"""
if not outfields:
outfields = ["outfiles"]
super(S3DataGrabber, self).__init__(**kwargs)
undefined_traits = {}
# used for mandatory inputs check
self._infields = infields
self._outfields = outfields
if infields:
for key in infields:
self.inputs.add_trait(key, traits.Any)
undefined_traits[key] = Undefined
# add ability to insert field specific templates
self.inputs.add_trait(
"field_template",
traits.Dict(
traits.Enum(outfields), desc="arguments that fit into template"
),
)
undefined_traits["field_template"] = Undefined
if not isdefined(self.inputs.template_args):
self.inputs.template_args = {}
for key in outfields:
if key not in self.inputs.template_args:
if infields:
self.inputs.template_args[key] = [infields]
else:
self.inputs.template_args[key] = []
self.inputs.trait_set(trait_change_notify=False, **undefined_traits)
def _add_output_traits(self, base):
"""
S3 specific: Downloads relevant files to a local folder specified
Using traits.Any instead out OutputMultiPath till add_trait bug
is fixed.
"""
return add_traits(base, list(self.inputs.template_args.keys()))
def _list_outputs(self):
# infields are mandatory, however I could not figure out how to set 'mandatory' flag dynamically
# hence manual check
import boto
if self._infields:
for key in self._infields:
value = getattr(self.inputs, key)
if not isdefined(value):
msg = (
"%s requires a value for input '%s' because it was listed in 'infields'"
% (self.__class__.__name__, key)
)
raise ValueError(msg)
outputs = {}
# get list of all files in s3 bucket
conn = boto.connect_s3(anon=self.inputs.anon)
bkt = conn.get_bucket(self.inputs.bucket)
bkt_files = list(k.key for k in bkt.list(prefix=self.inputs.bucket_path))
# keys are outfields, args are template args for the outfield
for key, args in list(self.inputs.template_args.items()):
outputs[key] = []
template = self.inputs.template
if (
hasattr(self.inputs, "field_template")
and isdefined(self.inputs.field_template)
and key in self.inputs.field_template
):
template = self.inputs.field_template[
key
] # template override for multiple outfields
if isdefined(self.inputs.bucket_path):
template = os.path.join(self.inputs.bucket_path, template)
if not args:
filelist = []
for fname in bkt_files:
if re.match(template, fname):
filelist.append(fname)
if len(filelist) == 0:
msg = "Output key: %s Template: %s returned no files" % (
key,
template,
)
if self.inputs.raise_on_empty:
raise IOError(msg)
else:
warn(msg)
else:
if self.inputs.sort_filelist:
filelist = human_order_sorted(filelist)
outputs[key] = simplify_list(filelist)
for argnum, arglist in enumerate(args):
maxlen = 1
for arg in arglist:
if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg):
arg = getattr(self.inputs, arg)
if isinstance(arg, list):
if (maxlen > 1) and (len(arg) != maxlen):
raise ValueError(
"incompatible number of arguments for %s" % key
)
if len(arg) > maxlen:
maxlen = len(arg)
outfiles = []
for i in range(maxlen):
argtuple = []
for arg in arglist:
if isinstance(arg, (str, bytes)) and hasattr(self.inputs, arg):
arg = getattr(self.inputs, arg)
if isinstance(arg, list):