示例#1
0
    def __init__(self, ir_node):
        """method __init__(): Parameter 'ir_node' is a ref to an instance of an RzvcIfRouteNode."""

        Thread.__init__(self)

        self._ir_node = ir_node
        self._file = self._ir_node._file
        self._fd = self._ir_node._file.fileno()

        self._poll_obj = None

        self.go = 1

        self._rd_buf_len = 256
        self._rd_buf = array.array("B", "\0" * self._rd_buf_len)
        self._rd_buf_start_idx = 0  # holds index of first byte in (potential) pkt
        self._rd_buf_cur_idx = (
            0
        )  # holds index of current byte in buffer (logically, if not physically, between start and end)
        self._rd_buf_end_idx = 0  # holds index of last byte read
        self._bytes_read = 0

        self._rd_state = 0  # start the subclass reading state machine in the 1st state
        self._pkt_ext_len = 0  # set to non-zero in transition from State 2 to State 3, if any for a given pkt
        self._total_pkt_len = 0  # sum of _pkt_hdr_len and _pkt_ext_len for any given pkt

        self._ser_num = (
            30000
        )  # 0x7530: choose higher number than expected from regular Mozaic, RZ100, or Tessera; @fixme: what about multi-Mediator systems?
        # Prepare to send pkts by breaking _ser_num into component bytes:
        self._ser_num_bytes = long_to_bytes(self._ser_num)

        self._low_rzc = sys.maxint  # listen for and store lowest dst/src address
        self._high_rzc = 0  # listen for and store highest dst/src address
示例#2
0
 def handle_entry(self, event):
     self.debug_information('Log entry event caught.')
     self.debug_information('Going to start export thread.')
     self._seq_stati.queue_pending(event.seq)
     thread = Thread(name=self.name, target=self.go, args=(event, ))
     thread.start()
     return
示例#3
0
    def start(self):
        AVRNode.start(self)
        self._start_called = 1
        self.devices, self.device_addresses = self.findall()
        if self.running:
            raise EAlreadyRunning()

        # Inform in msglog the number of devices on the dallas bus and their addresses (CSCtl81599)
        if(self.devices == None ):
            no_of_devices=0
        else:
            no_of_devices=len(self.device_addresses)
        msglog.log('broadway',msglog.types.INFO,'There are %d devices found on "%s" bus' %(no_of_devices, self.name))
        if no_of_devices:
            addr_str=''
            for addr in self.device_addresses:
                dallas_bus_addr=address_to_asciihex(addr)
                addr_str=addr_str+' '+dallas_bus_addr
            msglog.log('broadway',msglog.types.INFO,'The device addresses on "%s" bus : %s\n' %(self.name,addr_str))
        
        # Start the thread to read the dallas bus irrespective for whether the devices are
        # present or not (CSCtl81599)
        self.running = 1
        thread = Thread(name=self.name,target=self._queue_thread,args=())
        self.request(self._convert_temperature_sensor_list)
        thread.start()            
示例#4
0
    def __init__(self, conn, expected_data):
        self.conn = conn
        self.expected_data = expected_data
        self.got_data = 0
        self.got_expected_data = 0

        Thread.__init__(self)
示例#5
0
    def __init__(self, ir_nodes):
        """method __init__(): Parameter 'ir_nodes' is a list (not dictionary) of one 
		or more valid InterfaceRouteNode subclass instance refs."""

        Thread.__init__(self)

        self._poll_obj = None

        self.go = 1

        self._timeout_iw = None  # ref to IW responsible for any timeout given to poll()
        self._timeout_param = None  # ref to param provided by IW above, to be handed back to IW at timeout

        self._router = RzRouter()

        self._iws = {}  # a dict of IWs

        # Walk the list of given ports, create an IW for each, and add the
        # new IW to the local dict, keyed by fd:
        for ir_node in ir_nodes:
            try:
                iw = ir_node.get_wrapper()
                self._iws[iw._file.fileno()] = iw
                if iw._type != 'listen':
                    self._router.add_interface_wrap(iw)
            except:
                self.debug_print(
                    'Failed to create InterfaceWrap to wrap %s.' %
                    str(ir_node.parent.name), 0)
                continue

        # Add a socket to send monitor output, (and eventually by which to receive cmds?):
        self._mon_skt = None  # created in response to a query from a specific port_num (10001)
示例#6
0
	def __init__(self, ir_nodes):
		"""method __init__(): Parameter 'ir_nodes' is a list (not dictionary) of one 
		or more valid InterfaceRouteNode subclass instance refs."""
		
		Thread.__init__(self)
		
		self._poll_obj = None
		
		self.go = 1
		
		self._timeout_iw = None # ref to IW responsible for any timeout given to poll()
		self._timeout_param = None # ref to param provided by IW above, to be handed back to IW at timeout
				
		self._router = RzRouter()
		
		self._iws = {} # a dict of IWs
		
		# Walk the list of given ports, create an IW for each, and add the
		# new IW to the local dict, keyed by fd:
		for ir_node in ir_nodes:
			try:
				iw = ir_node.get_wrapper()
				self._iws[iw._file.fileno()] = iw
				if iw._type != 'listen':
					self._router.add_interface_wrap(iw)
			except:
				self.debug_print('Failed to create InterfaceWrap to wrap %s.' % str(ir_node.parent.name), 0)
				continue
		
		# Add a socket to send monitor output, (and eventually by which to receive cmds?):
		self._mon_skt = None # created in response to a query from a specific port_num (10001)
