Exemplo n.º 1
0
 def test_errorTraceToString(self):
     """ErrorTraceHelper errorTraceToString creates formatted message"""
     rv = 'ErrorTrace (TimeStamp=Tue Feb  3 21:42:26 2009,\n                File=myfile,\n                Line=myline,\n                Routine=myroutine,\n                Host=myhost,\n                Process=myprocess,\n                Thread=mythread,\n                Type=0,\n                Code=0,\n                ShortDescrip=Description,\n                Severity=Routine,\n                Data: )\n'
     tu = TimeUtil()
     et = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'myprocess', 'mythread',
                            tu.py2epoch(1233697346).value, 'mySourceObj', 0,
                            0, 'Routine', 'Description', [], None)
     self.assertEqual(rv, self.eth.errorTraceToString(et, '    '))
Exemplo n.º 2
0
 def test_Print(self):
     """ErrorTraceHelper Print produces output for a single trace"""
     tu = TimeUtil()
     et = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'myprocess', 'mythread',
                            tu.py2epoch(1233697346).value, 'mySourceObj', 0,
                            0, 'Routine', 'Description', [], [])
     self.eth = ET.ErrorTraceHelper(et)
     self.eth.Print()
     self.assertEqual('write', sys.stdout.method_calls[0][0])
Exemplo n.º 3
0
 def test_errorTraceToString(self):
     """ErrorTraceHelper errorTraceToString creates formatted message"""
     rv = 'ErrorTrace (TimeStamp=Tue Feb  3 21:42:26 2009,\n                File=myfile,\n                Line=myline,\n                Routine=myroutine,\n                Host=myhost,\n                Process=myprocess,\n                Thread=mythread,\n                Type=0,\n                Code=0,\n                ShortDescrip=Description,\n                Severity=Routine,\n                Data: )\n'
     tu = TimeUtil()
     et = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'myprocess', 'mythread',
                            tu.py2epoch(1233697346).value,
                            'mySourceObj', 0, 0, 'Routine', 'Description',
                            [], None)
     self.assertEqual(rv, self.eth.errorTraceToString(et, '    '))
Exemplo n.º 4
0
 def test_Print(self):
     """ErrorTraceHelper Print produces output for a single trace"""
     tu = TimeUtil()
     et = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'myprocess', 'mythread',
                            tu.py2epoch(1233697346).value,
                            'mySourceObj', 0, 0, 'Routine', 'Description',
                            [], [])
     self.eth = ET.ErrorTraceHelper(et)
     self.eth.Print()
     self.assertEqual('write', sys.stdout.method_calls[0][0])
Exemplo n.º 5
0
    def errorTraceToString(self, error_trace, ws):
        '''
        Converts an error trace to a human-readable string.
        
        Parameters: error_trace is an errortrace
        ws is whitespace

        Returns: Nothing

        Raises: Nothing
        '''
        #figure out a nice format for time first
        epoch = acstime.Duration(
            error_trace.timeStamp)  #convert to an ACS epoch
        timehelper = TimeUtil()
        epoch = timehelper.epoch2py(epoch)  #convert to Python time
        epoch = gmtime(epoch)  #convert to gm time
        epoch = asctime(epoch)  #convert to nice string format

        nice_space = "            "
        for i in range(0, len(ws) / 4):
            nice_space = nice_space + "    "

        message = "ErrorTrace ("
        message = message + "TimeStamp=" + epoch + "," + linesep
        message = message + nice_space + "File=" + str(
            error_trace.file) + "," + linesep
        message = message + nice_space + "Line=" + str(
            error_trace.lineNum) + "," + linesep
        message = message + nice_space + "Routine=" + str(
            error_trace.routine) + "," + linesep
        message = message + nice_space + "Host=" + str(
            error_trace.host) + "," + linesep
        message = message + nice_space + "Process=" + str(
            error_trace.process) + "," + linesep
        message = message + nice_space + "Thread=" + str(
            error_trace.thread) + "," + linesep
        message = message + nice_space + "Type=" + str(
            error_trace.errorType) + "," + linesep
        message = message + nice_space + "Code=" + str(
            error_trace.errorCode) + "," + linesep
        message = message + nice_space + "ShortDescrip=" + str(
            error_trace.shortDescription) + "," + linesep
        message = message + nice_space + "Severity=" + str(
            error_trace.severity) + "," + linesep
        message = message + nice_space + "Data: "
        for i in error_trace.data:
            message = message + "Name=" + str(i.name) + ", Value=" + str(
                i.value) + "; "
        message = message + ")" + linesep

        return message
