Ejemplo n.º 1
0
 def __init__(self):
     self.uiSocketServer = socket(AF_INET, SOCK_STREAM)
     self.uiSocketServer.bind(('0.0.0.0', 12347))
     self.uiSocketServer.listen(5)
     self.ctlChannel = ServerControl()
     self.ctlChannel.Start()
     self.stop = False
     self.typeID = -1
Ejemplo n.º 2
0
 def test_start_EDNA_server(self):
     # Read test data - note that this depends on the system
     strPathToConfigFile = "../config/%s.xml" % socket.gethostname()
     if not os.path.exists(strPathToConfigFile):
         raise BaseException("Cannot find configuration file: %s" % strPathToConfigFile)
     print "Using configuration file: %s" % os.path.abspath(strPathToConfigFile)
     with open(strPathToConfigFile) as f:
         strXmlConfig = f.read()
         config = DASConfig.parseString(strXmlConfig)
         serverControl = ServerControl()
         serverControl.startServer(config.EDNA)
Ejemplo n.º 3
0
Archivo: DAS.py Proyecto: ESRF/DAS
 def init_device(self):
     self.get_device_properties(self.get_device_class())
     # To make sure we get events without polling
     self.set_change_event("State", True, False)
     self.set_change_event("jobSuccess", True, False)
     self.set_change_event("jobFailure", True, False)
     self.set_change_event("dataAnalysisInformation", True, False)
     # Get configuration from Tango properties
     self._config = self.loadConfig()
     # Start the state machine
     #self._dasStateMachine = DASStateMachine(self)
     #self._dasStateMachine.start()
     #self._serverControl = ServerControl()
     self._serverControl = ServerControl(_logger_method=self.debug_stream)
     self.startRemoteServers()
     self.push_change_event("State", self.get_state())
Ejemplo n.º 4
0
def main():
    server = ServerControl()
    server.Start()

    try:
        while True:
            command = raw_input("command:")
            if command == "end":
                server.Stop()
                break
            elif command == "help":
                print "end: stop the server"
                print "help: show this message"
                pass
            elif command == "setratio":
                ratioStr = raw_input("ratio is:")
                ratio = float(ratioStr)
                server.SetRatio(ratio)
    except KeyboardInterrupt:
        server.Stop()
