diff --git a/DataFileUtil.html b/DataFileUtil.html index 4f3b295..a025f6c 100644 --- a/DataFileUtil.html +++ b/DataFileUtil.html @@ -1 +1 @@ -DataFileUtil
/*
*Contains utilities for saving and retrieving data to and from KBase data
*services. Requires Shock 0.9.6+ and Workspace Service 0.4.1+.
*
*Note that some calls may create files or directories in the root of the scratch space (typically
*/kb/module/work/tmp). For this reason client programmers should not request that DFU archive from
*the root of the scratch space - always create a new directory (e.g. using a UUID for a name or a
*standard library temporary directory utility) and add the target files to that directory when
*archiving.
*/
moduleDataFileUtil{

/*
*A boolean - 0 for false, 1 for true.
*@range(0, 1)
*/
typedefintboolean;

/*
*A handle for a file stored in Shock.
*hid - the id of the handle in the Handle Service that references this
*shock node
*id - the id for the shock node
*url - the url of the shock server
*type - the type of the handle. This should always be shock.
*file_name - the name of the file
*remote_md5 - the md5 digest of the file.
*/
typedefstructure{
stringhid;
stringfile_name;
stringid;
stringurl;
stringtype;
stringremote_md5;
}
Handle;

/*
*Input for the shock_to_file function.
*
*Required parameters:
*shock_id | handle_id - the ID of the Shock node, or the Handle to a shock node.
*file_path - the location to save the file output. If this is a
*directory, the file will be named as per the filename in Shock.
*
*Optional parameters:
*unpack - either null, 'uncompress', or 'unpack'. 'uncompress' will cause
*any bzip or gzip files to be uncompressed. 'unpack' will behave the
*same way, but it will also unpack tar and zip archive files
*(uncompressing gzipped or bzipped archive files if necessary). If
*'uncompress' is specified and an archive file is encountered, an
*error will be thrown. If the file is an archive, it will be
*unbundled into the directory containing the original output file.
*
*Note that if the file name (either as provided by the user or by
*Shock) without the a decompression extension (e.g. .gz, .zip or
*.tgz -> .tar) points to an existing file and unpack is specified,
*that file will be overwritten by the decompressed Shock file.
*/
typedefstructure{
stringshock_id;
stringhandle_id;
stringfile_path;
stringunpack;
}
ShockToFileParams;

/*
*Output from the shock_to_file function.
*
*node_file_name - the filename of the file as stored in Shock.
*file_path - the path to the downloaded file. If a directory was
*specified in the input, this will be the directory appended with the
*shock file name. If a file was specified, it will be that file path.
*In either case, if the file is uncompressed any compression file
*extensions will be removed (e.g. .gz) and or altered (e.g. .tgz ->
*.tar) as appropriate.
*size - the size of the file in bytes as stored in Shock, prior to
*unpacking.
*attributes - the file attributes, if any, stored in Shock.
*/
typedefstructure{
stringnode_file_name;
stringfile_path;
intsize;
mapping<string,UnspecifiedObject>attributes;
}
ShockToFileOutput;

/*
*Download a file from Shock.
*/
funcdefshock_to_file(ShockToFileParamsparams)returns(ShockToFileOutputout)authenticationrequired;

/*
*Download multiple files from Shock.
*/
funcdefshock_to_file_mass(list<ShockToFileParams>params)returns(list<ShockToFileOutput>out)authenticationrequired;

/*
*Input for the file_to_shock function.
*
*Required parameters:
*file_path - the location of the file (or directory if using the
*pack parameter) to load to Shock.
*
*Optional parameters:
*attributes - DEPRECATED: attributes are currently ignored by the upload function and
*will be removed entirely in a future version. User-specified attributes to save to the
*Shock node along with the file.
*make_handle - make a Handle Service handle for the shock node. Default
*false.
*pack - compress a file or archive a directory before loading to Shock.
*The file_path argument will be appended with the appropriate file
*extension prior to writing. For gzips only, if the file extension
*denotes that the file is already compressed, it will be skipped. If
*file_path is a directory and tarring or zipping is specified, the
*created file name will be set to the directory name, possibly
*overwriting an existing file. Attempting to pack the root directory
*is an error. Do not attempt to pack the scratch space root as noted
*in the module description.
*
*The allowed values are:
*gzip - gzip the file given by file_path.
*targz - tar and gzip the directory specified by the directory
*portion of the file_path into the file specified by the
*file_path.
*zip - as targz but zip the directory.
*/
typedefstructure{
stringfile_path;
mapping<string,UnspecifiedObject>attributes;
booleanmake_handle;
stringpack;
}
FileToShockParams;

/*
*Output of the file_to_shock function.
*
*shock_id - the ID of the new Shock node.
*handle - the new handle, if created. Null otherwise.
*node_file_name - the name of the file stored in Shock.
*size - the size of the file stored in shock.
*/
typedefstructure{
stringshock_id;
Handlehandle;
stringnode_file_name;
stringsize;
}
FileToShockOutput;

/*
*Load a file to Shock.
*/
funcdeffile_to_shock(FileToShockParamsparams)returns(FileToShockOutputout)authenticationrequired;

typedefstructure{
stringfile_path;
}
UnpackFileParams;

typedefstructure{
stringfile_path;
}
UnpackFileResult;

/*
*Using the same logic as unpacking a Shock file, this method will cause
*any bzip or gzip files to be uncompressed, and then unpack tar and zip
*archive files (uncompressing gzipped or bzipped archive files if
*necessary). If the file is an archive, it will be unbundled into the
*directory containing the original output file.
*/
funcdefunpack_file(UnpackFileParamsparams)returns(UnpackFileResultout)authenticationrequired;

/*
*Input for the pack_file function.
*
*Required parameters:
*file_path - the location of the file (or directory if using the
*pack parameter) to load to Shock.
*pack - The format into which the file or files will be packed.
*The file_path argument will be appended with the appropriate file
*extension prior to writing. For gzips only, if the file extension
*denotes that the file is already compressed, it will be skipped. If
*file_path is a directory and tarring or zipping is specified, the
*created file name will be set to the directory name, possibly
*overwriting an existing file. Attempting to pack the root directory
*is an error. Do not attempt to pack the scratch space root as noted
*in the module description.
*
*The allowed values are:
*gzip - gzip the file given by file_path.
*targz - tar and gzip the directory specified by the directory
*portion of the file_path into the file specified by the
*file_path.
*zip - as targz but zip the directory.
*/
typedefstructure{
stringfile_path;
stringpack;
}
PackFileParams;

/*
*Output from the pack_file function.
*
*file_path - the path to the packed file.
*/
typedefstructure{
stringfile_path;
}
PackFileResult;

/*
*Pack a file or directory into gzip, targz, or zip archives.
*/
funcdefpack_file(PackFileParamsparams)returns(PackFileResultout)authenticationrequired;

/*
*Input for the package_for_download function.
*
*Required parameters:
*file_path - the location of the directory to compress as zip archive
*before loading to Shock. This argument will be appended with the
*'.zip' file extension prior to writing. If it is a directory, file
*name of the created archive will be set to the directory name
*followed by '.zip', possibly overwriting an existing file.
*Attempting to pack the root directory is an error. Do not attempt
*to pack the scratch space root as noted in the module description.
*ws_ref - list of references to workspace objects which will be used to
*produce info-files in JSON format containing workspace metadata and
*provenance structures. It produces new files in folder pointed
*by file_path (or folder containing file pointed by file_path if
*it's not folder).
*Optional parameters:
*attributes - DEPRECATED: attributes are currently ignored by the upload function and
*will be removed entirely in a future version. User-specified attributes to save to the
*Shock node along with the file.
*/
typedefstructure{
stringfile_path;
mapping<string,UnspecifiedObject>attributes;
list<string>ws_refs;
}
PackageForDownloadParams;

/*
*Output of the package_for_download function.
*
*shock_id - the ID of the new Shock node.
*node_file_name - the name of the file stored in Shock.
*size - the size of the file stored in shock.
*/
typedefstructure{
stringshock_id;
stringnode_file_name;
stringsize;
}
PackageForDownloadOutput;

funcdefpackage_for_download(PackageForDownloadParamsparams)returns(PackageForDownloadOutput)authenticationrequired;

/*
*Load multiple files to Shock.
*/
funcdeffile_to_shock_mass(list<FileToShockParams>params)returns(list<FileToShockOutput>out)authenticationrequired;

/*
*Input for the copy_shock_node function.
*
*Required parameters:
*shock_id - the id of the node to copy.
*
*Optional parameters:
*make_handle - make a Handle Service handle for the shock node. Default
*false.
*/
typedefstructure{
stringshock_id;
booleanmake_handle;
}
CopyShockNodeParams;

/*
*Output of the copy_shock_node function.
*
*shock_id - the id of the new Shock node.
*handle - the new handle, if created. Null otherwise.
*/
typedefstructure{
stringshock_id;
Handlehandle;
}
CopyShockNodeOutput;

/*
*Copy a Shock node.
*/
funcdefcopy_shock_node(CopyShockNodeParamsparams)returns(CopyShockNodeOutputout)authenticationrequired;

/*
*Input for the own_shock_node function.
*
*Required parameters:
*shock_id - the id of the node for which the user needs ownership.
*
*Optional parameters:
*make_handle - make or find a Handle Service handle for the shock node.
*Default false.
*/
typedefstructure{
stringshock_id;
booleanmake_handle;
}
OwnShockNodeParams;

/*
*Output of the own_shock_node function.
*
*shock_id - the id of the (possibly new) Shock node.
*handle - the handle, if requested. Null otherwise.
*/
typedefstructure{
stringshock_id;
Handlehandle;
}
OwnShockNodeOutput;

/*
*Gain ownership of a Shock node.
*
*Returns a shock node id which is owned by the caller, given a shock
*node id.
*
*If the shock node is already owned by the caller, returns the same
*shock node ID. If not, the ID of a copy of the original node will be
*returned.
*
*If a handle is requested, the node is already owned by the caller, and
*a handle already exists, that handle will be returned. Otherwise a new
*handle will be created and returned.
*/
funcdefown_shock_node(OwnShockNodeParamsparams)returns(OwnShockNodeOutputout)authenticationrequired;

/*
*Translate a workspace name to a workspace ID.
*/
funcdefws_name_to_id(stringname)returns(intid)authenticationrequired;

/*
*Information about an object, including user provided metadata.
*
*objid - the numerical id of the object.
*name - the name of the object.
*type - the type of the object.
*save_date - the save date of the object.
*ver - the version of the object.
*saved_by - the user that saved or copied the object.
*wsid - the id of the workspace containing the object.
*workspace - the name of the workspace containing the object.
*chsum - the md5 checksum of the object.
*size - the size of the object in bytes.
*meta - arbitrary user-supplied metadata about
*the object.
*/
typedeftuple<intobjid,stringname,stringtype,stringsave_date,intversion,stringsaved_by,intwsid,stringworkspace,stringchsum,intsize,mapping<string,string>meta>object_info;

/*
*An object and associated data required for saving.
*
*Required parameters:
*type - the workspace type string for the object. Omit the version
*information to use the latest version.
*data - the object data.
*
*Optional parameters:
*One of an object name or id. If no name or id is provided the name
*will be set to 'auto' with the object id appended as a string,
*possibly with -\d+ appended if that object id already exists as a
*name.
*name - the name of the object.
*objid - the id of the object to save over.
*meta - arbitrary user-supplied metadata for the object,
*not to exceed 16kb; if the object type specifies automatic
*metadata extraction with the 'meta ws' annotation, and your
*metadata name conflicts, then your metadata will be silently
*overwritten.
*hidden - true if this object should not be listed when listing
*workspace objects.
*extra_provenance_input_refs - (optional) if set, these refs will
*be appended to the primary ProveanceAction input_ws_objects
*reference list. In general, if the input WS object ref was
*passed in from a narrative App, this will be set for you.
*However, there are cases where the object ref passed to
*the App is a container, and you are operating on a member
*or subobject of the container, in which case to maintain
*that direct mapping to those subobjects in the provenance
*of new objects, you can provide additional object refs
*here. For example, if the input is a ReadsSet, and your
*App creates a new WS object for each read library in the
*set, you may want a direct reference from each new WS
*object not only to the set, but also to the individual
*read library.
*/
typedefstructure{
stringtype;
UnspecifiedObjectdata;
stringname;
intobjid;
mapping<string,string>meta;
booleanhidden;
list<string>extra_provenance_input_refs;
}
ObjectSaveData;

/*
*Input parameters for the "save_objects" function.
*
*Required parameters:
*id - the numerical ID of the workspace.
*objects - the objects to save.
*
*The object provenance is automatically pulled from the SDK runner.
*/
typedefstructure{
intid;
list<ObjectSaveData>objects;
}
SaveObjectsParams;

/*
*Save objects to the workspace. Saving over a deleted object undeletes
*it.
*/
funcdefsave_objects(SaveObjectsParamsparams)returns(list<object_info>info)authenticationrequired;

/*
*Input parameters for the "get_objects" function.
*
*Required parameters:
*object_refs - a list of object references in the form X/Y/Z, where X is
*the workspace name or id, Y is the object name or id, and Z is the
*(optional) object version. In general, always use ids rather than
*names if possible to avoid race conditions.
*A reference path may be specified by separating references by a semicolon, e.g.
*4/5/6;5/7/2;8/9/4 specifies that the user wishes to retrieve the fourth version of
*the object with id 9 in workspace 8, and that there exists a reference path from
*the sixth version of the object with id 5 in workspace 4, to which the user has access.
*The user may or may not have access to workspaces 5 and 8.
*
*
*Optional parameters:
*ignore_errors - ignore any errors that occur when fetching an object
*and instead insert a null into the returned list.
*/
typedefstructure{
list<string>object_refs;
booleanignore_errors;
}
GetObjectsParams;

/*
*The data and supplemental info for an object.
*
*UnspecifiedObject data - the object's data or subset data.
*object_info info - information about the object.
*/
typedefstructure{
UnspecifiedObjectdata;
object_infoinfo;
}
ObjectData;

/*
*Results from the get_objects function.
*
*list<ObjectData> data - the returned objects.
*/
typedefstructure{
list<ObjectData>data;
}
GetObjectsResults;

/*
*Get objects from the workspace.
*/
funcdefget_objects(GetObjectsParamsparams)returns(GetObjectsResultsresults)authenticationrequired;

/*
*Get the versions of the Workspace service and Shock service.
*/
funcdefversions()returns(stringwsver,stringshockver)authenticationrequired;

/*
*Input parameters for the "download_staging_file" function.
*
*Required parameters:
*staging_file_subdir_path: subdirectory file path
*e.g.
*for file: /data/bulk/user_name/file_name
*staging_file_subdir_path is file_name
*for file: /data/bulk/user_name/subdir_1/subdir_2/file_name
*staging_file_subdir_path is subdir_1/subdir_2/file_name
*/
typedefstructure{
stringstaging_file_subdir_path;
}
DownloadStagingFileParams;

/*
*Results from the download_staging_file function.
*
*copy_file_path: copied file scratch area path
*/
typedefstructure{
stringcopy_file_path;
}
DownloadStagingFileOutput;

/*
*Download a staging area file to scratch area
*/
funcdefdownload_staging_file(DownloadStagingFileParamsparams)returns(DownloadStagingFileOutputresults)authenticationrequired;

/*
*Input parameters for the "download_web_file" function.
*
*Required parameters:
*file_url: file URL
*download_type: one of ['Direct Download', 'FTP', 'DropBox', 'Google Drive']
*/
typedefstructure{
stringfile_url;
stringdownload_type;
}
DownloadWebFileParams;

/*
*Results from the download_web_file function.
*
*copy_file_path: copied file scratch area path
*/
typedefstructure{
stringcopy_file_path;
}
DownloadWebFileOutput;

/*
*Download a web file to scratch area
*/
funcdefdownload_web_file(DownloadWebFileParamsparams)returns(DownloadWebFileOutputresults)authenticationrequired;
};

