def start_srv(**_): ''' Server that listens to unix socket and handles encoded client requests Spawns threads of separate client communications Args: all are ignored ''' server = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM) wob = open_pipe() logger = EventLogger(wob=wob) try: server.bind(str(defined.SOCK_PATH)) except OSError: if manage_socket(): return server.bind(str(defined.SOCK_PATH)) print(f'{defined.SOCK_PATH}', pref='listen', pref_color='lg') try: server.listen() while not server._closed: # type: ignore pipe, _ = server.accept() thread = threading.Thread(target=handle_cmd, args=(pipe, logger)) thread.start() except KeyboardInterrupt: pass logger.wob.kill() os.remove(defined.SOCK_PATH) sys.exit(0)
def manage_socket(): ''' If socket file exists, check if ppsid server is running If not running, rename socket as .last_session (overwriting target) Returns: ``True`` if socket can be made available; ``False`` If Server is running ''' # check if ppsid another is running count_daemons = 0 for proc in psutil.process_iter(): try: # Check if process name contains the given name string. if 'ppsid' in proc.name().lower(): count_daemons += 1 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass if count_daemons > 1: # discounting THIS daemon print("Server is already running", mark='err') return True os.rename(defined.SOCK_PATH, defined.SOCK_PATH + ".last_session") return False
def client_call() -> None: ''' Parse command-line and communicate encoded request to unix socket Send coded request bytes with kwargs as subcommand bits to server socket if client was called without arguments, show short usage message pointing to -h argument ''' req, kwargs = cli() if req is None: print('usage: ppsi -h') return commands: typing.List[bytes] = [] inst, serial_bytes, serial_len = req2bytes(req, **kwargs) if inst is None: # bad instruction return if serial_bytes is not None: # pass serialized json object commands.append(defined.COMM['ACCEPT']) commands.append(serial_len) # type: ignore commands.append(serial_bytes) commands.append(inst) commands.insert(0, defined.COMM['OK']) # send command response: bytes = defined.COMM['OK'] try: client = socket.socket(family=socket.AF_UNIX, type=socket.SOCK_STREAM) client.connect(str(defined.SOCK_PATH)) for cmd in commands: if not (response and response == defined.COMM['OK']): print( f'SERVER replied {int.from_bytes(response, "big"):0{2}x}', mark='warn') break client.send(cmd) response = client.recv(defined.INST_SIZE) client.send(defined.COMM['BYE']) except (FileNotFoundError, ConnectionRefusedError): # scoket file not found print('Confirm that the server is running correctly', mark='err') return except BrokenPipeError: if response == defined.COMM['BYE']: print("Server Adios", mark='info') return print('Server Closed unexpectedly')
def main(): """ Main routine call """ config = configure() # correct licenses config.license_header = edit_modify(config.license_header, config) if config.project is None: raise NoProjectNameError tree_copy(config, INFO_BASE.templates, config.project, skip_deep=False) mod_exec(config) init_venv(config) init_git_repo(config) print(config, mark="info")
def send_reset_email(user: User): ''' send email to user ''' token = user.get_reset_token() msg = Message('Password Reset Request', sender='*****@*****.**', recipients=[user.email]) msg.body = f''' To reset your password, visit within next 30 minutes: the link: {url_for('users.reset_token', token=token, _external=True)} If you did not make this request, ignore this email. ''' try: # mail.send(msg) raise (ModuleNotFoundError) except (ModuleNotFoundError): print("Mail couldn't be sent, \ supplying the necessary information on terminal", pref='err') print(msg, pref='bug')
def handle_cmd(pipe: socket.socket, logger: EventLogger) -> None: ''' Args: pipe: socket = socket through which client communications arrive logger: EventLogger = container object holding logger objects Returns: None Talks to each client (called by threading module) ''' connected = True kwargs = {} while connected: in_bytes = pipe.recv(defined.INST_SIZE) if not in_bytes: pass comm = int.from_bytes(in_bytes, 'big') if comm < 0x10: # socket communication if in_bytes == defined.COMM['ACCEPT']: kwargs.update(read_json_bytes(pipe)) elif in_bytes == defined.COMM['BYE']: connected = False elif in_bytes == defined.COMM['EXIT']: print('Terminate Server Manually', mark='act') pipe.send(defined.COMM['BYE']) connected = False elif in_bytes == defined.COMM['FAULT']: print("Client sent fault, it shouldn't", mark='warn') pipe.send(defined.COMM['FAULT']) elif in_bytes == defined.COMM['OK']: pipe.send(defined.COMM['OK']) else: print("Bad communication code. This reflects a fault", mark='warn') pipe.send(defined.COMM['FAULT']) else: # ppsi command err = cmd_wrap(comm=comm, **kwargs) logger.event_registry(comm=comm) if err: pipe.send(defined.COMM['FAULT']) else: pipe.send(defined.COMM['OK']) pipe.close()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- print() print("*** WITHOUT PSPRINT ***") print("An output statement which informs the user") print("This statement requests the user to act") print("A debugging output useless to the user") print() from psprint import print print() print("*** WITH PSPRINT ***") print("An output statement which informs the user", mark=1) print("This statement requests the user to act", mark=2) print("A debugging output useless to the user", mark='bug') print()