def main():
    '''Start the buildserver and keep track of it, i.e., restart if it fails'''
    global server, log
    signal.signal(signal.SIGTERM, sighandler)
    signal.signal(signal.SIGQUIT, sighandler)
    signal.signal(signal.SIGINT, sighandler)
    count = 0
    buildpwd = pwd.getpwnam('buildserver')
    os.setgid(buildpwd.pw_gid)
    os.setuid(buildpwd.pw_uid)
    os.chdir('/home/buildserver')
    log = logging.getLogger()
    log.addHandler(SysLogHandler('/dev/log'))
    log.handlers[0].setFormatter(logging.Formatter('BUILDSERVER: %(levelname)s: %(message)s'))
    log.info('Buildserver Monitor Starting')
    while True:
        ts = time.time()
        server = Popen(['./launch-buildserver',], close_fds=True)
        while not server.poll():     # While we are still running
            time.sleep(10)      # Sleep for ten seconds
        nts = time.time()
        code = server.wait()
        server = None
        log.warn('Build Server Terminated with code = %d' % code)
        if (nts - ts) < 60:     # It was running less then a minute?
            log.error('Build Server Terminated within 1 minute of start!')
            count += 1          # Bump count
            if count > 4:
                log.critical('Count of looping buildserver > 4, just hanging...')
                while True:
                    signal.pause()
Exemple #2
0
def main():

    # Default subnet is required for the host tracker to work.
    subnet_control = SubnetControl()
    subnet_control.list()
    subnet_control.add_subnet("defaultSubnet", "10.0.0.254/8")

    raw_input("[Press enter when mininet is ready] ")
    print("-------------------------")

    # Add per-protocol flows so we can monitor stats that way
    x = analytics.add_protocol_flows()
    if (not x):
        print "Unable to add per-protocol flows"

    m = WaypointMonitor(Stats.TYPE_SUBNET, subnet="10.0.0.1/32")
    m.set_waypoint("10.0.0.2")
    m.set_large_flow_threshold(2000) # 2000 bytes
    m.start()

    # Register signal-handler to catch SIG_INT
    signal.signal(signal.SIGINT, signal_handler)
    signal.pause()

    # join() won't return until SIG_INT has been captured
    m.join()
Exemple #3
0
def _run(name, **kwargs):
    if isinstance(kwargs.get('stdin'), bytes):
        if 'stdout' in kwargs or 'stderr' in kwargs:
            raise NotImplementedError(
                'cannot write bytes to stdin if stdout or stderr are specified'
            )
        stdin = kwargs['stdin']
        kwargs['stdin'] = _subprocess.PIPE
    else:
        stdin = None
    process = _subprocess.Popen(**kwargs)
    _LOG.debug('spawned {} process with PID {}'.format(name, process.pid))
    if stdin:
        try:
            # stdin is buffered in the kernel, so this won't block for
            # sufficiently small state
            process.stdin.write(stdin)
            process.stdin.flush()
            process.stdin.close()
        except BrokenPipeError:
            pass
    while process.pid not in _REAPED_CHILDREN:
        _signal.pause()
    status = _REAPED_CHILDREN[process.pid]
    _LOG.debug('{} process exited with {}'.format(name, status))
    return status
Exemple #4
0
def main():

	port = common.PORT
	username = input("Choose a username : "******"", flush=True)

	signal.signal(41, pause_handler)
	signal.signal(42, chat_handler)

	signal.pause()

	chat.chat(port, username)

	p.terminate()
Exemple #5
0
def main():
    god = God(paper=PAPER)
    
    god.setup()
    god.start()
    signal.pause()
    god.world()
def execute(args):
    global exit_sig_value
    if len(args) != 1:
        log("Requires a single file option in execute mode")
        sys.exit(255)
    lines = open(args[0], 'r').readlines()
    command = lines[0].strip()
    if command == "hang":
        for i in range(0, signal.NSIG):
            try:
                signal.signal(i, signal.SIG_IGN)
            except ValueError:
                pass
            except RuntimeError:
                pass
            except OSError:
                # In Python 3.3, signal.signal() raises OSError
                # instead of RuntimeError
                pass
        while True:
            signal.pause()
    elif command == "term":
        val = int(lines[1])
        exit_sig_value = val
        signal.signal(signal.SIGTERM, exit_sig)
        while True:
            signal.pause()
    elif command == "return":
        val = int(lines[1])
        sys.exit(val)
    elif command == "signal":
        val = int(lines[1])
        os.kill(os.getpid(), val)
    else:
        sys.exit(255)
Exemple #7
0
 def reap(self):
   """Collect the dead jobs."""
   while self._running:
     dead = set()
     for job in self._running:
       st = job.state(self._cache)
       if st == _RUNNING: continue
       if st == _FAILURE or st == _KILLED:
         self._failures += 1
         if self._stop_on_failure:
           self._cancelled = True
           for job in self._running:
             job.kill()
       dead.add(job)
       break
     for job in dead:
       self._completed += 1
       self._running.remove(job)
     if dead: return
     if (not self._travis):
       message('WAITING', '%d jobs running, %d complete, %d failed' % (
           len(self._running), self._completed, self._failures))
     if platform.system() == 'Windows':
       time.sleep(0.1)
     else:
       global have_alarm
       if not have_alarm:
         have_alarm = True
         signal.alarm(10)
       signal.pause()
    def handle_noargs(self, **options):
        verbose = int(options['verbosity'])
        send_all = True

        if verbose:
            print 'Starting sending newsletters...'

        activate(settings.LANGUAGE_CODE)

        senders = SMTPServer.objects.all()
        workers = []

        for sender in senders:
            worker = SMTPMailer(sender, verbose=verbose)
            thread = Thread(target=functools.partial(worker.run, send_all), name=sender.name)
            workers.append((worker, thread))

        handler = term_handler(workers)
        for s in [signal.SIGTERM, signal.SIGINT]:
            signal.signal(s, handler)

        # first close current connection
        signals.request_finished.send(sender=self.__class__)

        for worker, thread in workers:
            thread.start()

        signal.pause()  # wait for sigterm

        for worker, thread in workers:
            if thread.is_alive():
                thread.join()

        sys.exit(0)
def test_sigchld():
    r = reaper.Reaper()
    old_sigchld = signal.getsignal(signal.SIGCHLD)
    r.hookup_sigchld()
    assert r.old_sigchld is old_sigchld
    assert signal.getsignal(signal.SIGCHLD) == reaper.theReaper.handle_sigchld
    del r

    waiting = [DelayedExitFork(i, (i % 32) / 32) for i in range(256)]
    while waiting:
        signal.pause()
        i = 0
        while i < len(waiting):
            if waiting[i].obit is not None:
                f = waiting.pop(i)
                assert f.obit.pid == f.pid
                assert f.obit.exitstatus == f.expectedstatus
                assert f.obit.termsig is None
                assert f.obit.stopsig is None
                assert f.obit.coredump is False
            else:
                i += 1

    reaper.theReaper.unhookup_sigchld()
    assert signal.getsignal(signal.SIGCHLD) is old_sigchld

    reaper.theReaper = None
Exemple #10
0
def main():
    global sig_usr_1

    if len(sys.argv) <= 2:
        print_usage_and_die()
    report_file = sys.argv[1]
    if os.path.abspath(report_file) != report_file:
        print("report-file must be an absolute path. Got %r" % (report_file,), file=sys.stderr)
        sys.exit(1)
    if not os.path.exists(report_file):
        print("No such file %r" % (report_file,), file=sys.stderr)
        sys.exit(1)

    command = sys.argv[2:]
    assert command

    reporter = open(report_file, "w")

    def report_field(field, value):
        reporter.write("%s: %d\n" % (field, value))
        reporter.flush()

    report_field(CONTROLLER, os.getpid())
    r, w = os.pipe()
    child = os.fork()
    sys.stdout.flush()
    if not child:
        try:
            os.close(w)
            while True:
                time.sleep(0.01)
                data = os.read(r, 1)
                if not data:
                    continue
                progress = data == b"1"
                os.close(r)
                assert progress, data
                break
            reporter.close()
            os.execvp(command[0], command)
        except:
            traceback.print_exc()
            os._exit(COMMAND_FAILED_STATUS)
    report_field(CHILD, child)
    os.close(r)

    def awaken_child(signal, frame):
        global sig_user_1
        sig_user_1 = True
        os.write(w, b"1")
        os.close(w)

    signal.signal(signal.SIGUSR1, awaken_child)
    while not sig_user_1:
        signal.pause()
    _, exit_status = os.waitpid(child, 0)
    report_field(EXIT_STATUS, exit_status)
    reporter.close()
    # Long sleep to give time to snapshot the screen
    time.sleep(1)
    def test_signals(self):
        # Test signal handling semantics of threads.
        # We spawn a thread, have the thread send two signals, and
        # wait for it to finish. Check that we got both signals
        # and that they were run by the main thread.
        signalled_all.acquire()
        self.spawnSignallingThread()
        signalled_all.acquire()
        # the signals that we asked the kernel to send
        # will come back, but we don't know when.
        # (it might even be after the thread exits
        # and might be out of order.)  If we haven't seen
        # the signals yet, send yet another signal and
        # wait for it return.
        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
           or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
            signal.alarm(1)
            signal.pause()
            signal.alarm(0)

        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR1]['tripped_by'],
                           thread.get_ident())
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped'], 1)
        self.assertEqual( signal_blackboard[signal.SIGUSR2]['tripped_by'],
                           thread.get_ident())
        signalled_all.release()