Ejemplo n.º 5
0
class ServerBackend(object):
    def __init__(self):
        self.uiSocketServer = socket(AF_INET, SOCK_STREAM)
        self.uiSocketServer.bind(('0.0.0.0', 12347))
        self.uiSocketServer.listen(5)
        self.ctlChannel = ServerControl()
        self.ctlChannel.Start()
        self.stop = False
        self.typeID = -1

    def AcceptUISocket(self):
        try:
            while not self.stop:
                rr, rw, err = select.select([self.uiSocketServer], [], [], 1)
                if rr:
                    (uiSocket, addr) = self.uiSocketServer.accept()
                    print "receive one ui ", addr
                    oneThread = threading.Thread(target=self.DealWithUICommand, args=[uiSocket])
                    oneThread.start()
        except KeyboardInterrupt:
            pass 
        self.uiSocketServer.close()
        self.ctlChannel.Stop()

    def Stop(self):
        self.stop = True
        self.StopClientGenerate()
        self.StopEstServer()
    
    def StartClientGenerate(self):
        print 'start client generate'
        self.clientGenerate = Client() 
        self.clientThread = threading.Thread(target = self.clientGenerate.work, args=())
        self.clientThread.start()

        self.SetClientType(1)
        
    def StartEstServer(self):
        print 'start est server'
        self.estServer = EstServer() 
        self.estServerThread = threading.Thread(target = self.estServer.listen, args=())
        self.estServerThread.start()

    def StopEstServer(self):
        print 'stop est server'
        self.estServer.stop()
        self.estServerThread.join()


    def StopClientGenerate(self):
        print 'stop client generate'
        self.clientGenerate.stop()
        self.clientThread.join()

    def SetClientType(self, typeID):
        if self.typeID == typeID:
            return
        self.typeID = typeID
        self.ctlChannel.typeID = typeID
        if typeID == 1:
            self.clientGenerate.SetParam(3, 62)
        elif typeID == 2:
            self.clientGenerate.SetParam(3.3, 72)
        else:
            self.clientGenerate.SetParam(3.6, 95)

    def DealWithUICommand(self, uiSocket):
        while True:
            command = RecvFixLen(uiSocket, 1)
            command = struct.unpack("!B", command)[0]
            if command == GetFreeDataChannel:
                print "get free data channel"
                number = self.ctlChannel.GetFreeDataChannelNumber()
                content = struct.pack("!BB", GiveFreeDataChannel, number)
            elif command == GetAllActiveClient:
                print " get all active client"
                clients = self.ctlChannel.clients
                print clients
                reqNumber = 0
                content = ''
                for clientMac, client in clients.items():
                    for reqID, req in client.reqs.items():
                        reqNumber += 1
                        content += struct.pack("!BIf", clientMac, reqID, req.allocFreqWidth)
                content = struct.pack("!BI", GiveAllActiveClient, reqNumber) + content
            elif command == GetOneActiveClient:
                print "Get One Active Client"
                content = RecvFixLen(uiSocket, 5)
                (mac, reqID) = struct.unpack("!BI", content)
                client = self.ctlChannel.GetOneClient(mac)
                if client != None:
                    req = client.GetOneReq(reqID)
                    if req != None:
                        content = struct.pack("!Bff", mac, req.midFreq, allocFreqWidth)
                    else:
                        content = struct.pack("!B", Error)
                else:
                    content = struct.pack("!B", Error)
            elif command == GetClientGenerateInfoCom:
                print 'get client generate info'
                (averageSerTime, inputrate) = (1.0/self.clientGenerate.serviceTimeLamb, self.clientGenerate.inputTimeLamb)
                content = struct.pack("!Bff", GiveClientGenerateInfoCom, averageSerTime, inputrate)
            elif command == GetEstParam:
                print "Get est param"
                (averageServiceTime, inputrate) = (self.estServer.est_serviceTime, self.estServer.est_lambda)
                content = struct.pack("!Bff", GiveEstParam, averageServiceTime, inputrate)

            elif command == SetClientParam:
                print "Set client param"
                content = RecvFixLen(uiSocket, 1)
                typeID = struct.unpack("!B", content)[0]
                self.SetClientType(typeID)
                content = ''

            elif command == GetServerInfoCom:
                print "get server info"
                (maxFreq, freeFreq, nowSatis, activeNum, servedNum) = self.estServer.GetServerInfo()

                content = struct.pack("!BfffIII", GiveServerInfoCom, maxFreq, freeFreq, nowSatis, activeNum, servedNum, self.typeID)

            elif command == End:
                break
            else:
                content = struct.pack("!B", Error)
            if len(content) > 0:
                uiSocket.send(content)
Ejemplo n.º 6
0
 def test_isLocalHost(self):
     serverControl = ServerControl()
     strLocalHost = socket.gethostname() 
     self.assertTrue(serverControl.isLocalHost(strLocalHost), "Host is localhost")
     self.assertTrue(serverControl.isLocalHost(strLocalHost+".esrf.fr"), "Host + .esrf.fr is localhost")
Ejemplo n.º 7
0
Archivo: DAS.py Proyecto: ESRF/DAS
class DAS(PyTango.Device_4Impl):

#--------- Add you global variables here --------------------------

#------------------------------------------------------------------
#    Device constructor
#------------------------------------------------------------------
    def __init__(self, cl, name):
        PyTango.Device_4Impl.__init__(self, cl, name)
        DAS.init_device(self)

#------------------------------------------------------------------
#    Device initialization
#------------------------------------------------------------------
    def init_device(self):
        self.get_device_properties(self.get_device_class())
        # To make sure we get events without polling
        self.set_change_event("State", True, False)
        self.set_change_event("jobSuccess", True, False)
        self.set_change_event("jobFailure", True, False)
        self.set_change_event("dataAnalysisInformation", True, False)
        # Get configuration from Tango properties
        self._config = self.loadConfig()
        # Start the state machine
        #self._dasStateMachine = DASStateMachine(self)
        #self._dasStateMachine.start()
        #self._serverControl = ServerControl()
        self._serverControl = ServerControl(_logger_method=self.debug_stream)
        self.startRemoteServers()
        self.push_change_event("State", self.get_state())