Function Index

copy_shock_node
download_staging_file
download_web_file
file_to_shock
file_to_shock_mass
get_objects
own_shock_node
pack_file
package_for_download
save_objects
shock_to_file
shock_to_file_mass
unpack_file
versions
ws_name_to_id

Type Index

boolean
CopyShockNodeOutput
CopyShockNodeParams
DownloadStagingFileOutput
DownloadStagingFileParams
DownloadWebFileOutput
DownloadWebFileParams
FileToShockOutput
FileToShockParams
GetObjectsParams
GetObjectsResults
Handle
object_info
ObjectData
ObjectSaveData
OwnShockNodeOutput
OwnShockNodeParams
PackageForDownloadOutput
PackageForDownloadParams
PackFileParams
PackFileResult
SaveObjectsParams
ShockToFileOutput
ShockToFileParams
UnpackFileParams
UnpackFileResult
\ No newline at end of file +DataFileUtil
/*
*Contains utilities for saving and retrieving data to and from KBase data
*services. Requires Shock 0.9.6+ and Workspace Service 0.4.1+.
*
*Note that some calls may create files or directories in the root of the scratch space (typically
*/kb/module/work/tmp). For this reason client programmers should not request that DFU archive from
*the root of the scratch space - always create a new directory (e.g. using a UUID for a name or a
*standard library temporary directory utility) and add the target files to that directory when
*archiving.
*/
moduleDataFileUtil{

/*
*A boolean - 0 for false, 1 for true.
*@range(0, 1)
*/
typedefintboolean;

/*
*A handle for a file stored in Shock.
*hid - the id of the handle in the Handle Service that references this
*shock node
*id - the id for the shock node
*url - the url of the shock server
*type - the type of the handle. This should always be shock.
*file_name - the name of the file
*remote_md5 - the md5 digest of the file.
*/
typedefstructure{
stringhid;
stringfile_name;
stringid;
stringurl;
stringtype;
stringremote_md5;
}
Handle;

/*
*Input for the shock_to_file function.
*
*Required parameters:
*shock_id | handle_id - the ID of the Shock node, or the Handle to a shock node.
*file_path - the location to save the file output. If this is a
*directory, the file will be named as per the filename in Shock.
*
*Optional parameters:
*unpack - either null, 'uncompress', or 'unpack'. 'uncompress' will cause
*any bzip or gzip files to be uncompressed. 'unpack' will behave the
*same way, but it will also unpack tar and zip archive files
*(uncompressing gzipped or bzipped archive files if necessary). If
*'uncompress' is specified and an archive file is encountered, an
*error will be thrown. If the file is an archive, it will be
*unbundled into the directory containing the original output file.
*
*Note that if the file name (either as provided by the user or by
*Shock) without the a decompression extension (e.g. .gz, .zip or
*.tgz -> .tar) points to an existing file and unpack is specified,
*that file will be overwritten by the decompressed Shock file.
*/
typedefstructure{
stringshock_id;
stringhandle_id;
stringfile_path;
stringunpack;
}
ShockToFileParams;

/*
*Output from the shock_to_file function.
*
*node_file_name - the filename of the file as stored in Shock.
*file_path - the path to the downloaded file. If a directory was
*specified in the input, this will be the directory appended with the
*shock file name. If a file was specified, it will be that file path.
*In either case, if the file is uncompressed any compression file
*extensions will be removed (e.g. .gz) and or altered (e.g. .tgz ->
*.tar) as appropriate.
*size - the size of the file in bytes as stored in Shock, prior to
*unpacking.
*attributes - the file attributes, if any, stored in Shock.
*/
typedefstructure{
stringnode_file_name;
stringfile_path;
intsize;
mapping<string,UnspecifiedObject>attributes;
}
ShockToFileOutput;

/*
*Download a file from Shock.
*/
funcdefshock_to_file(ShockToFileParamsparams)returns(ShockToFileOutputout)authenticationrequired;

/*
*Download multiple files from Shock.
*/
funcdefshock_to_file_mass(list<ShockToFileParams>params)returns(list<ShockToFileOutput>out)authenticationrequired;

/*
*Input for the file_to_shock function.
*
*Required parameters:
*file_path - the location of the file (or directory if using the
*pack parameter) to load to Shock.
*
*Optional parameters:
*attributes - DEPRECATED: attributes are currently ignored by the upload function and
*will be removed entirely in a future version. User-specified attributes to save to the
*Shock node along with the file.
*make_handle - make a Handle Service handle for the shock node. Default
*false.
*pack - compress a file or archive a directory before loading to Shock.
*The file_path argument will be appended with the appropriate file
*extension prior to writing. For gzips only, if the file extension
*denotes that the file is already compressed, it will be skipped. If
*file_path is a directory and tarring or zipping is specified, the
*created file name will be set to the directory name, possibly
*overwriting an existing file. Attempting to pack the root directory
*is an error. Do not attempt to pack the scratch space root as noted
*in the module description.
*
*The allowed values are:
*gzip - gzip the file given by file_path.
*targz - tar and gzip the directory specified by the directory
*portion of the file_path into the file specified by the
*file_path.
*zip - as targz but zip the directory.
*/
typedefstructure{
stringfile_path;
mapping<string,UnspecifiedObject>attributes;
booleanmake_handle;
stringpack;
}
FileToShockParams;

/*
*Output of the file_to_shock function.
*
*shock_id - the ID of the new Shock node.
*handle - the new handle, if created. Null otherwise.
*node_file_name - the name of the file stored in Shock.
*size - the size of the file stored in shock.
*/
typedefstructure{
stringshock_id;
Handlehandle;
stringnode_file_name;
stringsize;
}
FileToShockOutput;

/*
*Load a file to Shock.
*/
funcdeffile_to_shock(FileToShockParamsparams)returns(FileToShockOutputout)authenticationrequired;

typedefstructure{
stringfile_path;
}
UnpackFileParams;

typedefstructure{
stringfile_path;
}
UnpackFileResult;

/*
*Using the same logic as unpacking a Shock file, this method will cause
*any bzip or gzip files to be uncompressed, and then unpack tar and zip
*archive files (uncompressing gzipped or bzipped archive files if
*necessary). If the file is an archive, it will be unbundled into the
*directory containing the original output file.
*/
funcdefunpack_file(UnpackFileParamsparams)returns(UnpackFileResultout)authenticationrequired;

/*
*Input for the pack_file function.
*
*Required parameters:
*file_path - the location of the file (or directory if using the
*pack parameter) to load to Shock.
*pack - The format into which the file or files will be packed.
*The file_path argument will be appended with the appropriate file
*extension prior to writing. For gzips only, if the file extension
*denotes that the file is already compressed, it will be skipped. If
*file_path is a directory and tarring or zipping is specified, the
*created file name will be set to the directory name, possibly
*overwriting an existing file. Attempting to pack the root directory
*is an error. Do not attempt to pack the scratch space root as noted
*in the module description.
*
*The allowed values are:
*gzip - gzip the file given by file_path.
*targz - tar and gzip the directory specified by the directory
*portion of the file_path into the file specified by the
*file_path.
*zip - as targz but zip the directory.
*/
typedefstructure{
stringfile_path;
stringpack;
}
PackFileParams;

/*
*Output from the pack_file function.
*
*file_path - the path to the packed file.
*/
typedefstructure{
stringfile_path;
}
PackFileResult;

/*
*Pack a file or directory into gzip, targz, or zip archives.
*/
funcdefpack_file(PackFileParamsparams)returns(PackFileResultout)authenticationrequired;

/*
*Input for the package_for_download function.
*
*Required parameters:
*file_path - the location of the directory to compress as zip archive
*before loading to Shock. This argument will be appended with the
*'.zip' file extension prior to writing. If it is a directory, file
*name of the created archive will be set to the directory name
*followed by '.zip', possibly overwriting an existing file.
*Attempting to pack the root directory is an error. Do not attempt
*to pack the scratch space root as noted in the module description.
*ws_ref - list of references to workspace objects which will be used to
*produce info-files in JSON format containing workspace metadata and
*provenance structures. It produces new files in folder pointed
*by file_path (or folder containing file pointed by file_path if
*it's not folder).
*Optional parameters:
*attributes - DEPRECATED: attributes are currently ignored by the upload function and
*will be removed entirely in a future version. User-specified attributes to save to the
*Shock node along with the file.
*/
typedefstructure{
stringfile_path;
mapping<string,UnspecifiedObject>attributes;
list<string>ws_refs;
}
PackageForDownloadParams;

/*
*Output of the package_for_download function.
*
*shock_id - the ID of the new Shock node.
*node_file_name - the name of the file stored in Shock.
*size - the size of the file stored in shock.
*/
typedefstructure{
stringshock_id;
stringnode_file_name;
stringsize;
}
PackageForDownloadOutput;

funcdefpackage_for_download(PackageForDownloadParamsparams)returns(PackageForDownloadOutput)authenticationrequired;

/*
*Load multiple files to Shock.
*/
funcdeffile_to_shock_mass(list<FileToShockParams>params)returns(list<FileToShockOutput>out)authenticationrequired;

/*
*Input for the copy_shock_node function.
*
*Required parameters:
*shock_id - the id of the node to copy.
*
*Optional parameters:
*make_handle - make a Handle Service handle for the shock node. Default
*false.
*/
typedefstructure{
stringshock_id;
booleanmake_handle;
}
CopyShockNodeParams;

/*
*Output of the copy_shock_node function.
*
*shock_id - the id of the new Shock node.
*handle - the new handle, if created. Null otherwise.
*/
typedefstructure{
stringshock_id;
Handlehandle;
}
CopyShockNodeOutput;

/*
*Copy a Shock node.
*/
funcdefcopy_shock_node(CopyShockNodeParamsparams)returns(CopyShockNodeOutputout)authenticationrequired;

/*
*Input for the own_shock_node function.
*
*Required parameters:
*shock_id - the id of the node for which the user needs ownership.
*
*Optional parameters:
*make_handle - make or find a Handle Service handle for the shock node.
*Default false.
*/
typedefstructure{
stringshock_id;
booleanmake_handle;
}
OwnShockNodeParams;

/*
*Output of the own_shock_node function.
*
*shock_id - the id of the (possibly new) Shock node.
*handle - the handle, if requested. Null otherwise.
*/
typedefstructure{
stringshock_id;
Handlehandle;
}
OwnShockNodeOutput;

/*
*Gain ownership of a Shock node.
*
*Returns a shock node id which is owned by the caller, given a shock
*node id.
*
*If the shock node is already owned by the caller, returns the same
*shock node ID. If not, the ID of a copy of the original node will be
*returned.
*
*If a handle is requested, the node is already owned by the caller, and
*a handle already exists, that handle will be returned. Otherwise a new
*handle will be created and returned.
*/
funcdefown_shock_node(OwnShockNodeParamsparams)returns(OwnShockNodeOutputout)authenticationrequired;

/*
*Translate a workspace name to a workspace ID.
*/
funcdefws_name_to_id(stringname)returns(intid)authenticationrequired;

/*
*Information about an object, including user provided metadata.
*
*objid - the numerical id of the object.
*name - the name of the object.
*type - the type of the object.
*save_date - the save date of the object.
*ver - the version of the object.
*saved_by - the user that saved or copied the object.
*wsid - the id of the workspace containing the object.
*workspace - the name of the workspace containing the object.
*chsum - the md5 checksum of the object.
*size - the size of the object in bytes.
*meta - arbitrary user-supplied metadata about
*the object.
*/
typedeftuple<intobjid,stringname,stringtype,stringsave_date,intversion,stringsaved_by,intwsid,stringworkspace,stringchsum,intsize,mapping<string,string>meta>object_info;

/*
*An object and associated data required for saving.
*
*Required parameters:
*type - the workspace type string for the object. Omit the version
*information to use the latest version.
*data - the object data.
*
*One of an object name or id:
*name - the name of the object.
*objid - the id of the object to save over.
*
*Optional parameters:
*meta - arbitrary user-supplied metadata for the object,
*not to exceed 16kb; if the object type specifies automatic
*metadata extraction with the 'meta ws' annotation, and your
*metadata name conflicts, then your metadata will be silently
*overwritten.
*hidden - true if this object should not be listed when listing
*workspace objects.
*extra_provenance_input_refs - (optional) if set, these refs will
*be appended to the primary ProveanceAction input_ws_objects
*reference list. In general, if the input WS object ref was
*passed in from a narrative App, this will be set for you.
*However, there are cases where the object ref passed to
*the App is a container, and you are operating on a member
*or subobject of the container, in which case to maintain
*that direct mapping to those subobjects in the provenance
*of new objects, you can provide additional object refs
*here. For example, if the input is a ReadsSet, and your
*App creates a new WS object for each read library in the
*set, you may want a direct reference from each new WS
*object not only to the set, but also to the individual
*read library.
*/
typedefstructure{
stringtype;
UnspecifiedObjectdata;
stringname;
intobjid;
mapping<string,string>meta;
booleanhidden;
list<string>extra_provenance_input_refs;
}
ObjectSaveData;

/*
*Input parameters for the "save_objects" function.
*
*Required parameters:
*id - the numerical ID of the workspace.
*objects - the objects to save.
*
*The object provenance is automatically pulled from the SDK runner.
*/
typedefstructure{
intid;
list<ObjectSaveData>objects;
}
SaveObjectsParams;

/*
*Save objects to the workspace.
*
*The objects will be sorted prior to saving to avoid the Workspace sort memory limit.
*Note that if the object contains workspace object refs in mapping keys that may cause
*the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA
*format (e.g. #/#/#, where # is a positive integer).
*
*If the data is very large, using the WSLargeDataIO SDK module is advised.
*
*Saving over a deleted object undeletes it.
*/
funcdefsave_objects(SaveObjectsParamsparams)returns(list<object_info>info)authenticationrequired;

/*
*Input parameters for the "get_objects" function.
*
*Required parameters:
*object_refs - a list of object references in the form X/Y/Z, where X is
*the workspace name or id, Y is the object name or id, and Z is the
*(optional) object version. In general, always use ids rather than
*names if possible to avoid race conditions.
*A reference path may be specified by separating references by a semicolon, e.g.
*4/5/6;5/7/2;8/9/4 specifies that the user wishes to retrieve the fourth version of
*the object with id 9 in workspace 8, and that there exists a reference path from
*the sixth version of the object with id 5 in workspace 4, to which the user has access.
*The user may or may not have access to workspaces 5 and 8.
*
*
*Optional parameters:
*ignore_errors - ignore any errors that occur when fetching an object
*and instead insert a null into the returned list.
*/
typedefstructure{
list<string>object_refs;
booleanignore_errors;
}
GetObjectsParams;

/*
*The data and supplemental info for an object.
*
*UnspecifiedObject data - the object's data or subset data.
*object_info info - information about the object.
*/
typedefstructure{
UnspecifiedObjectdata;
object_infoinfo;
}
ObjectData;

/*
*Results from the get_objects function.
*
*list<ObjectData> data - the returned objects.
*/
typedefstructure{
list<ObjectData>data;
}
GetObjectsResults;

/*
*Get objects from the workspace.
*/
funcdefget_objects(GetObjectsParamsparams)returns(GetObjectsResultsresults)authenticationrequired;

/*
*Get the versions of the Workspace service and Shock service.
*/
funcdefversions()returns(stringwsver,stringshockver)authenticationrequired;

/*
*Input parameters for the "download_staging_file" function.
*
*Required parameters:
*staging_file_subdir_path: subdirectory file path
*e.g.
*for file: /data/bulk/user_name/file_name
*staging_file_subdir_path is file_name
*for file: /data/bulk/user_name/subdir_1/subdir_2/file_name
*staging_file_subdir_path is subdir_1/subdir_2/file_name
*/
typedefstructure{
stringstaging_file_subdir_path;
}
DownloadStagingFileParams;

/*
*Results from the download_staging_file function.
*
*copy_file_path: copied file scratch area path
*/
typedefstructure{
stringcopy_file_path;
}
DownloadStagingFileOutput;

/*
*Download a staging area file to scratch area
*/
funcdefdownload_staging_file(DownloadStagingFileParamsparams)returns(DownloadStagingFileOutputresults)authenticationrequired;

/*
*Input parameters for the "download_web_file" function.
*
*Required parameters:
*file_url: file URL
*download_type: one of ['Direct Download', 'FTP', 'DropBox', 'Google Drive']
*/
typedefstructure{
stringfile_url;
stringdownload_type;
}
DownloadWebFileParams;

/*
*Results from the download_web_file function.
*
*copy_file_path: copied file scratch area path
*/
typedefstructure{
stringcopy_file_path;
}
DownloadWebFileOutput;

/*
*Download a web file to scratch area
*/
funcdefdownload_web_file(DownloadWebFileParamsparams)returns(DownloadWebFileOutputresults)authenticationrequired;
};

