4 # --md5sum - display md5 of each file as read from disk
8 import arvados.collection
24 from apiclient import errors as apiclient_errors
26 import arvados.commands._util as arv_cmd
28 CAUGHT_SIGNALS = [signal.SIGINT, signal.SIGQUIT, signal.SIGTERM]
31 upload_opts = argparse.ArgumentParser(add_help=False)
33 upload_opts.add_argument('paths', metavar='path', type=str, nargs='*',
35 Local file or directory. Default: read from standard input.
38 _group = upload_opts.add_mutually_exclusive_group()
40 _group.add_argument('--max-manifest-depth', type=int, metavar='N',
42 Maximum depth of directory tree to represent in the manifest
43 structure. A directory structure deeper than this will be represented
44 as a single stream in the manifest. If N=0, the manifest will contain
45 a single stream. Default: -1 (unlimited), i.e., exactly one manifest
46 stream per filesystem directory that contains files.
49 _group.add_argument('--normalize', action='store_true',
51 Normalize the manifest by re-ordering files and streams after writing
55 _group = upload_opts.add_mutually_exclusive_group()
57 _group.add_argument('--as-stream', action='store_true', dest='stream',
62 _group.add_argument('--stream', action='store_true',
64 Store the file content and display the resulting manifest on
65 stdout. Do not write the manifest to Keep or save a Collection object
69 _group.add_argument('--as-manifest', action='store_true', dest='manifest',
71 Synonym for --manifest.
74 _group.add_argument('--in-manifest', action='store_true', dest='manifest',
76 Synonym for --manifest.
79 _group.add_argument('--manifest', action='store_true',
81 Store the file data and resulting manifest in Keep, save a Collection
82 object in Arvados, and display the manifest locator (Collection uuid)
83 on stdout. This is the default behavior.
86 _group.add_argument('--as-raw', action='store_true', dest='raw',
91 _group.add_argument('--raw', action='store_true',
93 Store the file content and display the data block locators on stdout,
94 separated by commas, with a trailing newline. Do not store a
98 upload_opts.add_argument('--use-filename', type=str, default=None,
99 dest='filename', help="""
100 Synonym for --filename.
103 upload_opts.add_argument('--filename', type=str, default=None,
105 Use the given filename in the manifest, instead of the name of the
106 local file. This is useful when "-" or "/dev/stdin" is given as an
107 input file. It can be used only if there is exactly one path given and
108 it is not a directory. Implies --manifest.
111 upload_opts.add_argument('--portable-data-hash', action='store_true',
113 Print the portable data hash instead of the Arvados UUID for the collection
114 created by the upload.
117 upload_opts.add_argument('--replication', type=int, metavar='N', default=None,
119 Set the replication level for the new collection: how many different
120 physical storage devices (e.g., disks) should have a copy of each data
121 block. Default is to use the server-provided default (if any) or 2.
124 run_opts = argparse.ArgumentParser(add_help=False)
126 run_opts.add_argument('--project-uuid', metavar='UUID', help="""
127 Store the collection in the specified project, instead of your Home
131 run_opts.add_argument('--name', help="""
132 Save the collection with the specified name.
135 _group = run_opts.add_mutually_exclusive_group()
136 _group.add_argument('--progress', action='store_true',
138 Display human-readable progress on stderr (bytes and, if possible,
139 percentage of total data size). This is the default behavior when
143 _group.add_argument('--no-progress', action='store_true',
145 Do not display human-readable progress on stderr, even if stderr is a
149 _group.add_argument('--batch-progress', action='store_true',
151 Display machine-readable progress on stderr (bytes and, if known,
155 _group = run_opts.add_mutually_exclusive_group()
156 _group.add_argument('--resume', action='store_true', default=True,
158 Continue interrupted uploads from cached state (default).
160 _group.add_argument('--no-resume', action='store_false', dest='resume',
162 Do not continue interrupted uploads from cached state.
165 arg_parser = argparse.ArgumentParser(
166 description='Copy data from the local filesystem to Keep.',
167 parents=[upload_opts, run_opts, arv_cmd.retry_opt])
169 def parse_arguments(arguments):
170 args = arg_parser.parse_args(arguments)
172 if len(args.paths) == 0:
175 args.paths = map(lambda x: "-" if x == "/dev/stdin" else x, args.paths)
177 if len(args.paths) != 1 or os.path.isdir(args.paths[0]):
180 --filename argument cannot be used when storing a directory or
184 # Turn on --progress by default if stderr is a tty.
185 if (not (args.batch_progress or args.no_progress)
186 and os.isatty(sys.stderr.fileno())):
189 if args.paths == ['-']:
191 if not args.filename:
192 args.filename = 'stdin'
196 class ResumeCacheConflict(Exception):
200 class ResumeCache(object):
201 CACHE_DIR = '.cache/arvados/arv-put'
203 def __init__(self, file_spec):
204 self.cache_file = open(file_spec, 'a+')
205 self._lock_file(self.cache_file)
206 self.filename = self.cache_file.name
209 def make_path(cls, args):
211 md5.update(arvados.config.get('ARVADOS_API_HOST', '!nohost'))
212 realpaths = sorted(os.path.realpath(path) for path in args.paths)
213 md5.update('\0'.join(realpaths))
214 if any(os.path.isdir(path) for path in realpaths):
215 md5.update(str(max(args.max_manifest_depth, -1)))
217 md5.update(args.filename)
219 arv_cmd.make_home_conf_dir(cls.CACHE_DIR, 0o700, 'raise'),
222 def _lock_file(self, fileobj):
224 fcntl.flock(fileobj, fcntl.LOCK_EX | fcntl.LOCK_NB)
226 raise ResumeCacheConflict("{} locked".format(fileobj.name))
229 self.cache_file.seek(0)
230 return json.load(self.cache_file)
232 def check_cache(self, api_client=None, num_retries=0):
237 if "_finished_streams" in state and len(state["_finished_streams"]) > 0:
238 locator = state["_finished_streams"][0][1][0]
239 elif "_current_stream_locators" in state and len(state["_current_stream_locators"]) > 0:
240 locator = state["_current_stream_locators"][0]
241 if locator is not None:
242 kc = arvados.keep.KeepClient(api_client=api_client)
243 kc.head(locator, num_retries=num_retries)
244 except Exception as e:
249 def save(self, data):
251 new_cache_fd, new_cache_name = tempfile.mkstemp(
252 dir=os.path.dirname(self.filename))
253 self._lock_file(new_cache_fd)
254 new_cache = os.fdopen(new_cache_fd, 'r+')
255 json.dump(data, new_cache)
256 os.rename(new_cache_name, self.filename)
257 except (IOError, OSError, ResumeCacheConflict) as error:
259 os.unlink(new_cache_name)
260 except NameError: # mkstemp failed.
263 self.cache_file.close()
264 self.cache_file = new_cache
267 self.cache_file.close()
271 os.unlink(self.filename)
272 except OSError as error:
273 if error.errno != errno.ENOENT: # That's what we wanted anyway.
279 self.__init__(self.filename)
282 class ArvPutUploadJob(object):
283 CACHE_DIR = '.cache/arvados/arv-put'
285 'manifest' : None, # Last saved manifest checkpoint
286 'files' : {} # Previous run file list: {path : {size, mtime}}
289 def __init__(self, paths, resume=True, reporter=None, bytes_expected=None,
290 name=None, owner_uuid=None, ensure_unique_name=False,
291 num_retries=None, write_copies=None, replication=None,
292 filename=None, update_time=60.0):
295 self.reporter = reporter
296 self.bytes_expected = bytes_expected
297 self.bytes_written = 0
298 self.bytes_skipped = 0
300 self.owner_uuid = owner_uuid
301 self.ensure_unique_name = ensure_unique_name
302 self.num_retries = num_retries
303 self.write_copies = write_copies
304 self.replication = replication
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 # Load cached data if any and if needed
320 Start supporting thread & file uploading
322 self._checkpointer.start()
324 for path in self.paths:
325 # Test for stdin first, in case some file named '-' exist
327 self._write_stdin(self.filename or 'stdin')
328 elif os.path.isdir(path):
329 self._write_directory_tree(path)
331 self._write_file(path, self.filename or os.path.basename(path))
333 # Stop the thread before doing anything else
334 self._stop_checkpointer.set()
335 self._checkpointer.join()
336 # Successful upload, one last _update()
339 self._cache_file.close()
340 # Correct the final written bytes count
341 self.bytes_written -= self.bytes_skipped
343 def save_collection(self):
344 with self._collection_lock:
345 self._my_collection().save_new(
346 name=self.name, owner_uuid=self.owner_uuid,
347 ensure_unique_name=self.ensure_unique_name,
348 num_retries=self.num_retries,
349 replication_desired=self.replication)
351 def destroy_cache(self):
354 os.unlink(self._cache_filename)
355 except OSError as error:
356 if error.errno != errno.ENOENT: # That's what we wanted anyway.
358 self._cache_file.close()
360 def _collection_size(self, collection):
362 Recursively get the total size of the collection
365 for item in collection.values():
366 if isinstance(item, arvados.collection.Collection) or isinstance(item, arvados.collection.Subcollection):
367 size += self._collection_size(item)
372 def _update_task(self):
374 Periodically called support task. File uploading is
375 asynchronous so we poll status from the collection.
377 while not self._stop_checkpointer.wait(self._update_task_time):
382 Update cached manifest text and report progress.
384 with self._collection_lock:
385 self.bytes_written = self._collection_size(self._my_collection())
386 # Update cache, if resume enabled
388 with self._state_lock:
389 self._state['manifest'] = self._my_collection().manifest_text()
392 # Call the reporter, if any
393 self.report_progress()
395 def report_progress(self):
396 if self.reporter is not None:
397 self.reporter(self.bytes_written, self.bytes_expected)
399 def _write_directory_tree(self, path, stream_name="."):
400 # TODO: Check what happens when multiple directories are passed as
402 # If the code below is uncommented, integration test
403 # test_ArvPutSignedManifest (tests.test_arv_put.ArvPutIntegrationTest)
404 # fails, I suppose it is because the manifest_uuid changes because
405 # of the dir addition to stream_name.
407 # if stream_name == '.':
408 # stream_name = os.path.join('.', os.path.basename(path))
409 for item in os.listdir(path):
410 if os.path.isdir(os.path.join(path, item)):
411 self._write_directory_tree(os.path.join(path, item),
412 os.path.join(stream_name, item))
414 self._write_file(os.path.join(path, item),
415 os.path.join(stream_name, item))
417 def _write_stdin(self, filename):
418 with self._collection_lock:
419 output = self._my_collection().open(filename, 'w')
420 self._write(sys.stdin, output)
423 def _write_file(self, source, filename):
426 # Check if file was already uploaded (at least partially)
427 with self._collection_lock:
429 file_in_collection = self._my_collection().find(filename)
432 file_in_collection = None
433 # If no previous cached data on this file, store it for an eventual
435 if source not in self._state['files']:
436 with self._state_lock:
437 self._state['files'][source] = {
438 'mtime': os.path.getmtime(source),
439 'size' : os.path.getsize(source)
441 cached_file_data = self._state['files'][source]
442 # See if this file was already uploaded at least partially
443 if file_in_collection:
444 if cached_file_data['mtime'] == os.path.getmtime(source) and cached_file_data['size'] == os.path.getsize(source):
445 if cached_file_data['size'] == file_in_collection.size():
446 # File already there, skip it.
447 self.bytes_skipped += cached_file_data['size']
449 elif cached_file_data['size'] > file_in_collection.size():
450 # File partially uploaded, resume!
451 resume_offset = file_in_collection.size()
453 # Inconsistent cache, re-upload the file
454 pass # TODO: log warning message
456 # Local file differs from cached data, re-upload it
458 with open(source, 'r') as source_fd:
459 if resume_offset > 0:
460 # Start upload where we left off
461 with self._collection_lock:
462 output = self._my_collection().open(filename, 'a')
463 source_fd.seek(resume_offset)
464 self.bytes_skipped += resume_offset
467 with self._collection_lock:
468 output = self._my_collection().open(filename, 'w')
469 self._write(source_fd, output)
472 def _write(self, source_fd, output):
474 data = source_fd.read(arvados.config.KEEP_BLOCK_SIZE)
479 def _my_collection(self):
481 Create a new collection if none cached. Load it from cache otherwise.
483 if self._collection is None:
484 with self._state_lock:
485 manifest = self._state['manifest']
486 if self.resume and manifest is not None:
487 # Create collection from saved state
488 self._collection = arvados.collection.Collection(
490 num_write_copies=self.write_copies)
492 # Create new collection
493 self._collection = arvados.collection.Collection(
494 num_write_copies=self.write_copies)
495 return self._collection
497 def _setup_state(self):
499 Create a new cache file or load a previously existing one.
503 md5.update(arvados.config.get('ARVADOS_API_HOST', '!nohost'))
504 realpaths = sorted(os.path.realpath(path) for path in self.paths)
505 md5.update('\0'.join(realpaths))
507 md5.update(self.filename)
508 cache_filename = md5.hexdigest()
509 self._cache_file = open(os.path.join(
510 arv_cmd.make_home_conf_dir(self.CACHE_DIR, 0o700, 'raise'),
511 cache_filename), 'a+')
512 self._cache_filename = self._cache_file.name
513 self._lock_file(self._cache_file)
514 self._cache_file.seek(0)
515 with self._state_lock:
517 self._state = json.load(self._cache_file)
518 if not set(['manifest', 'files']).issubset(set(self._state.keys())):
519 # Cache at least partially incomplete, set up new cache
520 self._state = copy.deepcopy(self.EMPTY_STATE)
522 # Cache file empty, set up new cache
523 self._state = copy.deepcopy(self.EMPTY_STATE)
524 # Load how many bytes were uploaded on previous run
525 with self._collection_lock:
526 self.bytes_written = self._collection_size(self._my_collection())
529 with self._state_lock:
530 self._state = copy.deepcopy(self.EMPTY_STATE)
532 def _lock_file(self, fileobj):
534 fcntl.flock(fileobj, fcntl.LOCK_EX | fcntl.LOCK_NB)
536 raise ResumeCacheConflict("{} locked".format(fileobj.name))
538 def _save_state(self):
540 Atomically save current state into cache.
543 with self._state_lock:
545 new_cache_fd, new_cache_name = tempfile.mkstemp(
546 dir=os.path.dirname(self._cache_filename))
547 self._lock_file(new_cache_fd)
548 new_cache = os.fdopen(new_cache_fd, 'r+')
549 json.dump(state, new_cache)
552 os.rename(new_cache_name, self._cache_filename)
553 except (IOError, OSError, ResumeCacheConflict) as error:
555 os.unlink(new_cache_name)
556 except NameError: # mkstemp failed.
559 self._cache_file.close()
560 self._cache_file = new_cache
562 def collection_name(self):
563 with self._collection_lock:
564 name = self._my_collection().api_response()['name'] if self._my_collection().api_response() else None
567 def manifest_locator(self):
568 with self._collection_lock:
569 locator = self._my_collection().manifest_locator()
572 def portable_data_hash(self):
573 with self._collection_lock:
574 datahash = self._my_collection().portable_data_hash()
577 def manifest_text(self, stream_name=".", strip=False, normalize=False):
578 with self._collection_lock:
579 manifest = self._my_collection().manifest_text(stream_name, strip, normalize)
582 def _datablocks_on_item(self, item):
584 Return a list of datablock locators, recursively navigating
585 through subcollections
587 if isinstance(item, arvados.arvfile.ArvadosFile):
589 for segment in item.segments():
590 loc = segment.locator
593 elif isinstance(item, arvados.collection.Collection):
594 l = [self._datablocks_on_item(x) for x in item.values()]
595 # Fast list flattener method taken from:
596 # http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python
597 return [loc for sublist in l for loc in sublist]
601 def data_locators(self):
602 with self._collection_lock:
603 # Make sure all datablocks are flushed before getting the locators
604 self._my_collection().manifest_text()
605 datablocks = self._datablocks_on_item(self._my_collection())
609 def expected_bytes_for(pathlist):
610 # Walk the given directory trees and stat files, adding up file sizes,
611 # so we can display progress as percent
613 for path in pathlist:
614 if os.path.isdir(path):
615 for filename in arvados.util.listdir_recursive(path):
616 bytesum += os.path.getsize(os.path.join(path, filename))
617 elif not os.path.isfile(path):
620 bytesum += os.path.getsize(path)
623 _machine_format = "{} {}: {{}} written {{}} total\n".format(sys.argv[0],
625 def machine_progress(bytes_written, bytes_expected):
626 return _machine_format.format(
627 bytes_written, -1 if (bytes_expected is None) else bytes_expected)
629 def human_progress(bytes_written, bytes_expected):
631 return "\r{}M / {}M {:.1%} ".format(
632 bytes_written >> 20, bytes_expected >> 20,
633 float(bytes_written) / bytes_expected)
635 return "\r{} ".format(bytes_written)
637 def progress_writer(progress_func, outfile=sys.stderr):
638 def write_progress(bytes_written, bytes_expected):
639 outfile.write(progress_func(bytes_written, bytes_expected))
640 return write_progress
642 def exit_signal_handler(sigcode, frame):
645 def desired_project_uuid(api_client, project_uuid, num_retries):
647 query = api_client.users().current()
648 elif arvados.util.user_uuid_pattern.match(project_uuid):
649 query = api_client.users().get(uuid=project_uuid)
650 elif arvados.util.group_uuid_pattern.match(project_uuid):
651 query = api_client.groups().get(uuid=project_uuid)
653 raise ValueError("Not a valid project UUID: {}".format(project_uuid))
654 return query.execute(num_retries=num_retries)['uuid']
656 def main(arguments=None, stdout=sys.stdout, stderr=sys.stderr):
659 args = parse_arguments(arguments)
661 if api_client is None:
662 api_client = arvados.api('v1')
664 # Determine the name to use
666 if args.stream or args.raw:
667 print >>stderr, "Cannot use --name with --stream or --raw"
669 collection_name = args.name
671 collection_name = "Saved at {} by {}@{}".format(
672 datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC"),
673 pwd.getpwuid(os.getuid()).pw_name,
674 socket.gethostname())
676 if args.project_uuid and (args.stream or args.raw):
677 print >>stderr, "Cannot use --project-uuid with --stream or --raw"
680 # Determine the parent project
682 project_uuid = desired_project_uuid(api_client, args.project_uuid,
684 except (apiclient_errors.Error, ValueError) as error:
685 print >>stderr, error
688 # write_copies diverges from args.replication here.
689 # args.replication is how many copies we will instruct Arvados to
690 # maintain (by passing it in collections().create()) after all
691 # data is written -- and if None was given, we'll use None there.
692 # Meanwhile, write_copies is how many copies of each data block we
693 # write to Keep, which has to be a number.
695 # If we simply changed args.replication from None to a default
696 # here, we'd end up erroneously passing the default replication
697 # level (instead of None) to collections().create().
698 write_copies = (args.replication or
699 api_client._rootDesc.get('defaultCollectionReplication', 2))
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,
713 bytes_expected = bytes_expected,
714 num_retries = args.retries,
715 write_copies = write_copies,
716 replication = 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)
777 writer.destroy_cache()
782 if __name__ == '__main__':