Ejemplo n.º 1
0
    def setUp(self):
        """ Get ready to test.
          Read the configs for the target.
          Ensure the Target is running with a clean start  """

        # Read in test setup variables from config file
        configs = readConfigFile(CONFIG_FILE)
        self.base_url = configs["base_url"]
        self.port = configs["port"]
        self.hash_route = configs["hash_route"]
        self.stats_route = configs["stats_route"]
        self.network_latency = int(configs["network_latency"])
        self.server_process_time = int(configs["server_process_time"])
        self.timeout = self.server_process_time + self.network_latency
        self.post_hash_endpoint = "%s:%s/%s" % (self.base_url, self.port,
                                                self.hash_route)
        self.get_stats_endpoint = "%s:%s/%s" % (self.base_url, self.port,
                                                self.stats_route)
        self.server_start_command = "nohup ../target/broken-hashserve_darwin > /dev/null 2>&1 &"

        # Check to see fo the server is running if it is then restart it
        # If it is not then just start it
        if VERBOSE: print("\n\n*** STARTING TEST CASE ***\n")
        r = None
        try:
            r = requests.get(self.get_stats_endpoint)
        except:
            pass
        if r != None:
            # Send shutdown signal
            if VERBOSE: print("Shutting down server ...\n")
            requests.post(self.post_hash_endpoint, data="shutdown")
            time.sleep(3)
        # Start server, Assumes that we know where it is
        c = Command(self.server_start_command)
        if VERBOSE:
            print("Starting Server ...\n")
            print(self.server_start_command)
        c.run()
        time.sleep(2)
        if VERBOSE: print("Server Started.\n")
        return
Ejemplo n.º 2
0
        "%s -- Unable to import the 'requests' third-party library\n" % ERROR)
    sys.stderr.write("         Try: pip3 install requests --user\n\n")
    sys.exit(2)

# Custom library imports
sys.path.append(LIBRARY_PATH)
try:
    from config import readConfigFile
    from api_utils import job_identifier_to_hash
    from sha512 import get_sha512_hash
except:
    sys.stderr.write("%s -- Unable to import custom library\n" % ERROR)
    sys.stderr.write("         Try: git pull\n\n")
    sys.exit(3)

configs = readConfigFile(CONFIG_FILE)
# Test Setup Variables
base_url = configs["base_url"]
port = configs["port"]
hash_route = configs["hash_route"]
stats_route = configs["stats_route"]
network_latency = int(configs["network_latency"])
server_process_time = int(configs["server_process_time"])
timeout = server_process_time + network_latency
post_hash_endpoint = "%s:%s/%s" % (base_url, port, hash_route)

# Quietly try to remove any old results file(s)
try:
    os.remove(RESULTS_FILE)
except:
    pass
            requestAt = time.time()
        else:
            pass
            
        remainingTime = SCREENSHOT_INTERVAL - ( time.time() - startAt )
            
        if( remainingTime > 0.01 ):
            time.sleep( remainingTime )
                    
        
                
###############################################################################    
         
initFilePath = '/etc/osago/terminal'

configs = config.readConfigFile( initFilePath )

ID_TERMINAL = configs['ID_TERMINAL'] 
GATEWAY_UPLOAD_URL = configs['GATEWAY_UPLOAD_URL']
GATEWAY_API_URL = configs['GATEWAY_API_URL']
    
SCREENSHOT_PATH = configs['SCREENSHOT_PATH'];
SCREENSHOTS_DATA_DIR = configs['SCREENSHOTS_DATA_DIR']    
        
SCREENSHOT_INTERVAL = int( configs['SCREENSHOT_INTERVAL'] )    
SCREENSHOT_UPLOAD_INTERVAL = int( configs['SCREENSHOT_UPLOAD_INTERVAL'] )

IS_SCREENSHOTS_ENABLED = configs['IS_SCREENSHOTS_ENABLED'].lower() == 'true'

if( SCREENSHOTS_DATA_DIR[-1] != '/' ):
	SCREENSHOTS_DATA_DIR+='/'
Ejemplo n.º 4
0
                        (mmdiscard, hdiscard, h))


def main(uiServer, fileDir, writeFileFlag, test_mode):
    source = MQTTReader()
    source.start()
    time.sleep(5)
    app = FileWebUpdater(source, fileDir, uiServer, writeFileFlag, test_mode)
    app.start()