示例#7
0
 def load_remote_hosts(self, remote_hosts):
     thread = Thread(
         name=self.name, 
         target=self._load_remote_hosts, 
         args=(remote_hosts,)
     )
     thread.start()
示例#8
0
 def test_cross_thread(self):
     # @note:  This test is relying on the write being large enough to
     #         fill all the OS buffers and block.
     #
     # @note:  Methinks this test relies on too many side effects...
     too_big_for_one_write = 1000000
     some_of_but_not_all_of_it = 65536
     stream = CrossThreadStream()
     cv = Condition()
     t1 = Thread(target=_writer, args=(cv,stream,too_big_for_one_write))
     cv.acquire()
     t1.start()
     # @note:  This pause should cause the _writer to block since it is
     #         trying to write too_big_for_one_write.
     pause(2)
     data = stream.read(some_of_but_not_all_of_it)
     count = len(data)
     self.failUnless(data == 'c'*count and
                     count <= some_of_but_not_all_of_it, 'First read ' + 
                     'failed to return the correct data or returned ' + 
                     'too much data')
     while count < too_big_for_one_write:
         data += stream.read(too_big_for_one_write - count)
         count = len(data)
     self.failUnless(data == 'c'*too_big_for_one_write,
                     'Overall stream did not return ' + 
                     'data written to it correctly or the wrong number')
     self.failUnless(stream.read(100) == '', 'Read did not return empty ' + 
                     'string even though no more data should have been ' + 
                     'waiting and the stream closed')
     cv.wait()
     try:
         self.failIf(_failed, _reason)
     finally:
         cv.release()
示例#9
0
    def start(self):
        AVRNode.start(self)
        self._start_called = 1
        self.devices, self.device_addresses = self.findall()
        if self.running:
            raise EAlreadyRunning()

        # Inform in msglog the number of devices on the dallas bus and their addresses (CSCtl81599)
        if (self.devices == None):
            no_of_devices = 0
        else:
            no_of_devices = len(self.device_addresses)
        msglog.log(
            'broadway', msglog.types.INFO,
            'There are %d devices found on "%s" bus' %
            (no_of_devices, self.name))
        if no_of_devices:
            addr_str = ''
            for addr in self.device_addresses:
                dallas_bus_addr = address_to_asciihex(addr)
                addr_str = addr_str + ' ' + dallas_bus_addr
            msglog.log(
                'broadway', msglog.types.INFO,
                'The device addresses on "%s" bus : %s\n' %
                (self.name, addr_str))

        # Start the thread to read the dallas bus irrespective for whether the devices are
        # present or not (CSCtl81599)
        self.running = 1
        thread = Thread(name=self.name, target=self._queue_thread, args=())
        self.request(self._convert_temperature_sensor_list)
        thread.start()
示例#10
0
 def handle_entry(self,event):
     self.debug_information('Log entry event caught.')
     self.debug_information('Going to start export thread.')
     self._seq_stati.queue_pending(event.seq)
     thread = Thread(name=self.name, target=self.go,args=(event,))
     thread.start()
     return
示例#11
0
	def __init__(self, ir_node):
		"""method __init__(): Parameter 'ir_node' is a ref to an instance of an RzvcIfRouteNode."""
		
		Thread.__init__(self)
		
		self._ir_node = ir_node
		self._file = self._ir_node._file
		self._fd = self._ir_node._file.fileno()
		
		self._poll_obj = None
		
		self.go = 1
		
		self._rd_buf_len = 256
		self._rd_buf = array.array('B', '\0' * self._rd_buf_len)
		self._rd_buf_start_idx = 0 # holds index of first byte in (potential) pkt
		self._rd_buf_cur_idx = 0 # holds index of current byte in buffer (logically, if not physically, between start and end)
		self._rd_buf_end_idx = 0 # holds index of last byte read
		self._bytes_read = 0
		
		self._rd_state = 0 # start the subclass reading state machine in the 1st state
		self._pkt_ext_len = 0 # set to non-zero in transition from State 2 to State 3, if any for a given pkt
		self._total_pkt_len = 0 # sum of _pkt_hdr_len and _pkt_ext_len for any given pkt
		
		self._ser_num = 30000 # 0x7530: choose higher number than expected from regular Mozaic, RZ100, or Tessera; @fixme: what about multi-Mediator systems?
		# Prepare to send pkts by breaking _ser_num into component bytes:
		self._ser_num_bytes = long_to_bytes(self._ser_num)
		
		self._low_rzc = sys.maxint # listen for and store lowest dst/src address
		self._high_rzc = 0 # listen for and store highest dst/src address
