Esempio n. 1
0
def main():
    host = sys.argv[1]
    port = sys.argv[2]
    server = SimpleXMLRPCServer((host, int(port)), allow_none=True)
    server.register_introspection_functions()
    server.register_instance(ChunkServer(host, port))
    server.serve_forever()
Esempio n. 2
0
class NetServer(Thread):
    def __init__(self, port=8080, logRequests=True):
        Thread.__init__(self)
        self.__port = port
        self.__logRequests = logRequests
        self.__server = None
        self.__running = False
        self.State = None
        self.start()
        while not self.__running:
            sleep(0)

    def stop(self):
        if self.State is not None:
            self.State.set_update_period(0)
        self.__server.shutdown()
        self.__server.server_close()
        self.join()

    def run(self):
        #register API
        self.State = NetServerState(
        )  # accessor for state object for tests and shutting down, etc
        self.__server = SimpleXMLRPCServer(("127.0.0.1", self.__port),
                                           CrossDomainXMLRPCRequestHandler,
                                           logRequests=self.__logRequests)
        self.__server.register_instance(self.State)
        self.__server.register_introspection_functions()

        #start server
        self.__running = True
        self.__server.serve_forever()
Esempio n. 3
0
class MasterServerProcess(multiprocessing.Process):
    quit = False

    def __init__(self, myIP, myPortNum, token, ready):
        multiprocessing.Process.__init__(self)
        #self.setDaemon(True)
        self.daemon = True
        self.server = SimpleXMLRPCServer((myIP, int(myPortNum)),
                                         requestHandler=RequestHandler,
                                         allow_none=True)
        self.server.register_introspection_functions()

        myFuncs = MyFuncs(token, ready)
        self.funcs = myFuncs
        self.server.register_instance(myFuncs)

    def run(self):
        # self.server.serve_forever()
        while not self.quit:
            self.server.handle_request()

    def stop_server(self):
        self.quit = True
        self.server.server_close()
        print("here")

        return 0
Esempio n. 4
0
def main():
    process_name = 'interp_python'
    killall(process_name) # kill previous instance if running
    set_process_name(process_name)
    tmp_dir = '/tmp/interp_python'
    shutil.rmtree(tmp_dir, ignore_errors = True)
    os.mkdir(tmp_dir)
    # with open(os.path.join(tmp_dir, 'pid'), 'w') as f:
    #     f.write(str(os.getpid()) + '\n')
    log_file = os.path.join(tmp_dir, 'log')
    log_handler = logging.handlers.RotatingFileHandler(log_file,
                                                       backupCount = 1,
                                                       maxBytes = 4 * 1024 * 1024)
    log_handler.setLevel(logging.INFO)
    global log
    log = logging.getLogger()
    log.setLevel(logging.INFO)
    log.addHandler(log_handler)
    global common
    common = import_module('interp_python_common.py')
    global request_num
    request_num = 0
    global separator
    separator = '-' * 80
    # sys.exit()
    # Create server:
    server = SimpleXMLRPCServer(('localhost', 8000), requestHandler = RequestHandler)
    server.register_introspection_functions()
    server.register_function(execute)
    server.serve_forever() # run the server's main loop
Esempio n. 5
0
	def xmlrpc_run(self, port=13100, bind='127.0.0.1', logRequests=False):
		'''Run xmlrpc server'''
		import umsgpack
		try:
			from xmlrpc.server import SimpleXMLRPCServer
			from xmlrpc.client import Binary
		except ImportError:
			from SimpleXMLRPCServer import SimpleXMLRPCServer
			from xmlrpclib import Binary

		logger.info("bloomfilter starting...")

		server = SimpleXMLRPCServer((bind, port), allow_none=True, logRequests=logRequests)
		server.register_introspection_functions()
		server.register_multicall_functions()

		server.register_function(self.quit, '_quit')

		server.register_function(self.add, 'add')

		server.timeout = 0.5
		while not self._quit:
			server.handle_request()

		logger.info("bloomfilter exiting...")
		server.server_close()
Esempio n. 6
0
def main():
    # Parse CLI options
    import argparse
    cli_parser = argparse.ArgumentParser(
        description="XML-RPC server for filtering recommendations."
        )

    # Add verbosity option
    cli_parser.add_argument('-v', '--verbose', action='store_true',
                            help='Be more verbose')
    args = cli_parser.parse_args()

    if args.verbose:
        logging.basicConfig(level=logging.INFO)

    filterServer = RecFilter()
    server = SimpleXMLRPCServer(
        (config.filter_server_hostname, config.filter_server_hostport),
        allow_none=True)

    server.register_introspection_functions()
    server.register_function(filterServer.getRecs, 'getrecs')
    print("Filter-server is running...")

    # Run the server's main loop
    server.serve_forever()
Esempio n. 7
0
def main():
    server = SimpleXMLRPCServer(('127.0.0.1', 7001))
    server.register_introspection_functions()
    server.register_multicall_functions()
    server.register_function(send)
    print("Server ready")
    server.serve_forever()
Esempio n. 8
0
class NetServer(Thread):

    def __init__(self, port=8080, logRequests=True):
        Thread.__init__(self)
        self.__port = port
        self.__logRequests = logRequests
        self.__server = None
        self.__running = False
        self.State = None
        self.start()
        while not self.__running:
            sleep(0)

    def stop(self):
        if self.State is not None:
            self.State.set_update_period(0)
        self.__server.shutdown()
        self.__server.server_close()
        self.join()

    def run(self):
        #register API
        self.State = NetServerState() # accessor for state object for tests and shutting down, etc
        self.__server = SimpleXMLRPCServer(("127.0.0.1", self.__port), CrossDomainXMLRPCRequestHandler, logRequests=self.__logRequests)
        self.__server.register_instance(self.State)
        self.__server.register_introspection_functions()

        #start server
        self.__running = True
        self.__server.serve_forever()
    def __init__(self, *args, **kwargs):
        super(HeavyHitterDetect, self).__init__(*args, **kwargs)
        # importing all functions from config file
        self.config_obj = Config()
        self.datapaths = {}
        self.GLOBAL_THRESHOLD = self.config_obj.global_threshold

        # this will run the polling method in a background thread
        self.monitor_thread = hub.spawn(self._hhapp)

        # running the XMLRPC in background
        server = SimpleXMLRPCServer(('0.0.0.0', 9009),
                                    logRequests=False,
                                    allow_none=True)

        server.register_introspection_functions()
        server.register_multicall_functions()

        # registering XMLRPC functions
        server.register_instance(self)
        server.register_function(self.updatestats, "updatestats")
        server.register_function(self.config_obj.update_threshold_values,
                                 "update_threshold")
        server.register_function(self.config_obj.fetch_config_stats, "fetch")

        self.key_stats = {}
        self.mac_key_stats = {}

        # xmlrpc commands that have to be run in a separate thread
        # the spawn function creates a new thread
        # normal threading does not work here
        self.new_thread = hub.spawn(server.serve_forever)
Esempio n. 10
0
def start_master(ip, port):
    m = Master(f'http://{ip}:{port}', OP_LOG_FILENAME)

    # restore previous launch's meta data
    load_metadata(m)

    # one time polling to get the list of chunks from each chunk server
    m.chunk_manager.poll_chunkservers()

    # call heartbeat
    m.heartbeat()

    master_server = SimpleXMLRPCServer((ip, port),
                                       logRequests=True,
                                       allow_none=True)

    # Read: https://gist.github.com/abnvanand/199cacf6c8f45258ff096b842b77b216
    master_server.register_introspection_functions()

    # register all methods to be available to client
    # can either use register_function(<function's_name>)
    # or register_instance(<class's_instance>)  # All the methods of the instance are published as XML-RPC methods
    master_server.register_instance(m)

    print("Master running at: ", m.my_addr)

    master_server.serve_forever()
Esempio n. 11
0
class RPCServerThread(threading.Thread):
    def __init__(self,
                 methods_to_register,
                 rpc_port,
                 rpc_address="",
                 multithreaded=True):
        threading.Thread.__init__(self)
        self.daemon = False
        self.stoprequest = threading.Event()
        if multithreaded:
            self.localServer = MultiThreadedXMLRPCServer(
                (rpc_address, rpc_port),
                LocalStackTraceHandler,
                allow_none=True,
                logRequests=False)
        else:
            self.localServer = SimpleXMLRPCServer((rpc_address, rpc_port),
                                                  LocalStackTraceHandler,
                                                  allow_none=True,
                                                  logRequests=False)
        self.localServer.register_introspection_functions()
        for method in methods_to_register:
            self.localServer.register_function(method)

    def run(self):
        self.localServer.serve_forever()
Esempio n. 12
0
def main():
    addr = ('localhost', 8000)
    server = SimpleXMLRPCServer(addr,
                                requestHandler=SimpleXMLRPCRequestHandler)
    server.register_introspection_functions()
    server.register_instance(ChatServer())
    server.serve_forever()
class CallbackThread(threading.Thread):
    """Thread for XML-RPC callback server

    To prevent SimpleXMLRPCServer blocking whole app it is started in a thread

    """

    def __init__(self, port):
        log("%s.%s port=%r", self.__class__.__name__, self.__init__.__name__, port)
        super().__init__()
        self.server = None
        self.callback = ClientCallback()
        self.port = port
        self.current_test_case = None

    def run(self):
        """Starts the xmlrpc callback server"""
        log("%s.%s", self.__class__.__name__, self.run.__name__)

        log("Serving on port %s ...", self.port)

        self.server = SimpleXMLRPCServer(("", self.port),
                                         allow_none=True, logRequests=False)
        self.server.register_instance(self.callback)
        self.server.register_introspection_functions()
        self.server.serve_forever()

    def stop(self):
        thread = threading.Thread(target=self._shutdown_thread)
        thread.start()
        thread.join()

    def _shutdown_thread(self):
        self.server.shutdown()

    def set_current_test_case(self, name):
        log("%s.%s %s", self.__class__.__name__, self.set_current_test_case.__name__, name)
        self.current_test_case = name

    def get_current_test_case(self):
        log("%s.%s %s", self.__class__.__name__, self.get_current_test_case.__name__, self.current_test_case)
        return self.current_test_case

    def error_code(self):
        log("%s.%s", self.__class__.__name__, self.error_code.__name__)
        return self.callback.error_code()

    def set_pending_response(self, pending_response):
        log("%s.%s, %r", self.__class__.__name__,
            self.set_pending_response.__name__, pending_response)
        return self.callback.set_pending_response(pending_response)

    def clear_pending_responses(self):
        log("%s.%s", self.__class__.__name__,
            self.clear_pending_responses.__name__)
        return self.callback.clear_pending_responses()

    def cleanup(self):
        log("%s.%s", self.__class__.__name__, self.cleanup.__name__)
        return self.callback.cleanup()