Exemplo n.º 6
0
 def test_log(self):
     """ErrorTraceHelper log records messages on stdout and ACS logger"""
     rv = 'ErrorTrace (TimeStamp=Tue Feb  3 21:42:26 2009,\n                File=myfile,\n                Line=myline,\n                Routine=myroutine,\n                Host=myhost,\n                Process=myprocess,\n                Thread=mythread,\n                Type=0,\n                Code=0,\n                ShortDescrip=Description,\n                Severity=Routine,\n                Data: )\n'
     logger = mock.Mock(spec=Logger)
     tu = TimeUtil()
     et = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'myprocess', 'mythread',
                            tu.py2epoch(1233697346).value, 'mySourceObj', 0,
                            0, 'Routine', 'Description', [], [])
     self.eth = ET.ErrorTraceHelper(et)
     self.eth.log(logger, ACSLog.ACS_LOG_TRACE)
     self.assertEqual('logErrorTrace', logger.method_calls[0][0])
     self.assertEqual(2, len(sys.stdout.method_calls))
Exemplo n.º 7
0
 def test_log(self):
     """ErrorTraceHelper log records messages on stdout and ACS logger"""
     rv = 'ErrorTrace (TimeStamp=Tue Feb  3 21:42:26 2009,\n                File=myfile,\n                Line=myline,\n                Routine=myroutine,\n                Host=myhost,\n                Process=myprocess,\n                Thread=mythread,\n                Type=0,\n                Code=0,\n                ShortDescrip=Description,\n                Severity=Routine,\n                Data: )\n'
     logger = mock.Mock(spec=Logger)
     tu = TimeUtil()
     et = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'myprocess', 'mythread',
                            tu.py2epoch(1233697346).value,
                            'mySourceObj', 0, 0, 'Routine', 'Description',
                            [], [])
     self.eth = ET.ErrorTraceHelper(et)
     self.eth.log(logger, ACSLog.ACS_LOG_TRACE)
     self.assertEqual('logErrorTrace', logger.method_calls[0][0])
     self.assertEqual(2, len(sys.stdout.method_calls))
Exemplo n.º 8
0
    def __init__(self,
                 error_type,
                 error_code,
                 exception=None,
                 description="None",
                 nvSeq=None,
                 create=1,
                 severity=None):
        '''
        The constructor basically allows the developer to specify any number of
        parameters for an error trace, but requires none.  Python is flexible enough
        to let us do this.
        
        Parameters:
        - error_type is the error type (a long)
        - error_code is the error code (a long)
        - exception is a previous exception from the ACS Error System, or a Python
        native exception, in which case, an ErrorTrace will be constructed. The traceback
        should be ok in most cases, but if you find that it isn't, a possible workaround is
        converting the python exception to an ACS exception using pyExceptionToCORBA()
        before passing it to an ACSError constructor. Remember, that if you don't use
	pyExceptionToCORBA(), if
        you are dealing with a native exception, you must pass create=1 to the ACSError
        constructor.
        - description is a stringified description of the errror
        - nvSeq is a name-value sequence describing the error condition. Each value
        should be of the type ACSErr.NameValue
        - create with a value of 1 implies error information will be added to the stack
        - severity is the ACSErr severity of the error
        
        Returns: Nothing
        
        Raises: Nothing
        '''
        if nvSeq == None:
            nvSeq = []

        # Get a Logger instance
        self.timehelper = TimeUtil()

        #If create has not been changed by the developer we create a new error trace
        #appending the old one if it exists
        if create == 1:
            self.errorTrace = ErrorTrace(error_type, error_code, exception,
                                         description, nvSeq, 3, severity)

        #Someone has caught a CORBA exception and is trying to convert it into
        #this helper class.
        elif exception != None:

            #If the previous exception is an ACS Error System Exception
            if hasattr(exception, "errorTrace"):
                #We can use an error stack...
                self.errorTrace = exception.errorTrace

            #if the previous exception was actually an ACSErr.Completion with a
            #non-empty error trace
            elif hasattr(exception, "previousError") and (len(
                    exception.previousError) == 1):
                self.errorTrace = exception.previousError[0]
Exemplo n.º 9
0
 def test_Print_nested(self):
     """ErrorTraceHelper Print produces output for a nested trace"""
     tu = TimeUtil()
     etg = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                             'grandson', 'mythread',
                             tu.py2epoch(1233697346).value, 'mySourceObj',
                             0, 0, 'Routine', 'Description', [], [])
     ets = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                             'son', 'mythread',
                             tu.py2epoch(1233697346).value, 'mySourceObj',
                             0, 0, 'Routine', 'Description', [], [etg])
     etf = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                             'father', 'mythread',
                             tu.py2epoch(1233697346).value, 'mySourceObj',
                             0, 0, 'Routine', 'Description', [], [ets])
     self.eth = ET.ErrorTraceHelper(etf)
     self.eth.Print()
     self.assertEqual(6, len(sys.stdout.method_calls))