示例#12
0
    def __init__(self, conn, expected_data):
        self.conn = conn
        self.expected_data = expected_data
        self.got_data = 0
        self.got_expected_data = 0

        Thread.__init__(self)
示例#13
0
 def export(self, value):
     if self.multi_threaded:
         thread = Thread(name=self.name,
                         target=self._export,
                         args=(value, ))
         thread.start()
     else:
         self._export(value)
示例#14
0
 def __init__(self, socket):
     _Thread.__init__(self)
     self._socket = socket
     self._my_stdin = None
     self._my_stdout = None
     self._my_stderr = None
     self._console = _InteractiveDiagConsole(self)
     return
示例#15
0
 def __init__(self, socket):
     _Thread.__init__(self)
     self._socket = socket
     self._my_stdin = None
     self._my_stdout = None
     self._my_stderr = None
     self._console = _InteractiveDiagConsole(self)
     return
示例#16
0
 def start(self):
     self._test = getattr(Factory(), self.factory)()
     for mthd_name in self._test.public:
         try:
             setattr(self, mthd_name, getattr(self._test, mthd_name))
         except:
             msglog.exception()
     self._worker_thread = Thread(target=self._work, args=())
     self._worker_thread.start()
     super(DiagIon, self).start()
     return
示例#17
0
 def go( self ):
     # Lock here
     self._lock.acquire()
     try:
         if self.thread and self.thread.isAlive():
             # Don't do it!
             return
         self.thread = Thread( name = self.name, target = self._complete, args = () )
         self.thread.start()
     finally:
         self._lock.release()
示例#18
0
 def go( self ): #spin off a thread to allow _synchronize to run at its own pace
     # Lock here
     self._lock.acquire()
     try:
         if self.thread and self.thread.isAlive():
             # Don't do it!
             return
         self.thread = Thread( name = self.name, target = self._complete, args = () )
         self.thread.start()
     finally:
         self._lock.release()
示例#19
0
 def __init__(self, parent, sock, client_ip):
     self.parent = parent
     self.sock = sock
     self.clientip = client_ip
     self.should_run = 1
     #
     Thread.__init__(self)
     #
     syslog.syslog('Got a new connection.')
     #mstr = 'From: %s' % str(socket.inet_ntoa(client_ip))
     mstr = 'From: %s' % str(client_ip)
     syslog.syslog(mstr)
示例#20
0
 def __init__(self, parent, sock, client_ip):
     self.parent = parent
     self.sock = sock
     self.clientip = client_ip
     self.should_run = 1
     #
     Thread.__init__(self)
     #
     syslog.syslog('Got a new connection.')
     #mstr = 'From: %s' % str(socket.inet_ntoa(client_ip))
     mstr = 'From: %s' % str(client_ip)
     syslog.syslog(mstr)
示例#21
0
 def test_release_by_other_thread(self):
     def acquire_it_elsewhere(lock):
         lock.acquire()
     l = allocate1()
     test_thread = Thread(target=acquire_it_elsewhere,args=(l,))
     test_thread.start()
     while l not in l.locked_list:
         pause(0.1)
     try:
         l.release()
     except _WrongThreadAssertion:
         return
     raise "Failed to detect a release of another thread's acquire."
示例#22
0
文件: safe.py 项目: mcruse/monotone
 def __init__(self,target,args,cleanup,c_args,group=None,name=None,
              kwargs=None,verbose=None,*vargs,**keywords):
     if kwargs is None:
         kwargs={}
     self._cleanup = cleanup
     self._cleanup_args = c_args
     self._complete = 0
     self._expired = 0
     self._lock = Lock()
     self._exception = None
     self._result = None
     Thread.__init__(self,group,target,name,args,
                     kwargs,verbose,*vargs,**keywords)
示例#23
0
 def test_transport(self):
     self._listen()
     thread = Thread(target=self._transporter.transport,args=('Test Data',))
     thread.start()
     conn = self._accept()
     data = ''
     more = conn.recv(1024)
     while more:
         data += more
         more = conn.recv(1024)
     self.failUnless(string.split(data,'\r\n\r\n')[-1] == 'Test Data',
                     'Transport sent wrong data: %s' % data)
     conn.send('HTTP/1.1 200 OK\r\n\r\n')
     conn.close()
示例#24
0
    def test_release_by_other_thread(self):
        def acquire_it_elsewhere(lock):
            lock.acquire()

        l = allocate1()
        test_thread = Thread(target=acquire_it_elsewhere, args=(l,))
        test_thread.start()
        while l not in l.locked_list:
            pause(0.1)
        try:
            l.release()
        except _WrongThreadAssertion:
            return
        raise "Failed to detect a release of another thread's acquire."
示例#25
0
 def test_transport(self):
     self._listen()
     thread = Thread(target=self._transporter.transport,
                     args=('Test Data', ))
     thread.start()
     conn = self._accept()
     data = ''
     more = conn.recv(1024)
     while more:
         data += more
         more = conn.recv(1024)
     self.failUnless(
         string.split(data, '\r\n\r\n')[-1] == 'Test Data',
         'Transport sent wrong data: %s' % data)
     conn.send('HTTP/1.1 200 OK\r\n\r\n')
     conn.close()