if __name__ == "__main__":
    #Usage: python mqttMonStream.py
    parser = argparse.ArgumentParser(
        description=
        'Start a deamon to save mqtt and pyslurm information in file and report to user interface.'
    )
    parser.add_argument('-c',
                        '--configFile',
                        help='The name of the config file.')
    args = parser.parse_args()
    configFile = args.configFile
    if configFile:
        config.readConfigFile(configFile)
    cfg = config.APP_CONFIG
    f_dir = cfg["fileStorage"]["dir"]
    if f_dir and not os.path.isdir(f_dir):
        os.mkdir(f_dir)
    main(cfg['ui']['urls'], cfg['fileStorage']['dir'],
         cfg['fileStorage']['writeFile'], cfg['test'])
                reportNotChanged()
            requestAt = time.time()
        else:
            pass

        remainingTime = SCREENSHOT_INTERVAL - (time.time() - startAt)

        if (remainingTime > 0.01):
            time.sleep(remainingTime)


###############################################################################

initFilePath = '/etc/osago/terminal'

configs = config.readConfigFile(initFilePath)

ID_TERMINAL = configs['ID_TERMINAL']
GATEWAY_UPLOAD_URL = configs['GATEWAY_UPLOAD_URL']
GATEWAY_API_URL = configs['GATEWAY_API_URL']

SCREENSHOT_PATH = configs['SCREENSHOT_PATH']
SCREENSHOTS_DATA_DIR = configs['SCREENSHOTS_DATA_DIR']

SCREENSHOT_INTERVAL = int(configs['SCREENSHOT_INTERVAL'])
SCREENSHOT_UPLOAD_INTERVAL = int(configs['SCREENSHOT_UPLOAD_INTERVAL'])

IS_SCREENSHOTS_ENABLED = configs['IS_SCREENSHOTS_ENABLED'].lower() == 'true'

if (SCREENSHOTS_DATA_DIR[-1] != '/'):
    SCREENSHOTS_DATA_DIR += '/'
Ejemplo n.º 6
0
            cmd = cmd.strip()
            if cmd == "quit":
                stillRunning = False
            if cmd != "":
                logging.info(">> %s", cmd)
                with self.childShellPipeLock:
                    self.childShellPipe.send(cmd)
                serverShellParentPipe.send(cmd)
        logger.info("Server Shell Input Thread terminating.")


if __name__ == "__main__":
    ##    masterMgr = Manager()
    ##
    ##    #Read the configuration file
    config.readConfigFile()
    logging.info("Config read.")
    ##    parentShellPipe, childShellPipe = Pipe()
    ##    childShellPipeLock = masterMgr.Lock()
    ##    serverShellParentPipe, serverShellChildPipe = Pipe()
    ##
    ##    #Start the interactive shell
    ##    displayThread = ServerShellDisplayThread(parentShellPipe)
    ##    displayThread.start()
    ##    logger.debug("Shell display started.")
    ##    inputThread = ServerShellInputThread(childShellPipe, childShellPipeLock, serverShellParentPipe)
    ##    inputThread.start()
    ##    logger.debug("Shell input started.")

    # Fire up the server
