def main(argv): for mibname in argv[1:]: load(mibname) traps.start_straps() scheduler.sleep(2) trapreceiver = traps.TrapDispatcher(_handler) asyncio.register(trapreceiver)
def _control(self, val): try: self.sPDUOutletControlMSPOutletCommand = val except: pass # agent does not respond to this scheduler.sleep(5) self.refresh()
def start_proc_manager(config, logfile): from pycopia import proctools from pycopia import scheduler from pycopia import asyncio asyncio.start_sigio() pm = proctools.get_procmanager() for name, serverlist in config.VHOSTS.items(): for servername in serverlist: print "Starting %s for %s." % (servername, name) p = pm.spawnpipe("%s/fcgi_server -n %s" % (config.LIBEXEC, servername), persistent=True, logfile=logfile) asyncio.poller.register(p) scheduler.sleep(1.0) # give it time to init... if config.USEFRONTEND: lighttpd = proctools.which("lighttpd") pm.spawnpipe("%s -D -f %s" % (lighttpd, LTCONFIG), persistent=True, logfile=logfile) try: while 1: asyncio.poller.loop() for proc in pm.getprocs(): if proc.readable(): print proc.read(4096) except KeyboardInterrupt: asyncio.poller.unregister_all() for proc in pm.getprocs(): proc.kill() proc.wait() if os.path.exists(config.PIDFILE): os.unlink(config.PIDFILE)
def accept(self, timeout=60): tries = timeout / 6 count = 0 self.socket.setblocking(0) while 1: try: conn, self.otheraddr = self.socket.accept() except socket.error as why: if why.errno == EINTR: continue if why.errno == EAGAIN: if timeout > 0 and count > tries: self.socket.setblocking(1) raise TimeoutError("did not accept() in time.") count += 1 scheduler.sleep(6) continue else: raise else: break self.socket.setblocking(1) conn.setblocking(1) self.file = conn.makefile() self.conn = conn return self.file
def _control(self, val): try: self.outletControlAction = val except: pass # agent does not respond to this scheduler.sleep(5) self.refresh()
def __init__(self, port=9025, logfile=None, parser=None): self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.file = None self.conn = None self.envelopes = [] self.hostname = socket.gethostname() self._client = None self._callback = None self._reset() while 1: try: self.socket.bind(("", self.port)) break except socket.error as msg: print("couldn't bind port", self.port, " - ", msg, "retrying...", file=sys.stderr) scheduler.sleep(5) self.socket.listen(50) self.conversation = None self.logfile = logfile self.parser = parser
def _symbols(self, c, fsm): d = self._device val = self._symbolmapping[c] code = val & 0x1ff shifted = val & SHIFT alt = val & ALT meta = val & META compose = val & COMPOSE if compose: d.write(EV_KEY, KEY_COMPOSE, 1) if shifted: d.write(EV_KEY, KEY_LEFTSHIFT, 1) if alt: d.write(EV_KEY, KEY_LEFTALT, 1) if meta: d.write(EV_KEY, KEY_LEFTMETA, 1) self._presskey(code) if meta: d.write(EV_KEY, KEY_LEFTMETA, 0) if alt: d.write(EV_KEY, KEY_LEFTALT, 0) if shifted: d.write(EV_KEY, KEY_LEFTSHIFT, 0) if compose: d.write(EV_KEY, KEY_COMPOSE, 0) scheduler.sleep(0.1)
def ping(host, retries=3, timeout=5, delay=1, size=64, hops=30): """Perform a typical "ping" to a destinatino host. Prints time statistics until interrupted. """ pinger = get_pinger(retries, timeout, delay, size, hops) sum = 0 Nxmit = 0 Nrecv = 0 _min = sys.maxint _max = 0 print "Pinging %s with %d bytes of data." % (host, size) try: while 1: # escape with SIGINT (^C) Nxmit = Nxmit + 1 host, rttime = pinger.ping(host)[0] if rttime >= 0: sum += rttime Nrecv = Nrecv + 1 _min = min(_min, rttime) _max = max(_max, rttime) print "%-16s %d ms" % (host, rttime) scheduler.sleep(pinger.delay) except KeyboardInterrupt: print "%d packets transmitted, %d packets received, %d%% packet loss" % (Nxmit, Nrecv, 100-(Nxmit/Nrecv*100)) print "round-trip min/avg/max = %d/%d/%d ms" % (_min, sum/Nrecv, _max)
def accept(self, timeout=60): tries = timeout/6 count = 0 self.socket.setblocking(0) while 1: try: conn, self.otheraddr = self.socket.accept() except socket.error as why: if why.errno == EINTR: continue if why.errno == EAGAIN: if timeout > 0 and count > tries: self.socket.setblocking(1) raise TimeoutError("did not accept() in time.") count += 1 scheduler.sleep(6) continue else: raise else: break self.socket.setblocking(1) conn.setblocking(1) self.file = conn.makefile() self.conn = conn return self.file
def start_slogsink(port=514): from pycopia import scheduler if port != 514: cmd = "daemonize slogsink %d" % port else: cmd = "daemonize slogsink" rv = os.system(cmd) scheduler.sleep(2) return rv
def SendMail(body, from_, subject, To=DEFAULTACCOUNT, headers=None, retries=3): while retries > 0: try: return ezmail.ezmail(body, To=To, From=from_, subject=subject, extra_headers=headers) except ezmail.MailError: # server might be busy scheduler.sleep(1) retries -= 1
def run_modules(self, modlist): """run_modules(modlist) Runs the run_module() function on the supplied list of modules (or module names). """ for mod in modlist: self.run_module(mod) # give things time to "settle" from previous suite. Some spawned # processes may delay exiting and hold open TCP ports, etc. scheduler.sleep(2)
def _persistent_callback(self, deadproc): if not deadproc.exitstatus: # abnormal exit deadproc.log("*** process '%s' died: %s (restarting).\n" % (deadproc.cmdline, deadproc.exitstatus)) scheduler.sleep(1.0) new = self.clone(deadproc) new.logfile = deadproc.logfile if new._async: self.poller.register(new) else: deadproc.log("*** process '%s' normal exit (NOT restarting).\n" % (deadproc.cmdline,))
def get_dispatcher(*handlers): """Return a TrapDispatcher instance ready to respond to traps. """ from pycopia import scheduler from pycopia import asyncio start_straps() scheduler.sleep(2) dispatcher = TrapDispatcher(list(handlers)) asyncio.register(dispatcher) return dispatcher
def _specials(self, c, fsm): if c == "t": self._device.write(EV_KEY, KEY_TAB, 0) elif c == "n": self._device.write(EV_KEY, KEY_ENTER, 0) elif c == "r": self._device.write(EV_KEY, KEY_KPENTER, 0) elif c == "b": self._device.write(EV_KEY, KEY_BACKSPACE, 0) elif c == "e": self._device.write(EV_KEY, KEY_ESC, 0) scheduler.sleep(0.1)
def _connect(self, addr, retries): retry = 0 while retry < retries: try: self.sock.connect(addr) except socket.error as msg: if msg[0] == ECONNREFUSED: # might be busy scheduler.sleep(2) continue else: raise else: return retry += 1
def _SoonerUpdate(self, zfile, wipe, flash): if self.GetState() != BOOTLOADER: self.Reboot(bootloader=True) retries = 3 while retries: scheduler.sleep(2) try: self.WaitForBootloader() except AdbError: # may or may not get this error first time. retries -= 1 else: break else: raise AdbError("Did not detect bootloader after reboot.") else: self.WaitForBootloader() # make sure we are truly in bootloader if self.GetState() != BOOTLOADER: raise AdbError("Did not enter bootloader from update.") try: for dname, fname in (("recovery", "recovery.img"), ("boot", "boot.img"), ("systemfs", "system.img")): data = zfile.read(fname) self.UploadData(dname, data) scheduler.sleep(2) if flash: data = zfile.read("userdata.img") self.UploadData("userdata", data) scheduler.sleep(2) elif wipe: self.UploadData("eraseuserdata", " ") scheduler.sleep(2) finally: zfile.close() self.Reboot() retries = 5 while retries: scheduler.sleep(10) try: self.WaitForDevice() except AdbError: # may or may not get this error first time. retries -= 1 else: self.GetState() break else: raise AdbError("Did not detect device after update.")
def clear(self): if self._eqcache: eqc = self._eqcache self._eqcache = {} while eqc: name, obj = eqc.popitem() try: obj.clear() except: logging.exception_error("environment clear: {!r}".format(obj)) gc.collect() for obj in gc.garbage: try: obj.close() except: logging.exception_warning("environment garbage collect: {!r}".format(obj)) del gc.garbage[:] scheduler.sleep(2) # some devices need time to fully clear or disconnect
def go(self, callback=None): """Start the reboot detection. If a callback is provided it is called after device is gone through its unreachable phase and is now reachable again. Returns a boolean value indication success. May raise RebootDetectorError if something is not right with the reboot process. """ isreachable = False pinger = self._pinger state = RebootDetector.UNKNOWN while True: if state == RebootDetector.UNKNOWN: host, isreachable = pinger.reachable(self._target)[0] if isreachable: state = RebootDetector.REACHABLE if callback is not None: callback() else: raise RebootDetectorError("Could not reach host initially.") elif state == RebootDetector.REACHABLE: r_retries = pinger.retries while isreachable: host, isreachable = pinger.reachable(self._target)[0] scheduler.sleep(pinger.delay) r_retries -= 1 if r_retries == 0: raise RebootDetectorError("Target did not become unreachable.") else: state = RebootDetector.NOTREACHABLE elif state == RebootDetector.NOTREACHABLE: r_retries = pinger.retries while not isreachable: host, isreachable = pinger.reachable(self._target)[0] scheduler.sleep(pinger.delay) r_retries -= 1 if r_retries == 0: raise RebootDetectorError("Target did not become reachable again.") else: state = RebootDetector.REACHABLE2 break return state == RebootDetector.REACHABLE2
def clear(self): if self._eqcache: eqc = self._eqcache self._eqcache = {} while eqc: name, obj = eqc.popitem() try: obj.clear() except: logging.exception_error( "environment clear: {!r}".format(obj)) gc.collect() for obj in gc.garbage: try: obj.close() except: logging.exception_warning( "environment garbage collect: {!r}".format(obj)) del gc.garbage[:] scheduler.sleep( 2) # some devices need time to fully clear or disconnect
def __init__ (self, port=9025, logfile=None, parser=None): self.port = port self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.file = None self.conn = None self.envelopes = [] self.hostname = socket.gethostname() self._client = None self._callback = None self._reset() while 1: try: self.socket.bind(("", self.port)) break except socket.error as msg: print ("couldn't bind port",self.port," - ",msg,"retrying...", file=sys.stderr) scheduler.sleep(5) self.socket.listen(50) self.conversation = None self.logfile = logfile self.parser = parser
def __do_command(self, cmdstr, hosts): for host in hosts: if isinstance(host, list): s = [] for hle in host: s.append(str(hle)) cmdstr += " ".join(s) else: cmdstr += " %s" % host rqst = "-size %d -timeout %d -retries %d -delay %d %s\n" % \ (self.size, self.timeout, self.retries, self.delay, cmdstr) self._write(rqst) # now try and get all of pyntping's output resstr = self._read(4096) scheduler.sleep(1) while self.fstat().st_size != 0: next = self._read(4096) if next: resstr += next scheduler.sleep(1) # we should have got a tuple of tuples result = eval(resstr) return result
def go(self, callback=None): isreachable = False pinger = self._pinger state = PoweroffDetector.UNKNOWN while True: if state == PoweroffDetector.UNKNOWN: host, isreachable = pinger.reachable(self._target)[0] if isreachable: state = PoweroffDetector.REACHABLE if callback is not None: callback() else: raise RebootDetectorError("Could not reach host initially.") elif state == PoweroffDetector.REACHABLE: r_retries = pinger.retries while isreachable: host, isreachable = pinger.reachable(self._target)[0] scheduler.sleep(pinger.delay) r_retries -= 1 if r_retries == 0: raise RebootDetectorError("Target did not become unreachable in time.") else: return True
def _stickies(self, c, fsm): if c == "S" and not self._shift: self._shift = 1 self._device.write(EV_KEY, KEY_LEFTSHIFT, 1) elif c == "s" and self._shift: self._shift = 0 self._device.write(EV_KEY, KEY_LEFTSHIFT, 0) elif c == "C" and not self._ctrl: self._ctrl = 1 self._device.write(EV_KEY, KEY_LEFTCTRL, 1) elif c == "c" and self._ctrl: self._shift = 0 self._device.write(EV_KEY, KEY_LEFTCTRL, 0) elif c == "A" and not self._alt: self._alt = 1 self._device.write(EV_KEY, KEY_LEFTALT, 1) elif c == "a" and self._alt: self._alt = 0 self._device.write(EV_KEY, KEY_LEFTALT, 0) elif c == "M" and not self._meta: self._meta = 1 self._device.write(EV_KEY, KEY_LEFTMETA, 1) elif c == "m" and self._meta: self._meta = 0 self._device.write(EV_KEY, KEY_LEFTMETA, 0) elif c == "O" and not self._compose: self._compose = 1 self._device.write(EV_KEY, KEY_COMPOSE, 1) elif c == "o" and self._compose: self._compose = 0 self._device.write(EV_KEY, KEY_COMPOSE, 0) scheduler.sleep(0.1)
def _keycode(self, c, fsm): val = _VALUEMAP[fsm.keyname] self._presskey(val) scheduler.sleep(0.1)
if __name__ == "__main__": from pycopia.OS import Input class MockDevice(object): def write(self, evtype, code, value): print "%s %s %s" % (evtype, code, value) def close(self): pass #fo = MockDevice() fo = Input.EventDevice("/dev/input/event1") g = KeyEventGenerator(fo) scheduler.sleep(2) g('sent = """') g(ascii.lowercase) g("\n") g(ascii.uppercase) g("\n") g(ascii.digits) g("\n") # You have to slash escape the "<" and \ itself. g( r"""!"#$&'()*+,-./:;\<=>?@[\\]^_`{|}~""" ) g("\n") g("ab\%c<TAB>%Sdef%s%Ci%cghi%%" ) g("\n") g('"""\n') fo.close() expected = (ascii.lowercase + "\n" + ascii.uppercase + "\n" + ascii.digits + "\n" +
def MeasureAllCurrentAsText(self): scheduler.sleep(0.1) return [ "3.22272E-3", "2.66413E-3", "1.64231E-2", "1.06339E-3", "1.64231E-2\n" ]
def MeasureAllCurrent(self): scheduler.sleep(0.1) return [3.22272, 2.66412, 16.4231, 1.06339, 16.4231]
def _upper(self, c, fsm): val = _LETTERS[c.lower()] self._device.write(EV_KEY, KEY_LEFTSHIFT, 1) self._presskey(val) self._device.write(EV_KEY, KEY_LEFTSHIFT, 0) scheduler.sleep(0.1)
def _digit(self, c, fsm): val = _DIGITS[c] self._presskey(val) scheduler.sleep(0.1)
def Run(self): self.Initiate() scheduler.sleep(self._delay) for n in range(self._number): self.Respond() scheduler.sleep(self._delay)
def _lower(self, c, fsm): val = _LETTERS[c] self._presskey(val) scheduler.sleep(0.1)
def _control(self, c, fsm): val = _LETTERS[chr(ord(c) | 0x60)] self._device.write(EV_KEY, KEY_LEFTCTRL, 1) self._presskey(val) self._device.write(EV_KEY, KEY_LEFTCTRL, 0) scheduler.sleep(0.1)
def _space(self, c, fsm): self._presskey(KEY_SPACE) scheduler.sleep(0.1)
def Sleep(self, Nsecs): """Sleep for N seconds. Sleep method simply sleeps for specified number of seconds. """ return scheduler.sleep(Nsecs)
def _backslash(self, c, fsm): self._presskey(KEY_BACKSLASH) scheduler.sleep(0.1)
def _co_function(): import sys from pycopia import scheduler sys.stdout.write("hello from co_function\n") scheduler.sleep(5) return None
def loop(self, timeout=-1.0, callback=NULL): while self._procs: poller.poll(timeout) callback(self) if scheduler.get_scheduler(): # wait for any restarts scheduler.sleep(1.5)
def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): ''' Receive a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'wb') >>> print modem.recv(stream) 2342 Returns the number of bytes received on success or ``None`` in case of failure. ''' # initiate protocol error_count = 0 char = 0 cancel = 0 while True: # first try CRC mode, if this fails, # fall back to checksum mode if error_count >= retry: self.abort(timeout=timeout) return None elif crc_mode and error_count < (retry / 2): if not self.putc(CRC): scheduler.sleep(delay) error_count += 1 else: crc_mode = 0 if not self.putc(NAK): scheduler.sleep(delay) error_count += 1 char = self.getc(1, timeout) if not char: error_count += 1 continue elif char == SOH: #crc_mode = 0 break elif char in [STX, CAN]: break elif char == CAN: if cancel: return None else: cancel = 1 else: error_count += 1 # read data error_count = 0 income_size = 0 packet_size = 128 sequence = 1 cancel = 0 while True: while True: if char == SOH: packet_size = 128 break elif char == STX: packet_size = 1024 break elif char == EOT: return income_size elif char == CAN: # cancel at two consecutive cancels if cancel: return None else: cancel = 1 else: if not quiet: print >> sys.stderr, \ 'recv ERROR expected SOH/EOT, got', ord(char) error_count += 1 if error_count >= retry: self.abort() return None # read sequence error_count = 0 cancel = 0 seq1 = ord(self.getc(1)) seq2 = 0xff - ord(self.getc(1)) if seq1 == sequence and seq2 == sequence: # sequence is ok, read packet # packet_size + checksum data = self.getc(packet_size + 1 + crc_mode) if crc_mode: csum = (ord(data[-2]) << 8) + ord(data[-1]) data = data[:-2] logging.debug('CRC (%04x <> %04x)' % (csum, self.calc_crc(data))) valid = csum == self.calc_crc(data) else: csum = data[-1] data = data[:-1] logging.debug('checksum (checksum(%02x <> %02x)' % (ord(csum), self.calc_checksum(data))) valid = ord(csum) == self.calc_checksum(data) # valid data, append chunk if valid: income_size += len(data) stream.write(data) self.putc(ACK) sequence = (sequence + 1) % 0x100 char = self.getc(1, timeout) continue else: # consume data self.getc(packet_size + 1 + crc_mode) self.debug('expecting sequence %d, got %d/%d' % \ (sequence, seq1, seq2)) # something went wrong, request retransmission self.putc(NAK)