示例#26
0
 def start(self):
     CompositeNode.start(self)
     self._set_zip_file()
     tread = Thread(name="AutoDiscovery",target=self.kick_start_discovery)
     scheduler.after(2, tread.start)
     self.ad = AutoDiscovery()
     self.ad.configure({"parent":self,"name":"AutoDiscover"})
示例#27
0
 def handle_log(self,event):
     self._event_count += 1
     self.debug_information('Log entry event caught.')
     if self._event_count >= self.log_multiple:
         self.debug_information('Going to start export thread.')
         if self._lock.acquire(0):
             try:
                 thread = Thread(name=self.name, target=self.go,
                                 args=(event.values[0],))
                 thread.start()
                 self._event_count = 0
             finally:
                 self._lock.release()
         else:
             msglog.log('broadway',msglog.types.WARN, 
                        ('Last export still active, ' + 
                         'skipping current request.'))
 def handle_log(self, event):
     self._event_count += 1
     self.debug_information('Log entry event caught.')
     if self._event_count >= self.log_multiple:
         self.debug_information('Going to start export thread.')
         if self._lock.acquire(0):
             try:
                 thread = Thread(name=self.name,
                                 target=self.go,
                                 args=(event.values[0], ))
                 thread.start()
                 self._event_count = 0
             finally:
                 self._lock.release()
         else:
             msglog.log('broadway', msglog.types.WARN,
                        ('Last export still active, ' +
                         'skipping current request.'))
示例#29
0
    def __init__(self):
        """method __init__(): Parameter 'ir_nodes' is a list (not dictionary) of one 
		or more valid InterfaceRouteNode subclass instance refs."""

        Thread.__init__(self)

        self._poll_obj = None

        self.go = 1

        self._com1 = as_internal_node('/interfaces/com1')
        self._com1.open()
        self._com1_file = self._com1.file
        self._com1_fd = self._com1_file.fileno()

        self._com2 = as_internal_node('/interfaces/com2')
        self._com2.open()
        self._com2_file = self._com2.file
        self._com2_fd = self._com2_file.fileno()
示例#30
0
 def handle_log(self,event):
     self.debug_information('Log export triggered.')
     self.evt = event #dil - debug 
     value = event.results()[1]['value']
     if isinstance(value,Exception):
         raise value
     if value: # only export when value is true
         self.debug_information('Going to start export thread.')
         if self._lock.acquire(0):
             try:
                 thread = Thread(name=self.name, target=self.go,
                                 args=(time.time(),))
                 thread.start()
             finally:
                 self._lock.release()
         else:
             msglog.log('broadway',msglog.types.WARN, 
                        ('Last export still active, ' + 
                         'skipping current request.'))
示例#31
0
	def __init__(self):
		"""method __init__(): Parameter 'ir_nodes' is a list (not dictionary) of one 
		or more valid InterfaceRouteNode subclass instance refs."""
		
		Thread.__init__(self)
		
		self._poll_obj = None
		
		self.go = 1
		
		self._com1 = as_internal_node('/interfaces/com1')
		self._com1.open()
		self._com1_file = self._com1.file
		self._com1_fd = self._com1_file.fileno()
		
		self._com2 = as_internal_node('/interfaces/com2')
		self._com2.open()
		self._com2_file = self._com2.file
		self._com2_fd = self._com2_file.fileno()
示例#32
0
 def handle_log(self, event):
     self.debug_information('Log export triggered.')
     self.evt = event  #dil - debug
     value = event.results()[1]['value']
     if isinstance(value, Exception):
         raise value
     if value:  # only export when value is true
         self.debug_information('Going to start export thread.')
         if self._lock.acquire(0):
             try:
                 thread = Thread(name=self.name,
                                 target=self.go,
                                 args=(time.time(), ))
                 thread.start()
             finally:
                 self._lock.release()
         else:
             msglog.log('broadway', msglog.types.WARN,
                        ('Last export still active, ' +
                         'skipping current request.'))
示例#33
0
 def __init__(self,
              target,
              args,
              cleanup,
              c_args,
              group=None,
              name=None,
              kwargs=None,
              verbose=None,
              *vargs,
              **keywords):
     if kwargs is None:
         kwargs = {}
     self._cleanup = cleanup
     self._cleanup_args = c_args
     self._complete = 0
     self._expired = 0
     self._lock = Lock()
     self._exception = None
     self._result = None
     Thread.__init__(self, group, target, name, args, kwargs, verbose,
                     *vargs, **keywords)