Exemple #12
0
def main():

	port = common.PORT
	username = input("Choose a username : "******"", flush=True)

	signal.signal(41, pause_handler)
	signal.signal(42, chat_handler)

	signal.pause()

	try:
		chat.chat(port, username)
	except (KeyboardInterrupt, SystemExit): # Handle the ctrl+c
		chat.broadcast(port, chat.encode(username, '{} leaved the chat'.format(username), special=True))
		print('*** Quitting ***')

	p.terminate()
Exemple #13
0
    def main(self):
        # See comment at top of file about zuul imports
        import zuul.scheduler
        import zuul.launcher.jenkins
        import zuul.trigger.gerrit

        self.sched = zuul.scheduler.Scheduler()

        jenkins = zuul.launcher.jenkins.Jenkins(self.config, self.sched)
        gerrit = zuul.trigger.gerrit.Gerrit(self.config, self.sched)

        self.sched.setLauncher(jenkins)
        self.sched.setTrigger(gerrit)

        self.sched.start()
        self.sched.reconfigure(self.config)
        self.sched.resume()
        signal.signal(signal.SIGHUP, self.reconfigure_handler)
        signal.signal(signal.SIGUSR1, self.exit_handler)
        while True:
            try:
                signal.pause()
            except KeyboardInterrupt:
                print "Ctrl + C: asking scheduler to exit nicely...\n"
                self.exit_handler(signal.SIGINT, None)
Exemple #14
0
def run_process(child_id, test_file=None):
    def send(msg):
        sys.stdout.write('{0}:{1}\n'.format(child_id, msg))
        sys.stdout.flush()

    names = {}
    signals = "HUP QUIT INT TERM USR1 USR2".split()
    exit_signals = set("INT TERM".split())
    children = []

    if not isinstance(child_id, int):
        child_id = 0
        for i in range(3):
            p = multiprocessing.Process(target=run_process, args=(i + 1,))
            p.daemon = True
            p.start()
            children.append(p)

    def callback(sig, frame=None):
        global exiting
        name = names[sig]
        send(name)
        if name in exit_signals:
            exiting = True

    for signal_name in signals:
        signum = getattr(signal, "SIG%s" % signal_name)
        names[signum] = signal_name
        signal.signal(signum, callback)

    send('STARTED')
    while not exiting:
        signal.pause()
    send('EXITING')
Exemple #15
0
def withEmpty(words):
    start = time.time()
    for w in words:
        pass
    print '%fs' % (time.time() - start)

    signal.pause()
Exemple #16
0
def start_node(nodetype):
    nodename = node_names[nodetype].lower()
    node = getattr(__import__('concoord.'+nodename, globals(), locals(), -1), nodename.capitalize())()
    node.startservice()
    signal.signal(signal.SIGINT, node.terminate_handler)
    signal.signal(signal.SIGTERM, node.terminate_handler)
    signal.pause()
def main():
    processes = {}

    create_ugc_directories()

    def restart(*args, **kwargs):
        for app, proc in processes.items():
            if proc:
                print 'killing %s (%s)...' % (app, proc.pid)
                proc.terminate()
                proc.communicate()

        if 'sass' in run('which sass', stdout=subprocess.PIPE).stdout.read():
            sass()

        redis()
        memcache()
        nginx()
        for app in processes.keys():
            processes[app] = globals()[app]()
            print '%s: %s' % (app, processes[app].pid if processes[app] else None)
        print 'All systems go! Ctrl+C to restart everything, Ctrl+Z to end.\n'

    restart()
    signal.signal(signal.SIGINT, restart)
    while True:
        signal.pause()
Exemple #18
0
    def run(self):
        self.logger.info("daemon running")

        actions = Actions(self.logger)
        
        try:
            actions.createSessionBus()
            actions.createManager()
            actions.wireEventHandlers()
            actions.openManager()
            
            # MAIN LOOP
            # ---------        
            while True:
                #self.logger.info("start loop")
                
                try:
                    signal.pause()
                    #time.sleep(0.1)
                    #sys.stdin.read()
                except Exception,e:
                    exc=str(e)
                    self.logger.error("error_untrapped", exc=exc)
                    
                #self.logger.info("tail loop")
                
        except Exception,e:
            exc=str(e)
            self.logger.error("error_untrapped", exc=exc)
Exemple #19
0
def main(logger):
    global terminated

    logger.info("clock.py starting")

    # Setup signal handlers for termination
    signal.signal(signal.SIGTERM, exit_handler)
    signal.signal(signal.SIGINT, exit_handler)
    signal.signal(signal.SIGHUP, wake_handler)
    signal.signal(signal.SIGALRM, wake_handler)

    displays = [SevenSegment(address=a) for n, a in DISP_ADDRS.items()]
    blank(displays, begin=True)

    while not terminated:

        # Refresh displays with current time
        now = datetime.datetime.now()
        refresh(now, displays)

        # Set wakeup for update ~one minute from now (next time the display
        # would need updated)
        signal.alarm(60 - datetime.datetime.now().second)
        signal.pause()

    blank(displays)

    logger.info("clock.py stopping")
Exemple #20
0
 def reap(self):
   """Collect the dead jobs."""
   while self._running:
     dead = set()
     for job in self._running:
       st = job.state(self._cache)
       if st == _RUNNING: continue
       if st == _FAILURE or st == _KILLED:
         self._failures += 1
         if self._stop_on_failure:
           self._cancelled = True
           for job in self._running:
             job.kill()
       dead.add(job)
       break
     for job in dead:
       self._completed += 1
       self.resultset[job.GetSpec().shortname].append(job.result)
       self._running.remove(job)
     if dead: return
     if (not self._travis):
       rstr = '' if self._remaining is None else '%d queued, ' % self._remaining
       message('WAITING', '%s%d jobs running, %d complete, %d failed' % (
           rstr, len(self._running), self._completed, self._failures))
     if platform_string() == 'windows':
       time.sleep(0.1)
     else:
       global have_alarm
       if not have_alarm:
         have_alarm = True
         signal.alarm(10)
       signal.pause()
Exemple #21
0
    def test_hello(self):
        global signal_received
        signal.signal(signal.SIGCHLD, simple_handler)
        signal.signal(signal.SIGTRAP, simple_handler)

        pid = fork()
        if pid == 0:
            # Child process
            pt.traceme()
            execl("./tests/helloworld", "helloworld")
            _exit(127)

        while not signal_received:
            print "Sleeping"
            signal.pause()
        
        print "Continuing"
        pt.cont(pid)

        print "Waiting for child to exit"
        while True:
            dummypid, status = waitpid(pid, 0)
            if WIFSIGNALED(status) or WIFEXITED(status):
                break

        self.assertFalse(WIFSIGNALED(status))
        self.assertTrue(WIFEXITED(status))
        self.assertEqual(WEXITSTATUS(status), 0)
        return
Exemple #22
0
def main(args):
    print "ufora-worker starting"
    setup = defaultSetup()
    with Setup.PushSetup(setup):
        setup.config.configureLoggingForBackgroundProgram()

        worker = createService(args)
        worker.startService(None)

        def signal_handler(sig, _):
            signal_name = '(unknown)'
            if sig == signal.SIGINT:
                signal_name = 'SIGINT'
            elif sig == signal.SIGTERM:
                signal_name = 'SIGTERM'

            print 'Received ', signal_name, 'signal. Exiting.'

            worker.stopService()
            sys.exit(0)

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        print "Press Ctrl+C to exit."
        signal.pause()
Exemple #23
0
def main():
    syncilainen = None

    def reload(signum, stack):
        if syncilainen:
            syncilainen.reload_config()

    def quit(signum, stack):
        if syncilainen:
            syncilainen.stop()
        exit(0)

    # listen for SIGHUP or SIGUSR1 and reload config
    signal.signal(signal.SIGHUP, reload)
    signal.signal(signal.SIGUSR1, reload)

    # listen for SIGINT and quit gracefully
    signal.signal(signal.SIGINT, quit)

    # boilerplate
    options = read_options()
    setup_logging(options.log_file, options.debug)
    
    logging.info("PID: %s" % os.getpid())
    
    # start the syncilainen daemon
    syncilainen = Syncilainen()
    syncilainen.start()

    # wait for signals
    while True:
        signal.pause()
