code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
self.data_store.clear_db() # Have the plugin manager reload all the plugins self.plugin_manager.load_all_plugins() # Store information about commands and workbench self._store_information()
def clear_db(self)
Clear the Main Database of all samples and worker output. Args: None Returns: Nothing
10.428782
10.911819
0.955733
self.data_store.clear_worker_output() # Have the plugin manager reload all the plugins self.plugin_manager.load_all_plugins() # Store information about commands and workbench self._store_information()
def clear_worker_output(self)
Drops all of the worker output collections Args: None Returns: Nothing
9.674991
9.716773
0.9957
# Pull the worker output work_results = self._recursive_work_resolver(worker_name, md5) # Subkeys (Fixme this is super klutzy) if subkeys: if isinstance(subkeys, str): subkeys = [subkeys] try: sub_results = {} ...
def work_request(self, worker_name, md5, subkeys=None)
Make a work request for an existing stored sample. Args: worker_name: 'strings', 'pe_features', whatever md5: the md5 of the sample (or sample_set!) subkeys: just get a subkey of the output: 'foo' or 'foo.bar' (None for all) Returns: ...
3.81869
3.733651
1.022776
# Does worker support sample_set_input? if self.plugin_meta[worker_name]['sample_set_input']: yield self.work_request(worker_name, sample_set, subkeys) # Loop through all the md5s and return a generator with yield else: md5_list = self.get_sample_set(s...
def set_work_request(self, worker_name, sample_set, subkeys=None)
Make a work request for an existing stored sample (or sample_set). Args: worker_name: 'strings', 'pe_features', whatever sample_set: the md5 of a sample_set in the Workbench data store subkeys: just get a subkey of the output: 'foo' or 'foo.bar' (None for all)...
3.713552
3.466196
1.071362
# Sanity check if not md5_list: print 'Warning: Trying to store an empty sample_set' return None # Remove any duplicates md5_list = list(set(md5_list)) for md5 in md5_list: if not self.has_sample(md5): raise RuntimeE...
def store_sample_set(self, md5_list)
Store a sample set (which is just a list of md5s). Note: All md5s must already be in the data store. Args: md5_list: a list of the md5s in this set (all must exist in data store) Returns: The md5 of the set (the actual md5 of the set)
3.645399
3.488574
1.044954
if isinstance(tags, str): tags = [tags] md5_list = self.data_store.tag_match(tags) return self.store_sample_set(md5_list)
def generate_sample_set(self, tags=None)
Generate a sample_set that maches the tags or all if tags are not specified. Args: tags: Match samples against this tag list (or all if not specified) Returns: The sample_set of those samples matching the tags
5.553783
6.446004
0.861585
if not topic: topic = 'workbench' # It's possible to ask for help on something that doesn't exist # so we'll catch the exception and push back an object that # indicates we didn't find what they were asking for try: return self.work_request('help...
def help(self, topic=None)
Returns the formatted, colored help
8.449688
8.254225
1.02368
help = '%sWelcome to Workbench Help:%s' % (color.Yellow, color.Normal) help += '\n\t%s- workbench.help(\'basic\') %s for getting started help' % (color.Green, color.LightBlue) help += '\n\t%s- workbench.help(\'workers\') %s for help on available workers' % (color.Green, color.LightBlue)...
def _help_workbench(self)
Help on Workbench
3.375545
3.308143
1.020375
help = '%sWorkbench: Getting started...' % (color.Yellow) help += '\n%sStore a sample into Workbench:' % (color.Green) help += '\n\t%s$ workbench.store_sample(raw_bytes, filename, type_tag)' % (color.LightBlue) help += '\n\n%sNotice store_sample returns an md5 of the sample......
def _help_basic(self)
Help for Workbench Basics
8.158406
7.693511
1.060427
help = 'Workbench Commands:' for command in self.list_all_commands(): full_help = self.work_request('help_formatter', command)['help_formatter']['help'] compact_help = full_help.split('\n')[:2] help += '\n\n%s' % '\n'.join(compact_help) return help
def _help_commands(self)
Help on all the available commands
6.832013
6.586749
1.037236
help = 'Workbench Workers:' for worker in self.list_all_workers(): full_help = self.work_request('help_formatter', worker)['help_formatter']['help'] compact_help = full_help.split('\n')[:4] help += '\n\n%s' % '\n'.join(compact_help) return help
def _help_workers(self)
Help on all the available workers
6.680459
6.265596
1.066213
commands = [name for name, _ in inspect.getmembers(self, predicate=inspect.isroutine) if not name.startswith('_')] return commands
def list_all_commands(self)
Returns a list of all the Workbench commands
3.290695
3.177384
1.035662
# Grab it, clean it and ship it work_results = self._get_work_results('info', component) return self.data_store.clean_for_serialization(work_results)
def get_info(self, component)
Get the information about this component
13.960976
13.554638
1.029978
# Enforce dictionary input if not isinstance(info_dict, dict): print 'Critical: info_dict must be a python dictionary, got %s' % type(info_dict) return # Ensure values are not functions/methods/classes info_storage = {key:value for key, value in info_di...
def store_info(self, info_dict, component, type_tag)
Store information about a component. The component could be a worker or a commands or a class, or whatever you want, the only thing to be aware of is name collisions.
4.964916
4.881874
1.01701
print '<<< Generating Information Storage >>>' # Stores information on Workbench commands and signatures for name, meth in inspect.getmembers(self, predicate=inspect.isroutine): if not name.startswith('_'): info = {'command': name, 'sig': str(funcsi...
def _store_information(self)
Store infomation about Workbench and its commands
3.90971
3.56283
1.097361
# First store the plugin info into our data store self.store_info(plugin, plugin['name'], type_tag='worker') # Place it into our active plugin list self.plugin_meta[plugin['name']] = plugin
def _new_plugin(self, plugin)
Internal: This method handles the mechanics around new plugins.
12.140245
11.681433
1.039277
self.data_store.store_work_results(results, collection, md5)
def _store_work_results(self, results, collection, md5)
Internal: Stores the work results of a worker.
4.240833
3.397381
1.248266
results = self.data_store.get_work_results(collection, md5) if not results: raise WorkBench.DataNotFound(md5 + ': Data/Sample not found...') return {collection: results}
def _get_work_results(self, collection, md5)
Internal: Method for fetching work results.
9.528154
8.571476
1.111612
# Bottom out on sample, info or tags if worker_name=='sample' or worker_name=='info' or worker_name=='tags': return datetime.datetime(1970, 1, 1) my_mod_time = self._get_work_results('info', worker_name)['info']['mod_time'] dependencies = self.plugin_meta[worker_na...
def _work_chain_mod_time(self, worker_name)
Internal: We compute a modification time of a work chain. Returns: The newest modification time of any worker in the work chain.
3.732574
3.837542
0.972647
# Looking for the sample? if worker_name == 'sample': return self.get_sample(md5) # Looking for info? if worker_name == 'info': return self._get_work_results('info', md5) # Looking for tags? if worker_name == 'tags': return ...
def _recursive_work_resolver(self, worker_name, md5)
Internal: Input dependencies are recursively backtracked, invoked and then passed down the pipeline until getting to the requested worker.
3.867402
3.819875
1.012442
# Recommend a tag if not tags: print '\n%sRequired: Add a list of tags when you load samples (put \'unknown\' if you must). \ \n\t%sExamples: [\'bad\'], [\'good\'], [\'bad\',\'aptz13\']%s' % (color.Yellow, color.Green, color.Normal) return # ...
def load_sample(self, file_path, tags=None)
Load a sample (or samples) into workbench Args: file_path: path to a file or directory tags (optional): a list of tags for the sample/samples ['bad','aptz13'] Returns: The list of md5s for all samples
5.115039
4.52917
1.129355
# Is the md5 a tag? ss = self.workbench.generate_sample_set(md5) if ss: tag = md5 if not tag else tag md5 = ss # Is the md5 a sample_set? if self.workbench.is_sample_set(md5): # Is the sample_set one sample? ss = self.wo...
def pivot(self, md5, tag='')
Pivot on an md5 (md5 can be a single sample or a sample_set) Args: md5: The md5 can be a single sample or a sample_set tags (optional): a tag for the sample (for the prompt) Returns: Nothing but it's sets the active sample/sample_set
3.320742
3.139055
1.057879
'''Display tag information for all samples in database''' tags = self.workbench.get_all_tags() if not tags: return tag_df = pd.DataFrame(tags) tag_df = self.vectorize(tag_df, 'tags') print '\n%sSamples in Database%s' % (color.LightPurple, color.Normal) ...
def tags(self)
Display tag information for all samples in database
7.372363
5.728629
1.286933
try: _packed_df = self.workbench.get_dataframe(md5) _df = pd.read_msgpack(lz4.loads(_packed_df)) return _df except zerorpc.exceptions.RemoteError as e: return repr_to_str_decorator.r_to_s(self._data_not_found)(e)
def pull_df(self, md5)
Wrapper for the Workbench get_dataframe method Args: md5: pull the dataframe identified by this md5 Returns: The uncompressed/unserialized dataframe
7.786499
6.567372
1.185634
vec_df = df[column_name].str.join(sep='-').str.get_dummies(sep='-') return vec_df
def vectorize(self, df, column_name)
Vectorize a column in the dataframe
4.203156
4.248926
0.989228
_exp_list = [[md5, x] for md5, value_list in zip(df['md5'], df[column_name]) for x in value_list] return pd.DataFrame(_exp_list, columns=['md5',column_name])
def flatten(self, df, column_name)
Flatten a column in the dataframe that contains lists
4.694326
4.540969
1.033772
tag_freq = df.sum() tag_freq.sort(ascending=False) corr = df.corr().fillna(1) corr_dict = corr.to_dict() for tag, count in tag_freq.iteritems(): print ' %s%s: %s%s%s (' % (color.Green, tag, color.LightBlue, count, color.Normal), tag_corrs = sor...
def top_corr(self, df)
Give aggregation counts and correlations
3.315767
3.234177
1.025227
if isinstance(tags, str): tags = [tags] return self.workbench.generate_sample_set(tags)
def search(self, tags=None)
Wrapper for the Workbench search method Args: tags: a single tag 'pcap' or a list of tags to search for ['bad','aptz13'] Returns: A sample_set that contains the md5s for all matching samples
8.895974
5.723063
1.554408
print '%s<<< Workbench CLI Version %s >>>%s' % (color.LightBlue, self.version, color.Normal) print self.workbench.help('version')
def versions(self)
Announce Versions of CLI and Server Args: None Returns: The running versions of both the CLI and the Workbench Server
15.12396
12.129555
1.246869
''' Running the workbench CLI ''' # Announce versions self.versions() # Sample/Tag info and Help self.tags() print '\n%s' % self.workbench.help('cli') # Now that we have the Workbench connection spun up, we register some stuff # with the embedded IPytho...
def run(self)
Running the workbench CLI
7.717581
7.412176
1.041203
# First we do a temp connect with a short heartbeat _tmp_connect = zerorpc.Client(timeout=300, heartbeat=2) _tmp_connect.connect('tcp://'+server_info['server']+':'+server_info['port']) try: _tmp_connect._zerorpc_name() _tmp_connect.close() de...
def _connect(self, server_info)
Connect to the workbench server
3.485623
3.332416
1.045975
percent = min(int(sent*100.0/total), 100) sys.stdout.write('\r{0}[{1}{2}] {3}{4}%{5}'. format(color.Green, '#'*(percent/2), ' '*(50-percent/2), color.Yellow, percent, color.Normal)) sys.stdout.flush()
def _progress_print(self, sent, total)
Progress print show the progress of the current upload with a neat progress bar Credits: http://redino.net/blog/2013/07/display-a-progress-bar-in-console-using-python/
3.497219
3.588047
0.974686
# I'm sure there's a better way to do this if not md5 and not self.session.md5: return 'Must call worker with an md5 argument...' elif not md5: md5 = self.session.md5 # Is the md5 a sample_set? if self.workbench.is_sample_set(md5): r...
def _work_request(self, worker, md5=None)
Wrapper for a work_request to workbench
5.531311
5.248158
1.053953
# First add all the workers commands = {} for worker in self.workbench.list_all_workers(): commands[worker] = lambda md5=None, worker=worker: self._work_request(worker, md5) # Next add all the commands for command in self.workbench.list_all_commands(): ...
def _generate_command_dict(self)
Create a customized namespace for Workbench with a bunch of shortcuts and helper/alias functions that will make using the shell MUCH easier.
5.263804
5.007682
1.051146
# Stores information on Workbench commands and signatures for name, meth in inspect.getmembers(self, predicate=inspect.isroutine): if not name.startswith('_') and name != 'run': info = {'command': name, 'sig': str(funcsigs.signature(meth)), 'docstring': meth.__doc__}...
def _register_info(self)
Register local methods in the Workbench Information system
2.879359
2.695243
1.068312
# Capture the original line orig_line = line # Get tokens from all the currently active namespace ns_token_set = set([token for nspace in self.shell.all_ns_refs for token in nspace]) # Build up token set and info out of the incoming line token_list = re.split(...
def transform(self, line, _continue_prompt)
Shortcut Workbench commands by using 'auto-quotes
3.640088
3.578258
1.01728
tree = etree.parse(io.BytesIO(bytes(s, encoding='UTF-8'))) collection = self.__parse_collection(tree.getroot()) collection.encoding = tree.docinfo.encoding collection.standalone = tree.docinfo.standalone collection.version = tree.docinfo.xml_version return collec...
def decodes(self, s: str) -> BioCCollection
Deserialize ``s`` to a BioC collection object. Args: s: a "str" instance containing a BioC collection Returns: an object of BioCollection
3.213532
3.748395
0.857309
# utf8_parser = etree.XMLParser(encoding='utf-8') tree = etree.parse(fp) collection = self.__parse_collection(tree.getroot()) collection.encoding = tree.docinfo.encoding collection.standalone = tree.docinfo.standalone collection.version = tree.docinfo.xml_version...
def decode(self, fp: TextIO) -> BioCCollection
Deserialize ``fp`` to a BioC collection object. Args: fp: a ``.read()``-supporting file-like object containing a BioC collection Returns: an object of BioCollection
3.178564
3.410006
0.932129
# Grab server args args = client_helper.grab_server_args() # Start up workbench connection workbench = zerorpc.Client(timeout=300, heartbeat=60) workbench.connect('tcp://'+args['server']+':'+args['port']) # Upload the file into workbench my_file = os.path.join(os.path.dirname(os....
def run()
This client pushes a file into Workbench.
5.829351
5.397584
1.079993
''' Execute method ''' # Grab the raw bytes of the sample raw_bytes = input_data['sample']['raw_bytes'] # Spin up the rekall session and render components session = MemSession(raw_bytes) renderer = WorkbenchRenderer(session=session) # Run the plugin ses...
def execute(self, input_data)
Execute method
9.90204
10.020615
0.988167
row = {} for key,value in data.iteritems(): if not value: value = '-' elif isinstance(value, list): value = value[1] elif isinstance(value, dict): if 'type_name' in value: if ...
def process_row(cls, data, column_map)
Process the row data from Rekall
3.676174
3.522947
1.043494
self.output = [] # Start basically resets the output data super(WorkbenchRenderer, self).start(plugin_name=plugin_name) return self
def start(self, plugin_name=None, kwargs=None)
Start method: initial data structures and store some meta data.
18.121437
15.10098
1.200017
# Make a new section if self.incoming_section: self.SendMessage(['s', {'name': args}]) self.incoming_section = False
def format(self, formatstring, *args)
Presentation Information from the Plugin
18.915335
18.47797
1.02367
# The way messages are 'encapsulated' by Rekall is questionable, 99% of the # time it's way better to have a dictionary...shrug... message_type = statement[0] message_data = statement[1] self.output.append({'type': message_type, 'data': message_data})
def SendMessage(self, statement)
Here we're actually capturing messages and putting them into our output
10.805263
10.130931
1.066562
path = os.path.join(directory, filename) return open(path, mode)
def open(self, directory=None, filename=None, mode="rb")
Opens a file for writing or reading.
3.578758
3.274649
1.092868
for i in xrange(0, len(data), chunk_size): yield self.compressor(data[i:i+chunk_size])
def _file_chunks(self, data, chunk_size)
Yield compressed chunks from a data array
3.405324
2.602187
1.308639
md5_list = [] sent_bytes = 0 total_bytes = len(raw_bytes) for chunk in self._file_chunks(raw_bytes, self.chunk_size): md5_list.append(self.workbench.store_sample(chunk, filename, self.compress_ident)) sent_bytes += self.chunk_size self.progres...
def stream_to_workbench(self, raw_bytes, filename, type_tag, tags)
Split up a large file into chunks and send to Workbench
3.757519
3.511518
1.070055
return json.dumps(obj, cls=BioCJSONEncoder, **kwargs)
def dumps(obj, **kwargs) -> str
Serialize a BioC ``obj`` to a JSON formatted ``str``.
9.393259
3.632084
2.58619
return json.dump(obj, fp, cls=BioCJSONEncoder, **kwargs)
def dump(obj, fp, **kwargs)
Serialize obj as a JSON formatted stream to fp (a .write()-supporting file-like object)
5.88407
5.413134
1.086999
if self.level == DOCUMENT and not isinstance(obj, BioCDocument): raise ValueError if self.level == PASSAGE and not isinstance(obj, BioCPassage): raise ValueError if self.level == SENTENCE and not isinstance(obj, BioCSentence): raise ValueError ...
def write(self, obj: BioCDocument or BioCPassage or BioCSentence)
Encode and write a single object. Args: obj: an instance of BioCDocument, BioCPassage, or BioCSentence Returns:
2.625427
2.809959
0.93433
''' Execute method ''' # Spin up the rekall adapter adapter = RekallAdapter() adapter.set_plugin_name(self.plugin_name) rekall_output = adapter.execute(input_data) # Process the output data for line in rekall_output: if line['type'] == 'm': # Meta ...
def execute(self, input_data)
Execute method
3.870912
3.916247
0.988424
''' Execute the ViewMemoryDeep worker ''' # Aggregate the output from all the memory workers, clearly this could be kewler output = input_data['view_memory'] output['tables'] = {} for data in [input_data[key] for key in ViewMemoryDeep.dependencies]: for name,table in...
def execute(self, input_data)
Execute the ViewMemoryDeep worker
14.657327
9.599968
1.52681
''' Execute the ViewMemory worker ''' # Aggregate the output from all the memory workers into concise summary info output = {'meta': input_data['mem_meta']['tables']['info']} output['connscan'] = list(set([item['Remote Address'] for item in input_data['mem_connscan']['tables']['connscan...
def execute(self, input_data)
Execute the ViewMemory worker
6.890601
6.125394
1.124924
''' store a config value in a dictionary, these values are used to populate a trasnfer spec validation -- check type, check allowed values and rename if required ''' if value is not None: _bad_type = (not isinstance(value, atype)) if not _bad_type: # s...
def store(self, name, value, atype, new_name=None, multiplier=None, allowed_values=None)
store a config value in a dictionary, these values are used to populate a trasnfer spec validation -- check type, check allowed values and rename if required
3.886526
2.668185
1.456618
''' convert the multi_session param a number ''' _val = 0 if "multi_session" in self._dict: _val = self._dict["multi_session"] if str(_val).lower() == 'all': _val = -1 return int(_val)
def multi_session(self)
convert the multi_session param a number
6.562616
4.446458
1.47592
''' get the Aspera connection details on Aspera enabled buckets ''' response = self._client.get_bucket_aspera(Bucket=bucket) # Parse metadata from response aspera_access_key = response['AccessKey']['Id'] aspera_secret_key = response['AccessKey']['Secret'] ats_endpoint = ...
def _raw_aspera_metadata(self, bucket)
get the Aspera connection details on Aspera enabled buckets
5.123586
3.520598
1.455317
''' make hhtp call to Aspera to fetch back trasnfer spec ''' aspera_access_key, aspera_secret_key, ats_endpoint = self._get_aspera_metadata(bucket_name) _headers = {'accept': "application/json", 'Content-Type': "application/json"} credentials = {'type': 'token', ...
def _fetch_transfer_spec(self, node_action, token, bucket_name, paths)
make hhtp call to Aspera to fetch back trasnfer spec
4.834377
3.895976
1.240864
''' pass the transfer details to aspera and receive back a populated transfer spec complete with access token ''' _paths = [] for _file_pair in call_args.file_pair_list: _path = OrderedDict() if call_args.direction == enumAsperaDirection.SEND: ...
def _create_transfer_spec(self, call_args)
pass the transfer details to aspera and receive back a populated transfer spec complete with access token
4.553735
3.77305
1.206911
''' upload a directory using Aspera ''' check_io_access(directory, os.R_OK) return self._queue_task(bucket, [FilePair(key, directory)], transfer_config, subscribers, enumAsperaDirection.SEND)
def upload_directory(self, directory, bucket, key, transfer_config=None, subscribers=None)
upload a directory using Aspera
22.141323
21.846817
1.013481
''' download a directory using Aspera ''' check_io_access(directory, os.W_OK) return self._queue_task(bucket, [FilePair(key, directory)], transfer_config, subscribers, enumAsperaDirection.RECEIVE)
def download_directory(self, bucket, key, directory, transfer_config=None, subscribers=None)
download a directory using Aspera
21.231236
21.248455
0.99919
''' upload a file using Aspera ''' check_io_access(fileobj, os.R_OK, True) return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config, subscribers, enumAsperaDirection.SEND)
def upload(self, fileobj, bucket, key, transfer_config=None, subscribers=None)
upload a file using Aspera
17.830826
18.806089
0.948141
''' download a file using Aspera ''' check_io_access(os.path.dirname(fileobj), os.W_OK) return self._queue_task(bucket, [FilePair(key, fileobj)], transfer_config, subscribers, enumAsperaDirection.RECEIVE)
def download(self, bucket, key, fileobj, transfer_config=None, subscribers=None)
download a file using Aspera
15.235694
15.585002
0.977587
''' set the aspera log path - used by th Ascp process set the internal aspera sdk activity - for debug purposes ''' if aspera_log_path: check_io_access(aspera_log_path, os.W_OK) AsperaTransferCoordinator.set_log_location(aspera_log_path) if sdk_log_level != l...
def set_log_details(aspera_log_path=None, sdk_log_level=logging.NOTSET)
set the aspera log path - used by th Ascp process set the internal aspera sdk activity - for debug purposes
4.714418
2.712736
1.737883
''' validate the user arguments ''' assert(args.bucket) if args.subscribers: for _subscriber in args.subscribers: assert(isinstance(_subscriber, AsperaBaseSubscriber)) if (args.transfer_config): assert(isinstance(args.transfer_config, AsperaConfi...
def _validate_args(self, args)
validate the user arguments
6.254436
6.249934
1.00072
''' queue the upload/download - when get processed when resources available Use class level transfer_config if not defined. ''' config = transfer_config if transfer_config else self._transfer_config _call_args = CallArgs(bucket=bucket, file_pair_list=fi...
def _queue_task(self, bucket, file_pair_list, transfer_config, subscribers, direction)
queue the upload/download - when get processed when resources available Use class level transfer_config if not defined.
6.197691
3.4117
1.816599
''' Internal shutdown used by 'shutdown' method above ''' if cancel: # Cancel all in-flight transfers if requested, before waiting # for them to complete. self._coordinator_controller.cancel(cancel_msg, exc_type) try: # Wait until there are no mor...
def _shutdown(self, cancel, cancel_msg, exc_type=CancelledError)
Internal shutdown used by 'shutdown' method above
8.097223
6.832886
1.185037
''' Stop backgroud thread and cleanup resources ''' self._processing_stop = True self._wakeup_processing_thread() self._processing_stopped_event.wait(3)
def cleanup(self)
Stop backgroud thread and cleanup resources
13.248764
8.584644
1.54331
''' count the number of cooridnators currently being processed or count the number of ascps currently being used ''' with self._lock: _count = 0 if count_ascps: for _coordinator in self._tracked_transfer_coordinators: _count += _coordin...
def tracked_coordinator_count(self, count_ascps=False)
count the number of cooridnators currently being processed or count the number of ascps currently being used
5.208109
2.891989
1.800874
''' add transfer to waiting queue if possible then notify the background thread to process it ''' if self._cancel_called: raise AsperaTransferQueueError("Cancel already called") elif self._wait_called: raise AsperaTransferQueueError("Cant queue items during wa...
def _queue_task(self, args)
add transfer to waiting queue if possible then notify the background thread to process it
5.631957
4.634913
1.215116
''' remove entry from the waiting waiting or remove item from processig queue and add to processed quque notify background thread as it may be able to process watiign requests ''' # usually called on processing completion - but can be called for a cancel if self._...
def remove_aspera_coordinator(self, transfer_coordinator)
remove entry from the waiting waiting or remove item from processig queue and add to processed quque notify background thread as it may be able to process watiign requests
9.088593
4.001338
2.271388
''' append item to waiting queue ''' logger.debug("Add to waiting queue count=%d" % self.waiting_coordinator_count()) with self._lockw: self._waiting_transfer_coordinators.append(transfer_coordinator)
def append_waiting_queue(self, transfer_coordinator)
append item to waiting queue
7.641223
7.774449
0.982864
''' call the Aspera sdk to freeup resources ''' with self._lock: if len(self._processed_coordinators) > 0: for _coordinator in self._processed_coordinators: _coordinator.free_resources() self._processed_coordinators = []
def free_processed_queue(self)
call the Aspera sdk to freeup resources
6.398396
3.703906
1.727473
''' has either of the stop processing flags been set ''' if len(self._processed_coordinators) > 0: self.free_processed_queue() return self._cancel_called or self._processing_stop
def is_stop(self)
has either of the stop processing flags been set
19.27623
10.653285
1.809417
''' thread to processes the waiting queue fetches transfer spec then calls start transfer ensures that max ascp is not exceeded ''' logger.info("Queue processing thread started") while not self.is_stop(): self._processing_event.wait(3) ...
def _process_waiting_queue(self)
thread to processes the waiting queue fetches transfer spec then calls start transfer ensures that max ascp is not exceeded
4.784077
3.648164
1.311366
''' remove all entries from waiting queue or cancell all in waiting queue ''' with self._lockw: if cancel: for _coordinator in self._waiting_transfer_coordinators: _coordinator.notify_cancelled("Clear Waiting Queue", False) self._waiting_transf...
def clear_waiting_coordinators(self, cancel=False)
remove all entries from waiting queue or cancell all in waiting queue
8.751549
5.958546
1.468739
self._cancel_called = True self.clear_waiting_coordinators(cancel=True) super(AsperaTransferCoordinatorController, self).cancel(*args, **kwargs)
def cancel(self, *args, **kwargs)
Cancel all queue items - then attempt to cancel all in progress items
10.540331
9.935542
1.060871
self._wait_called = True while self.tracked_coordinator_count() > 0 or \ self.waiting_coordinator_count() > 0: time.sleep(1) super(AsperaTransferCoordinatorController, self).wait() self._wait_called = False
def wait(self)
Wait until all in progress and queued items are processed
7.677197
6.883605
1.115287
''' Execute the ViewZip worker ''' # Just a small check to make sure we haven't been called on the wrong file type if (input_data['meta']['type_tag'] != 'zip'): return {'error': self.__class__.__name__+': called on '+input_data['meta']['type_tag']} view = {} view['p...
def execute(self, input_data)
Execute the ViewZip worker
7.348435
6.690037
1.098415
if not self.is_done(): raise TransferNotDoneError( 'set_exception can only be called once the transfer is ' 'complete.') self._coordinator.set_exception(exception, override=True)
def set_exception(self, exception)
Sets the exception on the future.
7.18985
6.736139
1.067355
''' the callback method used by the Aspera sdk during transfer to notify progress, error or successful completion ''' if self.is_stopped(): return True _asp_message = AsperaMessage(message) if not _asp_message.is_msg_type( [enumAsperaMsgType....
def transferReporter(self, xferId, message)
the callback method used by the Aspera sdk during transfer to notify progress, error or successful completion
2.87082
2.489114
1.15335
''' pass the transfer spec to the Aspera sdk and start the transfer ''' try: if not self.is_done(): faspmanager2.startTransfer(self.get_transfer_id(), None, self.get_transfer_spec(), ...
def start_transfer(self)
pass the transfer spec to the Aspera sdk and start the transfer
10.014987
5.687911
1.76075
''' check whether a transfer is currently running ''' if is_stopped and self.is_stopped(): return False return faspmanager2.isRunning(self.get_transfer_id())
def is_running(self, is_stopped)
check whether a transfer is currently running
12.810172
10.176167
1.258841
''' check whether a transfer is stopped or is being stopped ''' if is_stopping: return self._is_stopped or self._is_stopping return self._is_stopped
def is_stopped(self, is_stopping=True)
check whether a transfer is stopped or is being stopped
5.482924
3.773589
1.452973
''' call Apsera sdk modify an in progress eg pause/resume allowed values defined in enumAsperaModifyTransfer class ''' _ret = False try: if self.is_running(True): logger.info("ModifyTransfer called %d = %d" % (option, value)) _ret = faspman...
def _modify_transfer(self, option, value=0)
call Apsera sdk modify an in progress eg pause/resume allowed values defined in enumAsperaModifyTransfer class
11.111975
4.323802
2.569954
''' send a stop transfer request to the Aspera sdk, can be done for: cancel - stop an in progress transfer free_resource - request to the Aspera sdk free resouces related to trasnfer_id ''' if not self.is_stopped(): self._is_stopping = True try: ...
def stop(self, free_resource=False)
send a stop transfer request to the Aspera sdk, can be done for: cancel - stop an in progress transfer free_resource - request to the Aspera sdk free resouces related to trasnfer_id
5.580872
2.9112
1.917035
''' call stop to free up resources ''' if not self.is_stopped(): logger.info("Freeing resources: %s" % self.get_transfer_id()) self.stop(True)
def free_resources(self)
call stop to free up resources
8.096712
6.274302
1.290456
''' search message to find and extract a named value ''' name += ":" assert(self._message) _start = self._message.find(name) if _start >= 0: _start += len(name) + 1 _end = self._message.find("\n", _start) _value = self._message[_start:_end] ...
def extract_message_value(self, name)
search message to find and extract a named value
3.809667
3.074921
1.238948
''' set session status - eg failed, success -- valid values contained in enumAsperaControllerStatus class ''' self._status = status logger.debug("Set status(%s) for %s" % (self._status, self.session_id)) self.set_done() if ex: self._exception = ex
def _set_status(self, status, ex=None)
set session status - eg failed, success -- valid values contained in enumAsperaControllerStatus class
12.812052
3.736597
3.428803
''' set the number of bytes transferred - if it has changed return True ''' _changed = False if bytes_transferred: _changed = (self._bytes_transferred != int(bytes_transferred)) if _changed: self._bytes_transferred = int(bytes_transferred) ...
def set_bytes_transferred(self, bytes_transferred)
set the number of bytes transferred - if it has changed return True
5.182417
4.314258
1.20123
''' set the exception message and set the status to failed ''' logger.error("%s : %s" % (exception.__class__.__name__, str(exception))) self._set_status(enumAsperaControllerStatus.FAILED, exception)
def set_exception(self, exception)
set the exception message and set the status to failed
9.939529
7.81436
1.271957
''' wait for the done event to be set - no timeout''' self._done_event.wait(MAXINT) return self._status, self._exception
def wait(self)
wait for the done event to be set - no timeout
14.31807
9.289278
1.541354
_ret = False if not self.is_done(): self.notify_cancelled(msg, True) _ret = True return _ret
def cancel(self, msg='', exc_type=CancelledError)
Cancels the TransferFuture :param msg: The message to attach to the cancellation :param exc_type: The type of exception to set for the cancellation
7.397798
7.515097
0.984391
''' update the session/ascp count 0 : set the number of sessions being used to 1 or number specified in transfer config -1: decrement the session count by one 1: set the session count to param value ''' if type == 0: # init _count = 0 ...
def _update_session_count(self, type=0, actutal_session_count=0)
update the session/ascp count 0 : set the number of sessions being used to 1 or number specified in transfer config -1: decrement the session count by one 1: set the session count to param value
5.64033
2.438475
2.313056
_status = None _exception = None self._done_event.wait(MAXINT) # first wait for session global if self.is_failed(): # global exception set _exception = self._exception _status = enumAsperaControllerStatus.FAILED else: for _session in...
def result(self, raise_exception=True)
Waits until TransferFuture is done and returns the result If the TransferFuture succeeded, it will return the result. If the TransferFuture failed, it will raise the exception associated to the failure.
6.583512
6.538804
1.006837
''' run the queed callback for just the first session only ''' _session_count = len(self._sessions) self._update_session_count(1, _session_count) if _session_count == 1: self._run_queued_callbacks()
def notify_init(self)
run the queed callback for just the first session only
10.42861
4.243314
2.457657
''' if error clear all sessions otherwise check to see if all other sessions are complete then run the done callbacks ''' if error: for _session in self._sessions.values(): _session.set_done() self._session_count = 0 else: s...
def notify_done(self, error=False, run_done_callbacks=True)
if error clear all sessions otherwise check to see if all other sessions are complete then run the done callbacks
4.038297
2.314557
1.744738
''' only call the progress callback if total has changed or PROGRESS_MSGS_SEND_ALL is set ''' _total = 0 for _session in self._sessions.values(): _total += _session.bytes_transferred if AsperaSession.PROGRESS_MSGS_SEND_ALL: self._run_progress_callback...
def notify_progress(self)
only call the progress callback if total has changed or PROGRESS_MSGS_SEND_ALL is set
5.222896
3.13869
1.664037
''' set the exception message, stop transfer if running and set the done event ''' logger.error("%s : %s" % (exception.__class__.__name__, str(exception))) self._exception = exception if self.is_running(True): # wait for a short 5 seconds for it to finish for _cnt...
def notify_exception(self, exception, run_done_callbacks=True)
set the exception message, stop transfer if running and set the done event
5.701563
4.041172
1.410869
''' check all sessions to see if they have completed successfully ''' for _session in self._sessions.values(): if not _session.is_success(): return False return True
def is_success(self)
check all sessions to see if they have completed successfully
6.715663
3.631381
1.849342
''' run the function to set the transfer spec on error set associated exception ''' _ret = False try: self._args.transfer_spec_func(self._args) _ret = True except Exception as ex: self.notify_exception(AsperaTransferSpecError(ex), False) return...
def set_transfer_spec(self)
run the function to set the transfer spec on error set associated exception
12.084134
5.971203
2.023735