示例#34
0
 def test_cross_thread(self):
     # @note:  This test is relying on the write being large enough to
     #         fill all the OS buffers and block.
     #
     # @note:  Methinks this test relies on too many side effects...
     too_big_for_one_write = 1000000
     some_of_but_not_all_of_it = 65536
     stream = CrossThreadStream()
     cv = Condition()
     t1 = Thread(target=_writer, args=(cv, stream, too_big_for_one_write))
     cv.acquire()
     t1.start()
     # @note:  This pause should cause the _writer to block since it is
     #         trying to write too_big_for_one_write.
     pause(2)
     data = stream.read(some_of_but_not_all_of_it)
     count = len(data)
     self.failUnless(
         data == 'c' * count and count <= some_of_but_not_all_of_it,
         'First read ' + 'failed to return the correct data or returned ' +
         'too much data')
     while count < too_big_for_one_write:
         data += stream.read(too_big_for_one_write - count)
         count = len(data)
     self.failUnless(
         data == 'c' * too_big_for_one_write,
         'Overall stream did not return ' +
         'data written to it correctly or the wrong number')
     self.failUnless(
         stream.read(100) == '', 'Read did not return empty ' +
         'string even though no more data should have been ' +
         'waiting and the stream closed')
     cv.wait()
     try:
         self.failIf(_failed, _reason)
     finally:
         cv.release()
示例#35
0
 def start(self):
     self._start_thread_inst = Thread(name='Vista CPC Startup',
                                      target=self._start_thread)
     self._start_thread_inst.start()
     self.running = 1
     return
