Exemplo n.º 1
0
def standalone_server(bin_prefix, tmp_path):
    server = ServerThread(bin_prefix, str(tmp_path))
    server.start()
    wait_result = server.wait()

    if wait_result is not None:
        with open(os.path.join(server.log_dir, 'server', 'stdout.txt'),
                  'r') as f:
            print >> sys.stderr, f.read()
        with open(os.path.join(server.log_dir, 'server', 'stderr.txt'),
                  'r') as f:
            print >> sys.stderr, f.read()
        pytest.fail('Server died unexpectedly with code {code}'.format(
            code=server._proc.returncode),
                    pytrace=False)

    yield server

    server.stop()
Exemplo n.º 2
0
    def test_validation_2_3(self):
        """ test_validation_3
        Filter 2 against filter_validation 3
        """
        saved = SavedFilter(self.lc, 2)

        # Get loan list
        response = self.lc.session.get('/filter_validation', query={'id': 3})
        json_response = response.json()
        self.loan_list = json_response['loanFractions']

        # Validate, should fail on 'exclude_invested'
        try:
            saved.validate(self.loan_list)
            assert False, 'Test should fail on grade'
        except FilterValidationError as e:
            print e.criteria
            self.assertTrue(matches('grade', e.criteria))


if __name__ == '__main__':
    # Start the web-server in a background thread
    http = ServerThread()
    http.start()

    # Run tests
    unittest.main()

    # Stop threads
    http.stop()