Esempio n. 14
0
def main():
    server = SimpleXMLRPCServer(
        (getenv("DFS_IP", "localhost"), int(getenv("DFS_PORT", "8000"))),
        allow_none=True)
    server.register_introspection_functions()
    server.register_instance(Master())
    server.serve_forever()
class BackendServer():
    def __init__(self, address, functions_to_register):
        #print(address)
        #print(functions_to_register)
        self.server = SimpleXMLRPCServer(address, logRequests=False)
        self.register_functions(functions_to_register)
        self.address = address

    def register_functions(self, functions):
        for f in functions:
            self.server.register_function(f)
        self.server.register_function(self.is_alive)
        self.server.register_introspection_functions()

    def is_alive(self, value):
        return value

    def serve_forever(self, blocking):
        #print time.asctime(), "BackebdServer Starts - %s:%s " % self.address, "(blocking=%d)"%blocking
        if blocking:
            self.server.serve_forever()
        else:
            start_new_thread(self.server.serve_forever, ())

    def stop(self):
        pass
Esempio n. 16
0
def main(args=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--address',
                        '-a',
                        default='0.0.0.0',
                        help='the '
                        'address on which the server is listening (e.g., '
                        '"127.0.0.1", default "0.0.0.0").')
    parser.add_argument('--port',
                        '-p',
                        type=int,
                        default=9002,
                        help='the port'
                        ' on which the server is listening (default "9002").')
    args = parser.parse_args(args)

    logging.basicConfig(format="%(asctime)s %(levelname)s "
                        "%(filename)s:%(lineno)d %(message)s")

    LOG.setLevel(logging.INFO)

    LOG.info("psutil version %s at %s", psutil.__version__, psutil.__file__)

    server = SimpleXMLRPCServer((args.address, args.port))
    LOG.info("serving on %s:%d", args.address, args.port)
    server.register_introspection_functions()
    server.register_instance(MonHelperRPCInterface())
    server.serve_forever()
Esempio n. 17
0
def start_server(obj):
	"""
		Purpose:
		Start the XML-RPC server and register the "obj" class.
	"""
	try:
		commandServer = SimpleXMLRPCServer(('', 9000), allow_none=True)

		commandServer.register_introspection_functions()
		commandServer.register_instance(obj)

		print("{} - Starting to server forever".format(time.asctime()))
		#Now keep the server alive till killed or system reboots
		commandServer.serve_forever()

	except KeyboardInterrupt as err:
		print("{} - Keyboard Interrupt. Exiting.".format(time.asctime()))
		return

	except Exception as err:
		print(err)
		raise err

	except System.Exception as err:
		print(err)
		raise err
Esempio n. 18
0
def main():
    # Create server
    # commented block is for 3.7
    # with SimpleXMLRPCServer(('localhost', 8000),
    #                         requestHandler=RequestHandler) as server:
    server = SimpleXMLRPCServer(
        (HOST, PORT),
        requestHandler=SingleClientRequestHandler,
        allow_none=True,
    )
    server.register_introspection_functions()
    controller = GoPiGoController()
    server.register_instance(controller)

    # Run the server's main loop
    uprint('Serving XML-RPC on {host}:{port}'.format(host=HOST, port=PORT))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        uprint('\nKeyboard interrupt received, exiting.')
        server.shutdown()
        controller.cleanup()
        sys.exit(0)
    finally:
        del controller
Esempio n. 19
0
class SchedServer(object):
    def __init__(self, ip="localhost", port=8000):
        self.sched = scheduler.Scheduler()
        self.server = SimpleXMLRPCServer((ip, port), requestHandler=RequestHandler)
        self.server.register_introspection_functions()
        self.serving = 0
        self.server.register_function(self.push)
        self.server.register_function(self.shutdown)
        self.sched.run()
        self.server.serve_forever()

    def push(self, username, policy_number, code):
        user_id = db_session.query(User.id).filter(User.username == username).one()[0]
        db_task = Task(user_id, policy_number)

        t = task.Task(program.Program(code), username, 3, 1000)
        index = self.sched.add(t)
        if index == -1:
            print("Shutting down")
            return -1
        db_session.add(db_task)
        db_session.commit()
        ret_val = self.sched.get(index)
        while ret_val is None:
            ret_val = self.sched.get(index)
            sleep(0.2)
        return ret_val

    def shutdown(self):
        self.sched.join()
Esempio n. 20
0
def run():
    server = SimpleXMLRPCServer(("localhost", 22234),
                                requestHandler=RequestHandler,
                                logRequests=False)
    server.register_introspection_functions()
    server.register_function(translate, 'translate')
    # Run the server's main loop
    server.serve_forever()
Esempio n. 21
0
def rpcserver():
    server = SimpleXMLRPCServer(('localhost', 8000), requestHandler=TestRequestHandler)
    server.register_introspection_functions()
    server.register_function(pow)
    server.register_function(adder_func, 'add')
    server.register_instance(TestRPCClass())

    server.serve_forever()
Esempio n. 22
0
def get_server(host, port):
    x = Server()
    server = SimpleXMLRPCServer((host, port),
                                allow_none=True,
                                logRequests=False)
    server.register_instance(x)
    server.register_introspection_functions()
    return (x, server)
Esempio n. 23
0
class iCubTest:
    """ iCub Test
    tests XML-RPC with robot interface
    """
    def __init__(self, robot):
        self.robot = robot
        self.robot.init_robot_pos().wait_for_completed()

        self.logger = PykronLogger.getInstance()
        self.M = iCubStateMachine()

        self.yaw_threshold = 10
        self.gp_threshold = 5
        self.follow_threshold = 0.20  # follows for a between 0.0 and follow_threshold, max 1.0 for always

        self.log("init finished")

        # without allow_none the server will complain a lot about those functions not returning anything
        self.server = SimpleXMLRPCServer(('localhost', 8081),
                                         requestHandler=RequestHandler,
                                         allow_none=True)
        self.server.register_introspection_functions()

        # maybe forward the whole instance of the class?
        # TODO split it in half to allow that
        self.server.register_function(self.turnLeft, "turnLeft")
        self.server.register_function(self.turnRight, "turnRight")
        self.server.register_function(self.start_trial, "start_trial")
        self.server.register_function(self.end_trial, "end_trial")

    def turnLeft(self):
        self.log("leftStart")
        self.M.follow_left(self.robot)
        self.M.turnback_fromleft(self.robot)
        self.log("leftEnd")

    def turnRight(self):
        self.log("rightStart")
        self.M.follow_right(self.robot)
        self.M.turnback_fromright(self.robot)
        self.log("rightEnd")

    def start_trial(self):
        self.log('start trial')
        self.M.start_trial(self.robot)

    def end_trial(self):
        self.log('end trial')
        self.M.end_trial(self.robot)

    def log(self, message):
        # TODO add log type: error, debug
        self.logger.log.debug(message)

    def start(self):
        self.log("server starting")
        self.server.serve_forever()
        self.log("server ending")
Esempio n. 24
0
def main():
    server_address = ('localhost', 10000)
    server = SimpleXMLRPCServer(server_address)
    xmlrpc_service = CalcService()
    server.register_instance(xmlrpc_service)
    server.register_introspection_functions()

    print("CTRL-C to stop")
    server.serve_forever()
Esempio n. 25
0
    def run(self):
        server = SimpleXMLRPCServer((self.ip_address, self.port),
                                    allow_none=True)
        server.register_introspection_functions()
        server.register_instance(self.controller)

        print("Started server at %s:%s" % (self.ip_address, self.port))

        server.serve_forever()
Esempio n. 26
0
def main():
    server = SimpleXMLRPCServer(('127.0.0.1', 7001))
    server.register_introspection_functions()
    server.register_multicall_functions()
    server.register_function(addtogether)
    server.register_function(quadratic)
    server.register_function(remote_repr)
    print("Server ready")
    server.serve_forever()
Esempio n. 27
0
def main():
    server = SimpleXMLRPCServer(('127.0.0.1', 7001))
    server.register_introspection_functions()
    server.register_multicall_functions()
    server.register_function(addtogether)
    server.register_function(quadratic)
    server.register_function(remote_repr)
    print("Server ready")
    server.serve_forever()
Esempio n. 28
0
class ServerRPCMain:
    def __init__(self, ip, puerto, tipo="main"):
        self.server = SimpleXMLRPCServer((ip, puerto),
                                         requestHandler=RequestHandler)
        self.server.register_introspection_functions()
        self.ip = ip
        self.puerto = puerto
        self.tipo = tipo
        self.servers = {}

    def menu(self):
        return "---Operaciones---\n- suma - aplica valor1+valor2\n- resta - aplica valor1-valor2\n- multi - aplica valor1*valor2\n- div - aplica valor1/valor2\nDebe indicarse servidor, version, valor1, valor2, valor3, valor4\n la versión 1 es operación binarin, la 2 es de 3 valores y la 3 es de 4 valores"

    def runServer(self):
        print("corriendo server de tipo {}".format(self.tipo))
        if self.tipo == "main":
            print("conectado a servidores externos")
            for i in ["suma", "resta", "multi", "div"]:
                ipServer = str(
                    input("Ingrese la ip del server de {} -> ".format(i)))
                puertoServer = str(
                    input("ingrese el puerto del server de {} -> ".format(i)))
                print("server IP:", ipServer, i)
                print("server port:", puertoServer, i)
                self.servers[i] = xmlrpc.client.ServerProxy("http://" +
                                                            ipServer + ":" +
                                                            puertoServer)

            print(
                "Servidores conectados, iniciando servidor de comunicación media"
            )
            print("Server iniciado")
            self.server.register_function(self.soliOP, 'op')
            self.server.register_function(self.menu, 'menu')
            self.server.serve_forever()

    def soliOP(self, server, version, values):
        print(
            "Solicitando operación de los valores {} al servidor {}, versión {}"
            .format(values, server, version))
        if (server in [*self.servers]):
            if (version + 1 == len(values) and len(values) > 1):
                if (len(values) == 2):
                    value1, value2 = values
                    print("valores", value1, value2)
                    return self.servers[server].op1(value1, value2)
                elif (len(values) == 3):
                    value1, value2, value3 = values
                    return self.servers[server].op2(value1, value2, value3)
                elif (len(values) == 4):
                    value1, value2, value3, value4 = values
                    return self.servers[server].op3(value1, value2, value3,
                                                    value4)
                return "Formato incorrecto"
        else:
            return "el servidor {} No existe".format(server)