Exemplo n.º 10
0
 def test_Print_nested(self):
     """ErrorTraceHelper Print produces output for a nested trace"""
     tu = TimeUtil()
     etg = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'grandson', 'mythread',
                            tu.py2epoch(1233697346).value,
                            'mySourceObj', 0, 0, 'Routine', 'Description',
                            [], [])
     ets = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'son', 'mythread',
                            tu.py2epoch(1233697346).value,
                            'mySourceObj', 0, 0, 'Routine', 'Description',
                            [], [etg])
     etf = ACSErr.ErrorTrace('myfile', 'myline', 'myroutine', 'myhost',
                            'father', 'mythread',
                            tu.py2epoch(1233697346).value,
                            'mySourceObj', 0, 0, 'Routine', 'Description',
                            [], [ets])
     self.eth = ET.ErrorTraceHelper(etf)
     self.eth.Print()
     self.assertEqual(6, len(sys.stdout.method_calls))
Exemplo n.º 11
0
    def errorTraceToString(self, error_trace, ws):
        '''
        Converts an error trace to a human-readable string.
        
        Parameters: error_trace is an errortrace
        ws is whitespace

        Returns: Nothing

        Raises: Nothing
        '''
        #figure out a nice format for time first
        epoch = acstime.Duration(error_trace.timeStamp)  #convert to an ACS epoch
        timehelper = TimeUtil()
        epoch = timehelper.epoch2py(epoch)  #convert to Python time
        epoch = gmtime(epoch)  #convert to gm time
        epoch = asctime(epoch)  #convert to nice string format
        
        nice_space = "            "
        for i in range(0, len(ws)/4):
            nice_space = nice_space + "    "

        message = "ErrorTrace ("
        message = message + "TimeStamp=" + epoch + "," + linesep
        message = message + nice_space    + "File="      + str(error_trace.file)      + "," + linesep
        message = message + nice_space    + "Line="      + str(error_trace.lineNum)   + "," + linesep
        message = message + nice_space    + "Routine="   + str(error_trace.routine)   + "," + linesep
        message = message + nice_space    + "Host="      + str(error_trace.host)      + "," + linesep
        message = message + nice_space    + "Process="   + str(error_trace.process)   + "," + linesep
        message = message + nice_space    + "Thread="    + str(error_trace.thread)    + "," + linesep
        message = message + nice_space    + "Type="      + str(error_trace.errorType) + "," + linesep
        message = message + nice_space    + "Code="      + str(error_trace.errorCode) + "," + linesep
        message = message + nice_space    + "ShortDescrip="      + str(error_trace.shortDescription) + "," + linesep
        message = message + nice_space    + "Severity="      + str(error_trace.severity) + "," + linesep
        message = message + nice_space    + "Data: "
        for i in error_trace.data:
            message = message + "Name=" + str(i.name) + ", Value=" + str(i.value) + "; "
        message = message + ")" + linesep

        return message
Exemplo n.º 12
0
    def to_posixtime(tm):
        """
        Convert an ACS epoch to a POSIX timestamp...

        ...such as is returned by time.time().

        @param tm: A time in 100 nanoseconds that have passed since
        October 15, 1582.
        @type tm: acstime.Epoch
        @return: The POSIX timestamp.
        @rtype: float
        """
        return TimeUtil().epoch2py(tm)