Exemple #24
0
def serve_forever(host, port, childnum):
    # create, bind, listen
    listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # re-use the port
    listen_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    listen_sock.bind((host, port))
    listen_sock.listen(BACKLOG)

    print 'Listening on port %d ...' % port

    global MAP
    MAP = create_array(childnum)

    # prefork children
    global PIDS
    PIDS = [create_child(index, listen_sock) for index in range(childnum)]

    # setup SIGTERM handler - in case the parent is killed
    signal.signal(signal.SIGTERM, _cleanup)

    # parent never calls 'accept' - children do all the work
    # all parent does is sleeping :)
    try:
        signal.pause()
    except KeyboardInterrupt:
        _exit_handler()
        print_stats()
Exemple #25
0
    def stop(self):
        """Shutdown the MCP and child processes cleanly"""
        LOGGER.info('Shutting down controller')
        self.set_state(self.STATE_STOP_REQUESTED)

        # Clear out the timer
        signal.setitimer(signal.ITIMER_PROF, 0, 0)

        self._mcp.stop_processes()

        if self._mcp.is_running:
            LOGGER.info('Waiting up to 3 seconds for MCP to shut things down')
            signal.setitimer(signal.ITIMER_REAL, 3, 0)
            signal.pause()
            LOGGER.info('Post pause')

        # Force MCP to stop
        if self._mcp.is_running:
            LOGGER.warning('MCP is taking too long, requesting process kills')
            self._mcp.stop_processes()
            del self._mcp
        else:
            LOGGER.info('MCP exited cleanly')

        # Change our state
        self._stopped()
        LOGGER.info('Shutdown complete')
Exemple #26
0
def main():

	threads=[]

	t = threading.Thread(
				target=sniff,
				kwargs={'prn':arp_handler, 'filter':'arp', 'iface': iface_name, 'store': 0},
				name='ARP'
				)
	threads.append(t)

	t = threading.Thread(
				target=sniff,
				kwargs={'prn':icmp_handler, 'filter':'icmp', 'iface': iface_name, 'store': 0},
				name='ICMP'
				)
	threads.append(t)

	for worker in threads:
		worker.daemon=True
		print "%s worker starting" % (worker.name)
		worker.start()


	try:
		while (42):
			time.sleep(1)
			signal.pause()
	except KeyboardInterrupt:
		print "CTRL+C caught"
		for worker in threads:
			print "%s worker joining main thread" % (worker.name)
			worker.join(1)
		sys.exit(0)
Exemple #27
0
  def start(self):
    # Watch the source files for changes
    filewatch = Observer()
    filewatch.schedule(FilewatchHandler(parent=self,
        ignore_patterns=['*.swp', '*~']),
        self.src_dir,
        recursive=True)

    # Clean shutdown on ctrl+c
    def signal_handler(signal, frame):
      print
      print 'Shutting down...'
      self.stop_server()
      filewatch.stop()

    signal.signal(signal.SIGINT, signal_handler)

    self.rebuild()
    self.start_server()

    print 'Serving at port', self.port
    print 'Serving files from', self.final_build_dir
    print('Press Ctrl+C to stop')

    filewatch.start()
    signal.pause()
    filewatch.join(5000)
Exemple #28
0
    def main(self):
        self.setup_logging()
        self.pool = nodepool.nodepool.NodePool(self.args.secure,
                                               self.args.config,
                                               self.args.no_deletes,
                                               self.args.no_launches,
                                               self.args.no_images)
        if self.args.builder:
            self.builder = nodepool.builder.NodePoolBuilder(
                self.args.config, self.args.build_workers,
                self.args.upload_workers)

        if not self.args.no_webapp:
            self.webapp = nodepool.webapp.WebApp(self.pool)

        signal.signal(signal.SIGINT, self.exit_handler)
        # For back compatibility:
        signal.signal(signal.SIGUSR1, self.exit_handler)

        signal.signal(signal.SIGUSR2, stack_dump_handler)
        signal.signal(signal.SIGTERM, self.term_handler)

        self.pool.start()
        if self.args.builder:
            nb_thread = threading.Thread(target=self.builder.runForever)
            nb_thread.start()

        if not self.args.no_webapp:
            self.webapp.start()

        while True:
            signal.pause()
Exemple #29
0
 def reap(self):
     """Collect the dead jobs."""
     while self._running:
         dead = set()
         for job in self._running:
             st = job.state(self._cache)
             if st == _RUNNING:
                 continue
             if st == _FAILURE:
                 self._failures += 1
             if st == _KILLED:
                 self._failures += 1
             dead.add(job)
         for job in dead:
             self._completed += 1
             self._running.remove(job)
         if dead:
             return
         if not self._travis:
             message(
                 "WAITING",
                 "%d jobs running, %d complete, %d failed" % (len(self._running), self._completed, self._failures),
             )
         global have_alarm
         if not have_alarm:
             have_alarm = True
             signal.alarm(10)
         signal.pause()
Exemple #30
0
    def run(self):
        """When the consumer is ready to start running, kick off all of our
        consumer consumers and then loop while we process messages.

        """
        self.set_state(self.STATE_ACTIVE)
        self.setup_consumers()

        # Set the SIGCHLD handler for child creation errors
        signal.signal(signal.SIGCHLD, self.on_sigchld)

        # Set the SIGALRM handler for poll interval
        signal.signal(signal.SIGALRM, self.on_timer)

        # Kick off the poll timer
        signal.setitimer(signal.ITIMER_REAL, self.poll_interval, 0)

        # Loop for the lifetime of the app, pausing for a signal to pop up
        while self.is_running:
            if not self.is_sleeping:
                self.set_state(self.STATE_SLEEPING)
            signal.pause()

        # Note we're exiting run
        LOGGER.info('Exiting Master Control Program')
def wait_for_signal():
    print('Waiting signal in', threading.currentThread().name)
    signal.pause()
    print('Done Waiting')
file_name = f"{file}_{count}.csv"
if os.path.isfile(file_name):
    while os.path.isfile(file_name):
        if not os.path.isfile(file_name):
            break
        
        count = count + 1
        file_name = f"{file}_{count}.csv"
        


print("Bluetooth server is starting.")
server = BluetoothServer(
    data_received,
    auto_start = False,
    when_client_connects = client_connected,
    when_client_disconnects = client_disconnected)


server.start()
print("MAC Address: ", server.server_address)
print("Waiting for connection")

try:
    pause()
except KeyboardInterrupt as e:
    print("cancelled by user")
finally:
    print("stopping")
    server.stop()
print("stopped")
Exemple #33
0
def Button_Ctrl():  # 버튼 제어
    global power_state
    global fan_state
    powersw.when_pressed = powerctrl  #파워버튼 누르면 실행
    fansw.when_pressed = fan_speedsw  #팬속도 조정버튼 누르면 실행
    pause()  # 누를때까지 대기
 def test_itimer_real(self):
     self.itimer = signal.ITIMER_REAL
     signal.setitimer(self.itimer, 1.0)
     signal.pause()
     self.assertEqual(self.hndl_called, True)
