Splunk® Enterprise

Module System User Manual

Download manual as PDF

Download topic as PDF

Example 7 - Parameterize your module

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.

Example7.xml

<view template="dashboard.html">

 <label>Example 7: Parameterizing a Module</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 7: Parameterizing a Module</h1> <p> This example shows you how to statically parameterize your module when the app starts by specifying properties in the module configuration file. </p> <p> Search string: <tt>index=_internal source=*metrics.log group=pipeline | stats sum(cpu_seconds) as totalCPU by name, processor</tt> </p> <p> Example6 used hardcoded values for the treemap height and width. This example lets you specify those values in the <tt>ParameterizedTreeMap.conf</tt> configuration file. </p> ]]></param>

 </module>
  
 <module name="HiddenSearch" layoutPanel="panel_row2_col1" group="Threshold events" 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="ParameterizedTreeMap"></module>
 </module>

</view> ]]>

ParameterizedTreeMap.conf

[module]
# The JavaScript name of the module
className = Splunk.Module.ParameterizedTreeMap
 
# The module class to subclass from
superClass = Splunk.Module.DispatchingModule
 
[param:tmapWidth]
required = False
default = 640
label = This parameter defines the treemap width.
description = this module waits for the search to complete, formats JSON data, and renders a treemap.
 
[param:tmapHeight]
required = False
default = 320
label = This parameter defines the treemap height.

ParameterizedTreeMap.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="ParameterizedTreeMapID" class="ParameterizedTreeMapResults"></div>

ParameterizedTreeMap.js

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

   initialize: function($super, container) {
       $super(container);
       this.resultsContainer = this.container;
       this.tmapHeight = this.getParam('tmapHeight', 920);
       this.tmapWidth = this.getParam('tmapWidth', 420);
   },

   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(this.tmapWidth).height(this.tmapHeight).canvas(document.getElementById('ParameterizedTreeMapID'));
        
       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();
   }

})

ParameterizedTreeMap.py

# # Splunk UI module python renderer # This module is imported by the module loader (lib.module.ModuleMapper) into # the splunk.appserver.mrsparkle.controllers.module.* namespace. #

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.ParameterizedTreeMap')

import math import cgi

class ParameterizedTreeMap(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('ParameterizedTreeMap.generateResults - sid not passed!')

       try:
           job = splunk.search.getJob(sid)
       except splunk.ResourceNotFound, e:
           logger.error('ParameterizedTreeMap 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)

# return self.render_json(outputJSON)

   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("</", "<\\/")

       # Pad with 256 bytes of whitespace for IE security issue. See SPL-34355
       return ' ' * 256  + '\n' + response
PREVIOUS
Example 6 - Include 3rd-party libraries
 

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, 6.6.11, 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5, 7.0.6, 7.0.7, 7.1.0, 7.1.1, 7.1.2, 7.1.3, 7.2.0


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