Beispiel für vollständiges Custom Search Dashboard

Dieses Beispiel zeigt ein vollständiges Script, eine Anwendungsdatei und die resultierende Anzeige für ein angepasstes Suchdashboard mit dem Namen Performance_Msgs.

Script 'Performance_Msgs.py'

Das folgende Beispiel zeigt das Script Performance_Msgs.py, das Daten für Nachrichten über das Leistungsverhalten erfasst. Details können Sie den Codierungshinweisen im Script entnehmen.

######################################################### {COPYRIGHT-TOP} ###
# Licensed Materials - Property of IBM
# "Restricted Materials of IBM"
# 5725-K26
#
# (C) Copyright IBM Corp. 2013  All Rights Reserved.
#
# US Government Users Restricted Rights - Use, duplication, or
# disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
######################################################### {COPYRIGHT-END} ###
#Install simple json before trying the script

#Installing simplejson
# Download the rpm from 
http://pkgs.org/centos-5-rhel-5/centos-rhel-x86_64
/python-simplejson-2.0.9-8.el5.x86_64.rpm/download/
# Run the command rpm -i python-simplejson-2.0.9-8.el5.x86_64.rpm


from datetime import datetime, date, time, timedelta
import sys
from unity import UnityConnection, get_response_content
try:
    import json
except ImportError:
    import simplejson as json

