code
stringlengths
1
18.2k
daemon. # 1. Receive message from the client # 2. Check payload and call respective function with payload as parameter. # 3. Execute logic # 4. Return payload with response to client # Create list for waitable objects readable, writable, failed = select.select(self.read_list, [], [], 1) for waiting_socket in readable: ...
added to readlist to be processed. try: client_socket, client_address = self.socket.accept() self.read_list.append(client_socket) except Exception: self.logger.warning('Daemon rejected client') else: # Trying to receive instruction from client socket try: instruction = waiting_socket.recv(1048576) except (EOFError, OSE...
data can be unpickled. try: payload = pickle.loads(instruction) except EOFError: # Instruction is ignored if it can't be unpickled self.logger.error('Received message is incomplete, dropping received data.') self.read_list.remove(waiting_socket) waiting_socket.close() # Set invalid payload payload = {'mode': ''} functi...
self.reset_everything, 'clear': self.clear, 'config': self.set_config, 'STOPDAEMON': self.stop_daemon, } if payload['mode'] in functions.keys(): self.logger.debug('Payload received:') self.logger.debug(payload) response = functions[payload['mode']](payload) self.logger.debug('Sending payload:') self.logger.debug(respon...
self.process_handler.wait_for_finish() # Close socket, clean everything up and exit self.socket.close() cleanup(self.config_dir) sys.exit(0)
def stop_daemon(self, payload=None): """Kill current processes and initiate daemon shutdown. The daemon will shut down after a last check on all killed processes. """ kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.running = False return {'message': 'Pueue daemon shutting down', 'status...
def set_config(self, payload): """Update the current config depending on the payload and save it.""" self.config['default'][payload['option']] = str(payload['value']) if payload['option'] == 'maxProcesses': self.process_handler.set_max(payload['value']) if payload['option'] == 'customShell': path = payload['value'] if ...
def pipe_to_process(self, payload): """Send something to stdin of a specific process.""" message = payload['input'] key = payload['key'] if not self.process_handler.is_running(key): return {'message': 'No running process for this key', 'status': 'error'} self.process_handler.send_to_process(message, key) return {'messa...
def send_status(self, payload): """Send the daemon status and the current queue for displaying.""" answer = {} data = [] # Get daemon status if self.paused: answer['status'] = 'paused' else: answer['status'] = 'running' # Add current queue or a message, that queue is empty if len(self.queue) > 0: data = deepcopy(self.q...
big for the socket buffer # and this is not needed by the client for key, item in data.items(): if 'stderr' in item: del item['stderr'] if 'stdout' in item: del item['stdout'] else: data = 'Queue is empty' answer['data'] = data return answer
def reset_everything(self, payload): """Kill all processes, delete the queue and clean everything up.""" kill_signal = signals['9'] self.process_handler.kill_all(kill_signal, True) self.process_handler.wait_for_finish() self.reset = True answer = {'message': 'Resetting current queue', 'status': 'success'} return answer
def clear(self, payload): """Clear queue from any `done` or `failed` entries. The log will be rotated once. Otherwise we would loose all logs from thoes finished processes. """ self.logger.rotate(self.queue) self.queue.clear() self.logger.write(self.queue) answer = {'message': 'Finished entries have been removed.', 'st...
def start(self, payload): """Start the daemon and all processes or only specific processes.""" # Start specific processes, if `keys` is given in the payload if payload.get('keys'): succeeded = [] failed = [] for key in payload.get('keys'): success = self.process_handler.start_process(key) if success: succeeded.append(s...
message += '\nNo paused, queued or stashed process for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} # Start a all processes and the daemon else: self.process_handler.start_all() if self.paused: self.paused = False answer = {'message': 'Daemon and all proce...
def pause(self, payload): """Start the daemon and all processes or only specific processes.""" # Pause specific processes, if `keys` is given in the payload if payload.get('keys'): succeeded = [] failed = [] for key in payload.get('keys'): success = self.process_handler.pause_process(key) if success: succeeded.append(s...
message += '\nNo running process for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} # Pause all processes and the daemon else: if payload.get('wait'): self.paused = True answer = {'message': 'Pausing daemon, but waiting for processes to finish.', 'status': '...
= {'message': 'Daemon already paused, pausing all processes anyway.', 'status': 'success'} return answer
def edit_command(self, payload): """Edit the command of a specific entry.""" key = payload['key'] command = payload['command'] if self.queue[key]: if self.queue[key]['status'] in ['queued', 'stashed']: self.queue[key]['command'] = command answer = {'message': 'Command updated', 'status': 'error'} else: answer = {'messa...
answer
def stash(self, payload): """Stash the specified processes.""" succeeded = [] failed = [] for key in payload['keys']: if self.queue.get(key) is not None: if self.queue[key]['status'] == 'queued': self.queue[key]['status'] = 'stashed' succeeded.append(str(key)) else: failed.append(str(key)) else: failed.append(str(key))...
= 'error' answer = {'message': message.strip(), 'status': status} return answer
def kill_process(self, payload): """Pause the daemon and kill all processes or kill a specific process.""" # Kill specific processes, if `keys` is given in the payload kill_signal = signals[payload['signal'].lower()] kill_shell = payload.get('all', False) if payload.get('keys'): succeeded = [] failed = [] for key in pa...
"Signal '{}' sent to processes: {}.".format(payload['signal'], ', '.join(succeeded)) status = 'success' if len(failed) > 0: message += '\nNo running process for keys: {}'.format(', '.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} # Kill all processes and the daemon else: self.pro...
send to all processes.', 'status': 'success'} return answer
def remove(self, payload): """Remove specified entries from the queue.""" succeeded = [] failed = [] for key in payload['keys']: running = self.process_handler.is_running(key) if not running: removed = self.queue.remove(key) if removed: succeeded.append(str(key)) else: failed.append(str(key)) else: failed.append(str(ke...
'.join(failed)) status = 'error' answer = {'message': message.strip(), 'status': status} return answer
def switch(self, payload): """Switch the two specified entry positions in the queue.""" first = payload['first'] second = payload['second'] running = self.process_handler.is_running(first) or self.process_handler.is_running(second) if running: answer = { 'message': "Can't switch running processes, " "please stop the pr...
else: answer = {'message': "One or both entries do not exist or are not queued/stashed.", 'status': 'error'} return answer
def restart(self, payload): """Restart the specified entries.""" succeeded = [] failed = [] for key in payload['keys']: restarted = self.queue.restart(key) if restarted: succeeded.append(str(key)) else: failed.append(str(key)) message = '' if len(succeeded) > 0: message += 'Restarted entries: {}.'.format(', '.join(succ...
answer
def sendall(self, data, flags=0): '''Same as socket.sendall''' count = len(data) while count: sent = self.send(data, flags) # This could probably be a buffer object data = data[sent:] count -= sent
def do_ls(client, args): """List directory""" for item in client.get_folder_contents_iter(args.uri): # privacy flag if item['privacy'] == 'public': item['pf'] = '@' else: item['pf'] = '-' if isinstance(item, Folder): # type flag item['tf'] = 'd' item['key'] = item['folderkey'] item['size'] = '' else: item['tf'] = '-' i...
def do_file_upload(client, args): """Upload files""" # Sanity check if len(args.paths) > 1: # destination must be a directory try: resource = client.get_resource_by_uri(args.dest_uri) except ResourceNotFoundError: resource = None if resource and not isinstance(resource, Folder): print("file-upload: " "target '{}' is no...
def do_file_download(client, args): """Download file""" # Sanity check if not os.path.isdir(args.dest_path) and not args.dest_path.endswith('/'): print("file-download: " "target '{}' is not a directory".format(args.dest_path)) if not os.path.exists(args.dest_path): print("\tHint: add trailing / to create one") return N...
def do_file_show(client, args): """Output file contents to stdout""" for src_uri in args.uris: client.download_file(src_uri, sys.stdout.buffer) return True
def do_folder_create(client, args): """Create directory""" for folder_uri in args.uris: client.create_folder(folder_uri, recursive=True) return True
def do_resource_delete(client, args): """Remove resource""" for resource_uri in args.uris: client.delete_resource(resource_uri, purge=args.purge) print("Deleted {}".format(resource_uri)) return True
def do_file_update_metadata(client, args): """Update file metadata""" client.update_file_metadata(args.uri, filename=args.filename, description=args.description, mtime=args.mtime, privacy=args.privacy) return True
def do_folder_update_metadata(client, args): """Update file metadata""" client.update_folder_metadata(args.uri, foldername=args.foldername, description=args.description, mtime=args.mtime, privacy=args.privacy, privacy_recursive=args.recursive) return True
def main(): # pylint: disable=too-many-statements """Main entry point""" parser = argparse.ArgumentParser(prog='mediafire-cli', description=__doc__) parser.add_argument('--debug', dest='debug', action='store_true', default=False, help='Enable debug output') parser.add_argument('--email', dest='email', required=False, d...
# file-download subparser = actions.add_parser('file-download', help=do_file_download.__doc__) subparser.add_argument('uris', nargs='+', help='MediaFire File URI[s] to download') subparser.add_argument('dest_path', help='Destination path') # file-show subparser = actions.add_parser('file-show', help=do_file_show.__doc_...
subparser = actions.add_parser('file-update-metadata', help=do_file_update_metadata.__doc__) subparser.add_argument('uri', help='MediaFire file URI') subparser.add_argument('--filename', help='Set file name', default=None, dest='filename') subparser.add_argument('--privacy', help='Set file privacy', choices=['public', ...
default=None, dest='recursive') subparser.add_argument('--description', help='Set folder description', dest='description', default=None) subparser.add_argument('--mtime', help='Set folder mtime', default=None, dest='mtime') # debug-get-resource subparser = actions.add_parser('debug-get-resource', help=do_debug_get_reso...
do_folder_update_metadata, "debug-get-resource": do_debug_get_resource } if args.action in router: result = router[args.action](client, args) if not result: sys.exit(1) else: print('Unsupported action: {}'.format(args.action)) sys.exit(1)
def pub(self, topic, message): '''Publish a message to a topic''' return self.post('pub', params={'topic': topic}, data=message)
def mpub(self, topic, messages, binary=True): '''Send multiple messages to a topic. Optionally pack the messages''' if binary: # Pack and ship the data return self.post('mpub', data=pack(messages)[4:], params={'topic': topic, 'binary': True}) elif any('\n' in m for m in messages): # If any of the messages has a newline...
messages with newlines') else: return self.post( '/mpub', params={'topic': topic}, data='\n'.join(messages))
def clean_stats(self): '''Stats with topics and channels keyed on topic and channel names''' stats = self.stats() if 'topics' in stats: # pragma: no branch topics = stats['topics'] topics = dict((t.pop('topic_name'), t) for t in topics) for topic, data in topics.items(): if 'channels' in data: # pragma: no branch chann...
= topics return stats
def execute_add(args, root_dir=None): """Add a new command to the daemon queue. Args: args['command'] (list(str)): The actual programm call. Something like ['ls', '-a'] or ['ls -al'] root_dir (string): The path to the root directory the daemon is running in. """ # We accept a list of strings. # This is done to create a...
new instruction to daemon instruction = { 'command': command, 'path': os.getcwd() } print_command_factory('add')(instruction, root_dir)
def execute_edit(args, root_dir=None): """Edit a existing queue command in the daemon. Args: args['key'] int: The key of the queue entry to be edited root_dir (string): The path to the root directory the daemon is running in. """ # Get editor EDITOR = os.environ.get('EDITOR', 'vim') # Get command from server key = args...
entry exists and is queued or stashed if not isinstance(status['data'], str) and key in status['data']: if status['data'][key]['status'] in ['queued', 'stashed']: command = status['data'][key]['command'] else: print("Entry is not 'queued' or 'stashed'") sys.exit(1) else: print('No entry with this key') sys.exit(1) with...
'key': key, 'command': edited_command, }, root_dir=root_dir)
def command_factory(command): """A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to the daemon and returns the unpickled object which is returned by the daemon. Args: command (string): The type of payload this should be. This determines as wha...
""" def communicate(body={}, root_dir=None): """Communicate with the daemon. This function sends a payload to the daemon and returns the unpickled object sent by the daemon. Args: body (dir): Any other arguments that should be put into the payload. root_dir (str): The root directory in which we expect the daemon. We ne...
client = connect_socket(root_dir) body['mode'] = command # Delete the func entry we use to call the correct function with argparse # as functions can't be pickled and this shouldn't be send to the daemon. if 'func' in body: del body['func'] data_string = pickle.dumps(body, -1) client.send(data_string) # Receive message...
def get_descriptor(self, number): """Create file descriptors for process output.""" # Create stdout file and get file descriptor stdout_path = os.path.join(self.config_dir, 'pueue_process_{}.stdout'.format(number)) if os.path.exists(stdout_path): os.remove(stdout_path) out_descriptor = open(stdout_path, 'w+') # Create ...
err_descriptor
def clean_descriptor(self, number): """Close file descriptor and remove underlying files.""" self.descriptors[number]['stdout'].close() self.descriptors[number]['stderr'].close() if os.path.exists(self.descriptors[number]['stdout_path']): os.remove(self.descriptors[number]['stdout_path']) if os.path.exists(self.descrip...
def check_finished(self): """Poll all processes and handle any finished processes.""" changed = False for key in list(self.processes.keys()): # Poll process and check if it finshed process = self.processes[key] process.poll() if process.returncode is not None: # If a process is terminated by `stop` or `kill` # we want ...
and err_out output, error_output = process.communicate() descriptor = self.descriptors[key] descriptor['stdout'].seek(0) descriptor['stderr'].seek(0) output = get_descriptor_output(descriptor['stdout'], key, handler=self) error_output = get_descriptor_output(descriptor['stderr'], key, handler=self) # Mark queue entry a...
if key in self.to_remove: self.to_remove.remove(key) del self.queue[key] else: if key in self.to_stash: self.to_stash.remove(key) self.queue[key]['status'] = 'stashed' else: self.queue[key]['status'] = 'queued' self.queue[key]['start'] = '' self.queue[key]['end'] = '' self.queue.write() self.clean_descriptor(key) del s...
def check_for_new(self): """Check if we can start a new process.""" free_slots = self.max_processes - len(self.processes) for item in range(free_slots): key = self.queue.next() if key is not None: self.spawn_new(key)
def spawn_new(self, key): """Spawn a new task and save it to the queue.""" # Check if path exists if not os.path.exists(self.queue[key]['path']): self.queue[key]['status'] = 'failed' error_msg = "The directory for this command doesn't exist anymore: {}".format(self.queue[key]['path']) self.logger.error(error_msg) self....
'-c', self.queue[key]['command'], ], stdout=stdout, stderr=stderr, stdin=subprocess.PIPE, universal_newlines=True, preexec_fn=os.setsid, cwd=self.queue[key]['path'] ) else: # Create subprocess self.processes[key] = subprocess.Popen( self.queue[key]['command'], shell=True, stdout=stdout, stderr=stderr, stdin=subprocess....
def kill_all(self, kill_signal, kill_shell=False): """Kill all running processes.""" for key in self.processes.keys(): self.kill_process(key, kill_signal, kill_shell)
def start_process(self, key): """Start a specific processes.""" if key in self.processes and key in self.paused: os.killpg(os.getpgid(self.processes[key].pid), signal.SIGCONT) self.queue[key]['status'] = 'running' self.paused.remove(key) return True elif key not in self.processes: if self.queue[key]['status'] in ['queu...
def pause_process(self, key): """Pause a specific processes.""" if key in self.processes and key not in self.paused: os.killpg(os.getpgid(self.processes[key].pid), signal.SIGSTOP) self.queue[key]['status'] = 'paused' self.paused.append(key) return True return False
def daemon_factory(path): """Create a closure which creates a running daemon. We need to create a closure that contains the correct path the daemon should be started with. This is needed as the `Daemonize` library requires a callable function for daemonization and doesn't accept any arguments. This function cleans up s...
path config_dir = os.path.join(root_dir, '.config/pueue') try: daemon = Daemon(root_dir=root_dir) daemon.main() except KeyboardInterrupt: print('Keyboard interrupt. Shutting down') daemon.stop_daemon() except Exception: try: daemon.stop_daemon() except Exception: pass cleanup(config_dir) raise return start_daemon
def main(): """Execute entry function.""" args = parser.parse_args() args_dict = vars(args) root_dir = args_dict['root'] if 'root' in args else None # If a root directory is specified, get the absolute path and # check if it exists. Abort if it doesn't exist! if root_dir: root_dir = os.path.abspath(root_dir) if not os....
is specified else: root_dir = os.path.expanduser('~') if args.stopdaemon: print_command_factory('STOPDAEMON')(vars(args), root_dir) elif args.nodaemon: daemon_factory(root_dir)() elif args.daemon: config_dir = os.path.join(root_dir, '.config/pueue') os.makedirs(config_dir, exist_ok=True) daemon = Daemonize(app='pueue',...
def register(host=DFLT_ADDRESS[0], port=DFLT_ADDRESS[1], signum=signal.SIGUSR1): """Register a pdb handler for signal 'signum'. The handler sets pdb to listen on the ('host', 'port') internet address and to start a remote debugging session on accepting a socket connection. """ _pdbhandler._register(host, port, signum)
def get_handler(): """Return the handler as a named tuple. The named tuple attributes are 'host', 'port', 'signum'. Return None when no handler has been registered. """ host, port, signum = _pdbhandler._registered() if signum: return Handler(host if host else DFLT_ADDRESS[0].encode(), port if port else DFLT_ADDRESS[1],...
def wait(self, timeout): '''Wait for the provided time to elapse''' logger.debug('Waiting for %fs', timeout) return self._event.wait(timeout)
def delay(self): '''How long to wait before the next check''' if self._last_checked: return self._interval - (time.time() - self._last_checked) return self._interval
def callback(self): '''Run the callback''' self._callback(*self._args, **self._kwargs) self._last_checked = time.time()
def run(self): '''Run the callback periodically''' while not self.wait(self.delay()): try: logger.info('Invoking callback %s', self.callback) self.callback() except StandardError: logger.exception('Callback failed')
def login(self, email=None, password=None, app_id=None, api_key=None): """Login to MediaFire account. Keyword arguments: email -- account email password -- account password app_id -- application ID api_key -- API Key (optional) """ session_token = self.api.user_get_session_token( app_id=app_id, email=email, password=pa...
def get_resource_by_uri(self, uri): """Return resource described by MediaFire URI. uri -- MediaFire URI Examples: Folder (using folderkey): mf:r5g3p2z0sqs3j mf:r5g3p2z0sqs3j/folder/file.ext File (using quickkey): mf:xkr43dadqa3o2p2 Path: mf:///Documents/file.ext """ location = self._parse_uri(uri) if location.startswit...
by path result = self.get_resource_by_path( path, folder_key=parent_folder['folderkey']) else: # mf:abcdefjhijklm result = self.get_resource_by_key(location) return result
def get_resource_by_key(self, resource_key): """Return resource by quick_key/folder_key. key -- quick_key or folder_key """ # search for quick_key by default lookup_order = ["quick_key", "folder_key"] if len(resource_key) == FOLDER_KEY_LENGTH: lookup_order = ["folder_key", "quick_key"] resource = None for lookup_key in...
response code pass if resource: break if not resource: raise ResourceNotFoundError(resource_key) return resource
def get_resource_by_path(self, path, folder_key=None): """Return resource by remote path. path -- remote path Keyword arguments: folder_key -- what to use as the root folder (None for root) """ logger.debug("resolving %s", path) # remove empty path components path = posixpath.normpath(path) components = [t for t in pat...
for component in components: exists = False for item in self._folder_get_content_iter(folder_key): name = item['name'] if 'name' in item else item['filename'] if name == component: exists = True if components[-1] != component: # still have components to go through if 'filename' in item: # found a file, expected a direc...
resource is not None: break if not exists: # intermediate component does not exist - bailing out break if resource is None: raise ResourceNotFoundError(path) if "quickkey" in resource: file_info = self.api.file_get_info( resource['quickkey'])['file_info'] result = File(file_info) elif "folderkey" in resource: folder_in...
def _folder_get_content_iter(self, folder_key=None): """Iterator for api.folder_get_content""" lookup_params = [ {'content_type': 'folders', 'node': 'folders'}, {'content_type': 'files', 'node': 'files'} ] for param in lookup_params: more_chunks = True chunk = 0 while more_chunks: chunk += 1 content = self.api.folder_g...
def get_folder_contents_iter(self, uri): """Return iterator for directory contents. uri -- mediafire URI Example: for item in get_folder_contents_iter('mf:///Documents'): print(item) """ resource = self.get_resource_by_uri(uri) if not isinstance(resource, Folder): raise NotAFolderError(uri) folder_key = resource['folde...
def create_folder(self, uri, recursive=False): """Create folder. uri -- MediaFire URI Keyword arguments: recursive -- set to True to create intermediate folders. """ logger.info("Creating %s", uri) # check that folder exists already try: resource = self.get_resource_by_uri(uri) if isinstance(resource, Folder): return r...
Folder): raise NotAFolderError(parent_uri) parent_key = parent_node['folderkey'] except ResourceNotFoundError: if recursive: result = self.create_folder(parent_uri, recursive=True) parent_key = result['folderkey'] else: raise # We specify exact location, so don't allow duplicates result = self.api.folder_create( folder...
def delete_folder(self, uri, purge=False): """Delete folder. uri -- MediaFire folder URI Keyword arguments: purge -- delete the folder without sending it to Trash """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: # Nothing to remove return None if not isinstance(resource, Folder): raise Va...
== 100: logger.debug( "Delete folder returns error 900 but folder is deleted: " "http://forum.mediafiredev.com/showthread.php?129") result = {} else: raise return result
def delete_file(self, uri, purge=False): """Delete file. uri -- MediaFire file URI Keyword arguments: purge -- delete the file without sending it to Trash. """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: # Nothing to remove return None if not isinstance(resource, File): raise ValueError(...
def delete_resource(self, uri, purge=False): """Delete file or folder uri -- mediafire URI Keyword arguments: purge -- delete the resource without sending it to Trash. """ try: resource = self.get_resource_by_uri(uri) except ResourceNotFoundError: # Nothing to remove return None if isinstance(resource, File): result = ...
def _prepare_upload_info(self, source, dest_uri): """Prepare Upload object, resolve paths""" try: dest_resource = self.get_resource_by_uri(dest_uri) except ResourceNotFoundError: dest_resource = None is_fh = hasattr(source, 'read') folder_key = None name = None if dest_resource: if isinstance(dest_resource, File): fold...
raise ValueError("Target is a folder (file expected)") folder_key = result.get('parent_folderkey', None) name = result['filename'] except ResourceNotFoundError: # ok, neither a file nor folder, proceed folder_key = dest_resource['folderkey'] name = basename else: raise Exception("Unknown resource type") else: # get par...
folder_key, name
def upload_file(self, source, dest_uri): """Upload file to MediaFire. source -- path to the file or a file-like object (e.g. io.BytesIO) dest_uri -- MediaFire Resource URI """ folder_key, name = self._prepare_upload_info(source, dest_uri) is_fh = hasattr(source, 'read') fd = None try: if is_fh: # Re-using filehandle fd...
Close filehandle if we opened it if fd and not is_fh: fd.close()