示例#36
0
class VistaCpcServiceNode(CompositeNode):
    def __init__(self):
        CompositeNode.__init__(self)
        self._cpc_uhp_node = None
        self._cases = []
        self._racks = []
        self.running = 0
        self._start_thread_inst = None
        self._ready = 0
        self.debug_lvl = 1
        return

    def configure(self, cd):
        set_attribute(self, 'com_port', 'com1', cd, str)
        cd['name'] = 'vista_cpc_%s' % self.com_port
        CompositeNode.configure(self, cd)
        return

    def configuration(self):
        cd = CompositeNode.configuration(self)
        get_attribute(self, 'com_port', cd, str)
        return cd

    def start(self):
        self._start_thread_inst = Thread(name='Vista CPC Startup',
                                         target=self._start_thread)
        self._start_thread_inst.start()
        self.running = 1
        return

    def stop(self):
        self.running = 0
        return

    def _start_thread(self):
        # Create a CPC_UHP node under proper COM port:
        com_port_node = as_node('/interfaces/' + self.com_port)
        self._cpc_uhp_node = CpcNode()
        cd = {'parent': com_port_node, 'name': 'CPC_UHP'}
        self._cpc_uhp_node.configure(cd)
        self._cpc_uhp_node.start()
        # Create Circuits and Racks children:
        ckts_svc_node = CompositeNode()
        cd = {'parent': self, 'name': 'Circuits'}
        ckts_svc_node.configure(cd)
        racks_svc_node = CompositeNode()
        cd = {'parent': self, 'name': 'Racks'}
        racks_svc_node.configure(cd)
        # Force complete autodiscovery to create CPC node subtree:
        start_time = time.time()
        dev_nodes = self._cpc_uhp_node.children_nodes()
        for dev_node in dev_nodes:
            item_type_nodes = dev_node.children_nodes()
            for item_type_node in item_type_nodes:
                item_nodes = item_type_node.children_nodes()
                for item_node in item_nodes:
                    obj_nodes = item_node.children_nodes()
                    for obj_node in obj_nodes:
                        prop_nodes = obj_node.children_nodes()
        self.debug_print(
            '%s: Finished autodiscover of CPC_UHP nodetree' % time.time(), 1)
        # Scan CPC_UHP subnodetree for nodes needed for Vista handler clients:
        self._setup()
        self.debug_print('%s: Finished _setup()' % time.time(), 1)
        ckts_svc_node.start()  # starts all children as well
        racks_svc_node.start()  # starts all children as well
        self.debug_print(
            '%s: Finished starting Circuits and Racks children of vista_cpc node'
            % time.time(), 1)
        ##
        # Create a CpcClient at proper place in nodetree:
        self._setup_alarm_nodes()
        self.debug_print('%s: Finished creating Alarm CpcClient' % time.time(),
                         1)
        self._start_thread_inst = None
        self._ready = 1
        return

    ##
    # is_ready(): Called by any entity interested in calling get_XXX() methods,
    # and getting non-error values.
    # @return 1: CPC node tree is ready, 0: CPC node tree is not yet ready
    def is_ready(self):
        return self._ready

    def get_case_temps(self):
        return self._cases

    ##
    # get_cases(): Called by Vista handlers to get CaseTemp data. Handlers
    # display this data to user to allow user to associate CaseTemps with widgets.
    # @return List of lists: [[<ckt_name>,<case_temp_idx>,<temp_url>,<stat_url>,<desc_url>],...]
    def get_cases(self):
        return self._cases

    ##
    # get_racks(): Called by Vista handlers to get Rack data. Handlers
    # display this data to user to allow user to associate Racks with widgets.
    # @return List of lists: [[<rack_name>,<stat_url>],...]
    def get_racks(self):
        return self._racks

    ##
    # _setup(): Called by self._start_thread(), to scan existing CPC_UHP subtrees,
    # and to use the garnered info to create appropriate child nodes. These
    # children aggregate Rack and Case statuses for easy monitoring by Vista.
    def _setup(self):
        ckts_svc_node = self.get_child('Circuits')
        racks_svc_node = self.get_child('Racks')
        dev_nodes = self._cpc_uhp_node.children_nodes()
        has_CircuitStatus_node = 0
        for dev_node in dev_nodes:
            ckt_svc_nodes = []
            if dev_node.has_child('Circuit'):
                ckts_dev_node = dev_node.get_child('Circuit')
                ckt_dev_nodes = ckts_dev_node.children_nodes()
                for ckt_dev_node in ckt_dev_nodes:
                    ckt_name = ckt_dev_node.get_child('Name').get()
                    ckt_svc_node = CktStatusXltrNode(ckt_dev_node)
                    cd = {'parent': ckts_svc_node, 'name': ckt_dev_node.name}
                    ckt_svc_node.configure(cd)
                    ckt_svc_nodes.append(ckt_svc_node)
                    num_temps_node = ckt_dev_node.get_child(
                        'NumberOfTempSensors')
                    num_temps = num_temps_node.get()
                    if (num_temps is None) or isinstance(num_temps, Exception):
                        num_temps = 6
                    for i in range(num_temps):
                        case_temp_dev_node = ckt_dev_node.get_child(
                            'CaseTemps' + str(i))
                        case_temp_svc_node = CompositeNode()
                        cd = {
                            'parent': ckt_svc_node,
                            'name': str(case_temp_dev_node._obj_inst_num)
                        }
                        case_temp_svc_node.configure(cd)
                        status_svc_node = CktCaseTempsStatusXltrNode(
                            ckt_svc_node, case_temp_dev_node)
                        cd = {'parent': case_temp_svc_node, 'name': 'Status'}
                        status_svc_node.configure(cd)
                        descr_svc_node = SingleAttrNode('Not initialized')
                        cd = {
                            'parent': case_temp_svc_node,
                            'name': 'Description'
                        }
                        descr_svc_node.configure(cd)
                        self._cases.append([ckt_name, \
                                                 case_temp_dev_node._obj_inst_num, \
                                                 as_node_url(case_temp_dev_node), \
                                                 as_node_url(status_svc_node),
                                                 as_node_url(descr_svc_node)],)
            rack_svc_node = CompositeNode()
            cd = {'parent': racks_svc_node, 'name': dev_node.name}
            rack_svc_node.configure(cd)
            rack_status_node = RackStatusXltrNode(dev_node, ckt_svc_nodes)
            cd = {'parent': rack_svc_node, 'name': 'Status'}
            rack_status_node.configure(cd)
            dev_name = dev_node._dev.get_name()
            self._racks.append([dev_name, as_node_url(rack_status_node)])
        return

    def _setup_alarm_nodes(self):
        services = as_node('/services')
        if not services.has_child('External Alarms'):
            alarms_node = CompositeNode()
            alarms_node.configure({
                'name': 'External Alarms',
                'parent': services
            })
        alarms_node = as_node('/services/External Alarms')
        alarm_node = alarms.Manager()
        alarm_node.configure({'name': 'CPC Alarm', 'parent': alarms_node})
        cpc_client_node = cpc_client.CpcClient(self._cpc_uhp_node)
        cpc_client_node.configure({
            'name': 'CPC Client',
            'parent': alarm_node,
            'node': ''
        })
        ewebconnect_client_node = ewebconnect.EWebConnectAlarmClient()
        ewebconnect_client_node.configure({
            'name': 'eWebConnect Alarm Client',
            'parent': alarm_node,
            'host': '10.0.1.88',  #'mother.envenergy.com',
            'port': 16161,
            'enabled': 1,
        })
        alarms_node.start()
        return

    def debug_print(self, msg, msg_lvl):
        if msg_lvl < self.debug_lvl:
            if isinstance(msg, array.ArrayType):
                utils.print_array_as_hex(msg, 16)
            else:
                print 'opt.trane.vista.cpc.VistaCpcServiceNode: ' + msg
        return
示例#37
0
 def start(self):
     ARMNode.start(self)
     self.running = 1
     thread = Thread(name=self.name,target=self._scan_sensors,args=())
     thread.start()            