Exemplo n.º 13
0
    def __init__(self, parent, eventAdminRef, filename):
        '''
        Standard Constructor

        Paramters:
        - parent is the parent widget of this class
        - eventAdminRef is a reference to an ACSEventAdmin IDL interface

        Returns: Nothing

        Raises: ???
        '''

        self.archiveEventsFile = None 

        if filename != None:
           self.archiveEventsFile = file(filename, "w")

        #call superclass constructor
        CBstring.__init__(self)
        
        #time helper instance. used to format timestamps.
        self.timehelper = TimeUtil()
        
        #save the component reference
        self.eventAdminRef = eventAdminRef
        
        #activate ourself as a corba object
        self.corbaRef = self._this()

        #the fields that will be outputted for the Event browser
        self.ebFields = ["Timestamp", "Channel", "Source", "SupplierEvent#", "ChannelEvent#", "Type", "TypeEvent#"]
        #Layout of the columns
        self.ebFormat = '%25s %12s %12s %16s %15s %20s %15s'

        #Copy the parent widget
        self.parent = parent

        #place where we map events within the GUI to the real events
        self.outputEventMap = {}

        # Create and pack the MenuBar.
	menuBar = Pmw.MenuBar(parent,
                              hull_relief = 'raised',
                              hull_borderwidth = 1)
	menuBar.pack(fill = 'x')
	self.menuBar = menuBar
        
	menuBar.addmenu('Browser Options', 'Save, Clear, or Exit')
	menuBar.addmenuitem('Browser Options',
                            'command',
                            'Save events to a file',
                            command = self.saveEvents,
                            label = 'Save Events')
        menuBar.addmenuitem('Browser Options',
                            'command',
                            'Clear list of events from this browser',
                            command = self.clearEvents,
                            label = 'Clear Events')
        #--This does not work unless the modules for the events have been imported
        #--unfortunately. Commented out for now. DWF
        #menuBar.addmenuitem('Browser Options',
        #                    'command',
        #                    'Saves the events so they can be reloaded later.',
        #                    command = self.pickleEvents,
        #                    label = 'Pickle Events')
        #menuBar.addmenuitem('Browser Options',
        #                    'command',
        #                    'Loads pickled events into the browser.',
        #                    command = self.loadPickledEvents,
        #                    label = 'Load Pickled Events')
        
        #create the event browser group
        browserGroup = Pmw.Group(parent, tag_text='Event Browser')
	browserGroup.pack(fill='x', expand='1', side = 'top', padx = 5, pady = 3)
        
        headerLine = self.ebFormat % tuple(self.ebFields)
        
        #create the channel group
        channelGroup = Pmw.Group(parent, tag_text='Channels')
	channelGroup.pack(side = 'left', padx = 5, pady = 3)

        
        #create the admin group
        eventViewerGroup = Pmw.Group(parent, tag_text='Event Viewer')
	eventViewerGroup.pack(side = 'left', padx = 5, pady = 3)

        #create the admin group
        adminGroup = Pmw.Group(parent, tag_text='Channel Administration')
	adminGroup.pack(fill='both', expand='1', side = 'left', padx = 5, pady = 3)

        #-----------------------------------------------------------
        #--Event viewer box
        self.evST= Pmw.ScrolledText(eventViewerGroup.interior(),
                                    borderframe = 0,
                                    columnheader = 0,
                                    usehullsize = 1,
                                    hull_width = 300,
                                    hull_height = 300,
                                    text_wrap='none',
                                    text_font = Pmw.logicalfont('Fixed'),
                                    text_padx = 4,
                                    text_pady = 4)
        #make the scrolling text window big
	self.evST.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
        
        # Prevent users' modifying text and headers
        #self.evST.configure(text_state = 'disabled')
        
        ############################################################
        ##Event Browser#############################################
        # Create the ScrolledText with headers.
        
        self.ebST = Pmw.ScrolledListBox(browserGroup.interior(),
                                        items=(),
                                        labelpos='nw',
                                        label_text = "   " + headerLine,
                                        usehullsize = 1,
                                        hull_width = 1100,
                                        hull_height = 300,
                                        selectioncommand=self.displayEvent
                                        )

        #make the scrolling text window big
	self.ebST.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
        
        ############################################################
        #Active Channels############################################
	# Create and pack the simple ComboBox.
        self.channelNames = tuple(self.eventAdminRef.getActiveChannels())
	self.acScrolledLB = Pmw.ScrolledListBox(channelGroup.interior(),
                                                selectioncommand = self.displayActiveChannel,
                                                hscrollmode = 'dynamic',
                                                vscrollmode = 'dynamic',
                                                items = self.channelNames)
        #make it big
	self.acScrolledLB.pack(side = 'left',
                               fill = 'both',
                               expand = 0,
                               padx = 8,
                               pady = 8)

        ############################################################
        ##Admin Panel
        self.adminChannelName = Pmw.EntryField(adminGroup.interior(),
                                               labelpos = 'w',
                                               label_text = 'Channel name:',
                                               validate = None)
        self.adminChannelName.pack(expand=0,
                                   padx=10,
                                   pady=5,
                                   side = 'top')

        self.adminChannelMethod = Pmw.OptionMenu(adminGroup.interior(),
                                                 labelpos = 'w',
                                                 label_text = 'Choose administrative option:',
                                                 items = ('Create', 'Destroy'), #items = ('Create', 'Destroy', 'Reconfigure'),
                                                 menubutton_width = 10)
        self.adminChannelMethod.pack(anchor = 'w', padx = 10, pady = 10)
        
        
        createChannelSubmit = Pmw.ButtonBox(adminGroup.interior())
	createChannelSubmit.pack(side = 'bottom')
	createChannelSubmit.add('Submit', text = 'Submit', command = self.submit)
        ############################################################
        
        #finally we can begin receiving CORBA callbacks.
        self.eventAdminRef.monitorEvents(self.corbaRef, CBDescIn(0L, 0L, 0L))
        
        #constantly look for new channels
        self.running = 1
        start_new_thread(self.pollActiveChannels, ())
        return