Exemple #35
0
def main():
    arguments = docopt(__doc__, version='FeedCrawler')

    print(u"┌──────────────────────────────────────────────┐")
    print(u"  FeedCrawler " + version + " von RiX")
    print(u"  https://github.com/rix1337/FeedCrawler")
    print(u"└──────────────────────────────────────────────┘")

    if arguments['--docker']:
        configpath = "/config"
    else:
        configpath = files.config(arguments['--config'])
    configfile = os.path.join(configpath, "FeedCrawler.ini")
    dbfile = os.path.join(configpath, "FeedCrawler.db")

    # ToDo Remove this migration from RSScrawler to Feedcrawler in next major version
    if os.path.exists("RSScrawler.conf"):
        os.remove("RSScrawler.conf")

    # ToDo Remove this migration from RSScrawler to Feedcrawler in next major version
    if os.path.exists(os.path.join(configpath, "RSScrawler.log")):
        os.rename(os.path.join(configpath, "RSScrawler.log"),
                  os.path.join(configpath, "FeedCrawler.log"))
        print(u"Migration des RSScrawler-Logs erfolgreich!")

    # ToDo Remove this migration from RSScrawler to Feedcrawler in next major version
    if os.path.exists(os.path.join(configpath, "RSScrawler.ini")):
        with open(os.path.join(configpath, "RSScrawler.ini"), 'r') as file:
            filedata = file.read()

        filedata = filedata.replace("[RSScrawler]", "[FeedCrawler]")
        filedata = filedata.replace("[MB]", "[ContentAll]")
        filedata = filedata.replace("[SJ]", "[ContentShows]")
        filedata = filedata.replace("[DJ]", "[CustomDJ]")
        filedata = filedata.replace("[DD]", "[CustomDD]")

        with open(os.path.join(configpath, "FeedCrawler.ini"), 'w') as file:
            file.write(filedata)

        os.remove(os.path.join(configpath, "RSScrawler.ini"))
        print(u"Migration der RSScrawler-Einstellungen erfolgreich!")

    # ToDo Remove this migration from RSScrawler to Feedcrawler in next major version
    if os.path.exists(os.path.join(configpath, "RSScrawler.db")):
        os.rename(os.path.join(configpath, "RSScrawler.db"),
                  os.path.join(configpath, "FeedCrawler.db"))
        FeedDb(dbfile, 'rsscrawler').rename_table('FeedCrawler')
        FeedDb(dbfile, 'MB_Filme').rename_table('List_ContentAll_Movies')
        FeedDb(dbfile, 'MB_Regex').rename_table('List_ContentAll_Movies_Regex')
        FeedDb(dbfile, 'MB_Staffeln').rename_table('List_ContentAll_Seasons')
        FeedDb(dbfile, 'SJ_Serien').rename_table('List_ContentShows_Shows')
        FeedDb(dbfile,
               'SJ_Serien_Regex').rename_table('List_ContentShows_Shows_Regex')
        FeedDb(dbfile, 'SJ_Staffeln_Regex').rename_table(
            'List_ContentShows_Seasons_Regex')
        FeedDb(dbfile, 'DJ_Dokus').rename_table('List_CustomDJ_Documentaries')
        FeedDb(
            dbfile,
            'DJ_Dokus_Regex').rename_table('List_CustomDJ_Documentaries_Regex')
        print(u"Migration der RSScrawler-Datenbank erfolgreich!")

    print(u"Nutze das Verzeichnis " + configpath + u" für Einstellungen/Logs")

    log_level = logging.__dict__[arguments['--log-level']] if arguments[
        '--log-level'] in logging.__dict__ else logging.INFO
    log_file = os.path.join(configpath, 'FeedCrawler.log')
    log_format = '%(asctime)s - %(message)s'

    hostnames = CrawlerConfig('Hostnames', configfile)

    def clean_up_hostname(host, string):
        if '/' in string:
            string = string.replace('https://', '').replace('http://', '')
            string = re.findall(r'([a-z-.]*\.[a-z]*)', string)[0]
            hostnames.save(host, string)
        if re.match(r'.*[A-Z].*', string):
            hostnames.save(host, string.lower())
        if string:
            print(u'Hostname für ' + host.upper() + ": " + string)
        else:
            print(u'Hostname für ' + host.upper() + ': Nicht gesetzt!')
        return string

    set_hostnames = {}
    list_names = ['dw', 'fx', 'sj', 'dj', 'sf', 'ww', 'nk', 'by', 'dd']
    for name in list_names:
        hostname = clean_up_hostname(name, hostnames.get(name))
        if hostname:
            set_hostnames[name] = hostname

    if not arguments['--testlauf'] and not set_hostnames:
        print(
            u'Keine Hostnamen in der FeedCrawler.ini gefunden! Beende FeedCrawler!'
        )
        time.sleep(10)
        sys.exit(1)

    disable_request_warnings(InsecureRequestWarning)

    if arguments['--testlauf']:
        device = False
    else:
        if not os.path.exists(configfile):
            if arguments['--docker']:
                if arguments['--jd-user'] and arguments['--jd-pass']:
                    device = files.myjd_input(configfile, arguments['--port'],
                                              arguments['--jd-user'],
                                              arguments['--jd-pass'],
                                              arguments['--jd-device'])
                else:
                    device = False
            else:
                device = files.myjd_input(configfile, arguments['--port'],
                                          arguments['--jd-user'],
                                          arguments['--jd-pass'],
                                          arguments['--jd-device'])
        else:
            feedcrawler = CrawlerConfig('FeedCrawler', configfile)
            user = feedcrawler.get('myjd_user')
            password = feedcrawler.get('myjd_pass')
            if user and password:
                device = get_device(configfile)
                if not device:
                    device = get_if_one_device(user, password)
                    if device:
                        print(u"Gerätename " + device +
                              " automatisch ermittelt.")
                        feedcrawler.save('myjd_device', device)
                        device = get_device(configfile)
            else:
                device = files.myjd_input(configfile, arguments['--port'],
                                          arguments['--jd-user'],
                                          arguments['--jd-pass'],
                                          arguments['--jd-device'])

        if not device and not arguments['--testlauf']:
            print(
                u'My JDownloader Zugangsdaten fehlerhaft! Beende FeedCrawler!')
            time.sleep(10)
            sys.exit(1)
        else:
            print(u"Erfolgreich mit My JDownloader verbunden. Gerätename: " +
                  device.name)

    feedcrawler = CrawlerConfig('FeedCrawler', configfile)

    port = int(feedcrawler.get("port"))
    docker = False
    if arguments['--docker']:
        port = int('9090')
        docker = True
    elif arguments['--port']:
        port = int(arguments['--port'])

    if feedcrawler.get("prefix"):
        prefix = '/' + feedcrawler.get("prefix")
    else:
        prefix = ''
    local_address = 'http://' + common.check_ip() + ':' + str(port) + prefix
    if not arguments['--docker']:
        print(u'Der Webserver ist erreichbar unter ' + local_address)

    if arguments['--keep-cdc']:
        print(u"CDC-Tabelle nicht geleert!")
    else:
        FeedDb(dbfile, 'cdc').reset()

    p = multiprocessing.Process(target=web_server,
                                args=(port, local_address, docker, configfile,
                                      dbfile, log_level, log_file, log_format,
                                      device))
    p.start()

    if not arguments['--testlauf']:
        c = multiprocessing.Process(target=crawler,
                                    args=(configfile, dbfile, device,
                                          feedcrawler, log_level, log_file,
                                          log_format))
        c.start()

        w = multiprocessing.Process(target=crawldog, args=(configfile, dbfile))
        w.start()

        print(u'Drücke [Strg] + [C] zum Beenden')

        def signal_handler():
            print(u'Beende FeedCrawler...')
            p.terminate()
            c.terminate()
            w.terminate()
            sys.exit(0)

        signal.signal(signal.SIGINT, signal_handler)

        try:
            while True:
                signal.pause()
        except AttributeError:
            while True:
                time.sleep(1)
    else:
        crawler(configfile, dbfile, device, feedcrawler, log_level, log_file,
                log_format)
        p.terminate()
        sys.exit(0)
Exemple #36
0
GPIO.setup(pin, GPIO.OUT)

# Create an Infinite Loops
while True:  # Get Initial PIN State
    # To test the value of a PIN use the .input method
    # Returns 0 if OFF or 1 if ON
    pin_state = GPIO.input(pin)
    # if the PIN is ON
    if pin_state == 1:
        # Set the initial pin state to OFF
        GPIO.output(pin, GPIO.LOW)
    print(cpu.temperature)

    if cpu.temperature > 45:

        while cpu.temperature > 40:
            print(cpu.temperature)
            # Get the current PIN State, Returns 0 if OFF or 1 if ON
            pin_state = GPIO.input(pin)

            # if PIN state false or 0, the PIN if off then turn the pin ON
            if pin_state == 0:
                # Set the PIN state to ON
                GPIO.output(pin, GPIO.HIGH)
            (sleep(1))

    else:
        (sleep(1))

signal.pause()
Exemple #37
0
def _subproc_pre():
    os.setpgrp()
    signal.signal(signal.SIGTSTP, lambda n, f: signal.pause())
Exemple #38
0
def pause_handler(signum, frame):
    print("Paused")
    signal.pause()