示例#38
0
class DynDNSManager( ConfigurableNode ):
    def __init__( self ):
        ConfigurableNode.__init__( self )
        self.isRunning = 0
        self.ipcheck_pid = 0
        self._lock = Lock()
        self.thread = None
        self.first_time = 0
        self.log_name = 'broadway'
        self.update_count = 0
            
    def _is_debug( self ):
        if self.__dict__.has_key( 'debug' ):       
            if self.debug:
                return 1
        return 0

    def msglog( self, msg ):
        if self._is_debug():       
            msglog.log( self.log_name, msglog.types.DB, msg )
                
    def configure( self, config_dict ):     
        ConfigurableNode.configure( self, config_dict )
        set_attribute( self, 'enable', 0, config_dict, int )
        set_attribute( self, 'debug', 0, config_dict, int )
        
        set_attribute( self, 'ddns_service', 0, config_dict )
        set_attribute( self, 'ddns_acct', 0, config_dict )
        set_attribute( self, 'ddns_pswd', 0, config_dict )
        set_attribute( self, 'host_name', 0, config_dict )
        map_to_attribute( self, 'period', 0, config_dict, map_to_seconds )
        
    def configuration( self ):
        config_dict = ConfigurableNode.configuration( self )
        get_attribute( self, 'enable', config_dict )
        get_attribute( self, 'debug', config_dict )
        
        get_attribute( self, 'ddns_service', config_dict )
        get_attribute( self, 'ddns_acct', config_dict )
        get_attribute( self, 'ddns_pswd', config_dict )
        get_attribute( self, 'host_name', config_dict )
        map_from_attribute( self, 'period', config_dict, map_from_seconds )
        
        return config_dict

    def start( self ):
        if self.enable:
            msglog.log( self.log_name, msglog.types.INFO,
                        "STARTING %s, period = %d" % (self.name, self.period) )
            if not self.isRunning:
                self.isRunning = 1
                 # Wait for a bit to give time for a possible PPP connection
                 # to be brought up.
                scheduler.seconds_from_now_do( 90, self.go )
            else:
                raise EAlreadyRunning

    def stop( self ):
        if self.isRunning:
            if self.ipcheck_pid:
                os.kill( self.ipcheck_pid, signal.SIGKILL )
            self.isRunning = 0

    def go( self ):
        # Lock here
        self._lock.acquire()
        try:
            if self.thread and self.thread.isAlive():
                # Don't do it!
                return
            self.thread = Thread( name = self.name, target = self._complete, args = () )
            self.thread.start()
        finally:
            self._lock.release()
       
    def _complete( self ):
        try:
            self._ipcheck()
        except:
            msglog.exception()
            
        if self.isRunning and self.period:
            # Schedule another run in self.period seconds
            scheduler.seconds_from_now_do( self.period, self.go )

    def _ipcheck( self ):
        cmd = 'ipcheck -p ' + properties.ETC_DIR
        # Ignore errors the first time after startup.
        if self.update_count == 0:
            cmd += ' -e'
        if self._is_debug():
            cmd += ' -dv'
        cmd += ' %s %s %s' % (self.ddns_acct, self.ddns_pswd, self.host_name)

        # Start the ip checker
        self.msglog( "running %s" % cmd )
        child = Popen4( cmd )
        self.ipcheck_pid = child.pid
        outfile = child.fromchild
        
        # Wait for ip checker to finish.  Log any output in the message log.
        while 1:
            result = select( [outfile], [], [], 3.0 )
            if result[0]:
                lines = outfile.readlines()
                for line in lines:
                    self.msglog( line )
            status = child.poll()
            if not status == -1:
                break
        self.ipcheck_pid = 0
        
        if os.WIFEXITED( status ):
            exit_code = os.WEXITSTATUS( status )
            self.msglog( 'ipcheck exit status = %d' % exit_code )
        else:
            self.msglog( 'ipcheck forcibly stopped, status = %d' % status )
            
        self.update_count += 1
示例#39
0
 def start(self):
    self._start_thread_inst = Thread(name='Vista CPC Startup',target=self._start_thread)
    self._start_thread_inst.start()
    self.running = 1
    return
示例#40
0
 def __init__(self):
     self.secs = None
     self.go = 0
     self.going = 0
     self.stopped = 0
     Thread.__init__(self)
示例#41
0
文件: event.py 项目: mcruse/monotone
 def __init__(self):
     Thread.__init__(self, None, None, 'EventProducer Test')
     EventProducerMixin.__init__(self)
示例#42
0
def respond(server,response='response'):
    t = Thread(target=_accept_and_respond,args=(server,response))
    t.start()
示例#43
0
class DiagIon(CompositeNode):
    def __init__(self):
        self._worker_queue = Queue()
        return
        
    def configure(self, cd):
        super(DiagIon, self).configure(cd)
        set_attribute(self, 'factory', REQUIRED, cd)
        #@todo - allow config options
        return
    
    def configuration(self):
        cd = super(DiagIon, self).configuration()
        get_attribute(self, 'factory', cd)
        return cd
    
    def start(self):
        self._test = getattr(Factory(), self.factory)()
        for mthd_name in self._test.public:
            try:
                setattr(self, mthd_name, getattr(self._test, mthd_name))
            except:
                msglog.exception()
        self._worker_thread = Thread(target=self._work, args=())
        self._worker_thread.start()
        super(DiagIon, self).start()
        return
        
    def get(self, skipCache=0):
        rslt = None
        if self.parent.tech_support:
            rslt = self._test.runtest()
        return rslt
        
    def get_with_callback(self, callback_url):
        self._submit_work(callback_url)
        return
        
    def set_property(self, prop_name, prop_value):
        if not hasattr(self._test, prop_name):
            raise EInvalidValue(
                    'set_property',
                    prop_value,
                    'Error setting unknown property.'
                )
        setattr(self._test, prop_name, prop_value)
        return
        
    def _submit_work(self, callback):
        self._worker_queue.put(callback)
        return
        
    def _work(self):
        NETLOC = 1
        PATH = 2
        while 1:
            callback = self._worker_queue.get()
            try:
                result = self.get()
            except:
                msglog.exception()
                result = 'None'
            try:
                data = urllib.urlencode({'result':result})
                p_url = urlparse(callback)
                conn = httplib.HTTPConnection(p_url[NETLOC])
                conn.request('POST', p_url[PATH], data)
                rsp = conn.getresponse()
                msg = '%s sent a response of %s to %s.' % \
                    (self.as_node_url(), result, callback)
                msglog.log(
                        'broadway',
                        msglog.types.INFO,
                        msg
                    )
            except:
                msglog.exception()
        return