Exemplo n.º 14
0
class ACSEventAdminGUI(CBstring):
    '''
    ACSEventAdminGUI, derived from the IDL interface CBstring, is the primary GUI panel
    used with the ACSEventAdmin IDL interface.
    '''
    def __init__(self, parent, eventAdminRef, filename):
        '''
        Standard Constructor

        Paramters:
        - parent is the parent widget of this class
        - eventAdminRef is a reference to an ACSEventAdmin IDL interface

        Returns: Nothing

        Raises: ???
        '''

        self.archiveEventsFile = None 

        if filename != None:
           self.archiveEventsFile = file(filename, "w")

        #call superclass constructor
        CBstring.__init__(self)
        
        #time helper instance. used to format timestamps.
        self.timehelper = TimeUtil()
        
        #save the component reference
        self.eventAdminRef = eventAdminRef
        
        #activate ourself as a corba object
        self.corbaRef = self._this()

        #the fields that will be outputted for the Event browser
        self.ebFields = ["Timestamp", "Channel", "Source", "SupplierEvent#", "ChannelEvent#", "Type", "TypeEvent#"]
        #Layout of the columns
        self.ebFormat = '%25s %12s %12s %16s %15s %20s %15s'

        #Copy the parent widget
        self.parent = parent

        #place where we map events within the GUI to the real events
        self.outputEventMap = {}

        # Create and pack the MenuBar.
	menuBar = Pmw.MenuBar(parent,
                              hull_relief = 'raised',
                              hull_borderwidth = 1)
	menuBar.pack(fill = 'x')
	self.menuBar = menuBar
        
	menuBar.addmenu('Browser Options', 'Save, Clear, or Exit')
	menuBar.addmenuitem('Browser Options',
                            'command',
                            'Save events to a file',
                            command = self.saveEvents,
                            label = 'Save Events')
        menuBar.addmenuitem('Browser Options',
                            'command',
                            'Clear list of events from this browser',
                            command = self.clearEvents,
                            label = 'Clear Events')
        #--This does not work unless the modules for the events have been imported
        #--unfortunately. Commented out for now. DWF
        #menuBar.addmenuitem('Browser Options',
        #                    'command',
        #                    'Saves the events so they can be reloaded later.',
        #                    command = self.pickleEvents,
        #                    label = 'Pickle Events')
        #menuBar.addmenuitem('Browser Options',
        #                    'command',
        #                    'Loads pickled events into the browser.',
        #                    command = self.loadPickledEvents,
        #                    label = 'Load Pickled Events')
        
        #create the event browser group
        browserGroup = Pmw.Group(parent, tag_text='Event Browser')
	browserGroup.pack(fill='x', expand='1', side = 'top', padx = 5, pady = 3)
        
        headerLine = self.ebFormat % tuple(self.ebFields)
        
        #create the channel group
        channelGroup = Pmw.Group(parent, tag_text='Channels')
	channelGroup.pack(side = 'left', padx = 5, pady = 3)

        
        #create the admin group
        eventViewerGroup = Pmw.Group(parent, tag_text='Event Viewer')
	eventViewerGroup.pack(side = 'left', padx = 5, pady = 3)

        #create the admin group
        adminGroup = Pmw.Group(parent, tag_text='Channel Administration')
	adminGroup.pack(fill='both', expand='1', side = 'left', padx = 5, pady = 3)

        #-----------------------------------------------------------
        #--Event viewer box
        self.evST= Pmw.ScrolledText(eventViewerGroup.interior(),
                                    borderframe = 0,
                                    columnheader = 0,
                                    usehullsize = 1,
                                    hull_width = 300,
                                    hull_height = 300,
                                    text_wrap='none',
                                    text_font = Pmw.logicalfont('Fixed'),
                                    text_padx = 4,
                                    text_pady = 4)
        #make the scrolling text window big
	self.evST.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
        
        # Prevent users' modifying text and headers
        #self.evST.configure(text_state = 'disabled')
        
        ############################################################
        ##Event Browser#############################################
        # Create the ScrolledText with headers.
        
        self.ebST = Pmw.ScrolledListBox(browserGroup.interior(),
                                        items=(),
                                        labelpos='nw',
                                        label_text = "   " + headerLine,
                                        usehullsize = 1,
                                        hull_width = 1100,
                                        hull_height = 300,
                                        selectioncommand=self.displayEvent
                                        )

        #make the scrolling text window big
	self.ebST.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
        
        ############################################################
        #Active Channels############################################
	# Create and pack the simple ComboBox.
        self.channelNames = tuple(self.eventAdminRef.getActiveChannels())
	self.acScrolledLB = Pmw.ScrolledListBox(channelGroup.interior(),
                                                selectioncommand = self.displayActiveChannel,
                                                hscrollmode = 'dynamic',
                                                vscrollmode = 'dynamic',
                                                items = self.channelNames)
        #make it big
	self.acScrolledLB.pack(side = 'left',
                               fill = 'both',
                               expand = 0,
                               padx = 8,
                               pady = 8)

        ############################################################
        ##Admin Panel
        self.adminChannelName = Pmw.EntryField(adminGroup.interior(),
                                               labelpos = 'w',
                                               label_text = 'Channel name:',
                                               validate = None)
        self.adminChannelName.pack(expand=0,
                                   padx=10,
                                   pady=5,
                                   side = 'top')

        self.adminChannelMethod = Pmw.OptionMenu(adminGroup.interior(),
                                                 labelpos = 'w',
                                                 label_text = 'Choose administrative option:',
                                                 items = ('Create', 'Destroy'), #items = ('Create', 'Destroy', 'Reconfigure'),
                                                 menubutton_width = 10)
        self.adminChannelMethod.pack(anchor = 'w', padx = 10, pady = 10)
        
        
        createChannelSubmit = Pmw.ButtonBox(adminGroup.interior())
	createChannelSubmit.pack(side = 'bottom')
	createChannelSubmit.add('Submit', text = 'Submit', command = self.submit)
        ############################################################
        
        #finally we can begin receiving CORBA callbacks.
        self.eventAdminRef.monitorEvents(self.corbaRef, CBDescIn(0L, 0L, 0L))
        
        #constantly look for new channels
        self.running = 1
        start_new_thread(self.pollActiveChannels, ())
        return
    #------------------------------------------------------------------------------
    def displayEvent(self):
        '''
        Displays a single ICD-style event on the screen.
        '''
        #get the key
        t_key = self.ebST.getcurselection()[0]

        #get a textual representation
        t_list = getTextRepresentation(self.outputEventMap[t_key])

        #clear the box
        self.evST.clear()
        #write it to the box
        for line in t_list:
            self.evST.insert('end', line + '\n')
        
        return
    
    #------------------------------------------------------------------------------
    def displayActiveChannel(self):
        '''
        When someone clicks on a channel, a new widget is spawned displaying various
        pieces of information

        Paramters: None

        Returns: Nothing

        Raises: ???
        '''
        #just depend on a helper class to do the real work
        self.displayChannelHelper(list(self.acScrolledLB.getcurselection()))
    #------------------------------------------------------------------------------
    def displayChannelHelper(self, channelList):
        '''
        Responsibile for spawning a new widget displaying channel info. This is a
        recursive method so end-users can highlight multiple channels at the same time.
        Really this can never be the case given the current implementation though.

        Parameters:
        - channelList is a list of channel names

        Returns: Nothing

        Raises: ???
        '''
        #if this is the last call in the recursive chain...return control
        if len(channelList) == 0:
            return
        #pop a channel name; create a new widget; and make a recursive call
        else:
            #last channelName from the list
            channelName = channelList.pop()
            
            #get the channel info
            data = self.eventAdminRef.getChannelInfo(channelName)
            
            #create a new widget
            message  = "Channel name: " + str(channelName) + '\n'
            message += "Number of suppliers: " + str(data[0]) + '\n'
            message += "Number of consumers: " + str(data[1]) + '\n'
            message += "Total events recieved: " + str(data[2]) + '\n'
            message += "EventTypeInfo:\n"
            for eventType in data[5]:
                message += "     " + str(eventType) + '\n'
            ChannelInfo(self.parent, message_text = message, icon_bitmap = 'info')
            
            #recursive call
            self.displayChannelHelper(channelList)
            return        
    #------------------------------------------------------------------------------
    def working (self, value, completion, desc):
        '''
        Overriden method from the CBstring class which is invoked each time an event
        is received. The event is outputted to a scrolled textbox widget.

        Parameters:
        - value is the stringified event
        - completion is a CORBA completion structure
        - desc is callback struct description

        Returns: Nothing

        Raises: ???
        '''
        global EVENT_CACHE
        
        #to make pychecker happy
        del completion

        #to make pychecker happy
        del desc

        #backup
        orig_val = value
        
        # Create a new data row
        value = string.split(value)

        #convert the time to something human-readable
        epoch = acstime.Duration(long(value[0]))  #convert to an ACS epoch
        epoch = self.timehelper.epoch2py(epoch)  #convert to Python time
        epoch = gmtime(epoch)  #convert to gm time
        epoch = asctime(epoch)  #convert to nice string format
        
        dataLine = self.ebFormat % (epoch, value[1], value[2], value[3], value[4], value[5], value[6])  #tuple(value)

        #output the line to the GUI
        self.ebST.insert('end', dataLine)

        #if we are logging events to a file, save the event
        if self.archiveEventsFile != None:
           self.archiveEventsFile.write(dataLine)
           self.archiveEventsFile.write("\n")
           self.archiveEventsFile.flush()
    
        #save the original output for use with the cache
        try:
            self.outputEventMap[dataLine] = EVENT_CACHE[orig_val]
        except:
            self.outputEventMap[dataLine] = None
        
        return
    #------------------------------------------------------------------------------
    def pollActiveChannels(self):
        '''
        Gets an updated list of all notification channels and outputs them to the GUI.
        Designed to be invoked from a thread.

        Parameters: None

        Returns: Nothing

        Raises: ???
        '''
        while self.running:
            try:
                #list of all the channels the administrator knows about
                self.channelNames = tuple(self.eventAdminRef.getActiveChannels())
                
                #update the GUI
                self.acScrolledLB.setlist(self.channelNames)
            except:
                pass
            
            #sleep for awhile
            sleep(2)
    #------------------------------------------------------------------------------
    def saveEvents(self):
        '''
        Prompts user for a filename, then saves the entire list of all known events to the given text file.

        Parameters: None

        Returns: Nothing

        Raises: ???
        '''
        #save the events to the text file specified in the GUI
        filename = asksaveasfilename()
        if filename!=():
            # open the file
            temp_file = file(filename, "w")
            # write the events to the file, adding a new line after each event
            temp_file.writelines('\n'.join(self.ebST.get()))
            # close the file
            temp_file.close()
    
    #------------------------------------------------------------------------------
    def clearEvents(self):
        '''
        Saves the entire list of all known events to a given text file.

        Parameters: None

        Returns: Nothing

        Raises: ???
        '''
        global EVENT_CACHE
        
        #save the events to the text file specified in the GUI
        print dir(self.ebST)
        self.ebST.clear()
        self.evST.clear()
        #clear the caches
        EVENT_CACHE.clear()
        self.outputEventMap.clear()
    #------------------------------------------------------------------------------
    def pickleEvents(self):
        '''
        Pickles the list of all known events to a given file.

        Parameters: None

        Returns: Nothing

        Raises: ???
        '''
        #save the events to the text file specified in the GUI
        filename = asksaveasfilename()
        if filename!=():
            #open it
            temp_file = open(filename, "w")
            #dump the cache into the file
            pickle.dump(self.outputEventMap, temp_file)
            #close it
            temp_file.close()

    #------------------------------------------------------------------------------
    def loadPickledEvents(self):
        '''
        Loads a pickled list of all known events from a given file.

        Parameters: None

        Returns: Nothing

        Raises: ???
        '''
        #get the file containing the pickled cache from the user
        temp_file = askopenfile('r')
        #create a temporary dictionary with the cache
        t_cache = pickle.load(temp_file)
        #cleanup
        temp_file.close()
        
        #wipe out all of the old events
        self.clearEvents()

        #fill the cache again
        self.outputEventMap.update(t_cache)
        
        #populate the GUI with the events
        for key in self.outputEventMap.keys():
            self.ebST.insert('end', key)

        return
        
    #------------------------------------------------------------------------------
    def stopArchiving(self):
        '''
        Can be called to stop the archiving to a file.
        '''
        if self.archiveEventsFile != None:
           self.archiveEventsFile.close()
           self.archiveEventsFile = None

    #------------------------------------------------------------------------------
    def submit(self):
        '''
        Called each time the user tries to invoke some administrative function.
        DWF - needs a lot of work still.
        '''
        method = str(self.adminChannelMethod.getcurselection())
        parameter = str(self.adminChannelName.getvalue())

        #('Create', 'Destroy', 'Reconfigure')
        if method == 'Create':
            self.eventAdminRef.createChannel(parameter, [], [])
        elif method == 'Destroy':
            self.eventAdminRef.destroyChannel(parameter)
        elif method == 'Reconfigure':
            self.eventAdminRef.configChannelProperties(parameter, [], [])
            print "Reconfigure not yet implemented"
