3 # arv-copy [--recursive] [--no-recursive] object-uuid src dst
5 # Copies an object from Arvados instance src to instance dst.
7 # By default, arv-copy recursively copies any dependent objects
8 # necessary to make the object functional in the new instance
9 # (e.g. for a pipeline instance, arv-copy copies the pipeline
10 # template, input collection, docker images, git repositories). If
11 # --no-recursive is given, arv-copy copies only the single record
12 # identified by object-uuid.
14 # The user must have files $HOME/.config/arvados/{src}.conf and
15 # $HOME/.config/arvados/{dst}.conf with valid login credentials for
16 # instances src and dst. If either of these files is not found,
17 # arv-copy will issue an error.
33 logger = logging.getLogger('arvados.arv-copy')
35 # local_repo_dir records which git repositories from the Arvados source
36 # instance have been checked out locally during this run, and to which
38 # e.g. if repository 'twp' from src_arv has been cloned into
39 # /tmp/gitfHkV9lu44A then local_repo_dir['twp'] = '/tmp/gitfHkV9lu44A'
44 parser = argparse.ArgumentParser(
45 description='Copy a pipeline instance from one Arvados instance to another.')
48 '-v', '--verbose', dest='verbose', action='store_true',
49 help='Verbose output.')
51 '-f', '--force', dest='force', action='store_true',
52 help='Perform copy even if the object appears to exist at the remote destination.')
54 '--src', dest='source_arvados', required=True,
55 help='The name of the source Arvados instance (required). May be either a pathname to a config file, or the basename of a file in $HOME/.config/arvados/instance_name.conf.')
57 '--dst', dest='destination_arvados', required=True,
58 help='The name of the destination Arvados instance (required). May be either a pathname to a config file, or the basename of a file in $HOME/.config/arvados/instance_name.conf.')
60 '--recursive', dest='recursive', action='store_true',
61 help='Recursively copy any dependencies for this object. (default)')
63 '--no-recursive', dest='recursive', action='store_false',
64 help='Do not copy any dependencies. NOTE: if this option is given, the copied object will need to be updated manually in order to be functional.')
66 '--dst-git-repo', dest='dst_git_repo',
67 help='The name of the destination git repository. Required when copying a pipeline recursively.')
69 '--project-uuid', dest='project_uuid',
70 help='The UUID of the project at the destination to which the pipeline should be copied.')
73 help='The UUID of the object to be copied.')
74 parser.set_defaults(recursive=True)
76 args = parser.parse_args()
79 logger.setLevel(logging.DEBUG)
81 logger.setLevel(logging.INFO)
83 # Create API clients for the source and destination instances
84 src_arv = api_for_instance(args.source_arvados)
85 dst_arv = api_for_instance(args.destination_arvados)
87 # Identify the kind of object we have been given, and begin copying.
88 t = uuid_type(src_arv, args.object_uuid)
90 result = copy_collection(args.object_uuid,
93 elif t == 'PipelineInstance':
94 result = copy_pipeline_instance(args.object_uuid,
97 dst_project=args.project_uuid,
98 recursive=args.recursive,
100 elif t == 'PipelineTemplate':
101 result = copy_pipeline_template(args.object_uuid,
104 recursive=args.recursive,
107 abort("cannot copy object {} of type {}".format(args.object_uuid, t))
109 # Clean up any outstanding temp git repositories.
110 for d in local_repo_dir.values():
111 shutil.rmtree(d, ignore_errors=True)
113 # If no exception was thrown and the response does not have an
114 # error_token field, presume success
115 if 'error_token' in result or 'uuid' not in result:
116 logger.error("API server returned an error result: {}".format(result))
120 logger.info("Success: created copy with uuid {}".format(result['uuid']))
123 # api_for_instance(instance_name)
125 # Creates an API client for the Arvados instance identified by
128 # If instance_name contains a slash, it is presumed to be a path
129 # (either local or absolute) to a file with Arvados configuration
132 # Otherwise, it is presumed to be the name of a file in
133 # $HOME/.config/arvados/instance_name.conf
135 def api_for_instance(instance_name):
136 if '/' in instance_name:
137 config_file = instance_name
139 config_file = os.path.join(os.environ['HOME'], '.config', 'arvados', "{}.conf".format(instance_name))
142 cfg = arvados.config.load(config_file)
143 except (IOError, OSError) as e:
144 abort(("Could not open config file {}: {}\n" +
145 "You must make sure that your configuration tokens\n" +
146 "for Arvados instance {} are in {} and that this\n" +
147 "file is readable.").format(
148 config_file, e, instance_name, config_file))
150 if 'ARVADOS_API_HOST' in cfg and 'ARVADOS_API_TOKEN' in cfg:
152 cfg.get('ARVADOS_API_HOST_INSECURE', '').lower() in set(
153 ['1', 't', 'true', 'y', 'yes']))
154 client = arvados.api('v1',
155 host=cfg['ARVADOS_API_HOST'],
156 token=cfg['ARVADOS_API_TOKEN'],
157 insecure=api_is_insecure,
160 abort('need ARVADOS_API_HOST and ARVADOS_API_TOKEN for {}'.format(instance_name))
163 # copy_pipeline_instance(pi_uuid, dst_git_repo, dst_project, recursive, src, dst)
165 # Copies a pipeline instance identified by pi_uuid from src to dst.
167 # If the 'recursive' option evaluates to True:
168 # 1. Copies all input collections
169 # * For each component in the pipeline, include all collections
170 # listed as job dependencies for that component)
171 # 2. Copy docker images
172 # 3. Copy git repositories
173 # 4. Copy the pipeline template
175 # The 'force' option is passed through to copy_collections.
177 # The only changes made to the copied pipeline instance are:
178 # 1. The original pipeline instance UUID is preserved in
179 # the 'properties' hash as 'copied_from_pipeline_instance_uuid'.
180 # 2. The pipeline_template_uuid is changed to the new template uuid.
181 # 3. The owner_uuid of the instance is changed to the user who
184 def copy_pipeline_instance(pi_uuid, src, dst, dst_git_repo, dst_project=None, recursive=True, force=False):
185 # Fetch the pipeline instance record.
186 pi = src.pipeline_instances().get(uuid=pi_uuid).execute()
190 abort('--dst-git-repo is required when copying a pipeline recursively.')
191 # Copy the pipeline template and save the copied template.
192 if pi.get('pipeline_template_uuid', None):
193 pt = copy_pipeline_template(pi['pipeline_template_uuid'],
198 # Copy input collections, docker images and git repos.
199 pi = copy_collections(pi, src, dst, force)
200 copy_git_repos(pi, src, dst, dst_git_repo)
202 # Update the fields of the pipeline instance with the copied
204 if pi.get('pipeline_template_uuid', None):
205 pi['pipeline_template_uuid'] = pt['uuid']
209 print >>sys.stderr, "Copying only pipeline instance {}.".format(pi_uuid)
210 print >>sys.stderr, "You are responsible for making sure all pipeline dependencies have been updated."
212 # Update the pipeline instance properties, and create the new
214 pi['properties']['copied_from_pipeline_instance_uuid'] = pi_uuid
215 pi['description'] = "Pipeline copied from {}\n\n{}".format(
216 pi_uuid, pi.get('description', ''))
218 pi['owner_uuid'] = dst_project
222 pi['ensure_unique_name'] = True
224 new_pi = dst.pipeline_instances().create(body=pi).execute()
227 # copy_pipeline_template(pt_uuid, src, dst, dst_git_repo, recursive)
229 # Copies a pipeline template identified by pt_uuid from src to dst.
231 # If the 'recursive' option evaluates to true, also copy any collections,
232 # docker images and git repositories that this template references.
234 # The owner_uuid of the new template is changed to that of the user
235 # who copied the template.
237 # Returns the copied pipeline template object.
239 def copy_pipeline_template(pt_uuid, src, dst, dst_git_repo, recursive=True, force=False):
240 # fetch the pipeline template from the source instance
241 pt = src.pipeline_templates().get(uuid=pt_uuid).execute()
245 abort('--dst-git-repo is required when copying a pipeline recursively.')
246 # Copy input collections, docker images and git repos.
247 pt = copy_collections(pt, src, dst, force)
248 copy_git_repos(pt, src, dst, dst_git_repo)
250 pt['description'] = "Pipeline template copied from {}\n\n{}".format(
251 pt_uuid, pt.get('description', ''))
252 pt['name'] = "{} copied from {}".format(pt.get('name', ''), pt_uuid)
253 pt['ensure_unique_name'] = True
257 return dst.pipeline_templates().create(body=pt).execute()
259 # copy_collections(obj, src, dst)
261 # Recursively copies all collections referenced by 'obj' from src
264 # Returns a copy of obj with any old collection uuids replaced by
267 def copy_collections(obj, src, dst, force=False):
268 if type(obj) in [str, unicode]:
269 if uuid_type(src, obj) == 'Collection':
270 newc = copy_collection(obj, src, dst, force)
271 if obj != newc['uuid'] and obj != newc['portable_data_hash']:
274 elif type(obj) == dict:
275 return {v: copy_collections(obj[v], src, dst, force) for v in obj}
276 elif type(obj) == list:
277 return [copy_collections(v, src, dst, force) for v in obj]
280 # copy_git_repos(p, src, dst, dst_repo)
282 # Copies all git repositories referenced by pipeline instance or
283 # template 'p' from src to dst.
285 # For each component c in the pipeline:
286 # * Copy git repositories named in c['repository'] and c['job']['repository'] if present
287 # * Rename script versions:
288 # * c['script_version']
289 # * c['job']['script_version']
290 # * c['job']['supplied_script_version']
291 # to the commit hashes they resolve to, since any symbolic
292 # names (tags, branches) are not preserved in the destination repo.
294 # The pipeline object is updated in place with the new repository
295 # names. The return value is undefined.
297 def copy_git_repos(p, src, dst, dst_repo):
299 for c in p['components']:
300 component = p['components'][c]
301 if 'repository' in component:
302 repo = component['repository']
303 if repo not in copied:
304 copy_git_repo(repo, src, dst, dst_repo)
306 component['repository'] = dst_repo
307 if 'script_version' in component:
308 repo_dir = local_repo_dir[repo]
309 component['script_version'] = git_rev_parse(component['script_version'], repo_dir)
310 if 'job' in component:
312 if 'repository' in j:
313 repo = j['repository']
314 if repo not in copied:
315 copy_git_repo(repo, src, dst, dst_repo)
317 j['repository'] = dst_repo
318 repo_dir = local_repo_dir[repo]
319 if 'script_version' in j:
320 j['script_version'] = git_rev_parse(j['script_version'], repo_dir)
321 if 'supplied_script_version' in j:
322 j['supplied_script_version'] = git_rev_parse(j['supplied_script_version'], repo_dir)
324 # copy_collection(obj_uuid, src, dst, force)
326 # Copies the collection identified by obj_uuid from src to dst.
327 # Returns the collection object created at dst.
329 # If a collection with the desired portable_data_hash already
330 # exists at dst, and the 'force' argument is False, copy_collection
331 # returns the existing collection without copying any blocks.
332 # Otherwise (if no collection exists or if 'force' is True)
333 # copy_collection copies all of the collection data blocks from src
336 # For this application, it is critical to preserve the
337 # collection's manifest hash, which is not guaranteed with the
338 # arvados.CollectionReader and arvados.CollectionWriter classes.
339 # Copying each block in the collection manually, followed by
340 # the manifest block, ensures that the collection's manifest
341 # hash will not change.
343 def copy_collection(obj_uuid, src, dst, force=False):
344 c = src.collections().get(uuid=obj_uuid).execute()
346 # If a collection with this hash already exists at the
347 # destination, and 'force' is not true, just return that
350 if 'portable_data_hash' in c:
351 colhash = c['portable_data_hash']
354 dstcol = dst.collections().list(
355 filters=[['portable_data_hash', '=', colhash]]
357 if dstcol['items_available'] > 0:
358 logger.info("Skipping collection %s (already at dst)", obj_uuid)
359 return dstcol['items'][0]
361 logger.info("Copying collection %s", obj_uuid)
363 # Fetch the collection's manifest.
364 manifest = c['manifest_text']
366 # Enumerate the block locators found in the manifest.
367 collection_blocks = set()
368 src_keep = arvados.keep.KeepClient(api_client=src, num_retries=2)
369 for line in manifest.splitlines():
370 for block_hash in line.split()[1:]:
371 if arvados.util.portable_data_hash_pattern.match(block_hash):
372 collection_blocks.add(block_hash)
376 # Copy each block from src_keep to dst_keep.
377 dst_keep = arvados.keep.KeepClient(api_client=dst, num_retries=2)
378 for locator in collection_blocks:
379 parts = locator.split('+')
380 logger.info("Copying block %s (%s bytes)", locator, parts[1])
381 data = src_keep.get(locator)
384 # Copy the manifest and save the collection.
385 logger.debug('saving {} manifest: {}'.format(obj_uuid, manifest))
386 dst_keep.put(manifest)
390 if 'owner_uuid' in c:
392 c['ensure_unique_name'] = True
393 return dst.collections().create(body=c).execute()
395 # copy_git_repo(src_git_repo, src, dst, dst_git_repo)
397 # Copies commits from git repository 'src_git_repo' on Arvados
398 # instance 'src' to 'dst_git_repo' on 'dst'. Both src_git_repo
399 # and dst_git_repo are repository names, not UUIDs (i.e. "arvados"
402 # All commits will be copied to a destination branch named for the
403 # source repository URL.
405 # Because users cannot create their own repositories, the
406 # destination repository must already exist.
408 # The user running this command must be authenticated
409 # to both repositories.
411 def copy_git_repo(src_git_repo, src, dst, dst_git_repo):
412 # Identify the fetch and push URLs for the git repositories.
413 r = src.repositories().list(
414 filters=[['name', '=', src_git_repo]]).execute()
415 if r['items_available'] != 1:
416 raise Exception('cannot identify source repo {}; {} repos found'
417 .format(src_git_repo, r['items_available']))
418 src_git_url = r['items'][0]['fetch_url']
419 logger.debug('src_git_url: {}'.format(src_git_url))
421 r = dst.repositories().list(
422 filters=[['name', '=', dst_git_repo]]).execute()
423 if r['items_available'] != 1:
424 raise Exception('cannot identify destination repo {}; {} repos found'
425 .format(dst_git_repo, r['items_available']))
426 dst_git_push_url = r['items'][0]['push_url']
427 logger.debug('dst_git_push_url: {}'.format(dst_git_push_url))
429 dst_branch = re.sub(r'\W+', '_', src_git_url)
431 # Copy git commits from src repo to dst repo (but only if
432 # we have not already copied this repo in this session).
434 if src_git_repo in local_repo_dir:
435 logger.debug('already copied src repo %s, skipping', src_git_repo)
437 tmprepo = tempfile.mkdtemp()
438 local_repo_dir[src_git_repo] = tmprepo
439 arvados.util.run_command(
440 ["git", "clone", src_git_url, tmprepo],
441 cwd=os.path.dirname(tmprepo))
442 arvados.util.run_command(
443 ["git", "checkout", "-b", dst_branch],
445 arvados.util.run_command(["git", "remote", "add", "dst", dst_git_push_url], cwd=tmprepo)
446 arvados.util.run_command(["git", "push", "dst", dst_branch], cwd=tmprepo)
448 # git_rev_parse(rev, repo)
450 # Returns the 40-character commit hash corresponding to 'rev' in
451 # git repository 'repo' (which must be the path of a local git
454 def git_rev_parse(rev, repo):
455 gitout, giterr = arvados.util.run_command(
456 ['git', 'rev-parse', rev], cwd=repo)
457 return gitout.strip()
459 # uuid_type(api, object_uuid)
461 # Returns the name of the class that object_uuid belongs to, based on
462 # the second field of the uuid. This function consults the api's
463 # schema to identify the object class.
465 # It returns a string such as 'Collection', 'PipelineInstance', etc.
467 # Special case: if handed a Keep locator hash, return 'Collection'.
469 def uuid_type(api, object_uuid):
470 if re.match(r'^[a-f0-9]{32}\+[0-9]+(\+[A-Za-z0-9+-]+)?$', object_uuid):
472 p = object_uuid.split('-')
475 for k in api._schema.schemas:
476 obj_class = api._schema.schemas[k].get('uuidPrefix', None)
477 if type_prefix == obj_class:
481 def abort(msg, code=1):
482 print >>sys.stderr, "arv-copy:", msg
485 if __name__ == '__main__':