Esempio n. 29
0
class ServerAgent(InverseKinematicsAgent):
    '''ServerAgent provides RPC service
    '''

    # YOUR CODE HERE
    def __init__(self, ip_address='localhost', port=8888):
        super().__init__()
        self.__server = SimpleXMLRPCServer(addr=(ip_address, port),
                                           allow_none=True)

        self.__server.register_introspection_functions()
        self.__server.register_function(self.get_angle)
        self.__server.register_function(self.set_angle)
        self.__server.register_function(self.get_posture)
        self.__server.register_function(self.execute_keyframes)
        self.__server.register_function(self.get_transform)
        self.__server.register_function(self.set_transform)

        Thread(target=self.__server.serve_forever).start()

    def get_angle(self, joint_name):
        '''get sensor value of given joint'''
        # YOUR CODE HERE
        return self.perception.joint[joint_name]

    def set_angle(self, joint_name, angle):
        '''set target angle of joint for PID controller
        '''
        # YOUR CODE HERE
        self.target_joints[joint_name] = angle

    def get_posture(self):
        '''return current posture of robot'''
        # YOUR CODE HERE
        return self.posture

    def execute_keyframes(self, key_frames):
        '''excute keyframes, note this function is blocking call,
        e.g. return until keyframes are executed
        '''
        # YOUR CODE HERE
        self.keyframes = key_frames
        while self.keyframes[0]:
            sleep(0.2)

    def get_transform(self, name):
        '''get transform with given name
        '''
        # YOUR CODE HERE
        return self.transforms[name]

    def set_transform(self, effector_name, transform):
        '''solve the inverse kinematics and control joints use the results
        '''
        # YOUR CODE HERE
        self.set_transforms(effector_name, transform)
Esempio n. 30
0
def main():
    server = SimpleXMLRPCServer(('127.0.0.1', 7001))
    server.register_introspection_functions()
    server.register_multicall_functions()
    server.register_function(firstPhase)
    server.register_function(sendRand)
    server.register_function(countKey)
    server.register_function(secondPhase)
    print("Server ready")
    server.serve_forever()
Esempio n. 31
0
def server_details():
    server = SimpleXMLRPCServer(('127.0.0.1', 2346), requestHandler = MyXMLRPCServer, allow_none = True)
    print("Server up and running on port 2346")
    rpcgui.entry.insert(tk.END, "Server window "+ "\n")
	
    server.register_introspection_functions()
    server.register_function(connected_clients, "connected_clients")
    server.register_function(receive_updates, "receive_updates")
    server.register_function(consistent_files, "consistent_files")
    server.serve_forever()
Esempio n. 32
0
def main():
    # Create server
    server = SimpleXMLRPCServer(("localhost", 9004),
                                requestHandler=RequestHandler)
    server.register_introspection_functions()

    server.register_instance(RegisteredFunctions())

    # Run the server's main loop
    server.serve_forever()
Esempio n. 33
0
class Server:
    def __init__(self, name, port):
        self.server = SimpleXMLRPCServer((name, port),
                                         requestHandler=CARequestHandler)
        self.server.register_introspection_functions()
        self.server.register_instance(CentralAuthority(name))

    def run(self):
        # Run the server's main loop
        self.server.serve_forever()
Esempio n. 34
0
class RPCServer(threading.Thread):
    """
    The RPCServer thread provides an API for external programs to interact
    with MOM.
    """
    def __init__(self, config, momFuncs):
        threading.Thread.__init__(self, name="RPCServer")
        self.setDaemon(True)
        self.config = config
        self.momFuncs = momFuncs
        self.logger = logging.getLogger('mom.RPCServer')
        self.server = None
        self.start()

    def thread_ok(self):
        if self.server is None:
            return True
        return self.isAlive()

    def create_server(self):
        try:
            unix_port = None
            port = self.config.getint('main', 'rpc-port')
        except ValueError:
            port = None
            unix_port = self.config.get('main', 'rpc-port')
            self.logger.info("Using unix socket "+unix_port)

        if unix_port is None and (port is None or port < 0):
            return None

        if unix_port:
            self.server = UnixXmlRpcServer(unix_port)
        else:
            self.server = SimpleXMLRPCServer(("localhost", port),
                            requestHandler=RequestHandler, logRequests=0)

        self.server.register_introspection_functions()
        self.server.register_instance(self.momFuncs)

    def shutdown(self):
        if self.server is not None:
            self.server.shutdown()

    def run(self):
        try:
            self.create_server()
            if self.server is not None:
                self.logger.info("RPC Server starting")
                self.server.serve_forever()
                self.logger.info("RPC Server ending")
            else:
                self.logger.info("RPC Server is disabled")
        except Exception as e:
            self.logger.error("RPC Server crashed", exc_info=True)
Esempio n. 35
0
 def _start(self):
     s = SimpleXMLRPCServer(("", self.port),
                            requestHandler=RequestHandler,
                            logRequests=False)
     s.register_instance(self)
     # h = s.get_request()
     # x = h[1]
     s.register_introspection_functions()
     print("server start....")
     self.server = s
     s.serve_forever()
Esempio n. 36
0
class ServerThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.localServer = SimpleXMLRPCServer((HOST, PORT),
                                              requestHandler=RequestHandler,
                                              allow_none=True)
        self.localServer.register_introspection_functions()
        self.localServer.register_instance(RemoteProcedures())

    def run(self):
        self.localServer.serve_forever()
Esempio n. 37
0
def main():
    logging.basicConfig(format="%(asctime)s %(levelname)s "
                               "%(filename)s:%(lineno)d %(message)s")

    LOG.setLevel(logging.INFO)

    LOG.info("psutil version %s at %s", psutil.__version__, psutil.__file__)

    server = SimpleXMLRPCServer(("0.0.0.0", 9002))
    server.register_introspection_functions()
    server.register_instance(MonHelperRPCInterface())
    server.serve_forever()
Esempio n. 38
0
class RemoteController(metaclass=Singleton):
    """
        Provide control over a SimpleXMLRPCServer.
    """

    def __init__(self, ip='localhost', port=8070):
        try:
            self.server = SimpleXMLRPCServer((ip, port), allow_none=True,
                                             logRequests=False)
            self._announcer = Announcer()
        except OSError as error:
            # If address already in use
            if error.errno == 98:
                raise Exception(
                    "Only one application instance can use this module")
            else:
                raise error

        self.server.register_introspection_functions()
        self.server.register_instance(RemoteDispatcher())

    @async
    def start(self):
        logging.info('REMOTE: Session started at ' +
                     str(self.server.server_address))

        self._announcer.start()
        self.server.serve_forever()  # Blocking
        self._announcer.stop()

        logging.info('REMOTE: Session ended')

    def stop(self):
        self.server.shutdown()

    @staticmethod
    def connect_to(uri):
        proxy = ServerProxy(uri, transport=TimeoutTransport())

        try:
            # Call a fictive method.
            proxy._()
        except Fault:
            # Connected, the method doesn't exist, which is expected.
            pass
        except socket.error:
            # Not connected, socket error mean that the service is unreachable.
            raise OSError('Session at ' + uri + ' is unreachable')

        # Just in case the method is registered in the XmlRPC server
        return proxy
Esempio n. 39
0
def main():
    opt = parse_cmdline()
    logging.basicConfig(format="%(asctime)s %(levelname)s "
                               "%(filename)s:%(lineno)d %(message)s")

    LOG.setLevel(logging.INFO)

    LOG.info("psutil version %s at %s", psutil.__version__, psutil.__file__)

    server = SimpleXMLRPCServer((opt.ip, opt.port))
    LOG.info("listening at %s:%s", opt.ip, opt.port)
    server.register_introspection_functions()
    server.register_instance(MonHelperRPCInterface())
    server.serve_forever()
Esempio n. 40
0
def start_xmlrpc(bindaddr):
    from xmlrpc.server import (SimpleXMLRPCServer,
                               SimpleXMLRPCRequestHandler)

    class handler(SimpleXMLRPCRequestHandler):
        rpc_paths = ('/motionwol',)

    addr, port = bindaddr.split(':') #long live IPv4
    server = SimpleXMLRPCServer((addr, int(port)), allow_none=True, requestHandler=handler)
    server.register_introspection_functions()
    server.register_function(disable_rules, 'disable')
    server.register_function(enable_rules, 'enable')

    XmlRpcDispatch(server.fileno()).server = server
Esempio n. 41
0
def start_server(obj):
	"""
		Purpose:
		Create the XML-RPC Server to allow CPython (and other tools) to interact with
		the dksikuli instance and its Sikuli functions.

		Similar to remotesrv.py's "start_server" function.
	"""
	guiServer = SimpleXMLRPCServer(('', 8080), allow_none=True)

	guiServer.register_introspection_functions()
	guiServer.register_instance(obj)

	#Now keep the server alive till the end of the run
	guiServer.serve_forever()
Esempio n. 42
0
def startServer(box): 

    # Restrict to a particular path.
    class RequestHandler(SimpleXMLRPCRequestHandler):
        rpc_paths = ('/RPC2',)

    # Create server
    server = SimpleXMLRPCServer(("0.0.0.0", 8000),
                                requestHandler=RequestHandler, allow_none=True)
    server.register_introspection_functions()
    
    server.register_instance(box)
    
    # Run the server's main loop
    server.serve_forever()