#------------------------------------------------------------------
#    Device destructor
#------------------------------------------------------------------
    def delete_device(self):
        self.debug_stream("[Device delete_device method] for device", self.get_name())


#------------------------------------------------------------------
#    Always excuted hook method
#------------------------------------------------------------------
    def always_executed_hook(self):
        #self.debug_stream("In ", self.get_name(), "::always_excuted_hook()")
        pass


#------------------------------------------------------------------
#    jobFailure command:
#
#    Description: 
#    argin:  DevString    jobId
#    argout: None
#------------------------------------------------------------------
    def jobFailure(self, argin):
        self.debug_stream("In ", self.get_name(), "::jobFailure()")
        # Sometimes argin can be None...
        if argin is None:
            self.debug_stream("argin is None")
        else:
            self.debug_stream(" argin is ", argin)
            # And sometimes even argin.attr_value can be None!
            if argin.attr_value is None:
                self.debug_stream("argin.attr_value is None")
            elif argin.attr_value.value is None:
                self.debug_stream("argin.attr_value.value is None")
            else:
                self.push_change_event("jobFailure", argin.attr_value.value)
                self.push_change_event("dataAnalysisInformation", [argin.attr_value.value, "failure"])


#------------------------------------------------------------------
#    jobSuccess command:
#
#    Description: 
#    argin:  DevString    jobId
#    argout: None
#------------------------------------------------------------------
    def jobSuccess(self, argin):
        self.debug_stream("In ", self.get_name(), "::jobSuccess()")
        # Sometimes argin can be None...
        if argin is None:
            self.debug_stream("argin is None")
        else:
            self.debug_stream(" argin is ", argin)
            # And sometimes even argin.attr_value can be None!
            if argin.attr_value is None:
                self.debug_stream("argin.attr_value is None")
            elif argin.attr_value.value is None:
                self.debug_stream("argin.attr_value.value is None")
            else:
                self.push_change_event("jobSuccess", argin.attr_value.value)
                self.push_change_event("dataAnalysisInformation", [argin.attr_value.value, "success"])


#---- JobFailure attribute State Machine -----------------
    def is_JobFailure_allowed(self, req_type):
        if self.get_state() in [PyTango.DevState.OFF, PyTango.DevState.FAULT]:
            #    End of Generated Code
            #    Re-Start of Generated Code
            return False
        return True


#------------------------------------------------------------------
#    Read JobFailure attribute
#------------------------------------------------------------------
    def read_JobFailure(self, attr):
        self.debug_stream("In ", self.get_name(), "::read_JobFailure()")

        #    Add your own code here

        attr_JobFailure_read = "Hello Tango world"
        attr.set_value(attr_JobFailure_read)


#---- JobSuccess attribute State Machine -----------------
    def is_JobSuccess_allowed(self, req_type):
        if self.get_state() in [PyTango.DevState.OFF, PyTango.DevState.FAULT]:
            #    End of Generated Code
            #    Re-Start of Generated Code
            return False
        return True


#------------------------------------------------------------------
#    Read JobSuccess attribute
#------------------------------------------------------------------
    def read_JobSuccess(self, attr):
        self.debug_stream("In ", self.get_name(), "::read_JobSuccess()")

        #    Add your own code here

        attr_JobSuccess_read = "Hello Tango world"
        attr.set_value(attr_JobSuccess_read)


#------------------------------------------------------------------
#    Read Attribute Hardware
#------------------------------------------------------------------
    def read_attr_hardware(self, data):
        self.debug_stream("In ", self.get_name(), "::read_attr_hardware()")


    def getConfig(self):
        return self._config


    def loadConfig(self):
        db = PyTango.Database()
        listXmlConfig = db.get_device_property(self.get_name(), "Config")["Config"]
        #self.debug_stream(listXmlConfig, type(listXmlConfig))
        config = None
        if len(listXmlConfig) == 0:
            self.debug_stream("ERROR! No property 'Config' defined in Tango data base for device server %s" % self.get_name())
            sys.exit(1)
        try:
            # Convert list of lines to one string
            strXmlConfig = ''.join(listXmlConfig)
            config = DASConfig.parseString(strXmlConfig)
            #self.debug_stream(config.marshal())
        except Exception:
            self.debug_stream("ERROR! Exception caught when trying to unmarshal config XML for server %s" % self.get_name())
            self.debug_stream("Config XML:")
            self.debug_stream(strXmlConfig)
            raise
        return config