Function Index

copy_shock_node
download_staging_file
download_web_file
file_to_shock
file_to_shock_mass
get_objects
own_shock_node
pack_file
package_for_download
save_objects
shock_to_file
shock_to_file_mass
unpack_file
versions
ws_name_to_id

Type Index

boolean
CopyShockNodeOutput
CopyShockNodeParams
DownloadStagingFileOutput
DownloadStagingFileParams
DownloadWebFileOutput
DownloadWebFileParams
FileToShockOutput
FileToShockParams
GetObjectsParams
GetObjectsResults
Handle
object_info
ObjectData
ObjectSaveData
OwnShockNodeOutput
OwnShockNodeParams
PackageForDownloadOutput
PackageForDownloadParams
PackFileParams
PackFileResult
SaveObjectsParams
ShockToFileOutput
ShockToFileParams
UnpackFileParams
UnpackFileResult
\ No newline at end of file diff --git a/DataFileUtil.spec b/DataFileUtil.spec index fb3fdd6..2c786b9 100644 --- a/DataFileUtil.spec +++ b/DataFileUtil.spec @@ -350,13 +350,11 @@ module DataFileUtil { information to use the latest version. data - the object data. - Optional parameters: - One of an object name or id. If no name or id is provided the name - will be set to 'auto' with the object id appended as a string, - possibly with -\d+ appended if that object id already exists as a - name. + One of an object name or id: name - the name of the object. objid - the id of the object to save over. + + Optional parameters: meta - arbitrary user-supplied metadata for the object, not to exceed 16kb; if the object type specifies automatic metadata extraction with the 'meta ws' annotation, and your @@ -403,8 +401,16 @@ module DataFileUtil { } SaveObjectsParams; /* - Save objects to the workspace. Saving over a deleted object undeletes - it. + Save objects to the workspace. + + The objects will be sorted prior to saving to avoid the Workspace sort memory limit. + Note that if the object contains workspace object refs in mapping keys that may cause + the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA + format (e.g. #/#/#, where # is a positive integer). + + If the data is very large, using the WSLargeDataIO SDK module is advised. + + Saving over a deleted object undeletes it. */ funcdef save_objects(SaveObjectsParams params) returns (list info) authentication required; diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md index 8b22342..13f81ce 100644 --- a/RELEASE_NOTES.md +++ b/RELEASE_NOTES.md @@ -1,17 +1,23 @@ -#0.1.3 +# 0.1.4 +- objects saved to the workspace are now sorted prior to serialization. This prevents errors due + to workspace sort memory limits, and also moves the sort compute load (which is the most + expensive part of saving objects) from the workspace server node to the SDK job nodes. + +# 0.1.3 - tidying for github consistency - Added Actions workflow for KB SDK tests - Added Dependabot and LGTM configurations - Updated `README.md` to include standard build, coverage, and LGTM badging. -#0.1.2 +# 0.1.2 - deprecate handle service with handle service 2 -- replace the colon(:) [that was reported to have caused download error for Windows users] with underscore in shock filenames +- replace the colon(:) [that was reported to have caused download error for Windows users] with + underscore in shock filenames -#0.1.1 +# 0.1.1 - close no longer used sockets. -#0.1.0 +# 0.1.0 - shock attributes are now ignored on upload. In a future release they will be removed altogether and specifying attributes for upload will be an error. - shock indexes and attributes are no longer copied during a copy or ownership operation. diff --git a/lib/DataFileUtil/DataFileUtilClient.py b/lib/DataFileUtil/DataFileUtilClient.py index 2117a23..2c33d69 100644 --- a/lib/DataFileUtil/DataFileUtilClient.py +++ b/lib/DataFileUtil/DataFileUtilClient.py @@ -357,8 +357,13 @@ def ws_name_to_id(self, name, context=None): def save_objects(self, params, context=None): """ - Save objects to the workspace. Saving over a deleted object undeletes - it. + Save objects to the workspace. + The objects will be sorted prior to saving to avoid the Workspace sort memory limit. + Note that if the object contains workspace object refs in mapping keys that may cause + the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA + format (e.g. #/#/#, where # is a positive integer). + If the data is very large, using the WSLargeDataIO SDK module is advised. + Saving over a deleted object undeletes it. :param params: instance of type "SaveObjectsParams" (Input parameters for the "save_objects" function. Required parameters: id - the numerical ID of the workspace. objects - the objects to save. The @@ -367,15 +372,12 @@ def save_objects(self, params, context=None): type "ObjectSaveData" (An object and associated data required for saving. Required parameters: type - the workspace type string for the object. Omit the version information to use the latest - version. data - the object data. Optional parameters: One of an - object name or id. If no name or id is provided the name will be - set to 'auto' with the object id appended as a string, possibly - with -\d+ appended if that object id already exists as a name. - name - the name of the object. objid - the id of the object to - save over. meta - arbitrary user-supplied metadata for the object, - not to exceed 16kb; if the object type specifies automatic - metadata extraction with the 'meta ws' annotation, and your - metadata name conflicts, then your metadata will be silently + version. data - the object data. One of an object name or id: name + - the name of the object. objid - the id of the object to save + over. Optional parameters: meta - arbitrary user-supplied metadata + for the object, not to exceed 16kb; if the object type specifies + automatic metadata extraction with the 'meta ws' annotation, and + your metadata name conflicts, then your metadata will be silently overwritten. hidden - true if this object should not be listed when listing workspace objects. extra_provenance_input_refs - (optional) if set, these refs will be appended to the primary diff --git a/lib/DataFileUtil/DataFileUtilImpl.py b/lib/DataFileUtil/DataFileUtilImpl.py index 16c8610..11818a8 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 @@ -56,9 +56,9 @@ class DataFileUtil: # state. A method could easily clobber the state set by another while # the latter method is running. ######################################### noqa - VERSION = "0.1.2" - GIT_URL = "git@github.com:kbaseapps/DataFileUtil.git" - GIT_COMMIT_HASH = "d8091ef8acdee21c5b43d1b84d3983b04be3729e" + VERSION = "0.1.3" + GIT_URL = "https://github.com/kbaseapps/DataFileUtil.git" + GIT_COMMIT_HASH = "df19d64a4a70c6ab32d6248a216bc25be0ac35ba" #BEGIN_CLASS_HEADER @@ -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... @@ -1298,8 +1294,13 @@ def ws_name_to_id(self, ctx, name): def save_objects(self, ctx, params): """ - Save objects to the workspace. Saving over a deleted object undeletes - it. + Save objects to the workspace. + The objects will be sorted prior to saving to avoid the Workspace sort memory limit. + Note that if the object contains workspace object refs in mapping keys that may cause + the Workspace to resort the data. To avoid this, convert any refs in mapping keys to UPA + format (e.g. #/#/#, where # is a positive integer). + If the data is very large, using the WSLargeDataIO SDK module is advised. + Saving over a deleted object undeletes it. :param params: instance of type "SaveObjectsParams" (Input parameters for the "save_objects" function. Required parameters: id - the numerical ID of the workspace. objects - the objects to save. The @@ -1308,15 +1309,12 @@ def save_objects(self, ctx, params): type "ObjectSaveData" (An object and associated data required for saving. Required parameters: type - the workspace type string for the object. Omit the version information to use the latest - version. data - the object data. Optional parameters: One of an - object name or id. If no name or id is provided the name will be - set to 'auto' with the object id appended as a string, possibly - with -\d+ appended if that object id already exists as a name. - name - the name of the object. objid - the id of the object to - save over. meta - arbitrary user-supplied metadata for the object, - not to exceed 16kb; if the object type specifies automatic - metadata extraction with the 'meta ws' annotation, and your - metadata name conflicts, then your metadata will be silently + version. data - the object data. One of an object name or id: name + - the name of the object. objid - the id of the object to save + over. Optional parameters: meta - arbitrary user-supplied metadata + for the object, not to exceed 16kb; if the object type specifies + automatic metadata extraction with the 'meta ws' annotation, and + your metadata name conflicts, then your metadata will be silently overwritten. hidden - true if this object should not be listed when listing workspace objects. extra_provenance_input_refs - (optional) if set, these refs will be appended to the primary @@ -1355,45 +1353,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 +1422,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 +1435,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 +1507,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 +1549,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..4936dee --- /dev/null +++ b/lib/DataFileUtil/implementation.py @@ -0,0 +1,83 @@ +# 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)) + +# Copies of this in AssemblyUtil and GenomeFileUtil may be redundant since we're sorting here +# Note that insertion order is only maintained since python 3.6 and is only guaranteed since 3.7 +# In 3.6 it was an implementation detail. +# As of 2020/12/12 Python 3.6 is provided in the kbase/sdkbase2 image +def _sort_dict(in_struct): + """ + Recursively sort a dictionary by dictionary keys. + """ + if isinstance(in_struct, dict): + return {k: _sort_dict(in_struct[k]) for k in sorted(in_struct)} + elif isinstance(in_struct, list): + return [_sort_dict(k) for k in in_struct] + else: + return in_struct + + +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', 'name', 'objid', 'meta', 'hidden'] + for k in keys: + if k in o: + obj_to_save[k] = o[k] + """ + Sorting the data is important for 2 reasons: + 1) It prevents the workspace from rejecting the save because the sort takes too much memory. + The workspace puts limits on memory use because it has to service many apps / UIs / etc. + at once. + 2) It distributes the sort across the app worker nodes rather than concentrating them on + the workspace node. + """ + # TODO sort in WSLargeDataIO as well + if 'data' in o: + obj_to_save['data'] = _sort_dict(o['data']) + + 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 diff --git a/test/implementation_test.py b/test/implementation_test.py new file mode 100644 index 0000000..78a482c --- /dev/null +++ b/test/implementation_test.py @@ -0,0 +1,149 @@ +# unit tests for the implementation.py file. + +import json + +from unittest.mock import create_autospec + +from installed_clients.WorkspaceClient import Workspace + +from DataFileUtil.implementation import save_objects + +# TODO add more save_object unit tests. +# TODO upgrade to pytest. +# TODO figure out why the test results are interleaved with test logs & fix +# TODO figure out why there appear to be 2 test runs, 1 with this file, 1 without, per kb-sdk test +# TODO set up a makefile target to run only unit tests + +def test_save_objects_sorted(): + print("***** test_save_objects_sorted ****") + ws = create_autospec(Workspace, spec_set=True, instance=True) + + ws.save_objects.return_value = [ + [ + 17, + 'objname', + 'Some.Type-2.4', + '2020-12-12T19:52:29+0000', + 2367, + 'username', + 49778, + 'MyWorkspace', + '99914b932bd37a50b983c5e7c90ae93b', + 2, + {}], + [ + 18, + 'objname2', + 'Other.Type-2.4', + '2020-12-12T19:52:29+0000', + 1, + 'username', + 49778, + 'MyWorkspace', + '99914b932bd37a50b983c5e7c90ae93b', + 2, + {}] + ] + + params = { + 'id': 49778, + 'objects': [ + { + 'type': 'Some.Type-2.4', + 'name': 'objname', + 'data': {'sorted': [ + 3, + 2, + 1, + { + '4': 'a', + '3': 'a', + '1': 'a', + '2': 'a' + }], + 'by': 1, + 'yoda': ['whoo', 'whee', {'b': 1, 'a': 2}], + 'this was': 'foo'} + }, + { + 'type': 'Other.Type-2.4', + 'name': 'objname2', + 'data': { + 'a': 1, + 'c': 2, + 'b': 3, + } + }] + } + + res = save_objects(ws, params, {}) + expected = [ + [ + 17, + 'objname', + 'Some.Type-2.4', + '2020-12-12T19:52:29+0000', + 2367, + 'username', + 49778, + 'MyWorkspace', + '99914b932bd37a50b983c5e7c90ae93b', + 2, + {}], + [ + 18, + 'objname2', + 'Other.Type-2.4', + '2020-12-12T19:52:29+0000', + 1, + 'username', + 49778, + 'MyWorkspace', + '99914b932bd37a50b983c5e7c90ae93b', + 2, + {}] + ] + assert res == expected + + ws.save_objects.assert_called_once_with({ + 'id': 49778, + 'objects': [ + { + 'type': 'Some.Type-2.4', + 'name': 'objname', + 'data': {'sorted': [ + 3, + 2, + 1, + { + '4': 'a', + '3': 'a', + '1': 'a', + '2': 'a' + }], + 'by': 1, + 'yoda': ['whoo', 'whee', {'b': 1, 'a': 2}], + 'this was': 'foo' + }, + 'provenance': {} + }, + { + 'type': 'Other.Type-2.4', + 'name': 'objname2', + 'data': { + 'a': 1, + 'c': 2, + 'b': 3, + }, + 'provenance': {} + }] + }) + + assert json.dumps(ws.save_objects.call_args[0][0]['objects'][0]['data']) == ( + '{"by": 1, "sorted": [3, 2, 1, {"1": "a", "2": "a", "3": "a", "4": "a"}], ' + + '"this was": "foo", "yoda": ["whoo", "whee", {"a": 2, "b": 1}]}' + ) + + assert json.dumps(ws.save_objects.call_args[0][0]['objects'][1]['data']) == ( + '{"a": 1, "b": 3, "c": 2}' + )