Exemple #39
0
def main(args):
    # CONFIGURATION PARSING
    # load in the configuration file
    config = ConfigParser({
        'certfile': None,
        'keyfile': None,
        'ca_certs': None,
        'ssl': False,
        'port': '8000',
        'host': '0.0.0.0',
        'icons': 'link',
        'corpus_link': None,
        'doc_title_format': None,
        'doc_url_format': None,
        'topic_range': None,
        'fulltext': 'false',
        'raw_corpus': None,
        'topics': None
    })
    config.read(args.config_file)

    if config.get('main', 'topic_range'):
        topic_range = map(int, config.get('main', 'topic_range').split(','))
        topic_range = range(*topic_range)
    if config.get('main', 'topics'):
        topic_range = eval(config.get('main', 'topics'))
    print topic_range

    # LAUNCHING SERVERS
    # Cross-platform compatability
    def get_log_file(k):
        if config.has_section('logging'):
            path = config.get('logging', 'path')
            path = path.format(k)
            if not os.path.exists(os.path.dirname(path)):
                os.makedirs(os.path.dirname(path))

            return open(path, 'a')
        else:
            return subprocess.PIPE

    def test_baseport(host, baseport, topic_range):
        try:
            for k in topic_range:
                port = baseport + k
                try:
                    s = socket.create_connection((host, port), 2)
                    s.close()
                    raise IOError(
                        "Socket connectable on port {0}".format(port))
                except socket.error:
                    pass
            return baseport
        except IOError:
            baseport = int_prompt(
                "Conflict on port {0}. Enter new base port: [CURRENT: {1}]"\
                    .format(port, baseport))
            return test_baseport(host, baseport, topic_range)

    host = config.get("www", "host")
    if host == '0.0.0.0':
        host = socket.gethostname()

    baseport = int(config.get("www", "port").format(0))
    baseport = test_baseport(host, baseport, topic_range)

    # prompt to save
    if int(config.get("www", "port").format(0)) != baseport:
        if bool_prompt("Change default baseport to {0}?".format(baseport),
                       default=True):
            config.set("www", "port", baseport)

            # create deep copy of configuration
            # see http://stackoverflow.com/a/24343297
            config_string = StringIO()
            config.write(config_string)

            # skip DEFAULT section
            config_string.seek(0)
            idx = config_string.getvalue().index("[main]")
            config_string.seek(idx)

            # read deep copy
            new_config = ConfigParser()
            new_config.readfp(config_string)

            # write deep copy without DEFAULT section
            # this preserves DEFAULT for rest of program
            with open(args.config_file, 'wb') as configfh:
                new_config.write(configfh)

    try:
        grp_fn = os.setsid
    except AttributeError:
        grp_fn = None
    fulltext = '--fulltext' if args.fulltext else ''
    procs = [
        subprocess.Popen(
            "vsm serve -k {k} -p {port} {config_file} {fulltext}".format(
                k=k,
                port=(baseport + k),
                config_file=args.config_file,
                fulltext=fulltext),
            shell=True,
            stdout=get_log_file(k),
            stderr=subprocess.STDOUT,
            preexec_fn=grp_fn) for k in topic_range
    ]

    print "pid", "port"
    for proc, k in zip(procs, topic_range):
        port = baseport + k
        print proc.pid, "http://{host}:{port}/".format(host=host, port=port)

    # CLEAN EXIT AND SHUTDOWN OF SERVERS
    def signal_handler(signal, frame):
        print "\n"
        for p, k in zip(procs, topic_range):
            print "Stopping {}-topic model (Process ID: {})".format(k, p.pid)
            # Cross-Platform Compatability
            if platform.system() == 'Windows':
                subprocess.call(['taskkill', '/F', '/T', '/PID',
                                 str(p.pid)],
                                stdout=open(os.devnull),
                                stderr=open(os.devnull))
            else:
                os.killpg(p.pid, signal)

        sys.exit()

    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)

    port = baseport + topic_range[0]
    url = "http://{host}:{port}/".format(host=host, port=port)

    # TODO: Add enhanced port checking
    while True:
        wait_count = 0
        try:
            urllib.urlopen(url)
            print "Server successfully started"
            break
        except:
            time.sleep(1)
            wait_count += 1

        if wait_count == 60:
            print "\nLaunching the server seems to be taking a long time."
            print "This may be due to loading in a large corpus."

            print "\nTo test launching a single model, press Ctrl+C to abort launch,"
            print "then use the `serve` command to find the error message:"
            print "\tvsm serve {config} -k {k}".format(config=args.config_file,
                                                       k=topic_range[0])

        for proc, k in zip(procs, topic_range):
            if proc.poll() is not None:
                print "\nAn error has occurred launching the {}-topic model.".format(
                    k)
                try:
                    with get_log_file(k) as logfile:
                        print "A log has been written to: {}\n".format(
                            logfile.name)
                except AttributeError:
                    # No log file, things are a-ok.
                    pass

                print "Use the `serve` command to debug errors:"
                print "\tvsm serve {config} -k {k}".format(
                    config=args.config_file, k=k)
                for p in procs:
                    if p.poll() is None:
                        try:
                            os.killpg(p.pid, signal.SIGTERM)
                        except AttributeError:
                            # Cross-Platform Compatability
                            subprocess.call(
                                ['taskkill', '/F', '/T', '/PID',
                                 str(p.pid)])

                sys.exit(1)

    if args.browser:
        webbrowser.open(url)
        print "TIP: Browser launch can be disabled with the '--no-browser' argument:"
        print "vsm launch --no-browser", args.config_file, "\n"

    print "Press Ctrl+C to shutdown the Topic Explorer server"
    # Cross-platform Compatability
    try:
        signal.pause()
    except AttributeError:
        # Windows hack
        while True:
            time.sleep(1)
def playAgain():
    """Restarts the game"""
    # Task 3: complete this function
    pass


# MAIN-----------------------
# set up Sense Hat
sense = ttt.set_up_sense_hat()

#set functions for joystick buttons
sense.stick.direction_up = pushed_up
sense.stick.direction_down = pushed_down
sense.stick.direction_left = pushed_left
sense.stick.direction_right = pushed_right
sense.stick.direction_middle = buttonPushed

#red will play first
redTurn = True

sense.show_message("Get ready!")

# set grid
sense.set_pixels(grid)

# display position marker
sense.set_pixel(marker[0], marker[1], blue)

print("about to pause")
pause()  #stop execution and wait for event
Exemple #41
0
def run():
	zabbix=zabbixSender()
	signal.signal(signal.SIGTERM, zabbix.shutdown)
	signal.signal(signal.SIGINT, zabbix.shutdown)
	zabbix.start()
	signal.pause()
Exemple #42
0
    def execute_job(self, job, environ, extcmd_popen, stdin=None):
        """Run the 'binary' associated with the job."""
        target_user = job.user or self._user_provider()
        if target_user == getpass.getuser():
            target_user = None

        def call(extcmd_popen, *args, **kwargs):
            """Handle low-level subprocess stuff."""
            is_alive = True
            # Notify that the process is about to start
            extcmd_popen._delegate.on_begin(args, kwargs)
            # Setup stdout/stderr redirection
            kwargs['stdout'] = subprocess.PIPE
            kwargs['stderr'] = subprocess.PIPE
            kwargs['start_new_session'] = True
            # Prepare stdio supply
            in_r, in_w = os.pipe()
            # first let's punch the password in
            # we need it only if the target user differs from the one that
            # started checkbox and when changing the user (sudo) requires
            # password
            if target_user and self._password_provider:
                password = self._password_provider()
                if password:
                    os.write(in_w, password + b'\n')

            def stdin_forwarder(stdin):
                """Forward data from one pipe to the other."""
                # use systems stdin if the stdin pipe wasn't provided
                stdin = stdin or sys.stdin
                try:
                    while is_alive:
                        if stdin in select.select([stdin], [], [], 0)[0]:
                            buf = stdin.readline()
                            if buf == '':
                                break
                            os.write(in_w, buf.encode(stdin.encoding))
                        else:
                            time.sleep(0.1)
                except BrokenPipeError:
                    pass
                os.close(in_w)
            forwarder_thread = threading.Thread(
                target=stdin_forwarder, args=(stdin,))
            forwarder_thread.start()
            kwargs['stdin'] = in_r

            # Start the process
            proc = extcmd_popen._popen(*args, **kwargs)
            self._running_jobs_pid = proc.pid
            # Setup all worker threads. By now the pipes have been created and
            # proc.stdout/proc.stderr point to open pipe objects.
            stdout_reader = threading.Thread(
                target=extcmd_popen._read_stream, args=(proc.stdout, "stdout"))
            stderr_reader = threading.Thread(
                target=extcmd_popen._read_stream, args=(proc.stderr, "stderr"))
            queue_worker = threading.Thread(target=extcmd_popen._drain_queue)
            # Start all workers
            queue_worker.start()
            stdout_reader.start()
            stderr_reader.start()
            try:
                while True:
                    try:
                        proc.wait()
                        break
                    except KeyboardInterrupt:
                        is_alive = False
                        import signal
                        self.send_signal(signal.SIGKILL, target_user)
                        # And send a notification about this
                        extcmd_popen._delegate.on_interrupt()
            finally:
                self._running_jobs_pid = None
                # Wait until all worker threads shut down
                stdout_reader.join()
                proc.stdout.close()
                stderr_reader.join()
                proc.stderr.close()
                # Tell the queue worker to shut down
                extcmd_popen._queue.put(None)
                queue_worker.join()
                os.close(in_r)
                is_alive = False
                forwarder_thread.join()
            # Notify that the process has finished
            extcmd_popen._delegate.on_end(proc.returncode)
            return proc.returncode
        # Setup the executable nest directory
        with self.configured_filesystem(job) as nest_dir:
            # Get the command and the environment.
            # of this execution controller
            cmd = get_execution_command(job, environ, self._session_id,
                                        nest_dir, target_user, self._extra_env)
            env = get_execution_environment(job, environ, self._session_id,
                                            nest_dir)
            if self._user_provider():
                env['NORMAL_USER'] = self._user_provider()
            # run the command
            logger.debug(_("job[%(ID)s] executing %(CMD)r with env %(ENV)r"),
                         {"ID": job.id, "CMD": cmd,
                          "ENV": env})
            if 'preserve-cwd' in job.get_flag_set() or os.getenv("SNAP"):
                return_code = call(
                    extcmd_popen, cmd, stdin=subprocess.PIPE, env=env)
            else:
                with self.temporary_cwd(job) as cwd_dir:
                    return_code = call(
                        extcmd_popen, cmd, stdin=subprocess.PIPE, env=env,
                        cwd=cwd_dir)
            if 'noreturn' in job.get_flag_set():
                import signal
                signal.pause()
            return return_code