Exemplo n.º 15
0
    def sendLog(self, record):
        '''
        Method which sends logs to the real ACS logging service.
        '''
        if (not self.logThrottle.checkPublishLogRecord()):
            if self.logThrottleAlarmSender != None and not self.logThrottleAlarmActive:
                self.logThrottleAlarmActive = True
                self.logThrottleAlarmSender.sendThrottleAlarm(True)
            return
        else:
            if self.logThrottleAlarmSender != None and self.logThrottleAlarmActive:
                self.logThrottleAlarmActive = False
                self.logThrottleAlarmSender.sendThrottleAlarm(False)

        # Create an RTContext object
        rt_context = ACSLog.RTContext(
            str(record.threadName).replace("<", "").replace(">", ""),
            str(record.source).replace("<", "").replace(">", ""),
            str(gethostname()).replace("<", "").replace(">", ""), "",
            str(record.name).replace("<", "").replace(">", ""))

        src_info = ACSLog.SourceInfo(
            str(record.module).replace("<", "").replace(">", ""), "Unknown",
            long(record.lineno))

        # Put remaining keyword arguments into NVPairSeq
        data = []

        if TimeUtil().py2epoch(time()).value > TimeUtil().py2epoch(
                record.created + self.timestampThreshold).value:
            # Reformat the record
            originalMsg = NVPair("Original message", record.getMessage())
            data.append(originalMsg)
            originalTimestamp = NVPair("Original timestamp", record.asctime)
            data.append(originalTimestamp)

            record = self.replaceOldRecord(record)

        #timestamp
        acs_timestamp = TimeUtil().py2epoch(record.created).value

        if 'priority' in record.__dict__:
            # The more exotic log functions have priority keyword arguments
            if 'errortrace' in record.__dict__:
                # The message is an ErrorTrace.
                self.logSvc.logErrorWithPriority(record.errortrace,
                                                 record.priority)
            elif 'data' in record.__dict__:
                # The message is a type-safe log message
                self.logSvc.logWithPriority(
                    record.priority, acs_timestamp, record.getMessage(),
                    record.rtCont if 'rtCont' in record.__dict__
                    and record.rtCont is not None else rt_context,
                    record.srcInfo if 'srcInfo' in record.__dict__
                    and record.srcInfo is not None else src_info, record.data,
                    record.audience, record.array, record.antenna)
            else:
                # The message is a not-so-type-safe message
                self.logSvc.logWithAudience(record.priority, acs_timestamp,
                                            record.getMessage(), rt_context,
                                            src_info, record.audience,
                                            record.array, record.antenna)
        elif record.levelname == 'TRACE':
            self.logSvc.logTrace(acs_timestamp, record.getMessage(),
                                 rt_context, src_info, data)
        elif record.levelname == 'DELOUSE':
            self.logSvc.logDelouse(acs_timestamp, record.getMessage(),
                                   rt_context, src_info, data)
        elif record.levelname == 'DEBUG':
            self.logSvc.logDebug(acs_timestamp, record.getMessage(),
                                 rt_context, src_info, data)
        elif record.levelname == 'INFO':
            self.logSvc.logInfo(acs_timestamp, record.getMessage(), rt_context,
                                src_info, data)
        elif record.levelname == 'NOTICE':
            self.logSvc.logNotice(acs_timestamp, record.getMessage(),
                                  rt_context, src_info, data)
        elif record.levelname == 'WARNING' or record.levelname == 'WARN':
            self.logSvc.logWarning(acs_timestamp, record.getMessage(),
                                   rt_context, src_info, data)
        #this is a special case because logError only takes
        #in error traces
        elif record.levelname == 'ERROR':
            self.logSvc.logWithAudience(ACSLog.ACS_LOG_ERROR, acs_timestamp,
                                        record.getMessage(), rt_context,
                                        src_info, NO_AUDIENCE, "", "")
        elif record.levelname == 'CRITICAL':
            self.logSvc.logCritical(acs_timestamp, record.getMessage(),
                                    rt_context, src_info, data)
        elif record.levelname == 'ALERT':
            self.logSvc.logAlert(acs_timestamp, record.getMessage(),
                                 rt_context, src_info, data)
        elif record.levelname == 'EMERGENCY':
            self.logSvc.logEmergency(acs_timestamp, record.getMessage(),
                                     rt_context, src_info, data)
        #failsafe
        else:
            self.logSvc.logCritical(acs_timestamp, record.getMessage(),
                                    rt_context, src_info, data)
Exemplo n.º 16
0
 def testLogTypeSafeInvalidPriority(self):
     """Logger class Type-safe logging with invalid priority"""
     msg = "LogTypeSafe Message"
     ts = TimeUtil().py2epoch(time.time()).value
     self.assertRaises(KeyError, self.mylogger.logTypeSafe, 25, ts, msg,
                       None, None, None)