Dashboards & Visualizations

Dashboard button to run SPL on click

christoffertoft
Communicator

How can I add functionality to a button to make it append results to a csv file?

Currently I have the following js (@kamlesh_vaghela s - given in this answer)

require([
  'underscore',
  'jquery',
  'splunkjs/mvc',
  'splunkjs/mvc/tableview',
  'splunkjs/mvc/simplexml/ready!'
], function(_, $, mvc, TableView) {
  // Access the "default" token model
  var tokens = mvc.Components.get("default");
  var selected_values_array = [];
  var submittedTokens = mvc.Components.get('submitted');

  var CustomRangeRenderer = TableView.BaseCellRenderer.extend({
    canRender: function(cell) {
      return _(['checkbox']).contains(cell.field);
    },
    render: function($td, cell) {
      var a = $('<div>').attr({"id":"chk-sourcetype"+cell.value,"value":cell.value})
        .addClass('checkbox').click(function() {
        // console.log("checked",$(this).attr('class'));
        // console.log("checked",$(this).attr('value'));
        if($(this).attr('class')==="checkbox")
        {
          selected_values_array.push($(this).attr('value'));
          $(this).removeClass();
          $(this).addClass("checkbox checked");
        }
        else {
          $(this).removeClass();
          $(this).addClass("checkbox");
          var i = selected_values_array.indexOf($(this).attr('value'));
          if(i != -1) {
            selected_values_array.splice(i, 1);
          }
          // Change the value of a token $mytoken$
        }
        console.log(selected_values_array);
      }).appendTo($td);
    }
  });

  //List of table IDs
  var tableIDs = ["myTable"];
  for (i=0;i<tableIDs.length;i++) {
    var sh = mvc.Components.get(tableIDs[i]);
    if(typeof(sh)!="undefined") {
      sh.getVisualization(function(tableView) {
        // Add custom cell renderer and force re-render
        tableView.table.addCellRenderer(new CustomRangeRenderer());
        tableView.table.render();
      });
    }
  }
  $(document).ready(function () {
    $("#mybutton").on("click", function (e) {
      e.preventDefault();
      console.log("in");
      tokens.set("mytoken", selected_values_array.join());
      submittedTokens.set(tokens.toJSON());
    });
  });
});

Is there a way to make the button only perform an outputlookup to append the chosen values to a CSV file?

I have the following dashboard, which does add the rows succesfully to a csv, but it also shows a search panel with the results. I don't need this, but I dont know how to make the button only update the csv?

<form script="checkboxes.js" stylesheet="my.css">
   <row>
     <panel>
       <table id="myTable">
         <title>My Table</title>
         <search>
           <query>index=_internal NOT [|inputlookup dontshow | fields sourcetype] | stats count by sourcetype  | eval checkbox=sourcetype</query>
           <earliest>-15m</earliest>
           <latest>now</latest>
         </search>
         <option name="count">10</option>
         <option name="drilldown">row</option>
         <drilldown>
           <condition field="*">

           </condition>
           </drilldown>
       </table>
     </panel>
   </row>
   <row>
     <html>
       <div>
         <input type="button" id="mybutton" value="My Button" />
       </div>
     </html>
   </row>
   <row>
      <panel>
       <table>
         <title>My Selected Value</title>
         <search>
           <query>| makeresults | eval sourcetype="$mytoken$" | makemv delim="," sourcetype | stats count by sourcetype | table sourcetype | outputlookup append=t dontshow.csv </query>
           <earliest>-15m</earliest>
           <latest>now</latest>
         </search>
         <option name="count">10</option>
         <option name="drilldown">none</option>
       </table>
     </panel>
   </row>
 </form>
0 Karma

niketn
Legend

@christoffertoft, I created button behavior using Checkbox just to avoid JavaScript, as that is what mostly gets asked 🙂 You are right with JavaScript you can implemented whatever your want. So please find below run anywhere dashboard with similar out as above, but it uses Splunk Style Submit Button to Push search results to Lookup using JavaScript. PS: The outputlookup query building the lookup file on Button click is reset on changing the time range using Simple XML change event handler for dropdown input. This is also used to hide the results from lookup file which is only displayed after button is clicked and new search results are pushed to lookup file.

alt text

Following is the Run anywhere Simple XML dashboard code:

