コード例 #1
0
ファイル: manager.py プロジェクト: mcruse/monotone
 def load_remote_hosts(self, remote_hosts):
     thread = Thread(
         name=self.name, 
         target=self._load_remote_hosts, 
         args=(remote_hosts,)
     )
     thread.start()
コード例 #2
0
ファイル: _test_case_stream.py プロジェクト: mcruse/monotone
 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()
コード例 #3
0
ファイル: dallasbus.py プロジェクト: ed-aicradle/monotone
    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
ファイル: dallasbus.py プロジェクト: mcruse/monotone
    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()            
コード例 #5
0
ファイル: trap_exporter.py プロジェクト: mcruse/monotone
 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
コード例 #6
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
コード例 #7
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)
コード例 #8
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."
コード例 #9
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."
コード例 #10
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()
コード例 #11
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()
コード例 #12
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.'))
コード例 #13
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.'))
コード例 #14
0
ファイル: triggered_exporter.py プロジェクト: mcruse/monotone
 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.'))
コード例 #15
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.'))
コード例 #16
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()
コード例 #17
0
ファイル: __init__.py プロジェクト: mcruse/monotone
 def _handle_trigger(self, alarm):
     export_thread = Thread(name=alarm.source.name,
                            target=self._run_exports,
                            args=(alarm,))
     export_thread.start()
コード例 #18
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
コード例 #19
0
 def event_handler(self, event):
     t = Thread(target=self.event_thread, args=(event, ))
     t.start()
     return
コード例 #20
0
ファイル: _test_case_log.py プロジェクト: mcruse/monotone
 def event_handler(self,event):
     t = Thread(target=self.event_thread, args=(event,))
     t.start()
     return
コード例 #21
0
 def load_remote_hosts(self, remote_hosts):
     thread = Thread(name=self.name,
                     target=self._load_remote_hosts,
                     args=(remote_hosts, ))
     thread.start()
コード例 #22
0
ファイル: _test_case_httplib.py プロジェクト: mcruse/monotone
def respond(server,response='response'):
    t = Thread(target=_accept_and_respond,args=(server,response))
    t.start()
コード例 #23
0
ファイル: dumc_exporter.py プロジェクト: mcruse/monotone
 def export(self,value):
     if self.multi_threaded:
         thread = Thread(name=self.name,target=self._export,args=(value,))
         thread.start()
     else:
         self._export(value)
コード例 #24
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
コード例 #25
0
 def start(self):
     ARMNode.start(self)
     self.running = 1
     thread = Thread(name=self.name, target=self._scan_sensors, args=())
     thread.start()
コード例 #26
0
def respond(server, response='response'):
    t = Thread(target=_accept_and_respond, args=(server, response))
    t.start()