Exemple #43
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    server = None

    # SIGINT signal handler
    def program_cleanup(sig_num, frame):
        logger = log.getLogger("upq")
        logger.info("Shutting down socket server...")
        server.shutdown()
        logger.info("Disconnecting from DB...")
        upqdb.UpqDB().cleanup()
        log.getLogger("upq").info("Good bye.")
        sys.exit(0)

    usage = "usage: %prog -c CONFIGFILE [options]"
    parser = OptionParser(usage)
    parser.add_option("-c",
                      "--config",
                      dest="configfile",
                      default="",
                      help="path to config file CONFIGFILE")
    #TODO: use this to en/disable daemonization
    #		parser.add_option("-d", "--daemonize",
    #		help="detach from terminal etc")
    parser.add_option("-l",
                      "--logfile",
                      dest="logfile",
                      default="",
                      help="path to logfile LOGFILE")
    (options, argv) = parser.parse_args()

    try:
        # read ini file
        UpqConfig(options.configfile, options.logfile)
        UpqConfig().readConfig()

        #FIXME: remove following line + how does this $%$!" work?
        del UpqConfig().daemon['pidfile']
        #	 if UpqConfig().daemon.has_key('pidfile'):
        #		 lockfile=UpqConfig().daemon['pidfile']
        #		 UpqConfig().daemon['pidfile']=pidlockfile.TimeoutPIDLockFile(lockfile, acquire_timeout=1)
        context = daemon.DaemonContext(**UpqConfig().daemon)
        # daemonize
        context.stdout = sys.stderr
        context.stderr = sys.stderr

        upq = Upq()
        with context:
            # initialize logging
            logger = log.init_logging(UpqConfig().logging)
            logger.info("Starting logging...")
            logger.debug(UpqConfig().config_log)
            # setup and test DB
            logger.info("Connecting to DB...")
            db = upqdb.UpqDB()
            db.connect(UpqConfig().db['url'], UpqConfig().db['debug'])
            db.version()
            # start server
            logger.info("Starting socket server...")
            server = upq.start_server()

        # except SIGINT and SIGTERM
        signal.signal(signal.SIGINT, program_cleanup)
        signal.signal(signal.SIGTERM, program_cleanup)

        log.getLogger("upq").info(
            "Server running until receiving SIGTERM or SIGINT / Ctrl+C.")
        signal.pause()

    except Exception:
        traceback.print_exc(file=sys.stderr)
    try:
        db.cleanup()
    except:
        pass
    sys.exit(1)
Exemple #44
0
def rls():
	global held_for
	if (held_for > 5.0):
		#check_call(['/sbin/poweroff'])
		print('shutdown')
		held_for = 0.0
		motor.write_register(0, 0b0000000000000110, functioncode=6)#stop#stop
                check_call(['/sbin/poweroff'])

	elif (held_for > 2.0):
		print('stop motor')
		#check_call(['/sbin/reboot'])
		motor.write_register(0, 0b0000000000000110, functioncode=6)#stop#stop
		os.system("sudo systemctl stop motor.service")
		print('motor service killed')
                held_for = 0.0
	else:
		held_for = 0.0
def hld():
	global held_for
	# callback for when button is held
	#  is called every hold_time seconds global held_for
	# need to use max() as held_time resets to zero on last callback
	held_for = max(held_for, button.held_time + button.hold_time)

button=Button(use_button, hold_time=1.0, hold_repeat=True)
button.when_held = hld
button.when_released = rls

pause() # wait forever
def main():

    button=Button(18)
    button.when_pressed= click
    pause()
Exemple #46
0
def WaitForCtrlC(func=LibOnCtrlC):
    signal.signal(signal.SIGINT, func)
    signal.pause()
@skywriter.move()
def move(x, y, z):
    global lastLocation
    #r = int(255 * (z / 0.7))
    step = 25 - (int(25 * (z)) + 1)
    print(z, step)
    newLocation = [x, y, step]
    #print newLocation
    if newLocation != lastLocation:
        q.put(newLocation)
        lastLocation = newLocation


strip.begin()
#pulse(q)

#Lets try a thread...
t = threading.Thread(target=pulse, args = (q,strip, WIDTH, HEIGHT))
t.daemon = True
t.start()

while True:
    signal.pause() #wait for intetrrupt
    #Event.wait()

#Take move from skywriter
#import move from skywriter and input into x,y,z co-ordinates
#Give option for mood, create an input of 3 mechanical buttons
    #Sad, Happy, excited
      #each mood has it's own colour and and key signature
def main(args):
    args.config_file = os.path.abspath(args.config_file)
    with open(get_static_resource_path('ipynb/corpus.tmpl.py')) as corpustmpl:
        corpus_py = corpustmpl.read()
        corpus_py = Template(corpus_py)
        corpus_py = corpus_py.safe_substitute(config_file=args.config_file)

    ipynb_path = os.path.join(os.path.dirname(args.config_file), "notebooks")
    print(ipynb_path)
    if not os.path.exists(ipynb_path):
        os.makedirs(ipynb_path)

    filename = os.path.join(ipynb_path, "corpus.py")

    if overwrite_prompt(filename, default=True):
        print("Writing", filename)
        with open(filename, 'w') as corpusloader:
            corpusloader.write(corpus_py)
    pyflag = 'py2' if sys.version_info.major == 2 else 'py3'
    glob_path = (get_static_resource_path('ipynb') +
                 '/*.{}.ipynb').format(pyflag)

    for notebook in glob(glob_path):
        new_nb_name = os.path.basename(notebook).replace('.' + pyflag, '')
        new_nb_path = os.path.join(ipynb_path, new_nb_name)
        if overwrite_prompt(new_nb_path, default=False):
            print("Copying", notebook)
            shutil.copy(notebook, new_nb_path)

    if args.launch:
        import subprocess
        os.chdir(ipynb_path)
        try:
            # TODO: Fix KeyboardInterrupt errors
            try:
                grp_fn = os.setsid
            except AttributeError:
                grp_fn = None
            proc = subprocess.Popen("jupyter notebook",
                                    shell=True,
                                    preexec_fn=grp_fn)
            # stdin=subprocess.PIPE, preexec_fn=grp_fn)
            # stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        except OSError:
            print("ERROR: Command `jupyter notebook` not found.")
            print(
                "       If IPython or Anaconda is installed, check your PATH variable."
            )
            sys.exit(1)

        # CLEAN EXIT AND SHUTDOWN OF IPYTHON NOTEBOOK
        def signal_handler(signal, frame):
            # Cross-Platform Compatability
            try:
                os.killpg(proc.pid, signal)
                proc.communicate()
            except AttributeError:
                subprocess.call(
                    ['taskkill', '/F', '/T', '/PID',
                     str(proc.pid)])
                sys.exit(0)

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        print("\nPress Ctrl+C to shutdown the IPython notebook server\n")

        # Cross-platform Compatability
        try:
            signal.pause()
        except AttributeError:
            # Windows hack
            while True:
                time.sleep(1)
Exemple #49
0
def test_dnotify1():
    d = DNotify(".")
    while 1:
        signal.pause()
Exemple #50
0
    def run_test(self):
        # Install handlers. This function runs in a sub-process, so we
        # don't worry about re-setting the default handlers.
        signal.signal(signal.SIGHUP, self.handlerA)
        signal.signal(signal.SIGUSR1, self.handlerB)
        signal.signal(signal.SIGUSR2, signal.SIG_IGN)
        signal.signal(signal.SIGALRM, signal.default_int_handler)

        # Variables the signals will modify:
        self.a_called = False
        self.b_called = False

        # Let the sub-processes know who to send signals to.
        pid = os.getpid()
        if support.verbose:
            print("test runner's pid is", pid)

        child = ignoring_eintr(subprocess.Popen, ['kill', '-HUP', str(pid)])
        if child:
            self.wait(child)
            if not self.a_called:
                time.sleep(1)  # Give the signal time to be delivered.
        self.assertTrue(self.a_called)
        self.assertFalse(self.b_called)
        self.a_called = False

        # Make sure the signal isn't delivered while the previous
        # Popen object is being destroyed, because __del__ swallows
        # exceptions.
        del child
        try:
            child = subprocess.Popen(['kill', '-USR1', str(pid)])
            # This wait should be interrupted by the signal's exception.
            self.wait(child)
            time.sleep(1)  # Give the signal time to be delivered.
            self.fail('HandlerBCalled exception not thrown')
        except HandlerBCalled:
            self.assertTrue(self.b_called)
            self.assertFalse(self.a_called)
            if support.verbose:
                print("HandlerBCalled exception caught")

        child = ignoring_eintr(subprocess.Popen, ['kill', '-USR2', str(pid)])
        if child:
            self.wait(child)  # Nothing should happen.

        try:
            signal.alarm(1)
            # The race condition in pause doesn't matter in this case,
            # since alarm is going to raise a KeyboardException, which
            # will skip the call.
            signal.pause()
            # But if another signal arrives before the alarm, pause
            # may return early.
            time.sleep(1)
        except KeyboardInterrupt:
            if support.verbose:
                print("KeyboardInterrupt (the alarm() went off)")
        except:
            self.fail("Some other exception woke us from pause: %s" %
                      traceback.format_exc())
        else:
            self.fail("pause returned of its own accord, and the signal"
                      " didn't arrive after another second.")
