Friday, March 7, 2014

include search results as HTML content in Splunk6 simple xml

There is currently no native implementation in Splunk6 simple xml for including search results as HTML content in dashboard panels.

But Splunk6 allows it to easily inject custom javascript code into its simle xml structure. So here is a simple example that transforms a search result into HTML code and displays it in a simple xml dasboard panel

The basic search in this example counts the number of events over the last 7 days in the _internal index

> index=_internal |stats count


The simple XML

The simple XML panel we want to display in our panel should look as follows

<row>
<html>
  <h2>HTML content example</h2>
  <hr />
  <font size="3" color="red">
    <div id="htmlcontent-search"
      class="splunk-manager splunk-searchmanager"
      data-require="splunkjs/mvc/searchmanager"
      data-options='{
        "app": "htmlcontent-example",
        "search":  "index=_internal |stats count(sourcetype)",
        "earliest_time": "-7d",
        "preview": true
      }'/>
    <div id="htmlcontent"
      class="splunk-view"
      data-require="app/htmlcontent-example/components/htmlcontent/htmlcontent"
      data-options='{
      "managerid": "htmlcontent-search"
    }'/>
  </font>
  <hr />
</html>
</row>


As you can see we place the code in the App "htmlcontent-example" and refer to a directory called "app/htmlcontent-example/components/htmlcontent/htmlcontent". In this directory we will later place our javascript code. 


autoload javascript code

But first we have to make sure that the code in the htmlcontent directory will be loaded by Splunk when needed. Therefore we place a small javascript discover file called "autodiscover.js" in the app's static directory and call it in our dashboard

$app_home/appserver/static/autodiscover.js:

require.config({
    paths: {
        "app": "../app"
    }
});

require(['splunkjs/mvc/simplexml/ready!'], function(){

    require(['splunkjs/ready!'], function(){
    });
});

Include autodiscover.js in the <dashboard> tag of your simple xml

<dashboard script="autodiscover.js">

[...]
</dashboard>


the custom javascript 

Transformation into HTML code is done in a custom javascript file called "htmlcontent.js" 

$app_home/appserver/static/components/htmlcontent/htmlcontent.js

The script extends the SimpleSplunkView class from Splunk. It takes the first element from the search result and writes it back to the panel element.

define(function(require, exports, module) {
  [...]
  var HTMLContent = SimpleSplunkView.extend({

    [...]
    updateView: function(viz, data) {
      var myResults = data[0];
      this.$el.html(myResults);
    }
  });
  return HTMLContent;
});

Finally, the dashboard panel should look something like this:





.. That's it, get the full source code on >> github

No comments:

Post a Comment