Example #1
0
def stop_server():
    with lock:
        app.config['TARGETS'].clear()
        app.config['USERS'].clear()
    if worker.is_alive():
        worker.shutdown()
        worker.join()
    if bot.is_alive():
        bot.shutdown()
        bot.join()
    store_tasks(task_pool)
    with lock:
        for c in active_connections:
            try:
                c.cancel()
            except (DatabaseError, OperationalError):
                pass
    f = request.environ.get('werkzeug.server.shutdown')
    if f:
        f()
        return 'Good bye.'
    elif request.environ.get('uwsgi.version'):
        import uwsgi
        uwsgi.stop()
        return 'Good bye.'
    else:
        return 'Web server does not recognized, kill it manually.'
    def subscribe(self, channel, client_uuid=None, maxsize=None, timeout=settings.DEFAULT_SUBSCRIPTION_TIMEOUT, try_=1):
        """
        Subscribe to channel and store additional_data in channel_data with it.
        """
        queue = Queue(maxsize=maxsize)

        client_uuid = client_uuid or uuid.uuid1()
        self.client_data[channel][client_uuid] = queue

        if channel in self.channel_data:
            subscribe_event = self.channel_data[channel]
        else:
            subscribe_event = Event()
            self.channel_data[channel] = subscribe_event
            self.pubsub.subscribe(channel)

        if not self.pubsub_thread:
            self.pubsub_thread = gevent.spawn(self.listen)

        # If subscribe event timed out, reset connection
        if not subscribe_event.wait(timeout):
            self.channel_data[channel] = Event()
            self.reset()
            gevent.sleep(0.1)

            if try_ > self.SUBSCRIBE_MAX_TRIES:
                uwsgi.stop()

                raise RuntimeError('Subscribe failed. Max tries exceeded.')

            return self.subscribe(channel, client_uuid, maxsize, timeout, try_ + 1)

        return queue
