diff --git a/.travis.yml b/.travis.yml index d20cf3f2e..10a0fbcc7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -39,6 +39,7 @@ install: - mkdir -p ~/.aws && printf "[default]\naws_access_key_id = ABCDEFG\naws_secret_access_key = 123456789" > ~/.aws/credentials script: - ./unittests.sh + - ./functests.sh - if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ./build_macos.sh; else ./build_linux.sh; fi - ./build_package.sh after_sucess: diff --git a/dvc/cli.py b/dvc/cli.py index 10701d03f..1072d7272 100644 --- a/dvc/cli.py +++ b/dvc/cli.py @@ -10,11 +10,12 @@ from dvc.command.init import CmdInit from dvc.command.remove import CmdRemove from dvc.command.run import CmdRun from dvc.command.repro import CmdRepro -from dvc.command.data_sync import CmdDataSync, CmdDataPush, CmdDataPull +from dvc.command.data_sync import CmdDataSync, CmdDataPush, CmdDataPull, CmdDataStatus from dvc.command.lock import CmdLock from dvc.command.gc import CmdGC from dvc.command.import_file import CmdImportFile from dvc.command.target import CmdTarget +from dvc.command.config import CmdConfig from dvc.command.test import CmdTest from dvc.config import Config from dvc import VERSION @@ -156,6 +157,13 @@ def parse_args(argv=None): help='Push data files to the cloud') push_parser.set_defaults(func=CmdDataPush) + # Status + status_parser = subparsers.add_parser( + 'status', + parents=[parent_sync_parser], + help='Show status for data files') + status_parser.set_defaults(func=CmdDataStatus) + # Repro repro_parser = subparsers.add_parser( 'repro', @@ -291,6 +299,19 @@ def parse_args(argv=None): help='Reset target.') target_parser.set_defaults(func=CmdTarget) + # Config + config_parser = subparsers.add_parser( + 'config', + parents=[parent_parser], + help='Get or set repository options') + config_parser.add_argument('name', + help='Option name') + config_parser.add_argument('value', + nargs='?', + default=None, + help='Option value') + config_parser.set_defaults(func=CmdConfig) + if isinstance(argv, str): argv = argv.split() diff --git a/dvc/command/config.py b/dvc/command/config.py new file mode 100644 index 000000000..340c40fbf --- /dev/null +++ b/dvc/command/config.py @@ -0,0 +1,51 @@ +import os +import configobj + +from dvc.command.base import CmdBase +from dvc.logger import Logger +from dvc.config import Config + +class CmdConfig(CmdBase): + def __init__(self, settings): + super(CmdConfig, self).__init__(settings) + + @property + def _config_path(self): + return os.path.join(self.git.git_dir, Config.CONFIG) + + def _find_key(self, l, name): + for k in l: + if k.lower() == name.lower(): + return k + + return None + + def run(self): + _section, _opt = self.parsed_args.name.strip().split('.') + + # Using configobj because it doesn't + # drop comments like configparser does. + config = configobj.ConfigObj(self._config_path) + + section = self._find_key(config.keys(), _section) + if not section: + return 1 + + opt = self._find_key(config[section].keys(), _opt) + if not opt: + return 1 + + if self.parsed_args.value == None: + Logger.info(config[section][opt]) + return 0 + + try: + config[section][opt] = self.parsed_args.value + config.write() + except Exception as exc: + Logger.error('Failed to set \'{}\' to \'{}\': {}'.format(self.parsed_args.name, + self.parsed_args.value, + exc)) + return 1 + + return 0 diff --git a/dvc/command/data_sync.py b/dvc/command/data_sync.py index ce6c0b317..9b377c7b2 100644 --- a/dvc/command/data_sync.py +++ b/dvc/command/data_sync.py @@ -1,4 +1,7 @@ from dvc.command.base import CmdBase, DvcLock +from dvc.logger import Logger + +import dvc.data_cloud as cloud class CmdDataSync(CmdBase): def __init__(self, settings): @@ -25,3 +28,25 @@ class CmdDataPush(CmdBase): def run(self): with DvcLock(self.is_locker, self.git): self.cloud.push(self.parsed_args.targets, self.parsed_args.jobs) + +class CmdDataStatus(CmdBase): + def __init__(self, settings): + super(CmdDataStatus, self).__init__(settings) + + def run(self): + with DvcLock(self.is_locker, self.git): + status = self.cloud.status(self.parsed_args.targets, self.parsed_args.jobs) + + for s in status: + target, ret = s + + if ret == cloud.STATUS_UNKNOWN or ret == cloud.STATUS_OK: + continue + + prefix_map = { + cloud.STATUS_DELETED : 'deleted: ', + cloud.STATUS_MODIFIED : 'modified:', + cloud.STATUS_NEW : 'new file:', + } + + Logger.info('\t{}\t{}'.format(prefix_map[ret], target.resolved_cache.dvc)) diff --git a/dvc/command/import_file.py b/dvc/command/import_file.py index 981fd6f4c..e6530bf8b 100644 --- a/dvc/command/import_file.py +++ b/dvc/command/import_file.py @@ -1,15 +1,18 @@ import os import re -import requests + +try: + from urlparse import urlparse +except ImportError: + # Python 3 + from urllib.parse import urlparse from dvc.command.base import CmdBase, DvcLock -from dvc.data_cloud import sizeof_fmt +from dvc.data_cloud import sizeof_fmt, file_md5 from dvc.logger import Logger from dvc.exceptions import DvcException from dvc.state_file import StateFile from dvc.system import System -from dvc.progress import progress -from dvc.utils import copyfile, map_progress class ImportFileError(DvcException): def __init__(self, msg): @@ -106,111 +109,27 @@ class CmdImportFile(CmdBase): if not os.path.exists(cache_dir): os.makedirs(cache_dir) - data_targets.append((input, output, data_item)) + data_targets.append((input, data_item)) return data_targets def import_files(self, targets, lock=False): data_targets = self.collect_targets(targets) - self.download_targets(data_targets) - self.create_state_files(data_targets, lock) - - def download_target(self, target): - """ - Download single target from url or from local path. - """ - input = target[0] - output = target[2].cache.relative - - if self.is_url(input): - Logger.debug("Downloading {} -> {}.".format(input, output)) - self.download_file(input, output) - Logger.debug("Done downloading {} -> {}.".format(input, output)) - else: - Logger.debug("Copying {} -> {}".format(input, output)) - self.copy_file(input, output) - Logger.debug("Dony copying {} -> {}".format(input, output)) - - @staticmethod - def copy_file(input, output): - """ - Copy single file from local path. - """ - copyfile(input, output) - - def download_file(self, from_url, to_file): - """ - Download single file from url. - """ - - tmp_file = to_file + '.part' - name = os.path.basename(from_url) - chunk_size = 1024 * 100 - downloaded = 0 - last_reported = 0 - report_bucket = 100*1024*10 - - resume_header = None - mode = 'wb' - - # Resume download if we can - if os.path.exists(tmp_file) and self.parsed_args.cont: - mode = 'ab' - - downloaded = os.path.getsize(tmp_file) - resume_header = {'Range': 'bytes=%d-' % downloaded} - - Logger.debug('found existing {} file, resuming download'.format(tmp_file)) - - r = requests.get(from_url, stream=True, headers=resume_header) - - content_range = r.headers.get('content-range') - if resume_header and content_range == None: - mode = 'wb' - downloaded = 0 - - Logger.debug('\'range\' is not supported by the server. Can\'t resume download') - - total_length = r.headers.get('content-length') - if total_length == None: - Logger.debug('\'content-length\' is not supported by the server') - - with open(tmp_file, mode) as f: - for chunk in r.iter_content(chunk_size=chunk_size): - if not chunk: # filter out keep-alive new chunks - continue - - downloaded += len(chunk) - - last_reported += chunk_size - if last_reported >= report_bucket: - last_reported = 0 - Logger.debug('Downloaded {}'.format(sizeof_fmt(downloaded))) - - # update progress bar - progress.update_target(name, downloaded, total_length) - - f.write(chunk) - - # tell progress bar that this target is finished downloading - progress.finish_target(name) - - os.rename(tmp_file, to_file) - - def download_targets(self, targets): - """ - Download targets in a number of threads. - """ - map_progress(self.download_target, targets, self.parsed_args.jobs) + imported_targets = self.cloud.import_data(data_targets, self.parsed_args.jobs) + self.create_state_files(imported_targets, lock) def create_state_files(self, targets, lock): """ Create state files for all targets. """ for t in targets: - input = t[0] - output = t[1] - data_item = t[2] + orig_target, processed_data_item = t + input, data_item = orig_target + output = data_item.data.relative + + if processed_data_item == None: + Logger.debug('Skipping creating state file for failed import {}'.format(data_item.state.relative)) + continue Logger.debug('Creating symlink {} --> {}'.format(data_item.symlink_file, data_item.data.relative)) System.symlink(data_item.symlink_file, data_item.data.relative) @@ -225,14 +144,6 @@ class CmdImportFile(CmdBase): state_file.save() Logger.debug('State file "{}" was created'.format(data_item.state.relative)) - URL_REGEX = re.compile( - r'^(?:http|ftp)s?://' # http:// or https:// - r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... - r'localhost|' # localhost... - r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip - r'(?::\d+)?' # optional port - r'(?:/?|[/?]\S+)$', re.IGNORECASE) - @staticmethod def is_url(url): - return CmdImportFile.URL_REGEX.match(url) is not None + return len(urlparse(url).scheme) != 0 diff --git a/dvc/data_cloud.py b/dvc/data_cloud.py index 2adf09052..c79c0e186 100644 --- a/dvc/data_cloud.py +++ b/dvc/data_cloud.py @@ -4,10 +4,19 @@ import os import threading import configparser import tempfile +import requests +import configparser +import filecmp from boto.s3.connection import S3Connection from google.cloud import storage as gc +try: + from urlparse import urlparse +except ImportError: + # Python 3 + from urllib.parse import urlparse + import dvc from dvc.logger import Logger from dvc.exceptions import DvcException @@ -19,6 +28,20 @@ from dvc.system import System from dvc.utils import map_progress +STATUS_UNKNOWN = 0 +STATUS_OK = 1 +STATUS_MODIFIED = 2 +STATUS_NEW = 3 +STATUS_DELETED = 4 + +STATUS_MAP = { + # (local_exists, remote_exists, cmp) + (True, True, True) : STATUS_OK, + (True, True, False) : STATUS_MODIFIED, + (True, False, None) : STATUS_NEW, + (False, True, None) : STATUS_DELETED, +} + class DataCloudError(DvcException): def __init__(self, msg): super(DataCloudError, self).__init__('Data sync error: {}'.format(msg)) @@ -99,21 +122,35 @@ class DataCloudBase(object): def cache_file_key(self, file): return '{}/{}'.format(self.storage_prefix, file).strip('/') + def tmp_file(self, fname): + return fname + '.part' + def sanity_check(self): pass + def _import(self, bucket, path, fname, item): + pass + def push(self, item): pass def pull(self, item): - pass + fname = item.resolved_cache.dvc + key_name = self.cache_file_key(fname) + + return self._import(self.storage_bucket, key_name, fname, data_item) + + def import_data(self, url, item): + o = urlparse(url) + + return self._import(o.netloc, o.path, item.cache.relative, item) def sync(self, item): if os.path.isfile(item.resolved_cache.dvc): - self.push(item) + return self.push(item) else: self.create_directory(item) - self.pull(item) + return self.pull(item) def create_directory(self, item): self._lock.acquire() @@ -134,20 +171,151 @@ class DataCloudBase(object): def remove(self, item): pass + def _status(self, item): + pass + + def status(self, item): + return STATUS_MAP.get(self._status(item), STATUS_UNKNOWN) class DataCloudLOCAL(DataCloudBase): def push(self, item): Logger.debug('sync to cloud ' + item.resolved_cache.dvc + " " + self.storage_path) copyfile(item.resolved_cache.dvc, self.storage_path) + return item + + def _import(self, i, out, item): + tmp_file = self.tmp_file(out) + try: + copyfile(i, tmp_file) + os.rename(tmp_file, out) + except Exception as exc: + Logger.error('Failed to copy "{}": {}'.format(i, exc)) + return None + + return item def pull(self, item): Logger.debug('sync from cloud ' + self.storage_path + " " + item.resolved_cache.dvc) - copyfile(self.storage_path, item.resolved_cache.dvc) + return self._import(self.storage_path, item.resolved_cache.dvc, item) def remove(self, item): Logger.debug('rm from cloud ' + item.resolved_cache.dvc) os.remove(item.resolved_cache.dvc) + def import_data(self, path, item): + Logger.debug('import from cloud ' + path + " " + item.cache.relative) + return self._import(path, item.cache.relative, item) + + def _status(self, data_item): + local = data_item.resolved_cache.relative + remote = '{}/{}'.format(self.storage_path, os.path.basename(local)) + + remote_exists = os.path.exists(remove) + local_exists = os.path.exists(local) + c = None + if local_exists and remote_exists: + c = filecmp.cmp(local, remote) + + return (local_exists, remote_exists, c) + +class DataCloudHTTP(DataCloudBase): + def push(self, item): + raise Exception('Not implemented yet') + + def pull(self, item): + raise Exception('Not implemented yet') + + def remove(self, item): + raise Exception('Not implemented yet') + + def status(self, item): + raise Exception('Not implemented yet') + + def _downloaded_size(self, fname): + if os.path.exists(fname) and self.parsed_args.cont: + downloaded = os.path.getsize(fname) + header = {'Range': 'bytes=%d-' % downloaded} + + Logger.debug('found existing {} file, resuming download'.format(tmp_file)) + + return (downloaded, header) + + return (0, None) + + def _get_header(self, r, name): + val = r.headers.get(name) + if val == None: + Logger.debug('\'{}\' not supported by the server'.format(name)) + + return val + + def _verify_downloaded_size(self, r, downloaded_size): + content_range = self._get_header(r, 'content-range') + if downloaded_size and content_range == None: + Logger.debug('Can\'t resume download') + return 0 + + return downloaded_size + + def _download(self, r, fname, downloaded): + mode = 'ab' if downloaded else 'wb' + name = os.path.basename(r.url) + total_length = self._get_header(r, 'content-length') + chunk_size = 1024 * 100 + + progress.update_target(name, downloaded, total_length) + + with open(fname, mode) as f: + for chunk in r.iter_content(chunk_size=chunk_size): + if not chunk: # filter out keep-alive new chunks + continue + + f.write(chunk) + downloaded += len(chunk) + progress.update_target(name, downloaded, total_length) + + + progress.finish_target(name) + + def _verify_md5(self, r, fname): + md5 = file_md5(fname)[0] + content_md5 = self._get_header(r, 'content-md5') + + if content_md5 == None: + return True + + if md5 != content_md5: + Logger.error('Checksum mismatch') + return False + + Logger.debug('Checksum matches') + return True + + def import_data(self, url, item): + """ + Download single file from url. + """ + + to_file = item.cache.relative + tmp_file = self.tmp_file(to_file) + + downloaded, header = self._downloaded_size(tmp_file) + r = requests.get(url, stream=True, headers=header) + downloaded = self._verify_downloaded_size(r, downloaded) + + try: + self._download(r, tmp_file, downloaded) + except Exception as exc: + Logger.error('Failed to download "{}": {}'.format(url, exc)) + return None + + if not self._verify_md5(r, tmp_file): + return None + + os.rename(tmp_file, to_file) + + return item + class DataCloudAWS(DataCloudBase): """ DataCloud class for Amazon Web Services """ @@ -238,13 +406,12 @@ class DataCloudAWS(DataCloudBase): Logger.info("can't find aws credetials, assuming envirment variables or iam role") self._aws_creds = creds - def _get_bucket_aws(self): + def _get_bucket_aws(self, bucket_name): """ get a bucket object, aws """ if all([self.aws_access_key_id, self.aws_secret_access_key, self.aws_region_host]): conn = S3Connection(self.aws_access_key_id, self.aws_secret_access_key, host=self.aws_region_host) else: conn = S3Connection() - bucket_name = self.storage_bucket bucket = conn.lookup(bucket_name) if bucket is None: raise DataCloudError('Storage path is not setup correctly') @@ -259,50 +426,47 @@ class DataCloudAWS(DataCloudBase): return False - def pull(self, item): - """ sync from cloud, aws version """ + def _import(self, bucket_name, key_name, fname, data_item): - bucket = self._get_bucket_aws() + bucket = self._get_bucket_aws(bucket_name) - fname = item.resolved_cache.dvc - key_name = self.cache_file_key(fname) + tmp_file = self.tmp_file(fname) + name = os.path.basename(fname) key = bucket.get_key(key_name) if not key: Logger.error('File "{}" does not exist in the cloud'.format(key_name)) - return + return None if self._cmp_checksum(key, fname): Logger.debug('File "{}" matches with "{}".'.format(fname, key_name)) - return + return data_item - Logger.info('Downloading cache file from S3 "{}/{}"'.format(bucket.name, key_name)) + Logger.debug('Downloading cache file from S3 "{}/{}" to "{}"'.format(bucket.name, key_name, fname)) try: - temp_file = tempfile.NamedTemporaryFile(dir=item.resolved_cache.dirname, delete=False) - key.get_contents_to_filename(temp_file.name, - cb=create_cb(item.resolved_cache.relative)) - os.rename(temp_file.name, item.resolved_cache.relative) + key.get_contents_to_filename(tmp_file, cb=create_cb(name)) + os.rename(tmp_file, fname) except Exception as exc: Logger.error('Failed to download "{}": {}'.format(key_name, exc)) - if temp_file and os.path.exists(temp_file.name): - os.remove(temp_file.name) - return + return None - progress.finish_target(os.path.basename(item.resolved_cache.relative)) - Logger.info('Downloading completed') + progress.finish_target(name) + Logger.debug('Downloading completed') + + return data_item def push(self, data_item): """ push, aws version """ aws_key = self.cache_file_key(data_item.resolved_cache.dvc) - bucket = self._get_bucket_aws() + bucket = self._get_bucket_aws(self.storage_bucket) key = bucket.get_key(aws_key) if key: Logger.debug('File already uploaded to the cloud. Checksum validation...') if self._cmp_checksum(key, data_item.resolved_cache.dvc): Logger.debug('File checksum matches. No uploading is needed.') - return + return data_item Logger.debug('Checksum miss-match. Re-uploading is required.') @@ -313,10 +477,25 @@ class DataCloudAWS(DataCloudBase): cb=create_cb(data_item.resolved_cache.relative)) except Exception as exc: Logger.error('Failed to upload "{}": {}'.format(data_item.resolved_cache.relative, exc)) - return + return None progress.finish_target(os.path.basename(data_item.resolved_cache.relative)) + return data_item + + def _status(self, data_item): + aws_key = self.cache_file_key(data_item.resolved_cache.dvc) + bucket = self._get_bucket_aws(self.storage_bucket) + key = bucket.get_key(aws_key) + + remote_exists = key is not None + local_exists = os.path.exists(data_item.resolved_cache.relative) + c = None + if remote_exists and local_exists: + c = self._cmp_checksum(key, data_item.resolved_cache.dvc) + + return (local_exists, remote_exists, c) + def remove(self, data_item): aws_file_name = self.cache_file_key(data_item.cache.dvc) @@ -349,49 +528,93 @@ class DataCloudGCP(DataCloudBase): if project is None or len(project) < 1: raise ConfigError('can\'t read google cloud project name. Please set ProjectName in section GC.') - def _get_bucket_gc(self): + def _get_bucket_gc(self, storage_bucket): """ get a bucket object, gc """ client = gc.Client(project=self.gc_project_name) - bucket = client.bucket(self.storage_bucket) + bucket = client.bucket(storage_bucket) if not bucket.exists(): raise DataCloudError('sync up: google cloud bucket {} doesn\'t exist'.format(self.storage_bucket)) return bucket - def pull(self, item): - """ sync from cloud, gcp version """ + def _cmp_checksum(self, blob, fname): + b64_encoded_md5 = base64.b64encode(file_md5(fname)[1]) - bucket = self._get_bucket_gc() - key = self.cache_file_key(item.resolved_cache.dvc) + if blob.md5_hash == b64_encoded_md5: + return True + + return False + + def _import(self, bucket_name, key, fname, data_item): + + bucket = self._get_bucket_gc(bucket_name) + + name = os.path.basename(fname) + tmp_file = self.tmp_file(fname) blob = bucket.get_blob(key) if not blob: Logger.error('File "{}" does not exist in the cloud'.format(key)) - return + return None Logger.info('Downloading cache file from gc "{}/{}"'.format(bucket.name, key)) - blob.download_to_filename(item.resolved_cache.dvc) + # percent_cb is not available for download_to_filename, so + # lets at least update progress at keypoints(start, finish) + progress.update_target(name, 0, None) + + try: + blob.download_to_filename(tmp_file) + os.rename(tmp_file, fname) + except Exception as exc: + Logger.error('Failed to download "{}": {}'.format(key, exc)) + return None + + progress.finish_target(name) + Logger.info('Downloading completed') + return data_item + def push(self, data_item): """ push, gcp version """ - bucket = self._get_bucket_gc() + bucket = self._get_bucket_gc(self.storage_bucket) blob_name = self.cache_file_key(data_item.resolved_cache.dvc) + name = os.path.basename(data_item.resolved_cache.dvc) blob = bucket.get_blob(blob_name) if blob is not None and blob.exists(): - b64_encoded_md5 = base64.b64encode(file_md5(data_item.resolved_cache.dvc)[1]) - - if blob.md5_hash == b64_encoded_md5: + if self._cmp_checksum(blob, data_item.resolved_cache.dvc): Logger.debug('checksum %s matches. Skipping upload' % data_item.cache.relative) - return + return data_item Logger.debug('checksum %s mismatch. re-uploading' % data_item.cache.relative) + # same as in _import + progress.update_target(name, 0, None) + blob = bucket.blob(blob_name) blob.upload_from_filename(data_item.resolved_cache.relative) + + progress.finish_target(name) Logger.info('uploading %s completed' % data_item.resolved_cache.relative) + return data_item + + def _status(self, data_item): + """ status, gcp version """ + + bucket = self._get_bucket_gc(self.storage_bucket) + blob_name = self.cache_file_key(data_item.resolved_cache.dvc) + blob = bucket.get_blob(blob_name) + + remote_exists = blob is not None and blob.exists() + local_exists = os.path.exists(data_item.resolved_cache.relative) + c = None + if remote_exists and local_exists: + c = self._cmp_checksum(blob, data_item.resolved_cache.dvc) + + return (local_exists, remote_exists, c) + def remove(self, item): raise Exception('NOT IMPLEMENTED YET') @@ -400,9 +623,19 @@ class DataCloud(object): """ Generic class to do initial config parsing and redirect to proper DataCloud methods """ CLOUD_MAP = { - 'AWS': DataCloudAWS, - 'GCP': DataCloudGCP, - 'LOCAL': DataCloudLOCAL, + 'AWS' : DataCloudAWS, + 'GCP' : DataCloudGCP, + 'HTTP' : DataCloudHTTP, + 'LOCAL' : DataCloudLOCAL, + } + + SCHEME_MAP = { + 's3' : 'AWS', + 'http' : 'HTTP', + 'https' : 'HTTP', + 'ftp' : 'HTTP', + 'gs' : 'GCP', + '' : 'LOCAL', } def __init__(self, settings): @@ -410,6 +643,8 @@ class DataCloud(object): #To handle ConfigI case if not hasattr(settings.config, '_config'): + self._settings = settings + self._config = configparser.ConfigParser() self._cloud = DataCloudBase(None, None, None) return @@ -483,16 +718,39 @@ class DataCloud(object): def _map_targets(self, f, targets, jobs): collected = self._collect_targets(targets) - map_progress(f, collected, jobs) + return map_progress(f, collected, jobs) + + def _import(self, target): + url, item = target + o = urlparse(url) + + typ = self.SCHEME_MAP.get(o.scheme, None) + if typ == None: + Logger.error('Not supported scheme \'{}\''.format(o.scheme)) + return None + + cloud_config = None + if self._config.has_section(typ): + cloud_config = self._config[typ] + + cloud = self.CLOUD_MAP[typ](self._settings, self._config, cloud_config) + + return cloud.import_data(url, item) def sync(self, targets, jobs=1): - self._map_targets(self._cloud.sync, targets, jobs) + return self._map_targets(self._cloud.sync, targets, jobs) def push(self, targets, jobs=1): - self._map_targets(self._cloud.push, targets, jobs) + return self._map_targets(self._cloud.push, targets, jobs) def pull(self, targets, jobs=1): - self._map_targets(self._cloud.pull, targets, jobs) + return self._map_targets(self._cloud.pull, targets, jobs) + + def import_data(self, targets, jobs=1): + return map_progress(self._import, targets, jobs) def remove(self, item): return self._cloud.remove(item) + + def status(self, targets, jobs=1): + return self._map_targets(self._cloud.status, targets, jobs) diff --git a/dvc/path/data_item.py b/dvc/path/data_item.py index 04fb341a1..90e2fbff4 100644 --- a/dvc/path/data_item.py +++ b/dvc/path/data_item.py @@ -62,6 +62,9 @@ class DataItem(object): return self.data.dvc.__hash__() def __eq__(self, other): + if other == None: + return False + return self.data.dvc == other.data.dvc @property diff --git a/dvc/utils.py b/dvc/utils.py index bb4e8e11f..f2045f76b 100644 --- a/dvc/utils.py +++ b/dvc/utils.py @@ -68,8 +68,10 @@ def map_progress(func, targets, n_threads): p = ThreadPool(processes=n_threads) try: - p.map(func, targets) + ret = p.map(func, targets) except Exception as exc: Logger.error('Unexpected exception while processing targets: {}'.format(exc)) finally: progress.finish() + + return zip(targets, ret) diff --git a/functest/clean.sh b/functest/clean.sh index f75d4f11e..8d39fe6d4 100755 --- a/functest/clean.sh +++ b/functest/clean.sh @@ -1,5 +1,5 @@ +#!/bin/bash -source common.rc - -rm -rf $RAW_DATA_LOCAL $CODE_LOCAL $TEST_REPO +source common.sh +rm -rf $CACHE_DIR $TEST_REPO diff --git a/functest/common.rc b/functest/common.rc deleted file mode 100644 index dda00a5f8..000000000 --- a/functest/common.rc +++ /dev/null @@ -1,35 +0,0 @@ - -BASE_DIR_S3=https://s3-us-west-2.amazonaws.com/dataversioncontrol/functests -RAW_DATA_S3=$BASE_DIR_S3/stackoverflow_raw_small - -RAW_DATA_LOCAL=sync_raw_data -CODE_LOCAL=sync_code -TEST_REPO=repo_test - -function dvc_info() { - echo "=============== DVC test: $1 ===============" -} - -function _init_repo() { - dvc_info 'init reporitory' - git init - dvc init - - dvc_info 'import xml files' - mkdir data/xml - dvc data-import ../$RAW_DATA_LOCAL/* data/xml - - dvc_info 'copy code' - mkdir code - cp ../$CODE_LOCAL/* code/ - git add code/ - git commit -m 'Add code' -} - -function create_repo() { - dvc_info 'create reporitory' - rm -rf $TEST_REPO - mkdir $TEST_REPO - (cd $TEST_REPO && _init_repo) -} - diff --git a/functest/common.sh b/functest/common.sh new file mode 100644 index 000000000..094296428 --- /dev/null +++ b/functest/common.sh @@ -0,0 +1,120 @@ +#!/bin/bash + +set -e + +SDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +CACHE_DIR=$SDIR/cache +TEST_REPO=$SDIR/myrepo +CODE_CACHE=$CACHE_DIR/code +DATA_CACHE=$CACHE_DIR/data + +DATA="Badges.xml Tags.xml PostLinks.xml" +CODE="xmltotsv.py" + +REGION='us-west-2' +BASE_DIR_S3=https://s3-$REGION.amazonaws.com/dataversioncontrol/functests +DATA_S3=$BASE_DIR_S3/stackoverflow_raw_small +CODE_S3=$BASE_DIR_S3/code + +function dvc_print() { + echo -e "$1" +} + +function dvc_info() { + dvc_print "\e[34m$1\e[0m" +} + +function dvc_header() { + dvc_info "=============== DVC test: $1 ===============" +} + +function dvc_error() { + dvc_print "\e[31m$1\e[0m" +} + +function dvc_fail() { + dvc_error "FAIL" + exit 1 +} + +function dvc_fatal() { + dvc_error "$1" + dvc_fail +} + +function dvc_pass() { + dvc_print "\e[32mPASS\e[0m" + exit 0 +} + +trap 'dvc_fail;' ERR + +function dvc_prepare_cache() { + if [ -d $CACHE_DIR ]; then + return + fi + + mkdir -p $DATA_CACHE + pushd $DATA_CACHE + + for f in $DATA; do + wget $DATA_S3/$f + done + + popd + + mkdir -p $CODE_CACHE + pushd $CODE_CACHE + + for f in $CODE; do + wget $CODE_S3/$f + done + + popd +} + +function dvc_create_git_repo() { + dvc_info "Creating git repo" + + dvc_prepare_cache + + mkdir $TEST_REPO + cd $TEST_REPO + + git init + + git config user.name "DVC tester" + git config user.email "dvctester@dataversioncontrol.com" + + mkdir code + cp $CODE_CACHE/* code/ + git add code/ + git commit -m 'Add code' +} + +function dvc_create_repo() { + dvc_info "Creating dvc repo" + + dvc_create_git_repo + + dvc init + + mkdir data/xml + dvc import $DATA_CACHE/* data/xml +} + +function dvc_check_dirs() { + for d in $1; do + if [ ! -d "$d" ]; then + dvc_fatal "Directory $d doesn't exist" + fi + done +} + +function dvc_check_files() { + for f in $1; do + if [ ! -f "$f" ]; then + dvc_fatal "File $f doesn't exist" + fi + done +} diff --git a/functest/init.sh b/functest/init.sh deleted file mode 100755 index 7ef46b650..000000000 --- a/functest/init.sh +++ /dev/null @@ -1,16 +0,0 @@ - -source common.rc - -./clean.sh - -rm -rf $RAW_DATA_LOCAL -mkdir $RAW_DATA_LOCAL -for file in "Badges.xml" "Tags.xml" "PostLinks.xml" -do - (cd $RAW_DATA_LOCAL; wget $RAW_DATA_S3/$file) -done - -rm -rf $CODE_LOCAL -mkdir $CODE_LOCAL -(cd $CODE_LOCAL; wget "$BASE_DIR_S3/code/xmltotsv.py") - diff --git a/functest/run.sh b/functest/run.sh new file mode 100755 index 000000000..e6d3ef6db --- /dev/null +++ b/functest/run.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +set -e + +source common.sh + +TESTS+=" test-init.sh" +TESTS+=" test-import.sh" +TESTS+=" test-repro-code.sh" + +for t in $TESTS; do + rm -rf $TEST_REPO + dvc_header "$t" + ./$t +done + +rm -rf $TEST_REPO diff --git a/functest/test-import.sh b/functest/test-import.sh new file mode 100755 index 000000000..d57e1294a --- /dev/null +++ b/functest/test-import.sh @@ -0,0 +1,26 @@ +#!/bin/bash + +set -e + +source common.sh + +dvc_create_repo + +dvc_info "Import from local file" +dvc import $DATA_CACHE/Tags.xml data/local +dvc_check_files "data/local" + +dvc_info "Import from http url" +dvc import $DATA_S3/Tags.xml data/http +dvc_check_files "data/http" + +# Temporarily disabled for travis builds, as +# they don't have aws credentials setup yet. +if [ -z $TRAVIS ]; then + dvc_info "Import from s3 url" + dvc config aws.region $REGION + dvc import s3://dataversioncontrol/functests/stackoverflow_raw_small/Tags.xml data/s3 + dvc_check_files "data/s3" +fi + +dvc_pass diff --git a/functest/test-init.sh b/functest/test-init.sh new file mode 100755 index 000000000..e291597db --- /dev/null +++ b/functest/test-init.sh @@ -0,0 +1,17 @@ +#!/bin/bash + +set -e + +source common.sh + +dvc_create_git_repo + +dvc init + +DIRS="data .cache .state" +FILES="dvc.conf" + +dvc_check_dirs $DIRS +dvc_check_files $FILES + +dvc_pass diff --git a/functest/test-repro-code.sh b/functest/test-repro-code.sh index 479131f0a..58d071f3d 100755 --- a/functest/test-repro-code.sh +++ b/functest/test-repro-code.sh @@ -1,20 +1,22 @@ #!/bin/bash -source common.rc +set -e -function run_test() { - mkdir data/tsv +source common.sh - dvc_info 'convert Budget.xml to tsv' - dvc run --code code/xmltotsv.py python code/xmltotsv.py --extract row/@Id,row/@UserId,row/@Name,row/@Class,row/@TagBased,row/@Date data/xml/Badges.xml data/tsv/Badges.tsv +dvc_create_repo + +mkdir data/tsv + +dvc_info 'Convert Budget.xml to tsv' +pip2 install xmltodict +dvc run --code code/xmltotsv.py python2 code/xmltotsv.py --extract row/@Id,row/@UserId,row/@Name,row/@Class,row/@TagBased,row/@Date data/xml/Badges.xml data/tsv/Badges.tsv - dvc_info 'modify code' - echo " " >> code/xmltotsv.py - git commit -am 'Change code' +dvc_info 'Modify code' +echo " " >> code/xmltotsv.py +git commit -am 'Change code' - dvc_info 'reproduce tsv convertion code' - dvc repro data/tsv/Badges.tsv -} +dvc_info 'Reproduce tsv convertion code' +dvc repro data/tsv/Badges.tsv -create_repo -(cd $TEST_REPO; run_test) +dvc_pass diff --git a/functest/tutorial_end_to_end.sh b/functest/tutorial_end_to_end.sh index 26ffdb58c..e209023d6 100755 --- a/functest/tutorial_end_to_end.sh +++ b/functest/tutorial_end_to_end.sh @@ -1,3 +1,6 @@ +#!/bin/bash + +set -e # 1. First ML model diff --git a/functests.sh b/functests.sh new file mode 100755 index 000000000..4c55eee8c --- /dev/null +++ b/functests.sh @@ -0,0 +1,11 @@ +#!/bin/bash + +DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +BIN=$DIR/bin +DVC_HOME=$DIR + +export PATH=$BIN:$PATH +export DVC_HOME=$DIR + +cd functest +./run.sh diff --git a/requirements.txt b/requirements.txt index 5ee7b96f0..8e3d4ad16 100644 --- a/requirements.txt +++ b/requirements.txt @@ -86,3 +86,4 @@ traitlets==4.3.2 wcwidth==0.1.7 colorama==0.3.9 google-compute-engine==2.4.1 +configobj==5.0.6 diff --git a/setup.py b/setup.py index faef14732..d47341ba2 100644 --- a/setup.py +++ b/setup.py @@ -92,6 +92,7 @@ install_requires = [ 'wcwidth==0.1.7', 'colorama==0.3.9', 'google-compute-engine==2.4.1', + 'configobj==5.0.6', ] if platform.system() == 'Darwin': diff --git a/test-requirements.txt b/test-requirements.txt index 4ebc8aea5..21329b8d1 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1 +1,2 @@ coverage +xmltodict