示例#44
0
 def start(self):
    Client.start(self)
    self._thread = Thread(None, self._poll_alarms)
    self._go = 1
    self._thread.start()
    return
示例#45
0
class CpcClient(Client):
   def __init__(self, cpc_uhp_node):
      Client.__init__(self)
      self._cpc_uhp_node = cpc_uhp_node
      self._thread = None
      self._go = 1
      return
   def configure(self, config):
      set_attribute(self, 'period', 60.0, config, float)
      Client.configure(self, config)
   def configuration(self):
      config = Client.configuration(self)
      get_attribute(self, 'period', config, float)
      return config
   def start(self):
      Client.start(self)
      self._thread = Thread(None, self._poll_alarms)
      self._go = 1
      self._thread.start()
      return
   def stop(self):
      self._go = 0
      timeout = 30.0
      self._thread.join(timeout)
      if self._thread.isAlive():
         msglog.log('mpx',msglog.types.ERR,'%s failed to terminate its ' \
                    '_poll_alarms thread within %s sec.' % (as_node_url(self),timeout))
      Client.stop(self)
      return
   def _poll_alarms(self): # thread
      while 1:
         ideal_alarms = []
         cpc_alarms = self._cpc_uhp_node.get_alarms()
         for cpc_alarm in cpc_alarms:
            if not isinstance(cpc_alarm, CpcAlarm): # could be None or Exception
               continue
            src = '%s:%s:%s,%s:%s' % (cpc_alarm.device_name, str(cpc_alarm.item), \
                                      cpc_alarm.item_num, str(cpc_alarm.obj), \
                                      cpc_alarm.obj_num)
            tm_tuple = (cpc_alarm.orig_date[0], cpc_alarm.orig_date[1], cpc_alarm.orig_date[2], \
                  cpc_alarm.orig_time[0], cpc_alarm.orig_time[1], 0, 0, 0, -1)
            tm_sec = time.mktime(tm_tuple)
            state = 'Not acked'
            if cpc_alarm.ack_date >= cpc_alarm.orig_date:
               state = 'Acked'
            type = 'Alarm'
            if cpc_alarm.type == 0:
               type = 'Notice'
            i = cpc_alarm.text.find('\x00')
            data = cpc_alarm.text[:i]
            ideal_alarm = Alarm(id=cpc_alarm.id,
                                type=type,
                                source=src,
                                timestamp=tm_sec,
                                data=data,
                                state=state)
            ideal_alarms.append(ideal_alarm)
            msglog.log('mpx',msglog.types.INFO,'CPC Alarm: %s' % ideal_alarm.as_list()) # legal protection in case CPC eqpt fails or Costco doesn't see alarm
         if len(ideal_alarms) > 0:
            ae = NewAlarmsEvent(self, ideal_alarms)
            self.parent.event_generate(ae)
         for i in range(30):
            if self._go == 0:
               return
            time.sleep(1.0)
      return
      
      
      
      
        
示例#46
0
 def __init__(self, connection, device_server):
     Thread.__init__(self, name='MODBUS')
     self.connection = connection
     self.device_server = device_server
     if debug: print 'init MODBUS Connection '
     self.debug = debug
示例#47
0
 def event_handler(self,event):
     t = Thread(target=self.event_thread, args=(event,))
     t.start()
     return
示例#48
0
 def event_handler(self, event):
     t = Thread(target=self.event_thread, args=(event, ))
     t.start()
     return
示例#49
0
 def __init__(self, node):
     Thread.__init__(self)
     self.node = node
示例#50
0
 def __init__(self, node, **options):
     node_url = as_node_url(node)
     Thread.__init__(self, name='_DiscoveryThread(%r)' % node_url)
     if node.debug: print '%s.__init__()' % self.getName()        
     self.node = node
     self.options = options
示例#51
0
文件: rna.py 项目: mcruse/monotone
 def __init__(self, rna_service, name='RNA_Thread'):
     self.rna_service = rna_service
     Thread.__init__(self, name=name)
     self.rna_scan_thread = RNA_Scan_Thread()
示例#52
0
def respond(server, response='response'):
    t = Thread(target=_accept_and_respond, args=(server, response))
    t.start()