Example #3
0
File: webd.py Project: DevMK2/tools
def cnc_command():
    p = request.json

    if p['command'] == 'estop':
        if p['arg']:
            stop_homing()
            emc_command.state(emc.STATE_ESTOP)
        else:
            stop_homing()
            emc_command.state(emc.STATE_ESTOP_RESET)
    elif p['command'] == 'power':
        if p['arg']:
            stop_homing()
            emc_command.mode(emc.MODE_MANUAL)
            emc_command.wait_complete()
            emc_command.state(emc.STATE_ON)
        else:
            stop_homing()
            emc_command.mode(emc.MODE_MANUAL)
            emc_command.wait_complete()
            emc_command.state(emc.STATE_OFF)
    elif p['command'] == 'run':
        emc_command.mode(emc.MODE_AUTO)
        emc_command.wait_complete()
        emc_command.auto(emc.AUTO_RUN, 1)
    elif p['command'] == 'stop':
        emc_command.abort()
        emc_command.wait_complete()
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.wait_complete()
    elif p['command'] == 'pause':
        if p['arg']:
            emc_stat.poll()
            if emc_stat.task_mode != emc.MODE_AUTO or\
                    emc_stat.interp_state not in (emc.INTERP_READING, emc.INTERP_WAITING):
                return
            ensure_mode(emc_stat, emc_command, emc.MODE_AUTO)
            emc_command.auto(emc.AUTO_PAUSE)
        else:
            emc_stat.poll()
            if not emc_stat.paused:
                return
            if emc_stat.task_mode not in (emc.MODE_AUTO, emc.MODE_MDI):
                return
            ensure_mode(emc_stat, emc_command, emc.MODE_AUTO, emc.MODE_MDI)
            emc_command.auto(emc.AUTO_RESUME)
    elif p['command'] == 'step':
        ensure_mode(emc_stat, emc_command, emc.MODE_AUTO)
        emc_command.auto(emc.AUTO_STEP)
    elif p['command'] == 'homeall':
        do_homing()
    elif p['command'] == 'unhomeall':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.unhome(-1)
    elif p['command'] == 'feedrate':
        emc_command.feedrate(float(p['arg']))
    elif p['command'] == 'spindlerate':
        emc_command.spindleoverride(float(p['arg']))
    elif p['command'] == 'maxvelocity':
        emc_command.maxvel(float(p['arg']))
    elif p['command'] == 'mist':
        emc_command.mist(1 if p['arg'] else 0)
    elif p['command'] == 'flood':
        emc_command.flood(1 if p['arg'] else 0)
    elif p['command'] == 'spindle_forward':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.spindle(1, 100)
    elif p['command'] == 'spindle_backward':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.spindle(-1, 100)
    elif p['command'] == 'spindle_stop':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.spindle(0)
    elif p['command'] == 'spindle_inc':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.spindle(emc.SPINDLE_INCREASE)
    elif p['command'] == 'spindle_dec':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.spindle(emc.SPINDLE_DECREASE)
    elif p['command'] == 'jog':
        direction = p['arg']['direction']
        axis = p['arg']['axis']
        mode_ready = ensure_mode(emc_stat, emc_command, emc.MODE_MANUAL)
        if mode_ready is True:
            if direction == 0:
                emc_command.jog(emc.JOG_STOP, axis)
            else:
                distance = p['arg']['distance']
                rate = p['arg']['rate']

                if distance == 0:
                    emc_command.jog(emc.JOG_CONTINUOUS, axis, direction * rate)
                else:
                    length = [0.001, 0.01, 0.1, 1, 10]
                    emc_command.jog(emc.JOG_INCREMENT, axis, direction * rate, length[distance - 1] * units)
    elif p['command'] == 'jog_direct':
        position = float(p['arg']['position'])
        axis = p['arg']['axis']

        emc_command.mode(emc.MODE_MANUAL)
        #set_motion_mode()
        rate = p['arg']['rate']
        emc_command.jog(emc.JOG_ABSOLUTE, axis, rate, position)
    elif p['command'] == 'shutdown':
        os.system('/sbin/shutdown -h now')
    elif p['command'] == 'reset':
        #request.environ.get('werkzeug.server.shutdown')()
        uwsgi.stop()
    elif p['command'] == 'mdi':
        emc_command.mode(emc.MODE_MDI)
        if p['arg']:
            emc_command.mdi(p['arg']['command'])
    elif p['command'] == 'blow':
        halcomp['blow'] = p['arg']
    elif p['command'] == 'vacuum':
        halcomp['vacuum'] = p['arg']
    elif p['command'] == 'touch':
        halcomp['touch'] = p['arg']
    elif p['command'] == 'dresser':
        if p['arg'] == True :
            halcomp['dresseb'] = not p['arg']
            halcomp['dressef'] = p['arg']
        elif p['arg'] == False :
            halcomp['dressef'] = p['arg']
            halcomp['dresseb'] = not p['arg']
    elif p['command'] == 'dseal':
        halcomp['dseal'] = p['arg']
    elif p['command'] == 'zcyl':
        if p['arg'] == True :
            halcomp['zcyl2'] = not p['arg']
            halcomp['zcyl1'] = p['arg']
        elif p['arg'] == False :
            halcomp['zcyl1'] = p['arg']
            halcomp['zcyl2'] = not p['arg']
    elif p['command'] == 'ygclamp':
        halcomp['ygclamp'] = p['arg']
    elif p['command'] == 'zclamp':
        halcomp['zclamp'] = p['arg']
    elif p['command'] == 'fourR':
        halcomp['fourR'] = p['arg']
    elif p['command'] == 'ygmode':
        if ini.find('EMC', 'MODE') == 'YG' :
            os.system('/home/jmac/linuxcnc/configs/mode.sh UGM060Y')
            request.environ.get('werkzeug.server.shutdown')()
        elif ini.find('EMC', 'MODE') == 'Y' :
            os.system('/home/jmac/linuxcnc/configs/mode.sh UGM060YG')
            request.environ.get('werkzeug.server.shutdown')()
        
    elif p['command'] == 'test':
        halcomp['test'] = p['arg']

    # survo on off    
    elif p['command'] == 'jog_on':
        emc_command.teleop_enable(0)
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.wait_complete()
        emc_command.set_axis_on(int(p['axis']))
    elif p['command'] == 'jog_off':
        emc_command.mode(emc.MODE_MANUAL)
        emc_command.wait_complete()
        emc_command.set_axis_off(int(p['axis']))

    elif p['command'] == 'jogdial':
        mode_ready = ensure_mode(emc_stat, emc_command, emc.MODE_MANUAL)
        if mode_ready is True:
            halcomp['jog-scale'] = float(p['arg']['scale'])
            halcomp['jog-x'] = 0
            halcomp['jog-y'] = 0
            halcomp['jog-z'] = 0
            halcomp['jog-c'] = 0
            halcomp['jog-d'] = 0
            if(p['arg']['axis']==0) : 
                halcomp['jog-x'] = 1
                if  p['act'] == 'set':
                    halcomp['jog-count-latest'] = halcomp['jog0-wheel']
                elif p['act'] == 'wheel':
                    halcomp['jog0-wheel'] = halcomp['jog-count-latest'] + int(p['arg']['dial'])
            elif(p['arg']['axis']==1) : 
                halcomp['jog-y'] = 1
                if  p['act'] == 'set':
                    halcomp['jog-count-latest'] = halcomp['jog1-wheel']
                elif p['act'] == 'wheel':
                    halcomp['jog1-wheel'] = halcomp['jog-count-latest'] + int(p['arg']['dial'])
            elif(p['arg']['axis']==2) : 
                halcomp['jog-z'] = 1
                if  p['act'] == 'set':
                    halcomp['jog-count-latest'] = halcomp['jog2-wheel']
                elif p['act'] == 'wheel':
                    halcomp['jog2-wheel'] = halcomp['jog-count-latest'] + int(p['arg']['dial'])
            elif(p['arg']['axis']==3) : 
                halcomp['jog-c'] = 1
                if  p['act'] == 'set':
                    halcomp['jog-count-latest'] = halcomp['jog3-wheel']
                elif p['act'] == 'wheel':
                    halcomp['jog3-wheel'] = halcomp['jog-count-latest'] + int(p['arg']['dial'])
            elif(p['arg']['axis']==4) : 
                halcomp['jog-d'] = 1
                if  p['act'] == 'set':
                    halcomp['jog-count-latest'] = halcomp['jog4-wheel']
                elif p['act'] == 'wheel':
                    halcomp['jog4-wheel'] = halcomp['jog-count-latest'] + int(p['arg']['dial'])
            
    
    elif p['command'] == 'h1pressure':
        halcomp['H1.pressure'] = int(p['arg'])
    elif p['command'] == 'h2pressure':
        halcomp['H2.pressure'] = int(p['arg'])   

    return '{result:"ok"}'
