INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Establish a connection
def connect(self, force=False): '''Establish a connection''' # Don't re-establish existing connections if not force and self.alive(): return True self._reset() # Otherwise, try to connect with self._socket_lock: try: logger.info('...
Close our connection
def close(self): '''Close our connection''' # Flush any unsent message try: while self.pending(): self.flush() except socket.error: pass with self._socket_lock: try: if self._socket: self._soc...
Blockingly yield the socket
def socket(self, blocking=True): '''Blockingly yield the socket''' # If the socket is available, then yield it. Otherwise, yield nothing if self._socket_lock.acquire(blocking): try: yield self._socket finally: self._socket_lock.release()
Handle a response to our identify command. Returns response
def identified(self, res): '''Handle a response to our 'identify' command. Returns response''' # If they support it, they should give us a JSON blob which we should # inspect. try: res.data = json.loads(res.data) self._identify_response = res.data logg...
Set whether or not this message is blocking
def setblocking(self, blocking): '''Set whether or not this message is blocking''' for sock in self.socket(): sock.setblocking(blocking) self._blocking = blocking
Flush some of the waiting messages returns count written
def flush(self): '''Flush some of the waiting messages, returns count written''' # When profiling, we found that while there was some efficiency to be # gained elsewhere, the big performance hit is sending lots of small # messages at a time. In particular, consumers send many 'FIN' messa...
Send a command over the socket with length endcoded
def send(self, command, message=None): '''Send a command over the socket with length endcoded''' if message: joined = command + constants.NL + util.pack(message) else: joined = command + constants.NL if self._blocking: for sock in self.socket(): ...
Send an identification message
def identify(self, data): '''Send an identification message''' return self.send(constants.IDENTIFY, json.dumps(data))
Subscribe to a topic/ channel
def sub(self, topic, channel): '''Subscribe to a topic/channel''' return self.send(' '.join((constants.SUB, topic, channel)))
Publish to a topic
def pub(self, topic, message): '''Publish to a topic''' return self.send(' '.join((constants.PUB, topic)), message)
Publish multiple messages to a topic
def mpub(self, topic, *messages): '''Publish multiple messages to a topic''' return self.send(constants.MPUB + ' ' + topic, messages)
Indicate that you re ready to receive
def rdy(self, count): '''Indicate that you're ready to receive''' self.ready = count self.last_ready_sent = count return self.send(constants.RDY + ' ' + str(count))
Re - queue a message
def req(self, message_id, timeout): '''Re-queue a message''' return self.send(constants.REQ + ' ' + message_id + ' ' + str(timeout))
Return all the responses read
def _read(self, limit=1000): '''Return all the responses read''' # It's important to know that it may return no responses or multiple # responses. It depends on how the buffering works out. First, read from # the socket for sock in self.socket(): if sock is None: ...
Responses from an established socket
def read(self): '''Responses from an established socket''' responses = self._read() # Determine the number of messages in here and decrement our ready # count appropriately self.ready -= sum( map(int, (r.frame_type == Message.FRAME_TYPE for r in responses))) r...
Run the discovery mechanism
def discover(self, topic): '''Run the discovery mechanism''' logger.info('Discovering on topic %s', topic) producers = [] for lookupd in self._lookupd: logger.info('Discovering on %s', lookupd) try: # Find all the current producers on this instance...
Connect to all the appropriate instances
def check_connections(self): '''Connect to all the appropriate instances''' logger.info('Checking connections') if self._lookupd: self.discover(self._topic) # Make sure we're connected to all the prescribed hosts for hostspec in self._nsqd_tcp_addresses: ...
Run periodic reconnection checks
def connection_checker(self): '''Run periodic reconnection checks''' thread = ConnectionChecker(self) logger.info('Starting connection-checker thread') thread.start() try: yield thread finally: logger.info('Stopping connection-checker') ...
Connect to the provided host port
def connect(self, host, port): '''Connect to the provided host, port''' conn = connection.Connection(host, port, reconnection_backoff=self._reconnection_backoff, auth_secret=self._auth_secret, timeout=self._connect_timeout, **self._identify_options) ...
Add a connection
def add(self, connection): '''Add a connection''' key = (connection.host, connection.port) with self._lock: if key not in self._connections: self._connections[key] = connection self.added(connection) return connection else: ...
Remove a connection
def remove(self, connection): '''Remove a connection''' key = (connection.host, connection.port) with self._lock: found = self._connections.pop(key, None) try: self.close_connection(found) except Exception as exc: logger.warn('Failed to close %...
Read from any of the connections that need it
def read(self): '''Read from any of the connections that need it''' # We'll check all living connections connections = [c for c in self.connections() if c.alive()] if not connections: # If there are no connections, obviously we return no messages, but # we should...
Pick a random living connection
def random_connection(self): '''Pick a random living connection''' # While at the moment there's no need for this to be a context manager # per se, I would like to use that interface since I anticipate # adding some wrapping around it at some point. yield random.choice( ...
Wait for a response
def wait_response(self): '''Wait for a response''' responses = self.read() while not responses: responses = self.read() return responses
Publish the provided message to the provided topic
def pub(self, topic, message): '''Publish the provided message to the provided topic''' with self.random_connection() as client: client.pub(topic, message) return self.wait_response()
Publish messages to a topic
def mpub(self, topic, *messages): '''Publish messages to a topic''' with self.random_connection() as client: client.mpub(topic, *messages) return self.wait_response()
Create a socket for the daemon depending on the directory location.
def create_socket(self): """Create a socket for the daemon, depending on the directory location. Args: config_dir (str): The absolute path to the config directory used by the daemon. Returns: socket.socket: The daemon socket. Clients connect to this socket. """...
Create all directories needed for logs and configs.
def initialize_directories(self, root_dir): """Create all directories needed for logs and configs.""" if not root_dir: root_dir = os.path.expanduser('~') # Create config directory, if it doesn't exist self.config_dir = os.path.join(root_dir, '.config/pueue') if not o...
Send an answer to the client.
def respond_client(self, answer, socket): """Send an answer to the client.""" response = pickle.dumps(answer, -1) socket.sendall(response) self.read_list.remove(socket) socket.close()
Read a previous configuration file or create a new with default values.
def read_config(self): """Read a previous configuration file or create a new with default values.""" config_file = os.path.join(self.config_dir, 'pueue.ini') self.config = configparser.ConfigParser() # Try to get configuration file and return it # If this doesn't work, a new defa...
Write the current configuration to the config file.
def write_config(self): """Write the current configuration to the config file.""" config_file = os.path.join(self.config_dir, 'pueue.ini') with open(config_file, 'w') as file_descriptor: self.config.write(file_descriptor)
The main function containing the loop for communication and process management.
def main(self): """The main function containing the loop for communication and process management. This function is the heart of the daemon. It is responsible for: - Client communication - Executing commands from clients - Update the status of processes by polling the Pr...
Kill current processes and initiate daemon shutdown.
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 ...
Update the current config depending on the payload and save it.
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'] ...
Send something to stdin of a specific process.
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'} ...
Send the daemon status and the current queue for displaying.
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...
Kill all processes delete the queue and clean everything up.
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 c...
Clear queue from any done or failed entries.
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) ...
Start the daemon and all processes or only specific processes.
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'): succ...
Start the daemon and all processes or only specific processes.
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'): succ...
Edit the command of a specific entry.
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 answe...
Stash the specified processes.
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' ...
Pause the daemon and kill all processes or kill a specific process.
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'): ...
Remove specified entries from the queue.
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 remo...
Switch the two specified entry positions in the queue.
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 = { ...
Restart the specified entries.
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...
Same as socket. sendall
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
List directory
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 i...
Upload files
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 ...
Download file
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): ...
Output file contents to stdout
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
Create directory
def do_folder_create(client, args): """Create directory""" for folder_uri in args.uris: client.create_folder(folder_uri, recursive=True) return True
Remove resource
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
Update file metadata
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
Update file metadata
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, ...
Main entry point
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 de...
Publish a message to a topic
def pub(self, topic, message): '''Publish a message to a topic''' return self.post('pub', params={'topic': topic}, data=message)
Send multiple messages to a topic. Optionally pack the messages
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'...
Stats with topics and channels keyed on topic and channel names
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 top...
Add a new command to the daemon queue.
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 s...
Edit a existing queue command in the daemon.
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')...
A factory which returns functions for direct daemon communication.
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 ...
Create file descriptors for process output.
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): ...
Close file descriptor and remove underlying files.
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]['...
Poll all processes and handle any finished processes.
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 ...
Check if we can start a new process.
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)
Spawn a new task and save it to the queue.
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[...
Kill all running processes.
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)
Start a specific processes.
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 ...
Pause a specific processes.
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 ...
Create a closure which creates a running daemon.
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...
Execute entry function.
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 =...
Register a pdb handler for signal signum.
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. """ _pdbhand...
Return the handler as a named tuple.
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(), ...
Wait for the provided time to elapse
def wait(self, timeout): '''Wait for the provided time to elapse''' logger.debug('Waiting for %fs', timeout) return self._event.wait(timeout)
How long to wait before the next check
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
Run the callback
def callback(self): '''Run the callback''' self._callback(*self._args, **self._kwargs) self._last_checked = time.time()
Run the callback periodically
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')
Login to MediaFire account.
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.ap...
Return resource described by MediaFire URI.
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 ...
Return resource by quick_key/ folder_key.
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 ...
Return resource by remote path.
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 ...
Iterator for api. folder_get_content
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 = Tr...
Return iterator for directory contents.
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 isins...
Create folder.
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: res...
Delete 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: ...
Delete file.
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: # ...
Delete file or folder
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: ...
Prepare Upload object resolve paths
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 ...
Upload file to MediaFire.
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'...
Download file from MediaFire.
def download_file(self, src_uri, target): """Download file from MediaFire. src_uri -- MediaFire file URI to download target -- download path or file-like object in write mode """ resource = self.get_resource_by_uri(src_uri) if not isinstance(resource, File): ...
Update file metadata.
def update_file_metadata(self, uri, filename=None, description=None, mtime=None, privacy=None): """Update file metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change the metadata on the server side: filename -- r...
Update folder metadata.
def update_folder_metadata(self, uri, foldername=None, description=None, mtime=None, privacy=None, privacy_recursive=None): """Update folder metadata. uri -- MediaFire file URI Supplying the following keyword arguments would change ...
Parse and validate MediaFire URI.
def _parse_uri(uri): """Parse and validate MediaFire URI.""" tokens = urlparse(uri) if tokens.netloc != '': logger.error("Invalid URI: %s", uri) raise ValueError("MediaFire URI format error: " "host should be empty - mf:///path") if...
The clean stats from all the hosts reporting to this host.
def merged(self): '''The clean stats from all the hosts reporting to this host.''' stats = {} for topic in self.client.topics()['topics']: for producer in self.client.lookup(topic)['producers']: hostname = producer['broadcast_address'] port = producer[...
All the raw unaggregated stats ( with duplicates ).
def raw(self): '''All the raw, unaggregated stats (with duplicates).''' topic_keys = ( 'message_count', 'depth', 'backend_depth', 'paused' ) channel_keys = ( 'in_flight_count', 'timeout_count', 'paused',...
Stats that have been aggregated appropriately.
def stats(self): '''Stats that have been aggregated appropriately.''' data = Counter() for name, value, aggregated in self.raw: if aggregated: data['%s.max' % name] = max(data['%s.max' % name], value) data['%s.total' % name] += value else: ...
Return the current python source line.
def get_curline(): """Return the current python source line.""" if Frame: frame = Frame.get_selected_python_frame() if frame: line = '' f = frame.get_pyop() if f and not f.is_optimized_out(): cwd = os.path.join(os.getcwd(), '') ...
Subscribe connection and manipulate its RDY state
def reconnected(self, conn): '''Subscribe connection and manipulate its RDY state''' conn.sub(self._topic, self._channel) conn.rdy(1)
Distribute the ready state across all of the connections
def distribute_ready(self): '''Distribute the ready state across all of the connections''' connections = [c for c in self.connections() if c.alive()] if len(connections) > self._max_in_flight: raise NotImplementedError( 'Max in flight must be greater than number of co...