Esempio n. 43
0
	def start_server(self):
		"""
			Purpose:
			Start the XML-RPC server and register the "postrun" class.

		"""
		servicemanager.LogInfoMsg("Running in 'start_server'")

		postrunObj = postrun()
		commandServer = SimpleXMLRPCServer(("localhost", 9000), allow_none=True)

		commandServer.register_introspection_functions()
		commandServer.register_instance(postrunObj)

		#Now keep the server alive till the end of the run
		guiServer.serve_forever()
Esempio n. 44
0
class RemoteController(Thread, metaclass=Singleton):

    def __init__(self, ip='localhost', port=8070):
        super().__init__(daemon=True)
        self.setName('RemoteController')

        self.server = SimpleXMLRPCServer((ip, port), allow_none=True,
                                         logRequests=False)

        self.server.register_introspection_functions()
        self.server.register_instance(RemoteDispatcher())

        self._announcer = Announcer()

    def start(self):
        self._announcer.start()
        Thread.start(self)

    def run(self):
        logging.info('REMOTE: Session started at ' +
                     str(self.server.server_address))

        self.server.serve_forever()

        logging.info('REMOTE: Session ended')

    def stop(self):
        self.server.shutdown()
        self._announcer.stop()

    @staticmethod
    def connect_to(uri):
        proxy = ServerProxy(uri, transport=TimeoutTransport())

        try:
            # Call a fictive method.
            proxy._()
        except Fault:
            # Connected, the method doesn't exist, which is expected.
            pass
        except socket.error:
            # Not connected, socket error mean that the service is unreachable.
            raise Exception('Session at ' + uri + ' is unreachable')

        # Just in case the method is registered in the XmlRPC server
        return proxy
Esempio n. 45
0
def main():
    parser = learn.get_argparser()

    args = parser.parse_args()
    brownclusters.set_paths_file(args.clusterfn)
    triple_sentences = learn.load_bitext(args)
    tl_sentences = learn.get_target_language_sentences(triple_sentences)
    sl_sentences = [s for (s,t,a) in triple_sentences]
    tagged_sentences = [list(zip(ss, ts))
                        for ss,ts in zip(sl_sentences, tl_sentences)]
    learn.set_examples(sl_sentences,tagged_sentences)

    # Create server
    server = SimpleXMLRPCServer(("localhost", 8000),
                                requestHandler=RequestHandler)
    server.register_introspection_functions()
    server.register_function(label_sentence)
    print("SERVER IS NOW ON IT.")
    server.serve_forever()
def main(args=None):
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--address', '-a', default='0.0.0.0', help='the '
                        'address on which the server is listening (e.g., '
                        '"127.0.0.1", default "0.0.0.0").')
    parser.add_argument('--port', '-p', type=int, default=9002, help='the port'
                        ' on which the server is listening (default "9002").')
    args = parser.parse_args(args)

    logging.basicConfig(format="%(asctime)s %(levelname)s "
                               "%(filename)s:%(lineno)d %(message)s")

    LOG.setLevel(logging.INFO)

    LOG.info("psutil version %s at %s", psutil.__version__, psutil.__file__)

    server = SimpleXMLRPCServer((args.address, args.port))
    LOG.info("serving on %s:%d", args.address, args.port)
    server.register_introspection_functions()
    server.register_instance(MonHelperRPCInterface())
    server.serve_forever()
Esempio n. 47
0
def start_driverdb_server(correct_protocol=True):
    '''Create XML-RPC driver db server.

    This will listen on localhost:8080 and serve fake_db. This must be
    terminated with stop_driverdb_server().

    If correct_protocol is False, this will answer with a bogus protocol
    version.
    '''

    start_driverdb_server.pid = os.fork()
    if start_driverdb_server.pid == 0:
        try:
            s = SimpleXMLRPCServer(('localhost', 8080), logRequests=False)
            s.register_introspection_functions()
            if correct_protocol:
                s.register_function(xmlrpc_driverdb_query, 'query')
            else:
                s.register_function(xmlrpc_driverdb_query_bogus, 'query')
            s.serve_forever()
        except:
            sys.stderr.write('********** DEMO XML-RPC server failed: ***********\n')
            traceback.print_exc()
            os._exit(1)

    # wait until it is ready
    c = ServerProxy('http://localhost:8080')
    timeout = 100
    while timeout > 0:
        time.sleep(0.1)
        try:
            c.query('0', '0', {})
        except socket.error:
            timeout -= 1
            continue
        break
    if timeout == 0:
        raise SystemError('XML-RPC demo server did not start')
Esempio n. 48
0
class RPCBot(ChatBot):

    def __init__(self, *args, **kwargs):
        super(RPCBot, self).__init__(*args, **kwargs)
        self.lock = threading.RLock()
        with self.lock:
            self._pending_messages = []
        self.start_rpc_server()

    def run_pending(self):
        with self.lock:
            messages = copy.deepcopy(self._pending_messages)
            self._pending_messages.clear()
        for message in messages:
            channel_id = self.broker.channel_id(message['channel'])
            self.broker.post(
                message['text'],
                channel_id=channel_id,
            )

    def post(self, message):
        with self.lock:
            self._pending_messages.append(message)

    def start_rpc_server(self):
        def post_handler(channel, text):
            self.post({
                'channel': channel,
                'text': text,
            })
            return True
        self.server = SimpleXMLRPCServer(("localhost", 34278))
        self.server.register_introspection_functions()
        self.server.register_function(post_handler, 'post')
        self.rpc_thread = threading.Thread(target=self.server.serve_forever)
        self.rpc_thread.daemon = True
        self.rpc_thread.start()
Esempio n. 49
0
    class RequestHandler(ThreadingMixIn, SimpleXMLRPCRequestHandler):
        '''A (very) simple threaded XMLRPC server that accepts file
        uploads from client instances.
        '''
        def __init__(self, ip, port, lock, logger, data_dir):
            self.logger = logger
            self.data_dir = data_dir
            try:
                self.server = SimpleXMLRPCServer((ip, port), logRequests=False)
            except Exception as e:
                self.logger.critical('The XMLRPC server won\'t start: %s', e)
                sys.exit(1)
            # A synchronization variable so we're not fighting with clients over files
            # in the data directory
            self.lock = lock
            # This method gives us a way to check connectivity for clients
            self.server.register_introspection_functions()
            self.server.register_function(self.server_receive_file, 'server_receive_file')
            if not os.path.exists(self.data_dir):
                try:
                    os.makedirs(self.data_dir)
                except OSError as e:
                    self.logger.critical('ERROR: XMLRPC server unable to create data directory: %s', e)
                    sys.exit(1)
            try:
                self.server.serve_forever()
            except KeyboardInterrupt:
                self.logger.info('XMLRPC server exiting normally in response to KILL signal')
                sys.exit(0)

        def server_receive_file(self, filename, contents):
            self.logger.info('XMLRPC server received file from upstream client %s', filename.split('_')[0].replace('-', '.'))
            self.lock.acquire()
            with open(self.data_dir + '/' + filename, "wb") as handle:
                handle.write(contents.data)
            self.lock.release()
            return True                                                                                                                                            
Esempio n. 50
0
    if not type(message) is str: message = jsdumps(message)
    subject, message = map(b64enc, (subject, message))
    return bitmessage.sendMessage(toaddress, fromaddress, subject, message)

# Get a list of all new messages
from json import loads as jsloads
def receive():
    messages = []
    inbox = jsloads(bitmessage.getAllInboxMessages())['inboxMessages']
    for msgid in (m['msgid'] for m in inbox):
        message = jsloads(bitmessage.getInboxMessageByID(msgid))['inboxMessage'][0]
        subject, message = map(b64dec, (message['subject'], message['message']))
        messages.append({'subject': subject, 'message': message})
        bitmessage.trashMessage(msgid)
    return messages

# Serve RPC
from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
server = SimpleXMLRPCServer(("127.0.0.1", 6712), requestHandler=SimpleXMLRPCRequestHandler)
server.register_introspection_functions()

server.register_function(send, 'send')
server.register_function(receive, 'receive')

try:
    server.serve_forever()
except KeyboardInterrupt:
    from sys import exit
    exit(0)