Example #4
0
def routing(signum):
    state = getmemorystate()
    current_workers_tasks = state["current_workers_tasks"]
    workers_tasks = state["workers_tasks"]
    # reload
    if state.has_key("stoping"):
        print "seems we are reload"
        print "let's start"
        if not len(current_workers_tasks.keys()):
            print "oo there is no tasks"
            print uwsgi.workers()
            del state["stoping"]
            setmemorystate(state)
            uwsgi.reload()
        return

    # stop
    if state.has_key("stop"):
        print "seems we are stoping"
        print "let's start"
        if not len(current_workers_tasks.keys()):
            print "oo there is not tasks"
            print uwsgi.workers()
            uwsgi.stop()
        return
    # working or not
    if state.has_key("working") and state["working"]:
        print "working"
    else:
        print "idle"
        return

    # choose command to start
    tmp_commands = commands.copy()
    for working_task in current_workers_tasks.keys():
        print "delete %s " % current_workers_tasks[working_task]["comand_key"]
        del tmp_commands[current_workers_tasks[working_task]
                         ["comand_key"]]  # there is no possible exception here

    # if comman is existed in past half of length also do not start
    cmds = tmp_commands.keys()
    past_length = len(cmds) / 2
    for past_work in workers_tasks[-1 * past_length:]:
        try:
            del tmp_commands[past_work]  #but here it seems to be
        except KeyError:
            print "%s is already deleted  from possible executin" % past_work

    cmds = tmp_commands.keys()
    to_start_command = None
    if len(cmds):
        to_start_command = random.choice(cmds)
    else:
        print "it's seems that everything is working recently, do not let workers to be lazy"
        to_start_command = random.choice(commands.keys())

    workers_signal_tmp = workers_signal[:]
    for busy_worker in current_workers_tasks.keys():
        print "delete from choice busy worker %i" % busy_worker
        workers_signal_tmp.remove(busy_worker)

    if len(workers_signal_tmp) > 0:
        print "choosing from the workers"
        print workers_signal_tmp
        number_of_signal = random.choice(workers_signal_tmp)
        workers_tasks.append(to_start_command)

        # write to shard memory index of  command
        state["to_start"] = to_start_command
        current_workers_tasks[number_of_signal] = {
            "started": datetime.now(),
            "comand_key": to_start_command,
            "command": commands[to_start_command]
        }
        state["workers_tasks"] = workers_tasks[
            -300:]  # only 300 save in history
        state["current_workers_tasks"] = current_workers_tasks
        setmemorystate(state)

        try:
            print "ok sending signal %i" % number_of_signal
            print "and going start %s" % str(commands[to_start_command])
            print "and going start %s" % to_start_command
            uwsgi.signal(number_of_signal)
            print workers_tasks
        except:
            traceback.print_exc()
            print "oh no %i busy" % number_of_signal
    else:
        print "=" * 64
        print "there is no free workers ?!"
        print "=" * 64

    print "busy workers "
    nw = datetime.now()
    for working_id in current_workers_tasks.keys():
        print "%i -> %s" % (working_id, str(current_workers_tasks[working_id]))
        working_delta = nw - current_workers_tasks[working_id]["started"]
        if working_delta > dt(minutes=5):
            print "this process seems to be stuck"
            print "%i -> %s" % (
                working_id, str(current_workers_tasks[working_id]["command"]))
Example #5
0
 def uwsgi_stop(ctx):
     uwsgi.stop()