Ejemplo n.º 7
0
def startServerConnection(PORT):
    config_file = readConfigFile()

    number_of_clients = 1
    server, inputs, outputs, message_queues = startServerConfiguration(PORT, config_file.clients_number)

    search_bool = True
    playing_bool = False

    exit_token = False
    run = True

    timeout = 1

    while run:
        # Wait for at least one of the sockets to be ready for
        # processing print >>sys.stderr, '\nwaiting for the next event'
        readable, writable, exceptional = select.select(inputs, outputs, inputs, timeout)

        if not (readable or writable or exceptional):
            # print >>sys.stderr, '  Timed out, do some other work here'
            char = get_char_keyboard_nonblock()
            if char is not None:
                if char == 's':
                    if playing_bool:
                        print >> sys.stderr, '  Player already running, it will not inicialize.'
                    else:
                        search_bool = False
                        playing_bool = True
                        print >> sys.stdout, '  Music will start in ' + str(config_file.time_to_start) + ' seconds!'

                        time_stamp = int(time.time() * 1000)
                        time_to_send = time_stamp + (config_file.time_to_start * 1000)

                        message_to_send = "Action:start,StartTime:" + str(time_to_send) + ",ClientPosX:" + \
                                          str(config_file.clientPos[0]) + ",ClientPosY:" + \
                                          str(config_file.clientPos[1]) + ",Song:" + str(-1) + ",SongPosX:" + \
                                          str(config_file.inicialSongPos[0]) + ",SongPosY:" + str(
                            config_file.inicialSongPos[1])

                        notifyClients(inputs[1:], message_queues, outputs, message_to_send)

                if char == 'p':
                    try:
                        client_to_play = int(raw_input("Please enter a client number: "))
                        notifyClientsFlag(inputs[1:], 0, client_to_play, message_queues, outputs)

                    except ValueError:
                        server.close()
                        print >> sys.stderr, '  Oops!  That was no valid number.  Try again...'

                if char == 'c':
                    try:
                        client_pos_x = int(raw_input("Please enter a client position X: "))
                        client_pos_y = int(raw_input("Please enter a client position Y: "))
                        notifyClientsClientPos(inputs[1:], 0, (client_pos_x, client_pos_y), message_queues, outputs)

                    except ValueError:
                        server.close()
                        print >> sys.stderr, '  Oops!  That was no valid number.  Try again...'

                if char == 'f':
                    try:
                        print >> sys.stdout, '  Select one of the next %s songs to change position: ' % str(
                            config_file.number_sounds)
                        cont = 0
                        for songPos in config_file.Sound_List_Pos:
                            print >> sys.stdout, cont, songPos[0]  # , songPos[1][0], songPos[1][1]
                            cont += 1

                        selected_song = int(raw_input("Select: "))
                        print >> sys.stdout, ' Selected: "%s"' % config_file.Sound_List_Pos[selected_song][0]

                        song_pos_x = int(raw_input("Please enter a position X: "))
                        song_pos_y = int(raw_input("Please enter a position Y: "))
                        notifyClientsSongsPos(inputs[1:], 0, selected_song, (song_pos_x, song_pos_y), message_queues,
                                              outputs)

                    except ValueError:
                        server.close()
                        print >> sys.stderr, '  Oops!  That was no valid number.  Try again...'

                if char == 'e':
                    # notifyClientsFlag(inputs[1:], 0, -1, message_queues, outputs)
                    notifyClients(inputs[1:], message_queues, outputs, "Action:exit")
                    exit_token = True
                    if len(inputs[1:]) == 0:
                        break
            continue

        if search_bool:
            # Handle inputs
            for s in readable:
                if s is server:
                    # A "readable" server socket is ready to accept a connection
                    connection, client_address = s.accept()
                    print >> sys.stdout, 'New connection from', client_address
                    connection.setblocking(0)
                    inputs.append(connection)

                    # Give the connection a queue for data we want to send
                    message_queues[connection] = Queue.Queue()

                    notifyOneClient(connection, message_queues, outputs, "Action:identification,ID:{0}".format(str(number_of_clients)))
                    number_of_clients += 1

                else:
                    data = s.recv(1024)
                    if data:
                        # A readable client socket has data
                        print >> sys.stdout, 'Received "%s" from %s' % (data, s.getpeername())

                        # Respond client
                        # message_queues[s].put(data)
                        # Add output channel for response
                        # if s not in outputs:
                        #   outputs.append(s)
                    else:
                        # Interpret empty result as closed connection
                        print >> sys.stderr, 'Closing', client_address, 'after reading no data'
                        # Stop listening for input on the connection
                        if s in outputs:
                            outputs.remove(s)
                        inputs.remove(s)
                        s.close()

                        # Remove message queue
                        del message_queues[s]

        # Handle outputs
        for s in writable:
            try:
                next_msg = message_queues[s].get_nowait()
            except Queue.Empty:
                # No messages waiting so stop checking for writability.
                # print >> sys.stderr, 'Output queue for', s.getpeername(), 'is empty'
                outputs.remove(s)
                if exit_token:
                    run = False
            else:
                print >> sys.stdout, 'Sending "%s" to %s' % (next_msg, s.getpeername())
                s.send(next_msg)
    print "Server is closing."
    server.close()