Exemplo n.º 3
0
        """
        self.order.add_batch([
            {
                'loan_id': 123,
                'invest_amount': 50
            }, {
                'loan_id': 234,
                'invest_amount': 75
            }
        ])

        order_id = self.order.execute()
        self.assertNotEqual(order_id, 0)

        self.assertRaises(
            AssertionError,
            lambda: self.order.execute()
        )


if __name__ == '__main__':
    # Start the web-server in a background thread
    http = ServerThread()
    http.start()

    # Run tests
    unittest.main()

    # Stop threads
    http.stop()
Exemplo n.º 4
0
class MHServerTaskView(gui3d.TaskView):

    human = None  # Reference to the in-scene human
    toggle = None  # Toggle button for server enable / disable
    logbox = None  # Log view of any server spew
    server = None  # ServerThread instance

    def __init__(self, category):
        """ Constructor for the TaskView.  This accepts the category under which
            this feature is enabled.

            The category is registered with the app and passed into this
            constructor on the `load()` API below.
        """
        self.human = gui3d.app.selectedHuman
        gui3d.TaskView.__init__(self, category, "MHServer")

        fr_left = self.addLeftWidget(gui.GroupBox("Settings:"))
        self.txt_port = fr_left.addWidget(gui.TextEdit(text="18830"))
        self.btn_restart = fr_left.addWidget(gui.Button("Restart"))

        @self.btn_restart.mhEvent
        def onClicked(e):
            self.restart_server()

        self.logbox = self.addTopWidget(gui.DocumentEdit())
        self.logbox.setText("")
        self.logbox.setLineWrapMode(gui.DocumentEdit.NoWrap)

    def bootstrap(self, app):
        """ `bootstrap` allows this TaskView to figure out dependent task views
            to trigger downstream functions.
        """

        self.pose_lib = app.getTask("Pose/Animate", "Pose")
        self.skel_lib = app.getTask("Pose/Animate", "Skeleton")

        self.clothes_lib = app.getTask("Geometries", "Clothes")
        self.eyebrows_lib = app.getTask("Geometries", "Eyebrows")
        self.eyes_lib = app.getTask("Geometries", "Eyes")
        self.topologies_lib = app.getTask("Geometries", "Topologies")
        self.eyelashes_lib = app.getTask("Geometries", "Eyelashes")
        self.hair_lib = app.getTask("Geometries", "Hair")
        self.teeth_lib = app.getTask("Geometries", "Teeth")
        self.tongue_lib = app.getTask("Geometries", "Tongue")

    def log(self, msg):
        """ Logs a message to the text box `log`.
        """
        self.logbox.addText(msg + "\n")
        if self.server:
            self.server.broadcast(str(msg))

    def command(self, msg, conn=None):
        words = str(msg).rstrip().split(" ")
        cmd, args = words[0], words[1:]
        factory.run(self, cmd, args)

    def start_server(self):
        self.log("Trying to start server thread ...")
        self.server = ServerThread(port=int(self.txt_port.text, 10))
        self.logbox.connect(self.server, SIGNAL("log(QString)"), self.log)
        self.logbox.connect(self.server, SIGNAL("command(QString)"),
                            self.command)

        self.server.set_taskview(self)
        self.server.start()

    def stop_server(self):
        self.log("Trying to close server thread ...")
        if self.server is None:
            return

        self.server.stop()
        self.server = None

    def restart_server(self):
        self.stop_server()
        self.start_server()

    """ -----------------------------------------------------------------------

        Registered makehuman commands.

    """
    """ Modeling :: Main
    """

    @factory.register(
        "set_age", "Set the human's age",
        ["value", float, 0, "parameter value (between 1.0 and 90.0"])
    def set_age(self, age):
        age = min(max(age, 1.0), 90.0)
        G.mhapi.modifiers.setAge(age)

    @factory.register(
        "set_weight", "Set the human's weight",
        ["value", float, 0, "parameter value (between 50%% and 150%%"])
    def set_weight(self, weight):
        weight = min(max(weight, 50.0), 150.0)
        G.mhapi.modifiers.setWeight(weight)

    @factory.register(
        "set_muscle", "Set the human's muscle",
        ["value", float, 0, "parameter value (between 0%% and 100%%"])
    def set_muscle(self, muscle):
        muscle = min(max(muscle, 0.0), 100.0)
        G.mhapi.modifiers.setMuscle(muscle)

    @factory.register("set_height", "Set the human's height",
                      ["value", float, 0, "parameter value (in cm)"])
    def set_height(self, height):
        G.mhapi.modifiers.setHeight(height)

    @factory.register("set_gender", "Set the human's gender", [
        "value", float, 0, "parameter value (100%% is female and 0%% is male"
    ])
    def set_gender(self, gender):
        gender = min(max(gender, 0.0), 100.0)
        G.mhapi.modifiers.setGender(gender)

    """ ------------------------------------------------------------------- """
    """ Geometries :: Clothes
    """

    @factory.register(
        "add_clothes",
        "Set the human's clothes -- these are addititve (see remove_clothes)",
        [
            "clothes_path", str,
            "data/clothes/male_casualsuit02/male_casualsuit02.mhclo",
            "path to clothes file"
        ])
    def add_clothes(self, clothes_path):
        self.clothes_lib.selectProxy(clothes_path)

    @factory.register(
        "remove_clothes",
        "Remove the human's clothes -- these are addititve (see add_clothes)",
        [
            "clothes_path", str,
            "data/clothes/male_casualsuit02/male_casualsuit02.mhclo",
            "path to clothes file"
        ])
    def remove_clothes(self, clothes_path):
        self.clothes_lib.deselectProxy(clothes_path)

    """ Geometries :: Eyes
    """

    @factory.register(
        "set_eyes", "Set the human's eyes -- should always set low-poly", [
            "eyes_path", str, "data/eyes/low-poly/low-poly.mhclo",
            "path to eyes file"
        ])
    def set_eyes(self, eyes_path):
        self.eyes_lib.selectProxy(eyes_path)

    """ Geometries :: Hair
    """

    @factory.register("set_hair", "Set the human's hair", [
        "hair_path", str, "data/hair/afro01/afro01.mhclo", "path to hair file"
    ])
    def set_hair(self, hair_path):
        self.hair_lib.selectProxy(hair_path)

    """ Geometries :: Teeth
    """

    @factory.register("set_teeth", "Set the human's teeth", [
        "teeth_path", str, "data/teeth/teeth_shape01/teeth_shape01.mhclo",
        "path to teeth file"
    ])
    def set_teeth(self, teeth_path):
        self.teeth_lib.selectProxy(teeth_path)

    """ Geometries :: Topologies
    """

    @factory.register("set_topologies", "Set the human's topologies",
                      ["topologies_path", str, "", "path to topologies file"])
    def set_topologies(self, topologies_path):
        self.topologies_lib.selectProxy(topologies_path)

    """ Geometries :: Eyebrows
    """

    @factory.register("set_eyebrows", "Set the human's eyebrows", [
        "eyebrows_path", str, "data/eyebrows/eyebrow001/eyebrow001.mhclo",
        "path to eyebrows file"
    ])
    def set_eyebrows(self, eyebrows_path):
        self.eyebrows_lib.selectProxy(eyebrows_path)

    """ Geometries :: Eyelashes
    """

    @factory.register("set_eyelashes", "Set the human's eyelashes", [
        "eyelashes_path", str, "data/eyelashes/eyelashes02/eyelashes02.mhclo",
        "path to eyelashes file"
    ])
    def set_eyelashes(self, eyelashes_path):
        self.eyelashes_lib.selectProxy(eyelashes_path)

    """ Geometries :: Tongue
    """

    @factory.register("set_tongue", "Set the human's tongue",
                      ["tongue_path", str, None, "path to tongue file"])
    def set_tongue(self, tongue_path):
        self.tongue_lib.selectProxy(tongue_path)

    """ ------------------------------------------------------------------- """
    """ Pose/Animate :: Skeleton
    """

    @factory.register(
        "set_skeleton",
        "Set the human's skeleton from the specified .mhskel file", [
            "skel_path", str, "data/rigs/game_engine.mhskel",
            "path to .mhskel file"
        ])
    def set_skeleton(self, skel_path):
        self.skel_lib.filechooser.onFileSelected(skel_path)

    """ Pose/Animate :: Pose
    """

    @factory.register(
        "set_pose", "Set the human's pose to the specified bvh file",
        ["pose_path", str, "data/poses/tpose.bvh", "path to pose file"])
    def set_pose(self, pose_path):
        self.pose_lib.filechooser.onFileSelected(pose_path)
Exemplo n.º 5
0
class ServerThreadManager(Thread):
    '''
        A server thread manager functionality
        
        It periodically verifies the server thread's state, in the case of 
        blocking it restarts the thread.
    '''
    def __init__(self,
                 threadID,
                 server_address,
                 broadcast_ip,
                 host_ip,
                 negotiation_port,
                 subscription_port,
                 car_subscription_port,
                 car_communication_port,
                 max_wait_time_for_server,
                 logFile=None):
        '''
        Decide which simulated GPS starts the server.
        
        Arguments:
            threadID {int}                      -- the thread id
            server_address {str}                -- the server address
            broadcast_ip {str}                  -- broadcast IP address
            host_ip {str}                       -- localhost IP address
            negotiation_port {int}              -- negotiation port 
            subscription_port {int}             -- subscription port used to 
                                                 transmite the data from the 
                                                 detectors to the server
            car_subscription_port {int}         -- port used for the vechile 
                                                 client to subscribe on the 
                                                 server
            car_communication_port {int}        -- port used for trasmiting the 
                                                 data from the server to the 
                                                 clients
            max_wait_time_for_server {float}    -- maximum waiting time to 
                                                 receive a beacon from 
                                                 the server
        
        '''

        Thread.__init__(self)
        self.name = 'ServerManager'
        self.threadID = threadID
        self.logFile = logFile

        self.server_address = server_address
        self.beacon_thread = None
        self.server_thread = None
        self.forwarding_thread = None
        self.carSubscriber_thread = None
        self.carMap = None

        self.broadcast_ip = broadcast_ip
        self.host_ip = host_ip
        self.negotiation_port = negotiation_port
        self.subscription_port = subscription_port
        self.car_subscription_port = car_subscription_port
        self.car_communication_port = car_communication_port
        self.max_wait_time_for_server = max_wait_time_for_server

        self.runningThread = True

    #================================ NEGOTIATION SERVER  =====================
    def NegotiateServer(self):
        '''
            Function that decides which simulated GPS starts the server.
        '''

        print("Negotiation start!")
        s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)
        s.bind(('', self.negotiation_port))
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

        randTime = 10 * self.max_wait_time_for_server * random.random()
        wait_time = 2 + math.floor(randTime) / 100

        print("Waiting " + str(wait_time) + " seconds for server")

        t = time.time()
        server = []
        try:
            # listen for server broadcast
            s.settimeout(wait_time)
            data, SERVER_IP = s.recvfrom(1500, 0)
            # server beacon received
            s.close()
            print("Server started on " + str((SERVER_IP[0])))

            # store server info
            self.server_address.ip = str(SERVER_IP[0])
            self.server_address.port = self.subscription_port
        except KeyboardInterrupt:
            print('KeyboardInterrupt')
        except Exception as e:
            print("No response, starting server here", e)
            s.sendto(bytes(self.host_ip, "UTF-8"),
                     (self.broadcast_ip, self.negotiation_port))
            s.close()

            self.stopAllThread()

            self.server_address.ip = self.host_ip
            self.server_address.port = self.subscription_port
            if (self.logFile != None):
                log_message = 'NegotiateServer- server address %s' % str(
                    self.server_address)
                self.logFile.saveWithDate(log_message)

            self.carMap = Data4CarMap(256)

            # thread responsible for broadcasting itself as the server
            self.beacon_thread = ServerBeaconThread(
                threadID=self.threadID + 1,
                host_ip=self.host_ip,
                broadcast_ip=self.broadcast_ip,
                negotiation_port=self.negotiation_port,
                sleepDuration=1.9,
                logFile=self.logFile)
            self.beacon_thread.start()

            # thread responsible for collecting GPS data from clients
            self.server_thread = ServerThread(
                threadID=self.threadID + 2,
                address=self.server_address.asTuple(),
                carMap=self.carMap,
                logFile=self.logFile)
            self.server_thread.start()

            # thread responsible for sending GPS data to each registered vehicle
            self.forwarding_thread = Forward2CarThread(
                threadID=self.threadID + 3,
                car_communication_port=self.car_communication_port,
                carMap=self.carMap,
                period=1.0,
                logFile=self.logFile)
            self.forwarding_thread.start()

            # thread responsible for registering vehicles
            self.carSubscriber_thread = Listen4CarSubscriberThread(
                threadID=self.threadID + 4,
                host_ip=self.host_ip,
                car_subscription_port=self.car_subscription_port,
                carMap=self.carMap,
                logFile=self.logFile)
            self.carSubscriber_thread.start()

        print(str(time.time() - t) + " seconds elapsed")

    #================================ STOP ====================================
    def stopAllThread(self):
        '''
            Function responsible for stoppinf all threads
        '''
        #beacon thread
        if self.beacon_thread != None:
            self.beacon_thread.stop()
            if (self.beacon_thread.is_alive()):
                self.beacon_thread.join()
                self.beacon_thread = None
            print("beacon_thread stoped!")

        #server thread
        if self.server_thread != None:
            self.server_thread.stop()
            if (self.server_thread.is_alive()):
                self.server_thread.join()
                self.server_thread = None
            print("server_thread stoped!")

        #forwarding thread
        if self.forwarding_thread != None:
            self.forwarding_thread.stop()
            if (self.forwarding_thread.is_alive()):
                self.forwarding_thread.join()
                self.forwarding_thread = None
            print("forwarding_thread stoped!")

        #car subscriber thread
        if self.carSubscriber_thread != None:
            self.carSubscriber_thread.stop()
            if (self.carSubscriber_thread.is_alive()):
                self.carSubscriber_thread.join()
                self.carSubscriber_thread = None
            print("carSubscriber_thread stoped!")

    #================================ RUN THREADS =============================
    def run(self):
        while (self.runningThread):
            if (self.beacon_thread != None
                    and not self.beacon_thread.is_alive()):
                print("Restart beacon thread")
                self.logFile.saveWithDate("Restart beacon thread")
                self.beacon_thread = ServerBeaconThread(
                    threadID=self.threadID + 1,
                    host_ip=self.host_ip,
                    broadcast_ip=self.broadcast_ip,
                    negotiation_port=self.negotiation_port,
                    sleepDuration=1.9,
                    logFile=self.logFile)
                self.beacon_thread.start()

            if (self.server_thread != None
                    and not self.server_thread.is_alive()):
                print("Restart server thread")
                self.logFile.saveWithDate("Restart server thread")
                self.server_thread = ServerThread(
                    threadID=self.threadID + 2,
                    address=self.server_address.asTuple(),
                    carMap=self.carMap,
                    logFile=self.logFile)
                self.server_thread.start()

            if (self.forwarding_thread != None
                    and not self.forwarding_thread.is_alive()):
                print("Restart forwarding thread")
                self.logFile.saveWithDate("Restart forwarding thread")
                self.forwarding_thread = Forward2CarThread(
                    threadID=self.threadID + 3,
                    car_communication_port=self.car_communication_port,
                    carMap=self.carMap,
                    period=1.0,
                    logFile=self.logFile)
                self.forwarding_thread.start()

            if (self.carSubscriber_thread != None
                    and not self.carSubscriber_thread.is_alive()):
                print("Restart carSubscriber thread")
                self.logFile.saveWithDate("Restart carSubscriber thread")
                self.carSubscriber_thread = Listen4CarSubscriberThread(
                    threadID=self.threadID + 4,
                    host_ip=self.host_ip,
                    car_subscription_port=self.car_subscription_port,
                    carMap=self.carMap,
                    logFile=self.logFile)
                self.carSubscriber_thread.start()

            if (self.server_address.ip == ''
                    and self.server_address.port == -1):
                self.NegotiateServer()
            time.sleep(1.1)

    #============================= STOP =======================================
    def stop(self):
        self.runningThread = False