コード例 #27
0
class BcuTimeSynchronizer( CompositeNode ):
    # This class variable counts the number of nodes that are enabled.
    # The status file is removed when this count is zero.
    nodesEnabled = 0
    
    def __init__( self ):
        CompositeNode.__init__( self )
        self.timeout = 30
        self.isRunning = 0
        self._lock = Lock()
        self.thread = None
        self.fast_adjust_threshold = 600
        self.adjust_threshold = 15
        self.nudge_amount = 1
        self.adjustment = 0 #+/-/0 amount of adjustment
        self.period = 60
        self.bcu_time_node = None
        self.bcu_date_node = None
        self.debug = 0
        self.enabled = 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( 'broadway', msglog.types.DB, msg )
                
    def configure( self, config_dict ):     
        CompositeNode.configure( self, config_dict )
        set_attribute( self, 'enabled', 0, config_dict, int )
        set_attribute( self, 'debug', self.debug, config_dict, int )
        set_attribute( self, 'period', self.period, config_dict, int )
        set_attribute( self, 'fast_adjust_threshold', self.fast_adjust_threshold, config_dict, int )
        set_attribute( self, 'adjust_threshold', self.adjust_threshold, config_dict, int )
        set_attribute( self, 'nudge_amount', self.nudge_amount, config_dict, int )
        set_attribute( self, 'bcu_date', REQUIRED, config_dict )
        set_attribute( self, 'bcu_time', REQUIRED, config_dict )
        
    def configuration( self ):
        config_dict = CompositeNode.configuration( self )
        get_attribute( self, 'enabled', config_dict )
        get_attribute( self, 'debug', config_dict )
        get_attribute( self, 'period', config_dict )
        get_attribute( self, 'fast_adjust_threshold', config_dict )
        get_attribute( self, 'adjust_threshold', config_dict )
        get_attribute( self, 'nudge_amount', config_dict )
        get_attribute( self, 'bcu_date', config_dict )
        get_attribute( self, 'bcu_time', config_dict )
        return config_dict
    
    def start( self ):      
        msg = "Starting %s, period = %d" % (self.name, self.period)
        msglog.log( 'broadway', msglog.types.INFO, msg)            
        if not self.isRunning:
            self.isRunning = 1
            self._period = self.period
            self._schedule()
        else:
            raise EAlreadyRunning
    
    def _schedule( self ):        
        scheduler.seconds_from_now_do( self._period, self.go )

    def stop( self ):
        if self.isRunning:
            self.isRunning = 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()
       
    def _complete( self ):
        try:
            self._synchronize()
        except:
            if self.debug: print '_complete exception'
            msglog.exception()
            
        if self.isRunning and self.period:
            self._schedule()
        #and terminate thread

    def _synchronize( self ):        
        bcu_date, bcu_time = self._get_bcu_time() #date tuple and seconds
        # get system and bcu times
        system_date, system_time = self._get_system_time() 
        #only adjust time when system time is outside the range of 11pm to 3am
        #this is to prevent any funny business around midnight or daylight savings changeovers
        #also avoids having to deal with modulo math comparisons around midnight
        if system_time > 82800: return #it's after 11pm
        if system_time < 12600: return #it's before 3:30am

        time_error = bcu_time - system_time
        if self.debug: print 'time error is: ', time_error
        if bcu_date != system_date:
           time_error = self.fast_adjust_threshold + 1 #force big time error update 

        # if big time error, just force the system time to the bcu time
        if abs(time_error) > self.fast_adjust_threshold:
            if self.debug: print 'big time error'
            self.adjustment = 0
            self.msglog( 'Timesync to BCU due to large error: %d' % bcu_time )
            self._set_system_time(bcu_date, bcu_time)
            return

        # if the error has difted too far, nudge the system time back towards the bcu time
        if time_error > self.adjust_threshold:
            if self.debug: print 'mediator time is too slow'
            self.adjustment = self.nudge_amount + 2 #it takes about 1.something seconds to set the time
        elif time_error < -self.adjust_threshold:
            if self.debug: print 'mediator time is too fast'
            self.adjustment = -self.nudge_amount

        # test for adjustment in progress and if it's time to stop nudging the time
        if (self.adjustment > 0):
            if system_time > bcu_time:
                self.adjustment = 0
        elif (self.adjustment < 0):
            if system_time < bcu_time:
                self.adjustment = 0

        if (self.adjustment != 0):
            self.msglog( 'Timesync to BCU due to small error: %d' % time_error )
            self._set_system_time(system_date, system_time + self.adjustment)
            self._period = 5
        else:
            self._period = self.period

        # nudge system time towards bcu time.
        # max nudge is X unless error is greater than Y then slam it (should only happen rarely)
        # if nudging time back, never nudge more than Z
        # never set time around midnight 
    def _get_system_time( self ):
        y, m, d, hour, min, second, wday, yday, isdst = time.localtime()
        if self.debug: print 'get localtime', y, m, d, hour, min, second, wday, yday, isdst
        return ((m, d, y), hour * 3600 + min * 60 + second)
    def _set_system_time( self, mmddyyyy, seconds ):
        seconds = int(seconds)
        ss = seconds % 60
        mm = (seconds % 3600) / 60
        hh = (seconds / 3600)
        hhmmss = [hh, mm, ss]
        if self.debug: print 'set time: ', hh, mm, ss
        set_time( mmddyyyy, hhmmss, None )
        
    def _get_bcu_time( self ):
        if self.debug: print 'get bcu time'
        if self.bcu_time_node is None:
            self.bcu_time_node = as_node(self.bcu_time)  #could test classes etc
        if self.bcu_date_node is None:
            self.bcu_date_node = as_node(self.bcu_date)
        y, m, d, dwk = self.bcu_date_node.get(1).value.value #should be date list
        hour, min, second, hundreths = self.bcu_time_node.get(1).value.value #should be time list
        answer = ((m, d, y), hour * 3600 + min * 60 + second)
        if self.debug: print 'bcu time', y, m, d, dwk, hour, min, second, hundreths
        return answer
コード例 #28
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
コード例 #29
0
ファイル: dallasbus.py プロジェクト: mcruse/monotone
 def start(self):
     ARMNode.start(self)
     self.running = 1
     thread = Thread(name=self.name,target=self._scan_sensors,args=())
     thread.start()            
コード例 #30
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
      
      
      
      
        
コード例 #31
0
ファイル: __init__.py プロジェクト: ed-aicradle/monotone
 def _handle_trigger(self, alarm):
     export_thread = Thread(name=alarm.source.name,
                            target=self._run_exports,
                            args=(alarm, ))
     export_thread.start()
コード例 #32
0
ファイル: __init__.py プロジェクト: mcruse/monotone
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