4 # --md5sum - display md5 of each file as read from disk
8 import arvados.collection
25 from apiclient import errors as apiclient_errors
27 import arvados.commands._util as arv_cmd
29 CAUGHT_SIGNALS = [signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]
32 upload_opts = argparse.ArgumentParser(add_help=False)
34 upload_opts.add_argument('paths', metavar='path', type=str, nargs='*',
36 Local file or directory. Default: read from standard input.
39 _group = upload_opts.add_mutually_exclusive_group()
41 _group.add_argument('--max-manifest-depth', type=int, metavar='N',
43 Maximum depth of directory tree to represent in the manifest
44 structure. A directory structure deeper than this will be represented
45 as a single stream in the manifest. If N=0, the manifest will contain
46 a single stream. Default: -1 (unlimited), i.e., exactly one manifest
47 stream per filesystem directory that contains files.
50 _group.add_argument('--normalize', action='store_true',
52 Normalize the manifest by re-ordering files and streams after writing
56 _group = upload_opts.add_mutually_exclusive_group()
58 _group.add_argument('--as-stream', action='store_true', dest='stream',
63 _group.add_argument('--stream', action='store_true',
65 Store the file content and display the resulting manifest on
66 stdout. Do not write the manifest to Keep or save a Collection object
70 _group.add_argument('--as-manifest', action='store_true', dest='manifest',
72 Synonym for --manifest.
75 _group.add_argument('--in-manifest', action='store_true', dest='manifest',
77 Synonym for --manifest.
80 _group.add_argument('--manifest', action='store_true',
82 Store the file data and resulting manifest in Keep, save a Collection
83 object in Arvados, and display the manifest locator (Collection uuid)
84 on stdout. This is the default behavior.
87 _group.add_argument('--as-raw', action='store_true', dest='raw',
92 _group.add_argument('--raw', action='store_true',
94 Store the file content and display the data block locators on stdout,
95 separated by commas, with a trailing newline. Do not store a
99 upload_opts.add_argument('--use-filename', type=str, default=None,
100 dest='filename', help="""
101 Synonym for --filename.
104 upload_opts.add_argument('--filename', type=str, default=None,
106 Use the given filename in the manifest, instead of the name of the
107 local file. This is useful when "-" or "/dev/stdin" is given as an
108 input file. It can be used only if there is exactly one path given and
109 it is not a directory. Implies --manifest.
112 upload_opts.add_argument('--portable-data-hash', action='store_true',
114 Print the portable data hash instead of the Arvados UUID for the collection
115 created by the upload.
118 upload_opts.add_argument('--replication', type=int, metavar='N', default=None,
120 Set the replication level for the new collection: how many different
121 physical storage devices (e.g., disks) should have a copy of each data
122 block. Default is to use the server-provided default (if any) or 2.
125 run_opts = argparse.ArgumentParser(add_help=False)
127 run_opts.add_argument('--project-uuid', metavar='UUID', help="""
128 Store the collection in the specified project, instead of your Home
132 run_opts.add_argument('--name', help="""
133 Save the collection with the specified name.
136 _group = run_opts.add_mutually_exclusive_group()
137 _group.add_argument('--progress', action='store_true',
139 Display human-readable progress on stderr (bytes and, if possible,
140 percentage of total data size). This is the default behavior when
144 _group.add_argument('--no-progress', action='store_true',
146 Do not display human-readable progress on stderr, even if stderr is a
150 _group.add_argument('--batch-progress', action='store_true',
152 Display machine-readable progress on stderr (bytes and, if known,
156 _group = run_opts.add_mutually_exclusive_group()
157 _group.add_argument('--resume', action='store_true', default=True,
159 Continue interrupted uploads from cached state (default).
161 _group.add_argument('--no-resume', action='store_false', dest='resume',
163 Do not continue interrupted uploads from cached state.
166 arg_parser = argparse.ArgumentParser(
167 description='Copy data from the local filesystem to Keep.',
168 parents=[upload_opts, run_opts, arv_cmd.retry_opt])
170 def parse_arguments(arguments):
171 args = arg_parser.parse_args(arguments)
173 if len(args.paths) == 0:
176 args.paths = map(lambda x: "-" if x == "/dev/stdin" else x, args.paths)
178 if len(args.paths) != 1 or os.path.isdir(args.paths[0]):
181 --filename argument cannot be used when storing a directory or
185 # Turn on --progress by default if stderr is a tty.
186 if (not (args.batch_progress or args.no_progress)
187 and os.isatty(sys.stderr.fileno())):
190 if args.paths == ['-']:
192 if not args.filename:
193 args.filename = 'stdin'
197 class ResumeCacheConflict(Exception):
201 class ResumeCache(object):
202 CACHE_DIR = '.cache/arvados/arv-put'
204 def __init__(self, file_spec):
205 self.cache_file = open(file_spec, 'a+')
206 self._lock_file(self.cache_file)
207 self.filename = self.cache_file.name
210 def make_path(cls, args):
212 md5.update(arvados.config.get('ARVADOS_API_HOST', '!nohost'))
213 realpaths = sorted(os.path.realpath(path) for path in args.paths)
214 md5.update('\0'.join(realpaths))
215 if any(os.path.isdir(path) for path in realpaths):
216 md5.update(str(max(args.max_manifest_depth, -1)))
218 md5.update(args.filename)
220 arv_cmd.make_home_conf_dir(cls.CACHE_DIR, 0o700, 'raise'),
223 def _lock_file(self, fileobj):
225 fcntl.flock(fileobj, fcntl.LOCK_EX | fcntl.LOCK_NB)
227 raise ResumeCacheConflict("{} locked".format(fileobj.name))
230 self.cache_file.seek(0)
231 return json.load(self.cache_file)
233 def check_cache(self, api_client=None, num_retries=0):
238 if "_finished_streams" in state and len(state["_finished_streams"]) > 0:
239 locator = state["_finished_streams"][0][1][0]
240 elif "_current_stream_locators" in state and len(state["_current_stream_locators"]) > 0:
241 locator = state["_current_stream_locators"][0]
242 if locator is not None:
243 kc = arvados.keep.KeepClient(api_client=api_client)
244 kc.head(locator, num_retries=num_retries)
245 except Exception as e:
250 def save(self, data):
252 new_cache_fd, new_cache_name = tempfile.mkstemp(
253 dir=os.path.dirname(self.filename))
254 self._lock_file(new_cache_fd)
255 new_cache = os.fdopen(new_cache_fd, 'r+')
256 json.dump(data, new_cache)
257 os.rename(new_cache_name, self.filename)
258 except (IOError, OSError, ResumeCacheConflict) as error:
260 os.unlink(new_cache_name)
261 except NameError: # mkstemp failed.
264 self.cache_file.close()
265 self.cache_file = new_cache
268 self.cache_file.close()
272 os.unlink(self.filename)
273 except OSError as error:
274 if error.errno != errno.ENOENT: # That's what we wanted anyway.
280 self.__init__(self.filename)
283 class ArvPutUploadJob(object):
284 CACHE_DIR = '.cache/arvados/arv-put'
286 'manifest' : None, # Last saved manifest checkpoint
287 'files' : {} # Previous run file list: {path : {size, mtime}}
290 def __init__(self, paths, resume=True, reporter=None, bytes_expected=None,
291 name=None, owner_uuid=None, ensure_unique_name=False,
292 num_retries=None, replication_desired=None,
293 filename=None, update_time=1.0):
296 self.reporter = reporter
297 self.bytes_expected = bytes_expected
298 self.bytes_written = 0
299 self.bytes_skipped = 0
301 self.owner_uuid = owner_uuid
302 self.ensure_unique_name = ensure_unique_name
303 self.num_retries = num_retries
304 self.replication_desired = replication_desired
305 self.filename = filename
306 self._state_lock = threading.Lock()
307 self._state = None # Previous run state (file list & manifest)
308 self._current_files = [] # Current run file list
309 self._cache_file = None
310 self._collection = None
311 self._collection_lock = threading.Lock()
312 self._stop_checkpointer = threading.Event()
313 self._checkpointer = threading.Thread(target=self._update_task)
314 self._update_task_time = update_time # How many seconds wait between update runs
315 self.logger = logging.getLogger('arvados.arv_put')
316 # Load cached data if any and if needed
321 Start supporting thread & file uploading
323 self._checkpointer.daemon = True
324 self._checkpointer.start()
326 for path in self.paths:
327 # Test for stdin first, in case some file named '-' exist
329 self._write_stdin(self.filename or 'stdin')
330 elif os.path.isdir(path):
331 self._write_directory_tree(path)
333 self._write_file(path, self.filename or os.path.basename(path))
335 # Stop the thread before doing anything else
336 self._stop_checkpointer.set()
337 self._checkpointer.join()
338 # Commit all & one last _update()
342 self._cache_file.close()
343 # Correct the final written bytes count
344 self.bytes_written -= self.bytes_skipped
346 def save_collection(self):
347 with self._collection_lock:
348 self._my_collection().save_new(
349 name=self.name, owner_uuid=self.owner_uuid,
350 ensure_unique_name=self.ensure_unique_name,
351 num_retries=self.num_retries)
353 def destroy_cache(self):
356 os.unlink(self._cache_filename)
357 except OSError as error:
358 # That's what we wanted anyway.
359 if error.errno != errno.ENOENT:
361 self._cache_file.close()
363 def _collection_size(self, collection):
365 Recursively get the total size of the collection
368 for item in collection.values():
369 if isinstance(item, arvados.collection.Collection) or isinstance(item, arvados.collection.Subcollection):
370 size += self._collection_size(item)
375 def _update_task(self):
377 Periodically called support task. File uploading is
378 asynchronous so we poll status from the collection.
380 while not self._stop_checkpointer.wait(self._update_task_time):
385 Update cached manifest text and report progress.
387 with self._collection_lock:
388 self.bytes_written = self._collection_size(self._my_collection())
389 # Update cache, if resume enabled
391 with self._state_lock:
392 # Get the manifest text without comitting pending blocks
393 self._state['manifest'] = self._my_collection()._get_manifest_text(".", strip=False, normalize=False, only_committed=True)
395 # Call the reporter, if any
396 self.report_progress()
398 def report_progress(self):
399 if self.reporter is not None:
400 self.reporter(self.bytes_written, self.bytes_expected)
402 def _write_directory_tree(self, path, stream_name="."):
403 # TODO: Check what happens when multiple directories are passed as
405 # If the code below is uncommented, integration test
406 # test_ArvPutSignedManifest (tests.test_arv_put.ArvPutIntegrationTest)
407 # fails, I suppose it is because the manifest_uuid changes because
408 # of the dir addition to stream_name.
410 # if stream_name == '.':
411 # stream_name = os.path.join('.', os.path.basename(path))
412 for item in os.listdir(path):
413 if os.path.isdir(os.path.join(path, item)):
414 self._write_directory_tree(os.path.join(path, item),
415 os.path.join(stream_name, item))
417 self._write_file(os.path.join(path, item),
418 os.path.join(stream_name, item))
420 def _write_stdin(self, filename):
421 with self._collection_lock:
422 output = self._my_collection().open(filename, 'w')
423 self._write(sys.stdin, output)
426 def _write_file(self, source, filename):
429 # Check if file was already uploaded (at least partially)
430 with self._collection_lock:
432 file_in_collection = self._my_collection().find(filename)
435 file_in_collection = None
436 # If no previous cached data on this file, store it for an eventual
438 if source not in self._state['files']:
439 with self._state_lock:
440 self._state['files'][source] = {
441 'mtime': os.path.getmtime(source),
442 'size' : os.path.getsize(source)
444 with self._state_lock:
445 cached_file_data = self._state['files'][source]
446 # See if this file was already uploaded at least partially
447 if file_in_collection:
448 if cached_file_data['mtime'] == os.path.getmtime(source) and cached_file_data['size'] == os.path.getsize(source):
449 if cached_file_data['size'] == file_in_collection.size():
450 # File already there, skip it.
451 self.bytes_skipped += cached_file_data['size']
453 elif cached_file_data['size'] > file_in_collection.size():
454 # File partially uploaded, resume!
455 resume_offset = file_in_collection.size()
457 # Inconsistent cache, re-upload the file
458 self.logger.warning("Uploaded version of file '{}' is bigger than local version, will re-upload it from scratch.".format(source))
460 # Local file differs from cached data, re-upload it
462 with open(source, 'r') as source_fd:
463 if resume_offset > 0:
464 # Start upload where we left off
465 with self._collection_lock:
466 output = self._my_collection().open(filename, 'a')
467 source_fd.seek(resume_offset)
468 self.bytes_skipped += resume_offset
471 with self._collection_lock:
472 output = self._my_collection().open(filename, 'w')
473 self._write(source_fd, output)
474 output.close(flush=False)
476 def _write(self, source_fd, output):
479 data = source_fd.read(arvados.config.KEEP_BLOCK_SIZE)
480 # Allow an empty file to be written
481 if not data and not first_read:
487 def _my_collection(self):
489 Create a new collection if none cached. Load it from cache otherwise.
491 if self._collection is None:
492 with self._state_lock:
493 manifest = self._state['manifest']
494 if self.resume and manifest is not None:
495 # Create collection from saved state
496 self._collection = arvados.collection.Collection(
498 replication_desired=self.replication_desired)
500 # Create new collection
501 self._collection = arvados.collection.Collection(
502 replication_desired=self.replication_desired)
503 return self._collection
505 def _setup_state(self):
507 Create a new cache file or load a previously existing one.
511 md5.update(arvados.config.get('ARVADOS_API_HOST', '!nohost'))
512 realpaths = sorted(os.path.realpath(path) for path in self.paths)
513 md5.update('\0'.join(realpaths))
515 md5.update(self.filename)
516 cache_filename = md5.hexdigest()
517 self._cache_file = open(os.path.join(
518 arv_cmd.make_home_conf_dir(self.CACHE_DIR, 0o700, 'raise'),
519 cache_filename), 'a+')
520 self._cache_filename = self._cache_file.name
521 self._lock_file(self._cache_file)
522 self._cache_file.seek(0)
523 with self._state_lock:
525 self._state = json.load(self._cache_file)
526 if not set(['manifest', 'files']).issubset(set(self._state.keys())):
527 # Cache at least partially incomplete, set up new cache
528 self._state = copy.deepcopy(self.EMPTY_STATE)
530 # Cache file empty, set up new cache
531 self._state = copy.deepcopy(self.EMPTY_STATE)
532 # Load how many bytes were uploaded on previous run
533 with self._collection_lock:
534 self.bytes_written = self._collection_size(self._my_collection())
537 with self._state_lock:
538 self._state = copy.deepcopy(self.EMPTY_STATE)
540 def _lock_file(self, fileobj):
542 fcntl.flock(fileobj, fcntl.LOCK_EX | fcntl.LOCK_NB)
544 raise ResumeCacheConflict("{} locked".format(fileobj.name))
546 def _save_state(self):
548 Atomically save current state into cache.
551 with self._state_lock:
553 new_cache_fd, new_cache_name = tempfile.mkstemp(
554 dir=os.path.dirname(self._cache_filename))
555 self._lock_file(new_cache_fd)
556 new_cache = os.fdopen(new_cache_fd, 'r+')
557 json.dump(state, new_cache)
560 os.rename(new_cache_name, self._cache_filename)
561 except (IOError, OSError, ResumeCacheConflict) as error:
562 self.logger.error("There was a problem while saving the cache file: {}".format(error))
564 os.unlink(new_cache_name)
565 except NameError: # mkstemp failed.
568 self._cache_file.close()
569 self._cache_file = new_cache
571 def collection_name(self):
572 with self._collection_lock:
573 name = self._my_collection().api_response()['name'] if self._my_collection().api_response() else None
576 def manifest_locator(self):
577 with self._collection_lock:
578 locator = self._my_collection().manifest_locator()
581 def portable_data_hash(self):
582 with self._collection_lock:
583 datahash = self._my_collection().portable_data_hash()
586 def manifest_text(self, stream_name=".", strip=False, normalize=False):
587 with self._collection_lock:
588 manifest = self._my_collection().manifest_text(stream_name, strip, normalize)
591 def _datablocks_on_item(self, item):
593 Return a list of datablock locators, recursively navigating
594 through subcollections
596 if isinstance(item, arvados.arvfile.ArvadosFile):
599 return ["d41d8cd98f00b204e9800998ecf8427e+0"]
602 for segment in item.segments():
603 loc = segment.locator
606 elif isinstance(item, arvados.collection.Collection):
607 l = [self._datablocks_on_item(x) for x in item.values()]
608 # Fast list flattener method taken from:
609 # http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
610 return [loc for sublist in l for loc in sublist]
614 def data_locators(self):
615 with self._collection_lock:
616 # Make sure all datablocks are flushed before getting the locators
617 self._my_collection().manifest_text()
618 datablocks = self._datablocks_on_item(self._my_collection())
622 def expected_bytes_for(pathlist):
623 # Walk the given directory trees and stat files, adding up file sizes,
624 # so we can display progress as percent
626 for path in pathlist:
627 if os.path.isdir(path):
628 for filename in arvados.util.listdir_recursive(path):
629 bytesum += os.path.getsize(os.path.join(path, filename))
630 elif not os.path.isfile(path):
633 bytesum += os.path.getsize(path)
636 _machine_format = "{} {}: {{}} written {{}} total\n".format(sys.argv[0],
638 def machine_progress(bytes_written, bytes_expected):
639 return _machine_format.format(
640 bytes_written, -1 if (bytes_expected is None) else bytes_expected)
642 def human_progress(bytes_written, bytes_expected):
644 return "\r{}M / {}M {:.1%} ".format(
645 bytes_written >> 20, bytes_expected >> 20,
646 float(bytes_written) / bytes_expected)
648 return "\r{} ".format(bytes_written)
650 def progress_writer(progress_func, outfile=sys.stderr):
651 def write_progress(bytes_written, bytes_expected):
652 outfile.write(progress_func(bytes_written, bytes_expected))
653 return write_progress
655 def exit_signal_handler(sigcode, frame):
658 def desired_project_uuid(api_client, project_uuid, num_retries):
660 query = api_client.users().current()
661 elif arvados.util.user_uuid_pattern.match(project_uuid):
662 query = api_client.users().get(uuid=project_uuid)
663 elif arvados.util.group_uuid_pattern.match(project_uuid):
664 query = api_client.groups().get(uuid=project_uuid)
666 raise ValueError("Not a valid project UUID: {}".format(project_uuid))
667 return query.execute(num_retries=num_retries)['uuid']
669 def main(arguments=None, stdout=sys.stdout, stderr=sys.stderr):
672 args = parse_arguments(arguments)
674 if api_client is None:
675 api_client = arvados.api('v1')
677 # Determine the name to use
679 if args.stream or args.raw:
680 print >>stderr, "Cannot use --name with --stream or --raw"
682 collection_name = args.name
684 collection_name = "Saved at {} by {}@{}".format(
685 datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"),
686 pwd.getpwuid(os.getuid()).pw_name,
687 socket.gethostname())
689 if args.project_uuid and (args.stream or args.raw):
690 print >>stderr, "Cannot use --project-uuid with --stream or --raw"
693 # Determine the parent project
695 project_uuid = desired_project_uuid(api_client, args.project_uuid,
697 except (apiclient_errors.Error, ValueError) as error:
698 print >>stderr, error
702 reporter = progress_writer(human_progress)
703 elif args.batch_progress:
704 reporter = progress_writer(machine_progress)
708 bytes_expected = expected_bytes_for(args.paths)
710 writer = ArvPutUploadJob(paths = args.paths,
711 resume = args.resume,
712 filename = args.filename,
714 bytes_expected = bytes_expected,
715 num_retries = args.retries,
716 replication_desired = args.replication,
717 name = collection_name,
718 owner_uuid = project_uuid,
719 ensure_unique_name = True)
720 except ResumeCacheConflict:
721 print >>stderr, "\n".join([
722 "arv-put: Another process is already uploading this data.",
723 " Use --no-resume if this is really what you want."])
726 # Install our signal handler for each code in CAUGHT_SIGNALS, and save
728 orig_signal_handlers = {sigcode: signal.signal(sigcode, exit_signal_handler)
729 for sigcode in CAUGHT_SIGNALS}
731 if args.resume and writer.bytes_written > 0:
732 print >>stderr, "\n".join([
733 "arv-put: Resuming previous upload from last checkpoint.",
734 " Use the --no-resume option to start over."])
736 writer.report_progress()
739 if args.progress: # Print newline to split stderr from stdout for humans.
744 output = writer.manifest_text(normalize=True)
746 output = writer.manifest_text()
748 output = ','.join(writer.data_locators())
751 writer.save_collection()
752 print >>stderr, "Collection saved as '%s'" % writer.collection_name()
753 if args.portable_data_hash:
754 output = writer.portable_data_hash()
756 output = writer.manifest_locator()
757 except apiclient_errors.Error as error:
759 "arv-put: Error creating Collection on project: {}.".format(
763 # Print the locator (uuid) of the new collection.
768 if not output.endswith('\n'):
771 for sigcode, orig_handler in orig_signal_handlers.items():
772 signal.signal(sigcode, orig_handler)
778 writer.destroy_cache()
782 if __name__ == '__main__':