Esempio n. 51
0
class XMLRPCServer(HardwareObject):
    def __init__(self, name):
        HardwareObject.__init__(self, name)
        self.queue_model_hwobj = None
        self.queue_hwobj = None
        self.beamline_setup_hwobj = None
        self.wokflow_in_progress = True
        self.xmlrpc_prefixes = set()
        self.current_entry_task = None
        self.host = None
      
    def init(self):
        """
        Method inherited from HardwareObject, called by framework-2. 
        """

        # Listen on all interfaces if <all_interfaces>True</all_interfaces>
        # otherwise only on the interface corresponding to socket.gethostname()
        if hasattr(self, "all_interfaces") and self.all_interfaces:
            host = ''
        else:
            host = socket.gethostname()

        self.host = host    

        try:
            self.open()
        except:
            logging.getLogger("HWR").debug("Can't start XML-RPC server")
        

    def close(self):
        try:
          self.xmlrpc_server_task.kill()
          self._server.server_close()
          del self._server
        except AttributeError:
          pass
        logging.getLogger("HWR").info('XML-RPC server closed')

    def open(self):
        # The value of the member self.port is set in the xml configuration
        # file. The initialization is done by the baseclass HardwareObject.
        if hasattr(self, "_server" ):
          return
        self.xmlrpc_prefixes = set()
        self._server = SimpleXMLRPCServer((self.host, int(self.port)), logRequests = False, allow_none = True)

        msg = 'XML-RPC server listening on: %s:%s' % (self.host, self.port)
        logging.getLogger("HWR").info(msg)

        self._server.register_introspection_functions()
        self._server.register_function(self.start_queue)
        self._server.register_function(self.log_message)
        self._server.register_function(self.is_queue_executing)
        self._server.register_function(self.queue_execute_entry_with_id)
        self._server.register_function(self.shape_history_get_grid)
        self._server.register_function(self.shape_history_set_grid_data)
        self._server.register_function(self.beamline_setup_read)
        self._server.register_function(self.get_diffractometer_positions)
        self._server.register_function(self.move_diffractometer)
        self._server.register_function(self.save_snapshot)
        self._server.register_function(self.cryo_temperature)
        self._server.register_function(self.flux)
        self._server.register_function(self.set_aperture)
        self._server.register_function(self.get_aperture)
        self._server.register_function(self.get_aperture_list)
        self._server.register_function(self.get_cp)
        self._server.register_function(self.save_current_pos)
        self._server.register_function(self.anneal) 

        # Register functions from modules specified in <apis> element
        if self.hasObject("apis"):
            apis = next(self.getObjects("apis"))
            for api in apis.getObjects("api"):
                recurse = api.getProperty("recurse")
                if recurse is None:
                    recurse = True

                self._register_module_functions(api.module, recurse=recurse)

        self.queue_hwobj = self.getObjectByRole("queue")
        self.queue_model_hwobj = self.getObjectByRole("queue_model")
        self.beamline_setup_hwobj = self.getObjectByRole("beamline_setup")
        self.shape_history_hwobj = self.beamline_setup_hwobj.shape_history_hwobj
        self.diffractometer_hwobj = self.beamline_setup_hwobj.diffractometer_hwobj
        self.xmlrpc_server_task = gevent.spawn(self._server.serve_forever)
                	

    def anneal(self, time):
        cryoshutter_hwobj = self.getObjectByRole("cryoshutter")
        try:
            cryoshutter_hwobj.getCommandObject("anneal")(time)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True
    	
	
	
    def _add_to_queue(self, task, set_on = True):
        """
        Adds the TaskNode objects contained in the
        list of TaskNodes passed in <task>.

        The TaskNodes are marked as activated in the queue if <set_on>
        is True and to inactivated if False.

        :param task: TaskNode object to add to queue
        :type parent: TaskNode

        :param set_on: Mark TaskNode as activated if True and as inactivated
                       if false.
        :type set_on: bool

        :returns: True on success otherwise False
        :rtype: bool
        """

        # The exception is re raised so that it will
        # be sent to the client.
        try:
            self.emit('add_to_queue', (task, None, set_on))

        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True

    def start_queue(self):
        """
        Starts the queue execution.

        :returns: True on success otherwise False
        :rtype: bool
        """
        try:
            self.emit('start_queue')
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True

    def log_message(self, message, level = 'info'):
        """
        Logs a message in the user_level_log of MxCuBE,
        normally displayed at the bottom of the MxCuBE
        window.

        :param message: The message to log
        :type parent: str

        :param message: The log level, one of the strings:
                        'info'. 'warning', 'error'
        :type parent: str

        :returns: True on success otherwise False
        :rtype: bool
        """
        status = True

        if level == 'info':
            logging.getLogger('user_level_log').info(message)
        elif level == 'warning':
            logging.getLogger('user_level_log').warning(message)
        elif level == 'error':
            logging.getLogger('user_level_log').error(message)
        else:
            status = False

        return status

    def _model_add_child(self, parent_id, child):
        """
        Adds the model node task to parent_id.

        :param parent_id: The id of the parent.
        :type parent_id: int

        :param child: The TaskNode object to add.
        :type child: TaskNode

        :returns: The id of the added TaskNode object.
        :rtype: int
        """
        try:
            node_id = self.queue_model_hwobj.add_child_at_id(parent_id, child)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return node_id

    def _model_get_node(self, node_id):
        """
        :returns the TaskNode object with the node id <node_id>
        :rtype: TaskNode
        """
        try:
            node = self.queue_model_hwobj.get_node(node_id)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return node

    def queue_execute_entry_with_id(self, node_id):
        """
        Execute the entry that has the model with node id <node_id>.

        :param node_id: The node id of the model to find.
        :type node_id: int
        """
        try:
            model = self.queue_model_hwobj.get_node(node_id)
            entry = self.queue_hwobj.get_entry_with_model(model)

            if entry:
                self.current_entry_task = self.queue_hwobj.\
                                          execute_entry(entry)

        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True

    def is_queue_executing(self, node_id=None):
        """
        :returns: True if the queue is executing otherwise False
        :rtype: bool
        """
        try:
            return self.queue_hwobj.is_executing(node_id)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise

    def queue_status(self):
        pass

    def shape_history_get_grid(self):
        """
        :returns: The currently selected grid
        :rtype: dict

        Format of the returned dictionary:

        {'id': id,
         'dx_mm': float,
         'dy_mm': float,
         'steps_x': int,
         'steps_y': int,
         'x1': float,
         'y1': float,
         'angle': float}

        """
        grid_dict = self.shape_history_hwobj.get_grid()
        #self.shape_history_set_grid_data(grid_dict['id'], {})
        
        return grid_dict

    def shape_history_set_grid_data(self, key, result_data):
        int_based_result = {}
        for result in result_data.items():
            int_based_result[int(result[0])] = result[1]

        self.shape_history_hwobj.set_grid_data(key, int_based_result)
        return True

    def get_cp(self):
        """
        :returns: a json encoded list with all centred positions
        """
        cplist = []
        points  = self.shape_history_hwobj.get_points()

        for point in points:
            cp = point.get_centred_positions()[0].as_dict()
            cplist.append(cp)
        
        json_cplist = json.dumps(cplist)

        return json_cplist

    def beamline_setup_read(self, path):
        try:
            return self.beamline_setup_hwobj.read_value(path)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise

    def workflow_set_in_progress(self, state):
        if state:
            self.wokflow_in_progress = True
        else:
            self.wokflow_in_progress = False

    def get_diffractometer_positions(self):
        return self.diffractometer_hwobj.getPositions()

    def move_diffractometer(self, roles_positions_dict):
        self.diffractometer_hwobj.moveMotors(roles_positions_dict)
        return True

    def save_snapshot(self, imgpath):
        self.diffractometer_hwobj.save_snapshot(imgpath)
        return True

    def save_current_pos(self):
        """
        Saves the current position as a centered position.
        """
        self.diffractometer_hwobj.saveCurrentPos()
        return True

    def cryo_temperature(self):
        return self.beamline_setup_hwobj.collect_hwobj.get_cryo_temperature()

    def flux(self):
        flux = self.beamline_setup_hwobj.collect_hwobj.get_flux()
        if flux is None:
            flux = 0
        return float(flux)

    def set_aperture(self,pos_name, timeout=20):
        self.diffractometer_hwobj.beam_info.aperture_hwobj.moveToPosition(pos_name)
        t0=time.time()
        while self.diffractometer_hwobj.beam_info.aperture_hwobj.getState() == 'MOVING':
            time.sleep(0.1)
            if time.time()-t0 > timeout:
                 raise RuntimeError("Timeout waiting for aperture to move")
        return True

    def get_aperture(self):
        return self.diffractometer_hwobj.beam_info.aperture_hwobj.getPosition()

    def get_aperture_list(self):
        aperture_list=[]
        for i in range(0, len(self.diffractometer_hwobj.beam_info.aperture_hwobj['positions'])):
            aperture_list.append(self.diffractometer_hwobj.beam_info.aperture_hwobj['positions'][0][i].getProperty('name'))
        return aperture_list

    def _register_module_functions(self, module_name, recurse=True, prefix=""):
        log = logging.getLogger("HWR")
        log.info('Registering functions in module %s with XML-RPC server' %
                            module_name)

        if module_name not in sys.modules:
            __import__(module_name)
        module = sys.modules[module_name]

        if not hasattr(module, 'xmlrpc_prefix'):
            log.error(('Module %s  has no attribute "xmlrpc_prefix": cannot ' + 
                       'register its functions. Skipping') % module_name)
        else:
            prefix += module.xmlrpc_prefix
            if len(prefix) > 0 and prefix[-1] != '_':
                prefix += '_'

            if prefix in self.xmlrpc_prefixes:
                msg = "Prefix %s already used: cannot register for module %s" % (prefix, module_name)
                log.error(msg)
                raise Exception(msg)
            self.xmlrpc_prefixes.add(prefix)

            for f in inspect.getmembers(module, inspect.isfunction):
                if f[0][0] != '_':
                    xmlrpc_name = prefix + f[0]
                    log.info('Registering function %s.%s as XML-RPC function %s' %
                        (module_name, f[1].__name__, xmlrpc_name) )

                    # Bind method to this XMLRPCServer instance but don't set attribute
                    # This is sufficient to register it as an xmlrpc function. 
                    bound_method = types.MethodType(f[1], self, self.__class__)
                    self._server.register_function(bound_method, xmlrpc_name)

            # TODO: Still need to test with deeply-nested modules, in particular that
            # modules and packages are both handled correctly in complex cases.
            if recurse and hasattr(module, "__path__"):
                sub_modules = pkgutil.walk_packages(module.__path__)
                try:
                    sub_module = next(sub_modules)
                    self._register_module_functions( module_name + '.' + sub_module[1],
                        recurse=False, prefix=prefix)
                except StopIteration:
                    pass
Esempio n. 52
0
from xmlrpc.server import SimpleXMLRPCServer

class TestClass:
	def __init__(self):
		self.var = 1
	def readme(self):
		return self.var

srv = SimpleXMLRPCServer(("localhost", 2121))
srv.register_introspection_functions()


srv.register_instance(TestClass)
srv.serve_forever()
Esempio n. 53
0
 def start_rpc_server(self):
     server = SimpleXMLRPCServer(('0.0.0.0', 9012), logRequests=True)
     for f in self.get_rpc_functions():
         server.register_function(f)
     server.register_introspection_functions()
     server.serve_forever()