Exemple #51
0
    def mitm(self, ):
        self.setup_adapters()

        self.set_adapter_props()

        sdpthread = Thread(target=mitm_sdp,
                           args=(self.target_master, self.target_slave,
                                 self.script))
        sdpthread.daemon = True

        threads = []

        if not self.already_paired or args.inquire_again:
            self.socks = self.safe_connect(self.target_slave)

        if not self.already_paired:
            if not self.shared:
                enable_adapter(self.master_adapter, False)
            self.pair(self.slave_adapter, self.target_slave)
            if not self.shared:
                enable_adapter(self.master_adapter, True)
            self.already_paired = True
            print('paired')

        instrument_bluetoothd()

        time.sleep(1.5)
        self.set_adapter_props(
        )  # do this again because bluetoothd resets properties
        sdpthread.start()
        self.connections = []  # reset
        self.servers = []
        self.barrier = Barrier(len(self.socks) + 1)
        self.connections_lock = RLock()
        for j in self.socks:
            print_verbose(j)
        for service in self.socks:
            server_sock = self.start_service(service)
            if server_sock is None:
                self.socks.remove(service)
                continue
            print('Proxy listening for connections for "' +
                  str(service['name']) + '"')
            thread = Thread(target=self.do_mitm, args=(
                server_sock,
                service,
            ))
            thread.daemon = True
            threads.append(thread)

        for thr in threads:
            thr.start()
        #self.set_class();

        print('Attempting connections with %d services on slave' %
              len(self.socks))
        self.barrier.wait()
        #self.set_class();
        #if len(self.connections) < len(self.socks):
        #    if len(self.connections) == 0:
        #        exit(1)
        #    print('At least one service was unable to connect.  Continuing anyways but this may not work.')

        print('Now you\'re free to connect to "' + self.slave_name +
              '" from master device.')
        with open('.last-btproxy-pairing', 'wb+') as f:
            self.barrier = None
            self.connections_lock = None
            script_s = self.script
            self.script = None
            pickle.dump(self, f)
            self.script = script_s

        if not self.already_paired:
            if not self.shared:
                adapter_class(self.master_adapter, self.slave_info['class'])
                adapter_class(self.slave_adapter, self.master_info['class'])
            else:
                adapter_class(self.slave_adapter, self.slave_info['class'])

        import signal, sys

        def signal_handler(signal, frame):
            sys.exit(0)

        signal.signal(signal.SIGINT, signal_handler)
        signal.pause()

        print('Now connect to ' + self.master_name + ' from the master device')

        for i in threads:
            i.join()
        sdpthread.join()
Exemple #52
0
def main():
    nameservernode = Nameserver(instantiateobj=True)
    nameservernode.startservice()
    signal.signal(signal.SIGINT, nameservernode.terminate_handler)
    signal.signal(signal.SIGTERM, nameservernode.terminate_handler)
    signal.pause()
def run():
    logger.info("Modular Input mi_opcua_subscription command: %s" % sys.argv)
    if len(sys.argv) > 1:
        try:
            if sys.argv[1] == "--scheme":
                do_scheme()
            elif sys.argv[1] == "--validate-arguments":
                validate_arguments()
            elif sys.argv[1] == "--test":
                test()
            else:
                usage()
        except Exception as ex:
            logger.critical(ex)
    else:
        logger.info(
            "Modular Input mi_opcua_subscription Starts data collection.")

        configs = get_config()
        stanza = configs["name"]
        # server_uri = configs["server_uri"]
        # sessionKey = configs["session_key"]
        # userName = "******"   # make this modular input as application context only.
        patterns = configs["measures"].split(":")
        tout = configs["connection_timeout"].strip()
        timeout = 1 if len(tout) <= 0 else int(tout)
        ct = configs["collect_duration"].strip()
        duration = 1000 if len(ct) <= 0 else int(ct)

        conn = configs[
            "connection"]  ## "opc.tcp://ec2-54-190-162-94.us-west-2.compute.amazonaws.com:49320"

        if configs.has_key("username"):
            username = configs["username"].strip()
            if len(username) > 0:
                password = configs["password"].strip()
                conn = "%s?username=%s&password=%s" % (conn, username,
                                                       password)

        client = Client(conn, timeout=timeout)

        try:
            client.connect()
            measures = []
            root = client.get_root_node()

            node.collect_measures(measures, patterns, root)

            subscribers = []
            for m in measures:
                try:
                    subscribers.append(m[len(m) - 1])
                except:
                    logger.warn("The node of %s is invalid to subscribe." % m)

            handler = SubHandler(stanza)
            sub = client.create_subscription(duration, handler)
            dchandle = sub.subscribe_data_change(subscribers)

            def signal_handler(signal, frame):
                logger.info('Press Ctrl+C')

                if signal in [
                        signal.SIGABRT, signal.SIGINT, signal.SIGQUIT,
                        signal.SIGTERM
                ]:
                    sub.unsubscribe(dchandle)
                    sub.delete()
                    client.disconnect()

            signal.signal(signal.SIGINT, signal_handler)
            signal.signal(signal.SIGABRT, signal_handler)
            signal.signal(signal.SIGTERM, signal_handler)
            signal.signal(signal.SIGQUIT, signal_handler)

            signal.pause()

        except Exception as ex:
            logger.critical(ex)
        finally:
            sub.unsubscribe(dchandle)
            sub.delete()
            client.disconnect()

            logger.info("---- end of sub opc ua ----")
Exemple #54
0
def ssl_log(process, pcap=None, verbose=False):
  """Decrypts and logs a process's SSL traffic.

  Hooks the functions SSL_read() and SSL_write() in a given process and logs
  the decrypted data to the console and/or to a pcap file.

  Args:
    process: The target process's name (as a string) or process ID (as an int).
    pcap: The file path to which the pcap file should be written.
    verbose: If True, log the decrypted traffic to the console.

  Raises:
    NotImplementedError: Not running on a Linux or macOS system.
  """

  if platform.system() not in ("Darwin", "Linux"):
    raise NotImplementedError("This function is only implemented for Linux and "
                              "macOS systems.")

  def log_pcap(pcap_file, ssl_session_id, function, src_addr, src_port,
               dst_addr, dst_port, data):
    """Writes the captured data to a pcap file.

    Args:
      pcap_file: The opened pcap file.
      ssl_session_id: The SSL session ID for the communication.
      function: The function that was intercepted ("SSL_read" or "SSL_write").
      src_addr: The source address of the logged packet.
      src_port: The source port of the logged packet.
      dst_addr: The destination address of the logged packet.
      dst_port: The destination port of the logged packet.
      data: The decrypted packet data.
    """
    t = time.time()

    if ssl_session_id not in ssl_sessions:
      ssl_sessions[ssl_session_id] = (random.randint(0, 0xFFFFFFFF),
                                      random.randint(0, 0xFFFFFFFF))
    client_sent, server_sent = ssl_sessions[ssl_session_id]

    if function == "SSL_read":
      seq, ack = (server_sent, client_sent)
    else:
      seq, ack = (client_sent, server_sent)

    for writes in (
        # PCAP record (packet) header
        ("=I", int(t)),                   # Timestamp seconds
        ("=I", (t * 1000000) % 1000000),  # Timestamp microseconds
        ("=I", 40 + len(data)),           # Number of octets saved
        ("=i", 40 + len(data)),           # Actual length of packet
        # IPv4 header
        (">B", 0x45),                     # Version and Header Length
        (">B", 0),                        # Type of Service
        (">H", 40 + len(data)),           # Total Length
        (">H", 0),                        # Identification
        (">H", 0x4000),                   # Flags and Fragment Offset
        (">B", 0xFF),                     # Time to Live
        (">B", 6),                        # Protocol
        (">H", 0),                        # Header Checksum
        (">I", src_addr),                 # Source Address
        (">I", dst_addr),                 # Destination Address
        # TCP header
        (">H", src_port),                 # Source Port
        (">H", dst_port),                 # Destination Port
        (">I", seq),                      # Sequence Number
        (">I", ack),                      # Acknowledgment Number
        (">H", 0x5018),                   # Header Length and Flags
        (">H", 0xFFFF),                   # Window Size
        (">H", 0),                        # Checksum
        (">H", 0)):                       # Urgent Pointer
      pcap_file.write(struct.pack(writes[0], writes[1]))
    pcap_file.write(data)

    if function == "SSL_read":
      server_sent += len(data)
    else:
      client_sent += len(data)
    ssl_sessions[ssl_session_id] = (client_sent, server_sent)

  def on_message(message, data):
    """Callback for errors and messages sent from Frida-injected JavaScript.

    Logs captured packet data received from JavaScript to the console and/or a
    pcap file. See https://www.frida.re/docs/messages/ for more detail on
    Frida's messages.

    Args:
      message: A dictionary containing the message "type" and other fields
          dependent on message type.
      data: The string of captured decrypted data.
    """
    if message["type"] == "error":
      pprint.pprint(message)
      os.kill(os.getpid(), signal.SIGTERM)
      return
    if len(data) == 0:
      return
    p = message["payload"]
    if verbose:
      src_addr = socket.inet_ntop(socket.AF_INET,
                                  struct.pack(">I", p["src_addr"]))
      dst_addr = socket.inet_ntop(socket.AF_INET,
                                  struct.pack(">I", p["dst_addr"]))
      print("SSL Session: " + p["ssl_session_id"])
      print("[%s] %s:%d --> %s:%d" % (
          p["function"],
          src_addr,
          p["src_port"],
          dst_addr,
          p["dst_port"]))
      hexdump.hexdump(data)
      print()
    if pcap:
      log_pcap(pcap_file, p["ssl_session_id"], p["function"], p["src_addr"],
               p["src_port"], p["dst_addr"], p["dst_port"], data)

  device = get_usb_iphone()
  session = device.attach(process)

  if pcap:
    pcap_file = open(pcap, "wb", 0)
    for writes in (
        ("=I", 0xa1b2c3d4),     # Magic number
        ("=H", 2),              # Major version number
        ("=H", 4),              # Minor version number
        ("=i", time.timezone),  # GMT to local correction
        ("=I", 0),              # Accuracy of timestamps
        ("=I", 65535),          # Max length of captured packets
        ("=I", 228)):           # Data link type (LINKTYPE_IPV4)
      pcap_file.write(struct.pack(writes[0], writes[1]))

  script = session.create_script(_FRIDA_SCRIPT)
  script.on("message", on_message)
  script.load()

  print("Press Ctrl+C to stop logging.")
  try:
    signal.pause()
  except KeyboardInterrupt:
    pass

  session.detach()
  if pcap:
    pcap_file.close()
