async def _accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter): addr_repr = ':'.join(map(str, writer.get_extra_info('peername'))) logger.info('accepted connection from %s', addr_repr) try: writer.write(ControlServer.HANDSHAKE_MESSAGE) while True: # FIXME: maybe do not allow to execute arbitrary object action = cast(Callable[[ControlManager], Any], await ControlServer.receive_object(reader)) try: result = action(self._control) if asyncio.iscoroutine(result): result = await result except asyncio.CancelledError: raise except Exception as e: result = e ControlServer.send_object(result, writer) if isinstance(result, DaemonExit): logger.info('stop command received') if self._daemon_stop_handler is not None: self._daemon_stop_handler(self) return except asyncio.IncompleteReadError: pass except asyncio.CancelledError: raise except Exception as e: logger.warning('%s disconnected because of %r', addr_repr, e) finally: writer.close()
def onProfilesChanged(): app = runningApp() for wpName, wp in app.webProfiles.items(): log.warning(f'Reconfiguring webprofile: {wpName}') wp.configure()
async def ipfsConfig(binPath, param, value): ok, out, err = await shell("{0} config '{1}' '{2}'".format( binPath, param, value)) if err: log.warning(f'ipfsConfig({param}) with value {value}, error: {err}') return False else: log.debug(f'ipfsConfig({param}) with value {value}, OK') return True
def p2pEndpointAddrExplode(addr: str): """ Explode a P2P service endpoint address such as : /p2p/12D3KooWD3bfmNbuuuVCYwkjnFt3ukm3qaB3hDED3peHHXawvRAi/x/videocall/room1/1.0.0 /p2p/12D3KooWD3bfmNbuuuVCYwkjnFt3ukm3qaB3hDED3peHHXawvRAi/x/test into its components, returning a tuple in the form (peerId, protoFull, protoVersion) protoFull can be passed to 'ipfs p2p dial' Example: ('12D3KooWD3bfmNbuuuVCYwkjnFt3ukm3qaB3hDED3peHHXawvRAi', '/x/videocall/room1/1.0.0', '1.0.0') protoVersion is not mandatory """ parts = addr.lstrip(posixIpfsPath.sep).split(posixIpfsPath.sep) try: assert parts.pop(0) == 'p2p' peerId = parts.pop(0) prefix = parts.pop(0) assert peerIdRe.match(peerId) assert prefix == 'x' pVersion = None protoA = [prefix] protoPart = parts.pop(0) protoA.append(protoPart) while protoPart: try: protoPart = parts.pop(0) except IndexError: break protoA.append(protoPart) try: v = StrictVersion(protoPart) except Exception: pass else: # Found a version, should be last element pVersion = v assert len(parts) == 0 break protoFull = posixIpfsPath.sep + posixIpfsPath.join(*protoA) return peerId, protoFull, pVersion except Exception: log.warning(f'Invalid P2P endpoint address: {addr}') return None
async def ipfsConfigJson(binPath, param, value): ok, out, err = await shell("{0} config --json {1} {2}".format( binPath, param, json.dumps(value))) if err: log.warning( f'ipfsConfigJson({param}) with value {value}, error: {err}') return False else: log.debug(f'ipfsConfigJson({param}) with value {value}, OK') return True
async def shutdownScheduler(self): # It ain't that bad. STFS with dignity for stry in range(0, 12): try: async with async_timeout.timeout(2): await self.scheduler.close() except asyncio.TimeoutError: log.warning('Timeout shutting down the scheduler (not fooled)') continue else: log.debug(f'Scheduler went down (try: {stry})') return
def nsCacheLoad(self): try: assert len(self.cache) == 0 with open(str(self.nsCachePath), 'r') as fd: cache = json.load(fd) if not jsonSchemaValidate(cache, nsCacheSchema): raise Exception('Invalid NS cache schema') except Exception as err: log.debug(f'Error loading NS cache: {err}') else: log.warning(f'IPNS cache: loaded from {self.nsCachePath}') self.cache = cache
def mimeTypeProcess(mTypeText, buff, info=None): if mTypeText == 'text/xml': # If it's an XML, check if it's an Atom feed from the buffer # Can't call feedparser here cause we only got a partial buffer atomized = re.search('<feed xmlns="http://www.w3.org/[0-9]+/Atom".*>', buff.decode()) if atomized: return MIMEType('application/atom+xml') elif mTypeText == 'application/octet-stream': # Check for WASM magic number wasmMagic = binascii.unhexlify(b'0061736d') if buff[0:4] == wasmMagic: version = struct.unpack('<I', buff[4:8])[0] log.warning('Detected WASM binary, version {}'.format(version)) return mimeTypeWasm return MIMEType(mTypeText)
async def cancelAllTasks(*, timeout=None, raise_timeout_error=False): """ From sakaio.sakaio.cancel_all_tasks (version 3.0 not on pypi) https://github.com/nitely/sakaio """ from galacteek import log def _warn_pending(): running = _all_tasks(loop=loop) if running: log.debug( 'There are {tc} pending tasks, first 10: {first}', tc=len(running), first=list(running)[:10]) loop = asyncio.get_event_loop() running = _all_tasks(loop=loop) for t in running: t.cancel() for f in asyncio.as_completed(running, timeout=timeout, loop=loop): try: await f except asyncio.CancelledError: pass except asyncio.TimeoutError: _warn_pending() if raise_timeout_error: raise except Exception: log.warning('Task Error!', exc_info=True) pass # Tasks scheduled by clean-ups or # by tasks ignoring cancellation _warn_pending()
async def onJsonMessage(self, key, message): try: await self.processMessage(key, message) except Exception as err: log.warning(f'Unable to process pubsub message: {err}')