<form script="push_to_csv.js">
  <label>Click Button to Push Results to CSV Lookup Using JS</label>
  <!-- Run only on Click on Submit -->
  <search base="baseQuery">
    <query>$tokQueryOutputLookup$</query>
  </search>
  <fieldset submitButton="false"></fieldset>
  <row>
    <panel>
      <title>Query to Generate Source Table</title>
      <input type="dropdown" token="tokDay" searchWhenChanged="true">
        <label>Get Previous Day Stats</label>
        <choice value="earliest=-0d@d latest=now">Today</choice>
        <choice value="earliest=-1d@d latest=-0d@d">Yesterday</choice>
        <choice value="earliest=-7d@d latest=-6d@d">Last Week Same Day</choice>
        <default>earliest=-7d@d latest=-6d@d</default>
        <change>
          <unset token="tokQueryOutputLookup"></unset>
        </change>
      </input>
      <table>
        <search id="baseQuery">
          <query>index=_internal sourcetype=splunkd log_level!=INFO $tokDay$
| bin _time span=15m
| stats count as Errors by _time
| timechart span=1h sum(Errors) as Errors avg(Errors) as Average min(Errors) as Minimum  perc25(Errors) as Percentile25 perc75(Errors) as Percentile75 max(Errors) as Maximum
| fillnull value=0
| eval Average=round(Average)
| eval perc75=round(perc75)
| table _time Errors Minimum Average Percentile75 Maximum</query>
          <earliest>-24h@h</earliest>
          <latest>now</latest>
          <sampleRatio>1</sampleRatio>
        </search>
        <option name="count">10</option>
        <option name="dataOverlayMode">none</option>
        <option name="drilldown">none</option>
        <option name="percentagesRow">false</option>
        <option name="rowNumbers">true</option>
        <option name="totalsRow">false</option>
        <option name="wrap">true</option>
      </table>
    </panel>
  </row>
  <row>
    <panel>
      <html>
        <div>
          <a id="btnSubmitCSV" class="btn btn-primary pull-right">Push Results to CSV</a>
        </div>
      </html>
      <table depends="$tokQueryOutputLookup$">
        <title>Result from Destination CSV File</title>
        <search>
          <query>| inputlookup test.csv 
| eval token="$tokQueryOutputLookup$" 
| table _time Errors Minimum Average Percentile75 Maximum</query>
          <earliest>$earliest$</earliest>
          <latest>$latest$</latest>
          <progress>
            <condition match="$job.resultCount$=0">
              <unset token="tokShowOutput"></unset>
            </condition>
            <condition>
              <set token="tokShowOutput"></set>
            </condition>
          </progress>
        </search>
        <option name="refresh.display">progressbar</option>
      </table>
    </panel>
  </row>
</form>

Following is the code for push_to_csv.js JavaScript invoked on clicking the Submit Button using jQuery Selector for button i.e. id="btnSubmitCSV".

require([
    'jquery',
    'splunkjs/mvc',
    'splunkjs/mvc/simplexml/ready!'
], function($,mvc){
    var defaultTokens = mvc.Components.get("default");
    var submittedTokens = mvc.Components.get("submitted");
    $('#btnSubmitCSV').on("click",function(){
        // Change the value of a token $tokQueryOutputLookup$
        submittedTokens.set("tokQueryOutputLookup", "| outputlookup test.csv");
        defaultTokens.set("tokQueryOutputLookup", "| outputlookup test.csv");
    });
});

Please try out and confirm.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"

christoffertoft
Communicator

@niketnilay Ah, thanks. I will experiment with this - I didn't know you could append the search string to the tokens.set() method as you did. If i don't want to show the table with fields that were put into the CSV, do I need the tokQueryOutputlookup / tokshowOutput tokens?

0 Karma

christoffertoft
Communicator

@niketnilay I don't get the button to update the CSV unfortunately 😞 I use different JS functionality to set the token that contains the values to save ... The tokens get updated correctly but not pushed to the csv. . 😕

0 Karma

niketn
Legend

Do you have the dummy search like the one below in your SimpleXML?

 <query>$tokQueryOutputLookup$</query>

Instead of JavaScript you can check first in Simple XML using Radio Button (as per my first answer) to ensure that the query, token and outputlookup command is working as expected. Then modify from Simple XML to JS as per my second answer here.
Also print $tokQueryOutputLookup$ in SimpleXML like the following to see if it is being set.

<panel>
<title>$tokQueryOutputLookup$</title>

PS: I have used a base search (post processing) to prepare the table to be pushed to outputlookup command.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

christoffertoft
Communicator

Hi @niketnilay

I solved it by adding a SearchManager to the onclick listener of the button --> custom javascript and css to enable checkboxes that saves the clicked values in a list. On the onclick listener, I issue a search that outputs the values to the csv among other things.. 🙂 Thansk for your help

0 Karma

niketn
Legend

