Splunk® Enterprise

Module System User Manual

Download manual as PDF

Download topic as PDF

Example 6 - Include 3rd-party libraries

Important notice: As part of Advanced XML deprecation, the Module System is officially deprecated beginning with Splunk Enterprise 6.3. For more information, see Advanced XML Deprecation.

Example6.xml

<view template="dashboard.html">

 <label>Example 6: Rendering a Treemap Visualization</label>
 <module name="AccountBar" layoutPanel="appHeader"/>
 <module name="AppBar" layoutPanel="navigationHeader"/>
 <module name="Message" layoutPanel="messaging">
   <param name="filter">*</param>
   <param name="clearOnJobDispatch">False</param>
   <param name="maxSize">1</param>
 </module>
  
 <module name="StaticContentSample" layoutPanel="panel_row1_col1">
   <param name="text"><![CDATA[

<h1>Example 6: Rendering a Treemap Visualization</h1> <p> This simple application searches the metrics log and lists the CPU utilization of each processor of each indexer stage. </p> <p> Search string: <tt>index=_internal source=*metrics.log group=pipeline | stats sum(cpu_seconds) as totalCPU by name, processor</tt> </p> <p> JSON-formatted results are returned and rendered as a treemap using the custom <tt>TreeMap</tt> module. Treemap rectangles are sized by CPU utilization, with processors grouped by indexer type. </p> ]]></param>

 </module>
  
 <module name="HiddenSearch" layoutPanel="panel_row2_col1" group="CPU utilization thresholds" autoRun="True">
   <param name="search">index=_internal source=*metrics.log group=pipeline | stats sum(cpu_seconds) as totalCPU by name, processor</param>
   <param name="earliest">-7d</param>
   <module name="TreeMap"></module>
 </module>

</view> ]]>

TreeMap.conf

[module]
# The JavaScript name of the module
className = Splunk.Module.TreeMap
 
# The module class to subclass from
superClass = Splunk.Module.DispatchingModule
 
description = this module waits for the search to complete, formats JSON data, and renders results in a tabular format.
 
[param:myParam]
required = False
default = none
label = This is an example parameter (not currently used).

TreeMap.html

<%page args="module" expression_filter="h"/> <%namespace name="lib" file="//lib.html" import="*"/> <%lib:script_tags files="[u'/static/app/Dev_tutorial/protovis.js']" />

   <div id="TreeMapID" class="TreeMapResults"></div>

TreeMap.js

// A treemap renderer Splunk.Module.TreeMap = $.klass(Splunk.Module.DispatchingModule, {

   initialize: function($super, container) {
       $super(container);
       this.myParam = this.getParam("myParam");
       this.resultsContainer = this.container;
   },

   onJobDone: function(event) {
       this.getResults();
   },

   getResultParams: function($super) {
       var params = $super();
       var context = this.getContext();
       var search = context.get("search");
       var sid = search.job.getSearchId();

       if (!sid) this.logger.error(this.moduleType, "Assertion Failed.");

       params.sid = sid;
       return params;
   },

   renderResults: function($super, results) {

       if(!results) {
       this.resultsContainer.html('No content available.');
           return;
       }
       var re = "";
       var color = pv.Colors.category19().by(function(d){return d.parentNode.nodeName});
       var nodes = pv.dom(results).root("flare").nodes();
        
       var vis = new pv.Panel().width(920).height(420).canvas(document.getElementById('TreeMapID'));
        
       var treemap = vis.add(pv.Layout.Treemap).nodes(nodes).round(true);
        
       treemap.leaf.add(pv.Panel).fillStyle(function(d){return color(d).alpha(1)}).strokeStyle("#fff").lineWidth(1).antialias(false);
        
       treemap.label.add(pv.Label).textStyle(function(d){return pv.rgb(0, 0, 0, 1)});
        
       vis.render();
   }

})

TreeMap.py

import cherrypy import controllers.module as module

import splunk, splunk.search, splunk.util, splunk.entity import json from splunk.appserver.mrsparkle.lib import jsonresponse import lib.util as util import lib.i18n as i18n

import logging logger = logging.getLogger('splunk.module.TreeMap')

import math import cgi

class TreeMap(module.ModuleHandler):

   def generateResults(self, host_app, client_app, sid, count=1000,
           offset=0, entity_name='results'):

       count = max(int(count), 0)
       offset = max(int(offset), 0)
       if not sid:
           raise Exception('TreeMap.generateResults - sid not passed!')

       try:
           job = splunk.search.getJob(sid)
       except splunk.ResourceNotFound, e:
           logger.error('TreeMap could not find job %s. Exception: %s' % (sid, e))
           return _('<p class="resultStatusMessage">Could not get search data.</p>')
        
       dataset = getattr(job, entity_name)[offset: offset+count]

       outputJSON = {}
       for i, result in enumerate(dataset):
           tdict = {}
           tdict[str(result.get('processor', None))] = str(result.get('totalCPU', None))
           name = str(result.get('name', None))
           if name not in outputJSON:
               outputJSON[name] = dict()
           outputJSON[name].update(tdict)

       cherrypy.response.headers['Content-Type'] = 'text/json'
       return json.dumps(outputJSON, sort_keys=True)
        
   def render_json(self, response_data, set_mime='text/json'):
       cherrypy.response.headers['Content-Type'] = set_mime

       if isinstance(response_data, jsonresponse.JsonResponse):
           response = response_data.toJson().replace("</", "<\\/")
       else:
           response = json.dumps(response_data).replace("</", "<\\/")

       return ' ' * 256  + '\n' + response
PREVIOUS
Render JSON data
  NEXT
Example 7 - Parameterize your module

This documentation applies to the following versions of Splunk® Enterprise: 6.3.0, 6.3.1, 6.3.2, 6.3.3, 6.3.4, 6.3.5, 6.3.6, 6.3.7, 6.3.8, 6.3.9, 6.3.10, 6.3.11, 6.3.12, 6.3.13, 6.4.0, 6.4.1, 6.4.2, 6.4.3, 6.4.4, 6.4.5, 6.4.6, 6.4.7, 6.4.8, 6.4.9, 6.4.10, 6.5.0, 6.5.1, 6.5.1612 (Splunk Cloud only), 6.5.2, 6.5.3, 6.5.4, 6.5.5, 6.5.6, 6.5.7, 6.5.8, 6.5.9, 6.6.0, 6.6.1, 6.6.2, 6.6.3, 6.6.4, 6.6.5, 6.6.6, 6.6.7, 6.6.8, 6.6.9, 6.6.10, 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5, 7.0.6, 7.1.0, 7.1.1, 7.1.2, 7.1.3


Was this documentation topic helpful?

Enter your email address, and someone from the documentation team will respond to you:

Please provide your comments here. Ask a question or make a suggestion.

You must be logged into splunk.com in order to post comments. Log in now.

Please try to keep this discussion focused on the content covered in this documentation topic. If you have a more general question about Splunk functionality or are experiencing a difficulty with Splunk, consider posting a question to Splunkbase Answers.

0 out of 1000 Characters