diff --git a/lib/DataFileUtil/DataFileUtilImpl.py b/lib/DataFileUtil/DataFileUtilImpl.py index 16c8610..a36e3f8 100644 --- a/lib/DataFileUtil/DataFileUtilImpl.py +++ b/lib/DataFileUtil/DataFileUtilImpl.py @@ -1,6 +1,5 @@ # -*- coding: utf-8 -*- #BEGIN_HEADER -import copy import errno import ftplib import gzip @@ -12,7 +11,6 @@ import subprocess import tarfile import tempfile -import time import uuid import zipfile @@ -22,6 +20,8 @@ import semver from requests_toolbelt.multipart.encoder import MultipartEncoder +from DataFileUtil.implementation import log, save_objects + from installed_clients.AbstractHandleClient import AbstractHandle as HandleService from installed_clients.WorkspaceClient import Workspace from installed_clients.baseclient import ServerError as HandleError @@ -82,10 +82,6 @@ class DataFileUtil: STAGING_GLOBAL_FILE_PREFIX = '/data/bulk/' STAGING_USER_FILE_PREFIX = '/staging/' - def log(self, message, prefix_newline=False): - print(('\n' if prefix_newline else '') + - str(time.time()) + ': ' + str(message)) - def endswith(self, string, suffixes): strl = string.lower() for s in suffixes: @@ -97,10 +93,10 @@ def endswith(self, string, suffixes): # don't see a way to do that def gzip(self, oldfile): if self.endswith(oldfile, [self.GZ, self.GZIP, self.TGZ]): - self.log('File {} is already gzipped, skipping'.format(oldfile)) + log('File {} is already gzipped, skipping'.format(oldfile)) return oldfile newfile = oldfile + self.GZ - self.log('gzipping {} to {}'.format(oldfile, newfile)) + log('gzipping {} to {}'.format(oldfile, newfile)) with open(oldfile, 'rb') as s, gzip.open(newfile, 'wb') as t: shutil.copyfileobj(s, t) return newfile @@ -109,10 +105,10 @@ def gzip(self, oldfile): # the pigz parallel compression program def _pigz_compress(self, oldfile, n_proc=None, compression_level=None): if self.endswith(oldfile, [self.GZ, self.GZIP, self.TGZ]): - self.log('File {} is already gzipped, skipping'.format(oldfile)) + log('File {} is already gzipped, skipping'.format(oldfile)) return oldfile newfile = oldfile + self.GZ - self.log('gzipping (with pigz) {} to {}'.format(oldfile, newfile)) + log('gzipping (with pigz) {} to {}'.format(oldfile, newfile)) # -f to force overwrite # --keep to retain the original file @@ -158,7 +154,7 @@ def _pack(self, file_path, pack): if not f: f = os.path.basename(d) file_path = d + os.sep + f - self.log('Packing {} to {}'.format(d, pack)) + log('Packing {} to {}'.format(d, pack)) # tar is smart enough to not pack its own archive file into the new archive, zip isn't. # TODO is there a designated temp files dir in the scratch space? Nope. # check dir to archive is not self.tmp or its parent dir for zip @@ -195,7 +191,7 @@ def _decompress_file_name(self, file_path): def _decompress(self, openfn, file_path, unpack): new_file = self._decompress_file_name(file_path) - self.log('decompressing {} to {} ...'.format(file_path, new_file)) + log('decompressing {} to {} ...'.format(file_path, new_file)) with openfn(file_path, 'rb') as s, tempfile.NamedTemporaryFile( dir=self.tmp, delete=False) as tf: # don't create the target file until it's done decompressing @@ -211,7 +207,7 @@ def _decompress(self, openfn, file_path, unpack): # of the passed in file open function def _pigz_decompress(self, file_path, unpack, n_proc=None): new_file = self._decompress_file_name(file_path) - self.log('decompressing (with pigz) {} to {} ...'.format(file_path, new_file)) + log('decompressing (with pigz) {} to {} ...'.format(file_path, new_file)) # --keep to retain the original file # --processes to limit the number of processes @@ -250,7 +246,7 @@ def _unarchive(self, file_path, unpack, file_type): raise ValueError( 'File {} is tar file but only uncompress was specified' .format(file_path)) - self.log('unpacking {} ...'.format(file_path)) + log('unpacking {} ...'.format(file_path)) with tarfile.open(file_path) as tf: self._check_members(tf.getnames()) tf.extractall(file_dir) @@ -260,7 +256,7 @@ def _unarchive(self, file_path, unpack, file_type): raise ValueError( 'File {} is zip file but only uncompress was specified' .format(file_path)) - self.log('unpacking {} ...'.format(file_path)) + log('unpacking {} ...'.format(file_path)) with zipfile.ZipFile(file_path) as zf: self._check_members(zf.namelist()) zf.extractall(file_dir) @@ -273,7 +269,7 @@ def _check_members(self, member_list): if n.startswith('/') or n.startswith('..'): err = ('Dangerous archive file - entry [{}] points to a ' + 'file outside the archive directory').format(m) - self.log(err) + log(err) raise ValueError(err) def _unpack(self, file_path, unpack): @@ -308,7 +304,7 @@ def check_shock_response(self, response, errtxt): err = json.loads(response.content)['error'][0] except: # this means shock is down or not responding. - self.log("Couldn't parse response error content from Shock: " + + log("Couldn't parse response error content from Shock: " + response.content) response.raise_for_status() raise ShockException(errtxt + str(err)) @@ -382,7 +378,7 @@ def _retrieve_filepath(self, file_url, cookies=None): try: content_disposition = response.headers['content-disposition'] except KeyError: - self.log('Parsing file name directly from URL') + log('Parsing file name directly from URL') file_name = file_url.split('/')[-1] else: file_name = content_disposition.split('filename="')[-1].split('";')[0] @@ -391,7 +387,7 @@ def _retrieve_filepath(self, file_url, cookies=None): error_msg += 'Exception: {}'.format(error) raise ValueError(error_msg) - self.log('Retrieving file name from url: {}'.format(file_name)) + log('Retrieving file name from url: {}'.format(file_name)) copy_file_path = os.path.join(self.tmp, file_name) return copy_file_path @@ -407,8 +403,8 @@ def _wget_dl(self, url, destination_file, try_number=20, time_out=1800): try: download_state=subprocess.call(command) except Exception as e: - self.log('Error running wget') - self.log(e) + log('Error running wget') + log(e) return download_state @@ -422,7 +418,7 @@ def _download_to_file(self, file_url): """ copy_file_path = self._retrieve_filepath(file_url) - self.log('Connecting and downloading web source: {}'.format( + log('Connecting and downloading web source: {}'.format( file_url)) success = False @@ -439,7 +435,7 @@ def _download_to_file(self, file_url): if not success: raise ValueError('Dowload Failed!') - self.log('Downloaded file to {}'.format(copy_file_path)) + log('Downloaded file to {}'.format(copy_file_path)) return copy_file_path @@ -469,14 +465,14 @@ def _download_dropbox_link(self, file_url): if not file_url.startswith('https://www.dropbox.com/'): raise ValueError('Invalid DropBox Link: {}'.format(file_url)) - self.log('Connecting DropBox link: {}'.format(file_url)) + log('Connecting DropBox link: {}'.format(file_url)) # translate dropbox URL for direct download if "?" not in file_url: force_download_link = file_url + '?raw=1' else: force_download_link = file_url.partition('?')[0] + '?raw=1' - self.log('Generating DropBox direct download link\n' + + log('Generating DropBox direct download link\n' + ' from: {}\n to: {}'.format(file_url, force_download_link)) copy_file_path = self._download_to_file(force_download_link) @@ -502,7 +498,7 @@ def _download_google_drive_to_file(self, file_url, cookies=None): """ copy_file_path = self._retrieve_filepath(file_url, cookies) - self.log('Connecting and downloading web source: {}'.format( + log('Connecting and downloading web source: {}'.format( file_url)) try: @@ -510,7 +506,7 @@ def _download_google_drive_to_file(self, file_url, cookies=None): with open(copy_file_path, 'wb') as f: for chunk in response.iter_content(chunk_size=1024): f.write(chunk) - self.log('Downloaded file to {}'.format(copy_file_path)) + log('Downloaded file to {}'.format(copy_file_path)) except BaseException as error: error_msg = 'Cannot connect to URL: {}\n'.format(file_url) error_msg += 'Exception: {}'.format(error) @@ -530,7 +526,7 @@ def _download_google_drive_link(self, file_url): if not file_url.startswith('https://drive.google.com/'): raise ValueError('Invalid Google Drive Link: {}'.format(file_url)) - self.log('Connecting Google Drive link: {}'.format(file_url)) + log('Connecting Google Drive link: {}'.format(file_url)) # translate Google Drive URL for direct download force_download_link_prefix = 'https://docs.google.com/uc?export=download' @@ -552,7 +548,7 @@ def _download_google_drive_link(self, file_url): if confirm_token: force_download_link = force_download_link_prefix + '&confirm={}&id={}'.format(confirm_token, file_id) - self.log('Generating Google Drive direct download link\n' + + log('Generating Google Drive direct download link\n' + ' from: {}\n to: {}'.format(file_url, force_download_link)) copy_file_path = self._download_google_drive_to_file(force_download_link, response.cookies) @@ -577,7 +573,7 @@ def _download_ftp_link(self, file_url): if not file_url.startswith('ftp://'): raise ValueError('Invalid FTP Link: {}'.format(file_url)) - self.log('Connecting FTP link: {}'.format(file_url)) + log('Connecting FTP link: {}'.format(file_url)) ftp_url_format = re.match(r'ftp://.*:.*@.*/.*', file_url) # process ftp credentials if ftp_url_format: @@ -592,7 +588,7 @@ def _download_ftp_link(self, file_url): ftp_file_name = re.search( 'ftp://.*:.*@.*/(.+$)', file_url).group(1) else: - self.log('Setting anonymous FTP user_name and password') + log('Setting anonymous FTP user_name and password') ftp_user_name = 'anonymous' ftp_password = 'anonymous@domain.com' ftp_domain = re.search('ftp://(.+?)/', file_url).group(1) @@ -612,7 +608,7 @@ def _download_ftp_link(self, file_url): with open(copy_file_path, 'wb') as output: ftp_connection.retrbinary('RETR {}'.format(ftp_file_name), output.write) - self.log('Copied FTP file to: {}'.format(copy_file_path)) + log('Copied FTP file to: {}'.format(copy_file_path)) copy_file_path = self._unpack(copy_file_path, True) @@ -662,9 +658,9 @@ def __init__(self, config): # note that the unit tests cannot easily test this. Be careful with changes here with requests.get(config['kbase-endpoint'] + '/shock-direct', allow_redirects=False) as r: if r.status_code == 302: - self.log('Using direct shock url for transferring files') + log('Using direct shock url for transferring files') self.shock_effective = r.headers['Location'] - self.log('Shock url: ' + self.shock_effective) + log('Shock url: ' + self.shock_effective) self.handle_url = config['handle-service-url'] self.ws_url = config['workspace-url'] self.scratch = config['scratch'] @@ -731,7 +727,7 @@ def shock_to_file(self, ctx, params): shock_url = self.shock_effective if handle_id: - self.log('Fetching info for handle: '+handle_id) + log('Fetching info for handle: '+handle_id) hs = HandleService(self.handle_url, token=token) handles = hs.hids_to_handles([handle_id]) # don't override direct url if provided @@ -755,7 +751,7 @@ def shock_to_file(self, ctx, params): attributes = resp_obj['data']['attributes'] if os.path.isdir(file_path): file_path = os.path.join(file_path, node_file_name) - self.log('downloading shock node ' + shock_id + ' into file: ' + str(file_path)) + log('downloading shock node ' + shock_id + ' into file: ' + str(file_path)) with open(file_path, 'wb') as fhandle: with requests.get(node_url + '?download_raw', stream=True, headers=headers, allow_redirects=True) as r: @@ -773,7 +769,7 @@ def shock_to_file(self, ctx, params): 'attributes': attributes, 'file_path': file_path, 'size': size} - self.log('downloading done') + log('downloading done') #END shock_to_file # At some point might do deeper type checking... @@ -895,7 +891,7 @@ def file_to_shock(self, ctx, params): pack = params.get('pack') if pack: file_path = self._pack(file_path, pack) - self.log('uploading file ' + str(file_path) + ' into shock node') + log('uploading file ' + str(file_path) + ' into shock node') with open(os.path.abspath(file_path), 'rb') as data_file: # Content-Length header is required for transition to # https://github.com/kbase/blobstore @@ -917,7 +913,7 @@ def file_to_shock(self, ctx, params): 'size': shock_data['file']['size']} if params.get('make_handle'): out['handle'] = self.make_handle(shock_data, token) - self.log('uploading done into shock node: ' + shock_id) + log('uploading done into shock node: ' + shock_id) #END file_to_shock # At some point might do deeper type checking... @@ -1355,45 +1351,9 @@ def save_objects(self, ctx, params): # ctx is the context object # return variables are: info #BEGIN save_objects - prov = ctx.provenance() - objs = params.get('objects') - if not objs: - raise ValueError('Required parameter objects missing') - wsid = params.get('id') - if not wsid: - raise ValueError('Required parameter id missing') - objs_to_save = [] - for o in objs: - obj_to_save = {} - - prov_to_save = prov - if 'extra_provenance_input_refs' in o: - prov_to_save = copy.deepcopy(prov) # need to make a copy so we don't clobber other objects - extra_input_refs = o['extra_provenance_input_refs'] - if extra_input_refs: - if len(prov) > 0: - if 'input_ws_objects' in prov[0]: - prov_to_save[0]['input_ws_objects'].extend(extra_input_refs) - else: - prov_to_save[0]['input_ws_objects'] = extra_input_refs - else: - prov_to_save = [{'input_ws_objects': extra_input_refs}] - - keys = ['type', 'data', 'name', 'objid', 'meta', 'hidden'] - for k in keys: - if k in o: - obj_to_save[k] = o[k] - - obj_to_save['provenance'] = prov_to_save - objs_to_save.append(obj_to_save) - ws = Workspace(self.ws_url, token=ctx['token']) - try: - info = ws.save_objects({'id': wsid, 'objects': objs_to_save}) - except WorkspaceError as e: - self.log('Logging workspace error on save_objects: {}\n{}'.format( - e.message, e.data)) - raise + prov = ctx.provenance() + info = save_objects(ws, params, prov) #END save_objects # At some point might do deeper type checking... @@ -1460,7 +1420,7 @@ def get_objects(self, ctx, params): try: retobjs = ws.get_objects2(input_)['data'] except WorkspaceError as e: - self.log('Logging workspace error on get_objects: {}\n{}'.format( + log('Logging workspace error on get_objects: {}\n{}'.format( e.message, e.data)) raise results = [] @@ -1473,7 +1433,7 @@ def get_objects(self, ctx, params): hs = 'handle_stacktrace' if he in o or hs in o: ref = self.make_ref(o['info']) - self.log('Handle error for object {}: {}.\nStacktrace: {}' + log('Handle error for object {}: {}.\nStacktrace: {}' .format(ref, o.get(he), o.get(hs))) if ignore_err: res = None @@ -1545,10 +1505,10 @@ def download_staging_file(self, ctx, params): staging_file_name = os.path.basename(staging_file_subdir_path) staging_file_path = self._get_staging_file_path(ctx['user_id'], staging_file_subdir_path) - self.log('Start downloading staging file: %s' % staging_file_path) + log('Start downloading staging file: %s' % staging_file_path) shutil.copy2(staging_file_path, self.tmp) copy_file_path = os.path.join(self.tmp, staging_file_name) - self.log('Copied staging file from %s to %s' % + log('Copied staging file from %s to %s' % (staging_file_path, copy_file_path)) copy_file_path = self._unpack(copy_file_path, True) @@ -1587,7 +1547,7 @@ def download_web_file(self, ctx, params): file_url = params.get('file_url') download_type = params.get('download_type') - self.log('Start downloading web file from: {}'.format(file_url)) + log('Start downloading web file from: {}'.format(file_url)) copy_file_path = self._download_file(download_type, file_url) results = {'copy_file_path': copy_file_path} diff --git a/lib/DataFileUtil/implementation.py b/lib/DataFileUtil/implementation.py new file mode 100644 index 0000000..ff71b46 --- /dev/null +++ b/lib/DataFileUtil/implementation.py @@ -0,0 +1,58 @@ +# contains implementations for DFU methods. This allows for unit testing. + +# hmm, class or functions, class or functions... let's go with functions for now. +# If we wind up having to pass in a ton of crap every time try an OO approach. + +# TODO move more method implementations here - or in other files - as needed. +# TODO mypy this sucker up + +import copy +import time + +from installed_clients.baseclient import ServerError as WorkspaceError + + +def log(message, prefix_newline=False): + print(('\n' if prefix_newline else '') + str(time.time()) + ': ' + str(message)) + + +def save_objects(ws, params, prov): + # TODO unit tests + objs = params.get('objects') + if not objs: + raise ValueError('Required parameter objects missing') + wsid = params.get('id') + if not wsid: + raise ValueError('Required parameter id missing') + objs_to_save = [] + for o in objs: + obj_to_save = {} + + prov_to_save = prov + if 'extra_provenance_input_refs' in o: + # need to make a copy so we don't clobber other objects + prov_to_save = copy.deepcopy(prov) + extra_input_refs = o['extra_provenance_input_refs'] + if extra_input_refs: + if len(prov) > 0: + if 'input_ws_objects' in prov[0]: + prov_to_save[0]['input_ws_objects'].extend(extra_input_refs) + else: + prov_to_save[0]['input_ws_objects'] = extra_input_refs + else: + prov_to_save = [{'input_ws_objects': extra_input_refs}] + + keys = ['type', 'data', 'name', 'objid', 'meta', 'hidden'] + for k in keys: + if k in o: + obj_to_save[k] = o[k] + + obj_to_save['provenance'] = prov_to_save + objs_to_save.append(obj_to_save) + + try: + return ws.save_objects({'id': wsid, 'objects': objs_to_save}) + except WorkspaceError as e: + log('Logging workspace error on save_objects: {}\n{}'.format( + e.message, e.data)) + raise