#==================================================================
#
#    DAS read/write attribute methods
#
#==================================================================


#------------------------------------------------------------------
#    Read jobSuccess attribute
#------------------------------------------------------------------
    def read_jobSuccess(self, attr):
        self.debug_stream("In ", self.get_name(), "::read_jobSuccess()")

        #    Add your own code here

        attr_jobSuccess_read = "Hello Tango world"
        attr.set_value(attr_jobSuccess_read)


#------------------------------------------------------------------
#    Read jobFailure attribute
#------------------------------------------------------------------
    def read_jobFailure(self, attr):
        self.debug_stream("In ", self.get_name(), "::read_jobFailure()")

        #    Add your own code here

        attr_jobFailure_read = "Hello Tango world"
        attr.set_value(attr_jobFailure_read)


#------------------------------------------------------------------
#    Read dataAnalysisInformation attribute
#------------------------------------------------------------------
    def read_dataAnalysisInformation(self, attr):
        self.debug_stream("In ", self.get_name(), "::read_dataAnalysisInformation()")

        #    Add your own code here

        attr_dataAnalysisInformation_read = ["No job launched yet", "failure"]
        attr.set_value(attr_dataAnalysisInformation_read)


#---- dataAnalysisInformation attribute State Machine -----------------
    def is_dataAnalysisInformation_allowed(self, req_type):
        if self.get_state() in [PyTango.DevState.OFF,
                                PyTango.DevState.FAULT]:
            #    End of Generated Code
            #    Re-Start of Generated Code
            return False
        return True



#==================================================================
#
#    DAS command methods
#
#==================================================================

#------------------------------------------------------------------
#    State command:
#
#    Description: This command gets the device state (stored in its <i>device_state</i> data member) and returns it to the caller.
#                
#    argout: DevState    State Code
#------------------------------------------------------------------
    def dev_state(self):
        #self.debug_stream("In ", self.get_name(), "::dev_state() = " , self.get_state())
        #    Add your own code here
        if not self._serverControl.checkServer(self._config.EDNA.tangoDevice):
# trick - only restart the server if the server has already been detected down
#         this will happen the second time dev_state()
            if self.get_state() == PyTango.DevState.OFF:
                self.startRemoteServers(_serverToStart="EDNA")
            else:
                self.set_state(PyTango.DevState.OFF)

        if self._config.Workflow is not None:
            if not self._serverControl.checkServer(self._config.Workflow.tangoDevice):
# trick - same trick as above
                if self.get_state() == PyTango.DevState.OFF:
                    self.startRemoteServers(_serverToStart="Workflow")
                else:
                    self.set_state(PyTango.DevState.OFF)
        argout = self.get_state()
        return argout


#------------------------------------------------------------------
#    Status command:
#
#    Description: This command gets the device status (stored in its <i>device_status</i> data member) and returns it to the caller.
#                
#    argout: ConstDevString    Status description
#------------------------------------------------------------------
    def dev_status(self):
        self.debug_stream("In ", self.get_name(), "::dev_status()")
        self.the_status = self.get_status()
        #    Add your own code here

        self.set_status(self.the_status)
        return self.the_status


#------------------------------------------------------------------
#    startJob command:
#
#    Description: 
#    argin:  DevVarStringArray    [<Module to execute>,<XML input>]
#    argout: DevString    job id
#------------------------------------------------------------------
    def startJob(self, argin):
        self.debug_stream("In ", self.get_name(), "::startJob()")
        #self._config = self.loadConfig()        
        self.debug_stream("argin = ", argin)
        try:
            argout = self._ednaClient.startJob(argin)
        except Exception, e:
            self.debug_stream("ERROR in startJob! ", type(e))
            # TODO: Restart EDNA server
            raise
        self.debug_stream("argout = ", argout)
        return argout