#------------------------------------------------------
# getSearchData()
#------------------------------------------------------
def getSearchData(logsource, filter):

    # Build the request parameters using the Search Request APIs.
    # The logsource and filter values used in the query were passed
    # in as parameters to the script.
    request = {
        "start": 0,
        "results": 1,
        "filter": filter, 
        "logsources": logsource, 
        "query": "*",
        "sortKey":["-timestamp"],
        "getAttributes":["timestamp","perfMsgId"],
        "facets":{
            "dateFacet":{
                "date_histogram":{
                    "field":"timestamp",
                    "interval":"hour",
                    "outputDateFormat":"MM-dd HH:mm",
                    "nested_facet":{
                        "dlFacet":{
                            "terms":{
                                "field":"perfMsgId",
                                "size":20
                            }
                        }
                    }
                }
            }
        }
    } 
       
    # Post the search request
    response = connection.post
    ('/Search', json.dumps(request), content_type='application/json;
     charset=UTF-8');
    content = get_response_content(response)
	
	#convert the response data to JSON
    data = {}
    try:
		data = json.loads(content)
    except:
		pass
    if 'result' in data:
		result = data['result']
		if 'status' in result and result['status'] == 'failure':
			msg = result['message']
			print >> sys.stderr, msg
			sys.exit(1)

    return data

#------------------------------------------------------
# dateSort()
#------------------------------------------------------
def dateSort(dateFacet):
    # This function parses the UTC label found in the dateFacet in the
    # format "mm-hh-DDD-yyyy UTC"
    # and returns an array in the form [yyyy, DD, hh, mm]
    def parseDate(dateLabel):
        aDate = map(int, dateLabel.split(" ")[0].split("-"))
        aDate.reverse()
        return aDate
    
    # call an in-place List sort, using an anonymous function lambda 
    # as the sort function
    dateFacet.sort(lambda facet1, facet2:
    cmp(parseDate(facet1['label']), parseDate(facet2['label'])))
    return dateFacet



#--------------------------------------------------------------------------
# Main script starts here
#--------------------------------------------------------------------------

# define the URLs used for the http request
baseurl = 'https://localhost:9987/Unity'

connection = UnityConnection(baseurl, 'unityadmin', 'unityadmin')
connection.login()

# initialize variables
filter = {}
logsource = {}
chartdata = []

# Get the script parameters which were passed in via a temporary
# file in JSON format.  The name of the temporary file is in argv[1]
if len(sys.argv) > 1:
    filename = str(sys.argv[1])
    fk = open(filename,"r")
    data = json.load(fk)

    parameters = data['parameters']
    for i in parameters:
        if i['name'] == 'search':
            search = i['value']
            for key in search.keys():
                if key == 'filter':
                    filter = search['filter']
                elif key == 'logsources':
                    logsource = search['logsources'] 
	
	
#------------------------------------------------------
# get the data to be returned
#------------------------------------------------------

# define the fields to be returned in the chart data
# each row will contain the date, perfMsgId, and count
fields = [
    { "id":"date", "label":"Timestamp", "type":"TEXT"},
    { "id":"perfMsgId", "label":"perfMsgId", "type":"TEXT" },
    { "id":"count", "label":"count", "type":"LONG"}
]

rows = []

    
# call getSearchData() to post the search request and retrieve the data
data = getSearchData(logsource, filter)
    
if 'facetResults' in data:
   
    # get the facet results
    facetResults = data['facetResults']    
    #print 
    json.dumps(facetResults, sort_keys=False,indent=4, separators=(',', ': '))

    if 'dateFacet' in facetResults:
        # get the dateFacet rows
        dateFacet = facetResults['dateFacet']
        
        # the results of the dateFacet are not sorted, so call dateSort()
        dateSort(dateFacet)
            
        # iterate through each row in the dateFacet    
        for dateRow in dateFacet:
            for msgRow in dateRow['nested_facet']['dlFacet']['counts']:
                # create a row which includes the date, perfMsgId, and count
                rows.append({"date":dateRow['low'], "perfMsgId":msgRow['term'],
                "count":msgRow['count']} );
                #print rows
            
# create chart data with the id perfMsgIdCountsOverTime             
chartdata.append({'id':'perfMsgIdCountsOverTime','fields':fields, 'rows':rows})

# close the connection
connection.logout()

#------------------------------------------------------
# Create the HTML data to be returned
#------------------------------------------------------
html = "<!DOCTYPE html><html><body><h1>Hello World!</h1></body></html>"</p><p>
chartdata.append({"id": "htmlData", "htmltext": html })

 #------------------------------------------------------
# Build the final output data JSON
#------------------------------------------------------

# build the JSON structure containing the chart data which will be the
# output of this script
appData = {'data':chartdata}

#Print the JSON to system out
print json.dumps(appData, sort_keys=False,indent=4, separators=(',', ': '))
         

Datei 'Performance_Msgs.app'

Dieses Beispiel zeigt die Anwendungsdatei Performance_Msgs.app , die auf das Script Performance_Msgs.py verweist und das Diagramm angibt, das für das Dashboard für angepasste Sucheangezeigt werden soll.

{
    "name": "Performance Messages",  
    "description": "Displays charts showing performance messages over time",
    "customLogic": {
        "script": "Performance_Msgs.py",
        "description": "View chart on search results",
        "parameters": [
            {
                "name": "search",
                "type": "SearchQuery",
                "value": {
			        "filter": {
            			"range": {
                      		"timestamp":{
            	            	"from":"01/01/2013 00:00:00.000 EST",
                	        	"to":"01/01/2014 00:00:00.000 EST",
                    	    	"dateFormat":"MM/dd/yyyy HH:mm:ss.SSS Z"
                    		}
            			}
        			},
                    "logsources": [
                        {
                            "type": "logSource",
                            "name": "MyTest"
                        }
                    ],
                }
            },
        ],
        "output": {
            "type": "Data",
            "visualization": {
                "dashboard": {
                    "columns": 2,
                    "charts": [
 						{
                            "type": "Stacked Bar Chart",
                            "title": "Performance Message ID Counts - Last Year",
                            "data": {
                                "$ref": "perfMsgIdCountsOverTime"
                            },
                            "parameters": {
                                "xaxis": "date",
                                "yaxis": "count",
                                "categories": "perfMsgId"
                            }
                        },
                        {
                            "type": "html",
                            "title": "My Test - Expert Advice",
                            "data": {
                                "$ref": "htmlData"
                            },
                            "parameters": {
                                "html": "text"
                            }
                        }
                        
                    ]
                }
            }
        }
    }
}

Diagramm 'Performance_Msgs'

Das Diagramm zeigt die Anzahl der einzelnen Nachrichten für jeden Tag an.

Diagramm, das die Anzahl der verschiedenen Nachrichten für jeden Tag zeigt.