@christoffertoft , glad you were able figure out the solution for your problem. Please accept and up vote the comments that helped 🙂

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma

mwdbhyat
Builder

@niketnilay I have implemented this, however it seems that if i add an append in the js button for the outputlookup(as i dont want it to overwrite the values each time but build a long list of whatever is saved) it created 2 items per click each time. Do you know how to resolve this?

0 Karma

niketn
Legend

@christoffertoft, following is an example of having a checkbox to push from source table to csv on click. If you want a Submit button, you can add button using <html> panel and code Javascript to set the token tokQueryOutputLookup instead of checkbox change event.

<form>
  <label>Click Button to Push Results to CSV Lookup</label>
  <!-- Run only on Click on Submit -->
  <search base="baseQuery">
    <query>$tokQueryOutputLookup$</query>
  </search>
  <fieldset submitButton="false"></fieldset>
  <row>
    <panel>
      <title>Query to Generate Source Table</title>
      <input type="dropdown" token="tokDay" searchWhenChanged="true">
        <label>Get Previous Day Stats</label>
        <choice value="earliest=-0d@d latest=now">Today</choice>
        <choice value="earliest=-1d@d latest=-0d@d">Yesterday</choice>
        <choice value="earliest=-7d@d latest=-6d@d">Last Week Same Day</choice>
        <default>earliest=-7d@d latest=-6d@d</default>
      </input>
      <table>
        <search id="baseQuery">
          <query>index=_internal sourcetype=splunkd log_level!=INFO $tokDay$
| bin _time span=15m
| stats count as Errors by _time
| timechart span=1h sum(Errors) as Errors avg(Errors) as Average min(Errors) as Minimum  perc25(Errors) as Percentile25 perc75(Errors) as Percentile75 max(Errors) as Maximum
| fillnull value=0
| eval Average=round(Average)
| eval perc75=round(perc75)
| table _time Errors Minimum Average Percentile75 Maximum</query>
          <earliest>-24h@h</earliest>
          <latest>now</latest>
          <sampleRatio>1</sampleRatio>
        </search>
        <option name="count">10</option>
        <option name="dataOverlayMode">none</option>
        <option name="drilldown">none</option>
        <option name="percentagesRow">false</option>
        <option name="rowNumbers">true</option>
        <option name="totalsRow">false</option>
        <option name="wrap">true</option>
      </table>
    </panel>
  </row>
  <row>
    <panel>
      <input type="checkbox" token="tokPushResultsToCSV">
        <label></label>
        <choice value="submit">Push Results to CSV</choice>
        <change>
          <condition value="submit">
            <set token="tokQueryOutputLookup">| outputlookup test.csv</set>
            <unset token="form.tokPushResultsToCSV"></unset>
          </condition>
          <condition>
            <unset token="tokQueryOutputLookup"></unset>
          </condition>
        </change>
      </input>
      <table depends="$tokShowOutput$">
        <title>Result from Destination CSV File</title>
        <search>
          <query>| inputlookup test.csv 
| eval token="$tokQueryOutputLookup$" 
| table _time Errors Minimum Average Percentile75 Maximum</query>
          <earliest>$earliest$</earliest>
          <latest>$latest$</latest>
          <progress>
            <condition match="$job.resultCount$=0">
              <unset token="tokShowOutput"></unset>
            </condition>
            <condition>
              <set token="tokShowOutput"></set>              
            </condition>
          </progress>
        </search>
        <option name="refresh.display">progressbar</option>
      </table>
    </panel>
  </row>
</form>

Similar example is also present in the answer you are referring.

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"

christoffertoft
Communicator

This, again updates the view with a table showing it. I would really just like the button to update the csv on click. No table etc.

0 Karma

christoffertoft
Communicator

@niketnilay Do you know how I would go about changing the radio to a regular button? I can do the token setting in the js, but Im not sure how to do change the XML to a button with the same functionality? It seems like a hack to use the radio button instead of a regular button 🙂

0 Karma

niketn
Legend

@christoffertoft, I have added another option with JavaScript

____________________________________________
| makeresults | eval message= "Happy Splunking!!!"
0 Karma
Get Updates on the Splunk Community!

What's new in Splunk Cloud Platform 9.1.2312?

Hi Splunky people! We are excited to share the newest updates in Splunk Cloud Platform 9.1.2312! Analysts can ...

What’s New in Splunk Security Essentials 3.8.0?

Splunk Security Essentials (SSE) is an app that can amplify the power of your existing Splunk Cloud Platform, ...

Let’s Get You Certified – Vegas-Style at .conf24

Are you ready to level up your Splunk game? Then, let’s get you certified live at .conf24 – our annual user ...