Exemple #55
0
    def run(self, options):

        logger.info('Using version: {}'.format(pulseaudio_dlna.__version__))

        if not options['--host']:
            host = None
        else:
            host = str(options['--host'])

        port = int(options['--port'])
        pulseaudio_dlna.streamserver.StreamServer.HOST = host
        pulseaudio_dlna.streamserver.StreamServer.PORT = port

        logger.info('Binding to {host}:{port}'.format(host=host or '*',
                                                      port=port))

        if options['--disable-workarounds']:
            pulseaudio_dlna.workarounds.BaseWorkaround.ENABLED = False

        if options['--disable-ssdp-listener']:
            pulseaudio_dlna.plugins.upnp.ssdp.listener.\
                SSDPListener.DISABLE_SSDP_LISTENER = True

        if options['--disable-mimetype-check']:
            pulseaudio_dlna.plugins.renderer.DISABLE_MIMETYPE_CHECK = True

        if options['--chunk-size']:
            chunk_size = int(options['--chunk-size'])
            pulseaudio_dlna.streamserver.ProcessStream.CHUNK_SIZE = chunk_size

        if options['--ssdp-ttl']:
            ssdp_ttl = int(options['--ssdp-ttl'])
            pulseaudio_dlna.plugins.upnp.ssdp.discover.\
                SSDPDiscover.SSDP_TTL = ssdp_ttl
            pulseaudio_dlna.plugins.upnp.ssdp.listener.\
                SSDPListener.SSDP_TTL = ssdp_ttl

        if options['--ssdp-mx']:
            ssdp_mx = int(options['--ssdp-mx'])
            pulseaudio_dlna.plugins.upnp.ssdp.discover.\
                SSDPDiscover.SSDP_MX = ssdp_mx

        if options['--ssdp-amount']:
            ssdp_amount = int(options['--ssdp-amount'])
            pulseaudio_dlna.plugins.upnp.ssdp.discover.\
                SSDPDiscover.SSDP_AMOUNT = ssdp_amount

        msearch_port = options.get('--msearch-port', None)
        if msearch_port != 'random':
            pulseaudio_dlna.plugins.upnp.ssdp.discover.\
                SSDPDiscover.MSEARCH_PORT = int(msearch_port)

        if options['--create-device-config']:
            self.create_device_config()
            sys.exit(0)

        if options['--update-device-config']:
            self.create_device_config(update=True)
            sys.exit(0)

        device_config = None
        if not options['--encoder'] and not options['--bit-rate']:
            device_config = self.read_device_config()

        if options['--encoder-backend']:
            try:
                pulseaudio_dlna.codecs.set_backend(
                    options['--encoder-backend'])
            except pulseaudio_dlna.codecs.UnknownBackendException as e:
                logger.error(e)
                sys.exit(1)

        if options['--encoder']:
            logger.warning('The option "--encoder" is deprecated. '
                           'Please use "--codec" instead.')
        codecs = (options['--encoder'] or options['--codec'])
        if codecs:
            try:
                pulseaudio_dlna.codecs.set_codecs(codecs.split(','))
            except pulseaudio_dlna.codecs.UnknownCodecException as e:
                logger.error(e)
                sys.exit(1)

        bit_rate = options['--bit-rate']
        if bit_rate:
            try:
                pulseaudio_dlna.encoders.set_bit_rate(bit_rate)
            except (pulseaudio_dlna.encoders.InvalidBitrateException,
                    pulseaudio_dlna.encoders.UnsupportedBitrateException) as e:
                logger.error(e)
                sys.exit(1)

        cover_mode = options['--cover-mode']
        try:
            pulseaudio_dlna.covermodes.validate(cover_mode)
        except pulseaudio_dlna.covermodes.UnknownCoverModeException as e:
            logger.error(e)
            sys.exit(1)

        logger.info('Encoder settings:')
        for _type in pulseaudio_dlna.encoders.ENCODERS:
            _type.AVAILABLE = False
        for _type in pulseaudio_dlna.encoders.ENCODERS:
            encoder = _type()
            encoder.validate()
            logger.info('  {}'.format(encoder))

        logger.info('Codec settings:')
        for identifier, _type in pulseaudio_dlna.codecs.CODECS.iteritems():
            codec = _type()
            logger.info('  {}'.format(codec))

        fake_http_content_length = False
        if options['--fake-http-content-length']:
            fake_http_content_length = True
        if options['--fake-http10-content-length']:
            logger.warning(
                'The option "--fake-http10-content-length" is deprecated. '
                'Please use "--fake-http-content-length" instead.')
            fake_http_content_length = True

        disable_switchback = False
        if options['--disable-switchback']:
            disable_switchback = True

        disable_device_stop = False
        if options['--disable-device-stop']:
            disable_device_stop = True

        disable_auto_reconnect = True
        if options['--auto-reconnect']:
            disable_auto_reconnect = False

        pulse_queue = multiprocessing.Queue()
        stream_queue = multiprocessing.Queue()

        stream_server = pulseaudio_dlna.streamserver.ThreadedStreamServer(
            host,
            port,
            pulse_queue,
            stream_queue,
            fake_http_content_length=fake_http_content_length,
            proc_title='stream_server',
        )

        pulse = pulseaudio_dlna.pulseaudio.PulseWatcher(
            pulse_queue,
            stream_queue,
            disable_switchback=disable_switchback,
            disable_device_stop=disable_device_stop,
            disable_auto_reconnect=disable_auto_reconnect,
            cover_mode=cover_mode,
            proc_title='pulse_watcher',
        )

        device_filter = None
        if options['--filter-device']:
            device_filter = options['--filter-device'].split(',')

        locations = None
        if options['--renderer-urls']:
            locations = options['--renderer-urls'].split(',')

        if options['--request-timeout']:
            request_timeout = float(options['--request-timeout'])
            if request_timeout > 0:
                pulseaudio_dlna.plugins.renderer.BaseRenderer.REQUEST_TIMEOUT = \
                    request_timeout

        holder = pulseaudio_dlna.holder.Holder(
            plugins=self.PLUGINS,
            pulse_queue=pulse_queue,
            device_filter=device_filter,
            device_config=device_config,
            proc_title='holder',
        )

        self.run_process(stream_server.run)
        self.run_process(pulse.run)
        if locations:
            self.run_process(holder.lookup, locations)
        else:
            self.run_process(holder.search, host=host)

        setproctitle.setproctitle('pulseaudio-dlna')
        signal.signal(signal.SIGINT, self.shutdown)
        signal.signal(signal.SIGTERM, self.shutdown)
        signal.signal(signal.SIGHUP, self.shutdown)
        signal.pause()
Exemple #56
0
 def testing(self):
     self.button.when_pressed = self.repeatly_turning_on_led
     pause()
Exemple #57
0
 def turn_on_off_led(self):
     self.button.when_released = self.turn_off_led
     self.button.when_pressed = self.led_pulse
     pause()
 def run():
     signal.pause()
Exemple #59
0
 def when_pressed_or_released_print_something(self):
     self.button.when_pressed = self.print_message_pressed
     self.button.when_released = self.print_message_released
     pause()
Exemple #60
0
 def run(self):
     while self.running:
         pause()