Esempio n. 54
0
class ServerThread(threading.Thread):
    """XML-RPC server thread to handle messages from CCU / Homegear"""
    def __init__(self,
                 local=LOCAL,
                 localport=LOCALPORT,
                 remotes=REMOTES,
                 devicefile=DEVICEFILE,
                 interface_id=INTERFACE_ID,
                 eventcallback=False,
                 systemcallback=False,
                 resolveparamsets=False):
        LOG.debug("ServerThread.__init__")
        threading.Thread.__init__(self)

        # Member
        self._interface_id = interface_id
        self._local = local
        self._localport = int(localport)
        self._devicefile = devicefile
        self.remotes = remotes
        self.eventcallback = eventcallback
        self.systemcallback = systemcallback
        self.resolveparamsets = resolveparamsets
        self.proxies = {}

        # Create proxies to interact with CCU / Homegear
        LOG.debug("__init__: Creating proxies")
        for remote, host in self.remotes.items():
            try:
                socket.inet_pton(socket.AF_INET, host['ip'])
            except Exception as err:
                LOG.warning("Skipping proxy: %s" % str(err))
                continue
            LOG.info("Creating proxy %s. Connecting to http://%s:%i" % (remote, host['ip'], host['port']))
            try:
                self.proxies["%s-%s" % (self._interface_id, remote)] = LockingServerProxy("http://%s:%i" % (host['ip'], host['port']))
            except Exception as err:
                LOG.warning("Failed connecting to proxy at http://%s:%i" % (host['ip'], host['port']))
                LOG.debug("__init__: Exception: %s" % str(err))
                raise Exception

        if not self.proxies:
            LOG.warning("No proxies available. Aborting.")
            raise Exception

        self._rpcfunctions = RPCFunctions(devicefile=self._devicefile,
                                          proxies=self.proxies,
                                          remotes=self.remotes,
                                          eventcallback=self.eventcallback,
                                          systemcallback=self.systemcallback,
                                          resolveparamsets=self.resolveparamsets)

        # Setup server to handle requests from CCU / Homegear
        LOG.debug("ServerThread.__init__: Setting up server")
        self.server = SimpleXMLRPCServer((self._local, self._localport),
                                         requestHandler=RequestHandler,
                                         logRequests=False)
        self._localport = self.server.socket.getsockname()[1]
        self.server.register_introspection_functions()
        self.server.register_multicall_functions()
        LOG.debug("ServerThread.__init__: Registering RPC functions")
        self.server.register_instance(self._rpcfunctions, allow_dotted_names=True)

    def run(self):
        LOG.info("Starting server at http://%s:%i" % (self._local, self._localport))
        self.server.serve_forever()

    def proxyInit(self):
        """
        To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method.
        """
        # Call init() with local XML RPC config and interface_id (the name of the receiver) to receive events. XML RPC server has to be running.
        for interface_id, proxy in self.proxies.items():
            LOG.debug("ServerThread.proxyInit: init('http://%s:%i', '%s')" % (proxy._localip, self._localport, interface_id))
            try:
                proxy.init("http://%s:%i" % (proxy._localip, self._localport), interface_id)
                LOG.info("Proxy initialized")
            except Exception as err:
                LOG.debug("proxyInit: Exception: %s" % str(err))
                LOG.warning("Failed to initialize proxy")
                raise Exception

    def stop(self):
        """To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server."""
        stopped = []
        for interface_id in self.proxies:
            if not self.proxies[interface_id]._localip in stopped:
                LOG.debug("ServerThread.stop: Deregistering proxy for server %s" % self.proxies[interface_id]._localip)
                try:
                    self.proxies[interface_id].init("http://%s:%i" % (self.proxies[interface_id]._localip, self._localport))
                    stopped.append(self.proxies[interface_id]._localip)
                except Exception as err:
                    LOG.warning("Failed to deregister proxy")
                    LOG.debug("stop: Exception: %s" % str(err))
        del self.proxies[:]
        LOG.info("Shutting down server")
        self.server.shutdown()
        LOG.debug("ServerThread.stop: Stopping ServerThread")
        self.server.server_close()
        LOG.info("Server stopped")

    def parseCCUSysVar(self, data):
        if data['type'] == 'LOGIC':
            return data['name'], data['value'] == 'true'
        elif data['type'] == 'NUMBER':
            return data['name'], float(data['value'])
        elif data['type'] == 'LIST':
            return data['name'], int(data['value'])
        else:
            return data['name'], data['value']

    def jsonRpcLogin(self, remote):
        session = False
        try:
            params = {"username": self.remotes[remote]['username'], "password": self.remotes[remote]['password']}
            response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "Session.login", params)
            if response['error'] is None and response['result']:
                session = response['result']

            if not session:
                LOG.warning("ServerThread.jsonRpcLogin: Unable to open session.")
        except Exception as err:
            LOG.debug("ServerThread.jsonRpcLogin: Exception while logging in via JSON-RPC: %s" % str(err))
        return session

    def jsonRpcLogout(self, remote, session):
        logout = False
        try:
            params = {"_session_id_": session}
            response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "Session.logout", params)
            if response['error'] is None and response['result']:
                logout = response['result']
        except Exception as err:
            LOG.debug("ServerThread.jsonRpcLogout: Exception while logging in via JSON-RPC: %s" % str(err))
        return logout

    def getAllSystemVariables(self, remote):
        """Get all system variables from CCU / Homegear"""
        variables = {}
        if self.remotes[remote]['username'] and self.remotes[remote]['password']:
            LOG.debug("ServerThread.getAllSystemVariables: Getting all System variables via JSON-RPC")
            session = self.jsonRpcLogin(remote)
            if not session:
                return
            try:
                params = {"_session_id_": session}
                response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "SysVar.getAll", params)
                if response['error'] is None and response['result']:
                    for var in response['result']:
                        key, value = self.parseCCUSysVar(var)
                        variables[key] = value

                self.jsonRpcLogout(remote, session)
            except Exception as err:
                self.jsonRpcLogout(remote, session)
                LOG.warning("ServerThread.getAllSystemVariables: Exception: %s" % str(err))
        else:
            try:
                variables = self.proxies["%s-%s" % (self._interface_id, remote)].getAllSystemVariables()
            except Exception as err:
                LOG.debug("ServerThread.getAllSystemVariables: Exception: %s" % str(err))
        return variables

    def getSystemVariable(self, remote, name):
        """Get single system variable from CCU / Homegear"""
        var = None
        if self.remotes[remote]['username'] and self.remotes[remote]['password']:
            LOG.debug("ServerThread.getSystemVariable: Getting System variable via JSON-RPC")
            session = self.jsonRpcLogin(remote)
            if not session:
                return
            try:
                params = {"_session_id_": session, "name": name}
                response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "SysVar.getValueByName", params)
                if response['error'] is None and response['result']:
                    try:
                        var = float(response['result'])
                    except:
                        if response['result'] == 'true':
                            var = True
                        else:
                            var = False

                self.jsonRpcLogout(remote, session)
            except Exception as err:
                self.jsonRpcLogout(remote, session)
                LOG.warning("ServerThread.getSystemVariable: Exception: %s" % str(err))
        else:
            try:
                var = self.proxies["%s-%s" % (self._interface_id, remote)].getSystemVariable(name)
            except Exception as err:
                LOG.debug("ServerThread.getSystemVariable: Exception: %s" % str(err))
        return var

    def deleteSystemVariable(self, remote, name):
        """Delete a system variable from CCU / Homegear"""
        if self.remotes[remote]['username'] and self.remotes[remote]['password']:
            LOG.debug("ServerThread.deleteSystemVariable: Getting System variable via JSON-RPC")
            session = self.jsonRpcLogin(remote)
            if not session:
                return
            try:
                params = {"_session_id_": session, "name": name}
                response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "SysVar.deleteSysVarByName", params)
                if response['error'] is None and response['result']:
                    deleted = response['result']
                    LOG.warning("ServerThread.deleteSystemVariable: Deleted: %s" % str(deleted))

                self.jsonRpcLogout(remote, session)
            except Exception as err:
                self.jsonRpcLogout(remote, session)
                LOG.warning("ServerThread.deleteSystemVariable: Exception: %s" % str(err))
        else:
            try:
                return self.proxies["%s-%s" % (self._interface_id, remote)].deleteSystemVariable(name)
            except Exception as err:
                LOG.debug("ServerThread.deleteSystemVariable: Exception: %s" % str(err))

    def setSystemVariable(self, remote, name, value):
        """Set a system variable on CCU / Homegear"""
        if self.remotes[remote]['username'] and self.remotes[remote]['password']:
            LOG.debug("ServerThread.setSystemVariable: Setting System variable via JSON-RPC")
            session = self.jsonRpcLogin(remote)
            if not session:
                return
            try:
                params = {"_session_id_": session, "name": name, "value": value}
                if value is True or value is False:
                    response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "SysVar.setBool", params)
                else:
                    response = self._rpcfunctions.jsonRpcPost(self.remotes[remote]['ip'], "SysVar.setFloat", params)
                if response['error'] is None and response['result']:
                    res = response['result']
                    LOG.debug("ServerThread.setSystemVariable: Result while setting variable: %s" % str(res))
                else:
                    if response['error']:
                        LOG.debug("ServerThread.setSystemVariable: Error while setting variable: %s" % str(response['error']))

                self.jsonRpcLogout(remote, session)
            except Exception as err:
                self.jsonRpcLogout(remote, session)
                LOG.warning("ServerThread.setSystemVariable: Exception: %s" % str(err))
        else:
            try:
                return self.proxies["%s-%s" % (self._interface_id, remote)].setSystemVariable(name, value)
            except Exception as err:
                LOG.debug("ServerThread.setSystemVariable: Exception: %s" % str(err))

    def getServiceMessages(self, remote):
        """Get service messages from CCU / Homegear"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].getServiceMessages()
        except Exception as err:
            LOG.debug("ServerThread.getServiceMessages: Exception: %s" % str(err))

    def rssiInfo(self, remote):
        """Get RSSI information for all devices from CCU / Homegear"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].rssiInfo()
        except Exception as err:
            LOG.debug("ServerThread.rssiInfo: Exception: %s" % str(err))

    def setInstallMode(self, remote, on=True, t=60, mode=1, address=None):
        """Activate or deactivate installmode on CCU / Homegear"""
        try:
            args = [on]
            if on and t:
                args.append(t)
                if address:
                    args.append(address)
                else:
                    args.append(mode)

            return self.proxies["%s-%s" % (self._interface_id, remote)].setInstallMode(*args)
        except Exception as err:
            LOG.debug("ServerThread.setInstallMode: Exception: %s" % str(err))

    def getInstallMode(self, remote):
        """Get remaining time in seconds install mode is active from CCU / Homegear"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].getInstallMode()
        except Exception as err:
            LOG.debug("ServerThread.getInstallMode: Exception: %s" % str(err))

    def getAllMetadata(self, remote, address):
        """Get all metadata of device"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].getAllMetadata(address)
        except Exception as err:
            LOG.debug("ServerThread.getAllMetadata: Exception: %s" % str(err))

    def getMetadata(self, remote, address, key):
        """Get metadata of device"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].getMetadata(address, key)
        except Exception as err:
            LOG.debug("ServerThread.getMetadata: Exception: %s" % str(err))

    def setMetadata(self, remote, address, key, value):
        """Set metadata of device"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].setMetadata(address, key, value)
        except Exception as err:
            LOG.debug("ServerThread.setMetadata: Exception: %s" % str(err))

    def deleteMetadata(self, remote, address, key):
        """Delete metadata of device"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key)
        except Exception as err:
            LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err))

    def listBidcosInterfaces(self, remote):
        """Return all available BidCos Interfaces"""
        try:
            return self.proxies["%s-%s" % (self._interface_id, remote)].listBidcosInterfaces()
        except Exception as err:
            LOG.debug("ServerThread.listBidcosInterfaces: Exception: %s" % str(err))
Esempio n. 55
0
#coding=utf-8
'''
Created on 2013-6-3

@author: zhaojp
'''
from xmlrpc.server import SimpleXMLRPCServer;
import math;

def add(x, y):
    "Adds two numbers"
    return x + y;

s = SimpleXMLRPCServer(('', 8080));
s.register_function(add);
s.register_instance(math);
s.register_introspection_functions();
s.serve_forever();
class XMLRPCServer(HardwareObject):
    def __init__(self, name):
        HardwareObject.__init__(self, name)

        self.host = None
        self.port = None
        self.all_interfaces = None
        self.enforceUseOfToken = None

        self.queue_model_hwobj = None
        self.queue_hwobj = None
        self.beamline_setup_hwobj = None
        self.wokflow_in_progress = True
        self.xmlrpc_prefixes = set()
        self.current_entry_task = None
        self.host = None
        self.doEnforceUseOfToken = False

        atexit.register(self.close)
      
    def init(self):
        """
        Method inherited from HardwareObject, called by framework-2. 
        """

        
        self.all_interfaces = self.getProperty('all_interfaces')
        # Listen on all interfaces if <all_interfaces>True</all_interfaces>
        # otherwise only on the interface corresponding to socket.gethostname()
        if self.all_interfaces:
            host = ''
        else:
            host = socket.gethostname()

        self.host = host    
        self.port = self.getProperty('port')

        # Check if communication should be "secure". If self.doEnforceUseOfToken is set to True
        # all incoming http requests must have the correct token in the headers.
        self.enforceUseOfToken = self.getProperty('enforceUseOfToken')
        if self.enforceUseOfToken:
            self.doEnforceUseOfToken = True

        #try:
        self.open()
        #except:
        #    logging.getLogger("HWR").debug("Can't start XML-RPC server")
        

    def close(self):
        try:
            self.xmlrpc_server_task.kill()
            self._server.server_close()
            del self._server
        except AttributeError:
            pass
        logging.getLogger("HWR").info('XML-RPC server closed')

    def open(self):
        # The value of the member self.port is set in the xml configuration
        # file. The initialization is done by the baseclass HardwareObject.
        if hasattr(self, "_server" ):
            return
        self.xmlrpc_prefixes = set()
        if self.doEnforceUseOfToken:
            self._server = SimpleXMLRPCServer((self.host, int(self.port)), requestHandler=SecureXMLRpcRequestHandler, 
                                              logRequests = False, allow_none = True)
        else:
            self._server = SimpleXMLRPCServer((self.host, int(self.port)), logRequests = False, allow_none = True)
        msg = 'XML-RPC server listening on: %s:%s' % (self.host, self.port)
        logging.getLogger("HWR").info(msg)

        self._server.register_introspection_functions()
        self._server.register_function(self.start_queue)
        self._server.register_function(self.log_message)
        self._server.register_function(self.is_queue_executing)
        self._server.register_function(self.queue_execute_entry_with_id)
        self._server.register_function(self.shape_history_get_grid)
        self._server.register_function(self.shape_history_set_grid_data)
        self._server.register_function(self.beamline_setup_read)
        self._server.register_function(self.get_diffractometer_positions)
        self._server.register_function(self.move_diffractometer)
        self._server.register_function(self.save_snapshot)
        self._server.register_function(self.cryo_temperature)
        self._server.register_function(self.flux)
        self._server.register_function(self.set_aperture)
        self._server.register_function(self.get_aperture)
        self._server.register_function(self.get_aperture_list)
        self._server.register_function(self.get_cp)
        self._server.register_function(self.save_current_pos)
        self._server.register_function(self.anneal) 
        self._server.register_function(self.open_dialog) 
        self._server.register_function(self.workflow_end) 
        self._server.register_function(self.dozor_batch_processed)
        self._server.register_function(self.dozor_status_changed)
        self._server.register_function(self.add_processing_message)
        self.image_num = 0
        self._server.register_function(self.get_image_num, "get_image_num")
        self._server.register_function(self.set_zoom_level) 
        self._server.register_function(self.get_zoom_level) 
        self._server.register_function(self.get_available_zoom_levels) 
        self._server.register_function(self.set_front_light_level) 
        self._server.register_function(self.get_front_light_level) 
        self._server.register_function(self.set_back_light_level) 
        self._server.register_function(self.get_back_light_level) 
        self._server.register_function(self.centre_beam)

        # Register functions from modules specified in <apis> element
        if self.hasObject("apis"):
            apis = next(self.getObjects("apis"))
            for api in apis.getObjects("api"):
                recurse = api.getProperty("recurse")
                if recurse is None:
                    recurse = True

                self._register_module_functions(api.getProperty('module'), recurse=recurse)

        self.queue_hwobj = self.getObjectByRole("queue")
        self.queue_model_hwobj = self.getObjectByRole("queue_model")
        self.beamline_setup_hwobj = self.getObjectByRole("beamline_setup")
        self.shape_history_hwobj = self.beamline_setup_hwobj.shape_history_hwobj
        self.diffractometer_hwobj = self.beamline_setup_hwobj.diffractometer_hwobj
        self.collect_hwobj = self.beamline_setup_hwobj.collect_hwobj
        #self.connect(self.collect_hwobj,
        #             'collectImageTaken',
        #             self.image_taken) 

        self.xmlrpc_server_task = gevent.spawn(self._server.serve_forever)
        self.workflow_hwobj = self.getObjectByRole("workflow")
        self.beamcmds_hwobj = self.getObjectByRole("beamcmds")
               
    def anneal(self, time):
        cryoshutter_hwobj = self.getObjectByRole("cryoshutter")
        try:
            cryoshutter_hwobj.getCommandObject("anneal")(time)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True


    def _add_to_queue(self, task, set_on = True):
        """
        Adds the TaskNode objects contained in the
        list of TaskNodes passed in <task>.

        The TaskNodes are marked as activated in the queue if <set_on>
        is True and to inactivated if False.

        :param task: TaskNode object to add to queue
        :type parent: TaskNode

        :param set_on: Mark TaskNode as activated if True and as inactivated
                       if false.
        :type set_on: bool

        :returns: True on success otherwise False
        :rtype: bool
        """

        # The exception is re raised so that it will
        # be sent to the client.
        try:
            self.emit('add_to_queue', (task, None, set_on))

        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True

    def start_queue(self):
        """
        Starts the queue execution.

        :returns: True on success otherwise False
        :rtype: bool
        """
        try:
            self.emit('start_queue')
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True

    def log_message(self, message, level = 'info'):
        """
        Logs a message in the user_level_log of MxCuBE,
        normally displayed at the bottom of the MxCuBE
        window.

        :param message: The message to log
        :type parent: str

        :param message: The log level, one of the strings:
                        'info'. 'warning', 'error'
        :type parent: str

        :returns: True on success otherwise False
        :rtype: bool
        """
        status = True

        if level == 'info':
            logging.getLogger('user_level_log').info(message)
        elif level == 'warning':
            logging.getLogger('user_level_log').warning(message)
        elif level == 'error':
            logging.getLogger('user_level_log').error(message)
        else:
            status = False

        return status

    def _model_add_child(self, parent_id, child):
        """
        Adds the model node task to parent_id.

        :param parent_id: The id of the parent.
        :type parent_id: int

        :param child: The TaskNode object to add.
        :type child: TaskNode

        :returns: The id of the added TaskNode object.
        :rtype: int
        """
        try:
            node_id = self.queue_model_hwobj.add_child_at_id(parent_id, child)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return node_id

    def _model_get_node(self, node_id):
        """
        :returns the TaskNode object with the node id <node_id>
        :rtype: TaskNode
        """
        try:
            node = self.queue_model_hwobj.get_node(node_id)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return node

    def queue_execute_entry_with_id(self, node_id):
        """
        Execute the entry that has the model with node id <node_id>.

        :param node_id: The node id of the model to find.
        :type node_id: int
        """
        try:
            model = self.queue_model_hwobj.get_node(node_id)
            entry = self.queue_hwobj.get_entry_with_model(model)

            if entry:
                self.current_entry_task = self.queue_hwobj.\
                                          execute_entry(entry)

        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise
        else:
            return True

    def is_queue_executing(self, node_id=None):
        """
        :returns: True if the queue is executing otherwise False
        :rtype: bool
        """
        try:
            return self.queue_hwobj.is_executing(node_id)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise

    def queue_status(self):
        pass

    def shape_history_get_grid(self):
        """
        :returns: The currently selected grid
        :rtype: dict

        Format of the returned dictionary:

        {'id': id,
         'dx_mm': float,
         'dy_mm': float,
         'steps_x': int,
         'steps_y': int,
         'x1': float,
         'y1': float,
         'angle': float}

        """
        grid_dict = self.shape_history_hwobj.get_grid()
        #self.shape_history_set_grid_data(grid_dict['id'], {})
        
        return grid_dict

    def shape_history_set_grid_data(self, key, result_data):
        int_based_result = {}
        for result in result_data.iteritems():
            int_based_result[int(result[0])] = result[1]

        self.shape_history_hwobj.set_grid_data(key, int_based_result)
        return True

    def get_cp(self):
        """
        :returns: a json encoded list with all centred positions
        """
        cplist = []
        points  = self.shape_history_hwobj.get_points()

        for point in points:
            cp = point.get_centred_positions()[0].as_dict()
            cplist.append(cp)
        
        json_cplist = json.dumps(cplist)

        return json_cplist

    def beamline_setup_read(self, path):
        try:
            return self.beamline_setup_hwobj.read_value(path)
        except Exception as ex:
            logging.getLogger('HWR').exception(str(ex))
            raise

    def workflow_set_in_progress(self, state):
        if state:
            self.wokflow_in_progress = True
        else:
            self.wokflow_in_progress = False

    def get_diffractometer_positions(self):
        return self.diffractometer_hwobj.getPositions()

    def move_diffractometer(self, roles_positions_dict):
        self.diffractometer_hwobj.moveMotors(roles_positions_dict)
        return True

    def save_snapshot(self, imgpath, showScale=True):
        res = True

        try:
            if showScale:
                self.diffractometer_hwobj.save_snapshot(imgpath)
            else:
                self.diffractometer_hwobj.getObjectByRole("camera").takeSnapshot(imgpath)
        except Exception as ex:
            logging.getLogger('HWR').exception("Could not take snapshot %s " % str(ex))
            res = False

        return res

    def save_current_pos(self):
        """
        Saves the current position as a centered position.
        """
        self.diffractometer_hwobj.saveCurrentPos()
        return True

    def cryo_temperature(self):
        return self.beamline_setup_hwobj.collect_hwobj.get_cryo_temperature()

    def flux(self):
        flux = self.beamline_setup_hwobj.collect_hwobj.get_flux()
        if flux is None:
            flux = 0
        return float(flux)

    def set_aperture(self,pos_name, timeout=20):
        self.diffractometer_hwobj.beam_info.aperture_hwobj.moveToPosition(pos_name)
        t0=time.time()
        while self.diffractometer_hwobj.beam_info.aperture_hwobj.getState() == 'MOVING':
            time.sleep(0.1)
            if time.time()-t0 > timeout:
                raise RuntimeError("Timeout waiting for aperture to move")
        return True

    def get_aperture(self):
        return self.diffractometer_hwobj.beam_info.aperture_hwobj.getCurrentPositionName()

    def get_aperture_list(self):
        return self.diffractometer_hwobj.beam_info.aperture_hwobj.getPredefinedPositionsList()

    def open_dialog(self, dict_dialog):
        """
        Opens the workflow dialog in mxCuBE.
        This call blocks util the dialog is ended by the user.
        """
        return_map = {}
        if self.workflow_hwobj is not None:
            return_map = self.workflow_hwobj.open_dialog(dict_dialog)
        self.emit("open_dialog", dict_dialog)
        return return_map

    def workflow_end(self):
        """
        Notify the workflow HO that the workflow has finished.
        """
        if self.workflow_hwobj is not None:
            self.workflow_hwobj.workflow_end()
    
    def dozor_batch_processed(self, dozor_batch_dict):
        self.beamline_setup_hwobj.parallel_processing_hwobj.batch_processed(dozor_batch_dict)

    def dozor_status_changed(self, status):
        self.beamline_setup_hwobj.parallel_processing_hwobj.\
            set_processing_status(status)

    def add_processing_message(self, collection_id, msg):
        for queue_entry in self.queue_model_hwobj.get_all_dc_queue_entries():
            if queue_entry.get_data_model().id == collection_id:
                queue_entry.get_data_model().processing_msg_list.append(\
                   "%s: %s" % (str(time.strftime("%Y-%m-%d %H:%M:%S")), msg))

    def image_taken(self, image_num):
        self.image_num = image_num

    def get_image_num(self):
        return self.image_num
  
    def set_zoom_level(self, zoom_level):
        """
        Sets the zoom to a pre-defined level.
        """
        self.diffractometer_hwobj.zoomMotor.moveToPosition(zoom_level)

    def get_zoom_level(self):
        """
        Returns the zoom level.
        """
        return self.diffractometer_hwobj.zoomMotor.getCurrentPositionName()

    def get_available_zoom_levels(self):
        """
        Returns the avaliable pre-defined zoom levels.
        """
        return self.diffractometer_hwobj.zoomMotor.getPredefinedPositionsList()

    def set_front_light_level(self, level):
        """
        Sets the level of the front light
        """
        self.diffractometer_hwobj.setFrontLightLevel(level)

    def get_front_light_level(self):
        """
        Gets the level of the front light
        """
        return self.diffractometer_hwobj.getFrontLightLevel()

    def set_back_light_level(self, level):
        """
        Sets the level of the back light
        """
        self.diffractometer_hwobj.setBackLightLevel(level)

    def get_back_light_level(self):
        """
        Gets the level of the back light
        """
        return self.diffractometer_hwobj.getBackLightLevel()

    def centre_beam(self):
        """
        Centers the beam using the beamcmds hardware object.
        """
        self.beamcmds_hwobj.centrebeam()
        while self.beamcmds_hwobj.centrebeam._cmd_execution and not self.beamcmds_hwobj.centrebeam._cmd_execution.ready():
            time.sleep(1)

    def _register_module_functions(self, module_name, recurse=True, prefix=""):
        log = logging.getLogger("HWR")
        log.info('Registering functions in module %s with XML-RPC server' %
                            module_name)

        if not sys.modules.has_key(module_name):
            __import__(module_name)
        module = sys.modules[module_name]

        if not hasattr(module, 'xmlrpc_prefix'):
            log.error(('Module %s  has no attribute "xmlrpc_prefix": cannot ' + 
                       'register its functions. Skipping') % module_name)
        else:
            prefix += module.xmlrpc_prefix
            if len(prefix) > 0 and prefix[-1] != '_':
                prefix += '_'

            if prefix in self.xmlrpc_prefixes:
                msg = "Prefix %s already used: cannot register for module %s" % (prefix, module_name)
                log.error(msg)
                raise Exception(msg)
            self.xmlrpc_prefixes.add(prefix)

            for f in inspect.getmembers(module, inspect.isfunction):
                if f[0][0] != '_':
                    xmlrpc_name = prefix + f[0]
                    log.info('Registering function %s.%s as XML-RPC function %s' %
                        (module_name, f[1].__name__, xmlrpc_name) )

                    # Bind method to this XMLRPCServer instance but don't set attribute
                    # This is sufficient to register it as an xmlrpc function. 
                    bound_method = types.MethodType(f[1], self, self.__class__)
                    self._server.register_function(bound_method, xmlrpc_name)

            # TODO: Still need to test with deeply-nested modules, in particular that
            # modules and packages are both handled correctly in complex cases.
            if recurse and hasattr(module, "__path__"):
                sub_modules = pkgutil.walk_packages(module.__path__)
                try:
                    sub_module = next(sub_modules)
                    self._register_module_functions( module_name + '.' + sub_module[1],
                        recurse=False, prefix=prefix)
                except StopIteration:
                    pass

    def setToken(self, token):
        SecureXMLRpcRequestHandler.setReferenceToken(token)
Esempio n. 57
0
class ServerThread(threading.Thread):
    """XML-RPC server thread to handle messages from CCU / Homegear"""
    def __init__(   self,
                    local = LOCAL,
                    localport = LOCALPORT,
                    remote = REMOTE,
                    remoteport = REMOTEPORT,
                    devicefile = DEVICEFILE,
                    interface_id = INTERFACE_ID,
                    eventcallback = False,
                    systemcallback = False):
        global LOCAL, LOCALPORT, REMOTE, REMOTEPORT, DEVICEFILE, INTERFACE_ID
        LOG.debug("ServerThread.__init__")
        threading.Thread.__init__(self)
        INTERFACE_ID = interface_id
        LOCAL = local
        LOCALPORT = localport
        REMOTE = remote
        REMOTEPORT = remoteport
        DEVICEFILE = devicefile
        self.eventcallback = eventcallback
        self.systemcallback = systemcallback
        self.proxy = False
        
        # Setup server to handle requests from CCU / Homegear
        LOG.debug("ServerThread.__init__: Setting up server")
        self.server = SimpleXMLRPCServer( (LOCAL, int(LOCALPORT)),
                            requestHandler=RequestHandler )
        self.server.register_introspection_functions()
        self.server.register_multicall_functions()
        LOG.debug("ServerThread.__init__: Registering RPC functions")
        
        self.server.register_instance(RPCFunctions(devicefile = DEVICEFILE, proxy = self.proxy, eventcallback = self.eventcallback, systemcallback = self.systemcallback))

    def run(self):
        LOG.info("Starting server at http://%s:%i" % (LOCAL, int(LOCALPORT)))
        self.server.serve_forever()
    
    def connect(self):
        # Create proxy to interact with CCU / Homegear
        LOG.info("Creating proxy. Connecting to http://%s:%i" % (REMOTE, int(REMOTEPORT)))
        try:
            self.proxy = xmlrpc.client.ServerProxy("http://%s:%i" % (REMOTE, int(REMOTEPORT)))
        except:
            LOG.warning("Failed connecting to proxy at http://%s:%i" % (REMOTE, int(REMOTEPORT)))
            raise Exception
    
    def proxyInit(self):
        """To receive events the proxy has to tell the CCU / Homegear where to send the events. For that we call the init-method."""
        # Call init() with local XML RPC config and interface_id (the name of the receiver) to receive events. XML RPC server has to be running.
        LOG.debug("ServerThread.proxyInit: init(http://%s:%i, '%s')" % (LOCAL, int(LOCALPORT), INTERFACE_ID) )
        try:
            self.proxy.init("http://%s:%i" % (LOCAL, int(LOCALPORT)), INTERFACE_ID)
            LOG.info("Proxy initialized")
        except:
            LOG.warning("Failed to initialize proxy")
            raise Exception
    
    def stop(self):
        """To stop the server we de-init from the CCU / Homegear, then shut down our XML-RPC server."""
        if self.proxy:
            LOG.debug("ServerThread.stop: Deregistering proxy")
            try:
                self.proxy.init("http://%s:%i" % (LOCAL, int(LOCALPORT)))
            except:
                LOG.warning("Failed to deregister proxy")
        LOG.info("Shutting down server")
        self.server.shutdown()
        LOG.debug("ServerThread.stop: Stopping ServerThread")
        self.server.server_close()
        LOG.info("Server stopped")