Setup.xml examples

See the following examples to learn how to create a setup page:

 

Setup page example using searches and a scripted input

The following example shows a setup page for an app, MySampleApp.

MySampleApp contains three saved searches and a scripted input. In the setup page, the user specifies the following configurations:

  • Interval for running the scripted input
  • Enable or disable the Web Search
  • The cron schedule for each of the searches
  • The earliest dispatch time for all the searches.

This setup page modifies savedsearches.conf and inputs.conf.

Sample setup page

In this example:

  • The configuration files already exist in $SPLUNK_HOME/etc/apps/MySampleApp/default/.
  • The configuration file contains the stanzas you are modifying.
  • The values present in the stanza represent the default values displayed by the setup page.
  • If the user changes the default settings to a configuration file from the setup page, Splunk writes the updates to the configuration file in $SPLUNK_HOME/etc/apps/MySampleApp/local/.

The setup page uses the following REST endpoints to update the configuration:

https://localhost:8089/servicesNS/nobody/MySampleApp/saved/searches/
https://localhost:8089/servicesNS/nobody/MySampleApp/data/inputs/script/

Configuration files for the example

Here are the default configuration files:

savedsearches.conf

[Web Search]
search = sourcetype=access_combined ( 404 OR 500 OR 503 )
dispatch.earliest_time= -1d
cron_schedule = */5 * * * *
enableSched = 1

[Firewall Data Search]
search = sourcetype=cisco_wsa .exe usage!="Unknown"
dispatch.earliest_time = -1d
cron_schedule = */5 * * * *
enableSched = 0

[Email Data Search]
search = sourcetype=cisco_esa OUTBREAK_*
dispatch.earliest_time = -1d
cron_schedule = */5 * * * *
enableSched = 0

inputs.conf

[script://$SPLUNK_HOME/etc/apps/MySampleApp/bin/myscript.sh]
interval = 60
sourcetype = customsourcetype
source = customsource

setup.xml

Here is the setup.xml file that implements the setup page. Note the following in the setup.xml file:

  • The entity specifying the path to scripted input uses URI encoding
  • The field for the Web Search uses the REST endpoint, is_scheduled. This updates the enableSched field in the [Web Search] stanza.
  • The text blocks use HTML entities to specify italic and bold for the type.
  • In the block that configures the cron schedule, entity specifies the regex '*' to specify all searches. The block contain examples for specifying iteration mode and bulk mode
  • For details about the syntax, see Setup.xml syntax.

setup.xml

<setup>

  <!-- Note that the path to the script uses URI encoding -->
  <block title="Enable a scripted input"
         endpoint="data/inputs/script"
         entity="%24SPLUNK_HOME%252Fetc%252Fapps%252FMySampleApp%252Fbin%252Fmyscript.sh">
    <text>
      &lt;i&gt;Specify the configuration for a single setting in a stanza.&lt;/i&gt;
    </text>

    <input field="interval">
      <label>Specify the interval for [$name$] </label>
      <type>text</type>
    </input>

  </block>

  <block title="Enable the schedule for a search"
         endpoint="saved/searches" entity="Web Search">
    <text>
      &lt;i&gt;Specify the configuration for a single setting in a stanza.&lt;/i&gt;
    </text>

    <!-- The field "is_scheduled" maps to the enableSched setting in savedsearches.conf -->
    <input field="is_scheduled">
      <label>Enable Schedule for $name$</label>
      <type>bool</type>
    </input>
	
  </block>

<block title="Configure Cron Schedule" 
       endpoint="saved/searches" entity="*" mode="iter">
    <text>
      &lt;i&gt;&lt;b&gt;Iteration mode&lt;/b&gt;:
      specify the cron schedule for each search in the conf file.&lt;/i&gt;</text>
    <input field="cron_schedule">
      <label>$name$</label>
      <type>text</type>
    </input>
  </block>
        
  <!-- an example of bulk change - enable all searches -->
  <block title="Set earliest dispatch time" 
         endpoint="saved/searches" entity="*" mode="bulk">
    <text>
      &lt;i&gt;&lt;b&gt;Bulk mode&lt;/b&gt;: enable the earliest dispatch time for each search in the conf file.&lt;/i&gt;
    </text>
    <input field="dispatch.earliest_time">
      <label>Set earliest dispatch time for all searches</label>
      <type>text</type>
    </input>
  </block>

</setup>
 

Setup page example using a custom endpoint

This example shows how to create a setup page that use the Splunk Enterprise REST API to configure a custom endpoint. The custom endpoint maps to a configuration file you create at $SPLUNK_HOME/etc/apps/app_name/default/myappsetup.conf.

To update a custom endpoint:

  1. Create your custom configuration file with the initial values for your setup page.
  2. Create a stanza in restmap.conf that maps your endpoint to your custom configuration file.
  3. Write a python script that initializes your setup page and handles the user-entered values.
  4. Write setup.xml.

1. Create a custom configuration file with default values

This example uses a configuration file to initialize the default values for the stanza [setupentity]. The entity attribute in setup.xml refers to this stanza.

However, you can also initialize the default values in your python script.

myappsetup.conf

[setupentity]
field_1 =
field_3 = 60
field_2_boolean = 0

2. Example stanza in restmap.conf

The following example stanza in restmap.conf sets up a custom endpoint at:

https://localhost:8089/services/mycustom/customendpoint

restmap.conf

. . .
[admin:myendpoint]
match=/mycustom
members=customendpoint

[admin_external:customendpoint]
handlertype = python
handlerfile = MyApp_python_handler.py
handleractions = list, edit
. . .

[admin_external:endpoint_name]

Names the endpoint. Make sure you use a unique name for your endpoint.

handlertype

Specifies the language of the REST endpoint script. Currently, Splunk only supports python for custom endpoints.

handlerfile

The name of the python script. Place the script here:

$SPLUNK_HOME/etc/apps/app_name/bin

handleractions

Actions supported by the script. list displays the initial field values. edit updates the endpoint when the user saves the setup page.

3. Example python script that implements a new endpoint

The python script looks for the configuration file, myappsetup.conf in either .../default or .../local. It also searches for values for the fields defined in the configuration file, and writes any changes to .../local.

MyApp_python_handler.py

import splunk.admin as admin
import splunk.entity as en
# import your required python modules

'''
Copyright (C) 2005 - 2010 Splunk Inc. All Rights Reserved.
Description:  This skeleton python script handles the parameters in the configuration page.

      handleList method: lists configurable parameters in the configuration page
      corresponds to handleractions = list in restmap.conf

      handleEdit method: controls the parameters and saves the values 
      corresponds to handleractions = edit in restmap.conf

'''

class ConfigApp(admin.MConfigHandler):
  '''
  Set up supported arguments
  '''
  def setup(self):
    if self.requestedAction == admin.ACTION_EDIT:
      for arg in ['field_1', 'field_2_boolean', 'field_3']:
        self.supportedArgs.addOptArg(arg)
        
  '''
  Read the initial values of the parameters from the custom file
      myappsetup.conf, and write them to the setup page. 

  If the app has never been set up,
      uses .../app_name/default/myappsetup.conf. 

  If app has been set up, looks at 
      .../local/myappsetup.conf first, then looks at 
  .../default/myappsetup.conf only if there is no value for a field in
      .../local/myappsetup.conf

  For boolean fields, may need to switch the true/false setting.

  For text fields, if the conf file says None, set to the empty string.
  '''

  def handleList(self, confInfo):
    confDict = self.readConf("myappsetup")
    if None != confDict:
      for stanza, settings in confDict.items():
        for key, val in settings.items():
          if key in ['field_2_boolean']:
            if int(val) == 1:
              val = '0'
            else:
              val = '1'
          if key in ['field_1'] and val in [None, '']:
            val = ''
          confInfo[stanza].append(key, val)
          
  '''
  After user clicks Save on setup page, take updated parameters,
  normalize them, and save them somewhere
  '''
  def handleEdit(self, confInfo):
    name = self.callerArgs.id
    args = self.callerArgs
    
    if int(self.callerArgs.data['field_3'][0]) < 60:
      self.callerArgs.data['field_3'][0] = '60'
        
    if int(self.callerArgs.data['field_2_boolean'][0]) == 1:
      self.callerArgs.data['field_2_boolean'][0] = '0'
    else:
      self.callerArgs.data['field_2_boolean'][0] = '1'
    
    if self.callerArgs.data['field_1'][0] in [None, '']:
      self.callerArgs.data['field_1'][0] = ''  

        
    '''
    Since we are using a conf file to store parameters, 
write them to the [setupentity] stanza
    in app_name/local/myappsetup.conf  
    '''
        
    self.writeConf('myappsetup', 'setupentity', self.callerArgs.data)
      
# initialize the handler
admin.init(ConfigApp, admin.CONTEXT_NONE)

4. Create setup.xml

Here is the setup.xml file that creates the setup page for the custom endpoint.

<setup>
  <block title="Configure This App">
    <text>Setup page with custom endpoints</text>
  </block>

  <block title="A text input"
         endpoint="mycustom/customendpoint" entity="setupentity">

      <input field="field_1">
        <label>Enter your text</label>
        <type>text</type>
      </input>

  </block>

  <block title="Enable and set a numeric value"
         endpoint="mycustom/customendpoint" entity="setupentity">

    <input field="field_2_boolean">
      <label>Enable This Input</label>
      <type>bool</type>
    </input>

    <input field="field_3" endpoint="mycustom/customendpoint" entity="setupentity">
      <label>Set this number (minimum value=60)</label>
      <type>text</type>
    </input>

  </block>

</setup>

 

Setup page example with user credentials

This example shows the steps needed to create a set up page that accepts user/password credentials for a python script. The python script uses the credentials supplied in the setup page.

  1. Create the block in your setup page that accepts user credentials.
  2. Write a python script that uses the credentials
  3. Create a stanza in inputs.conf for your script.

1. Create a block in setup.xml that accepts user credentials

Add the following block to setup.xml to create the User input fields for your scripts. Place the block between setup tags.

<setup>
<block title="Add new credentials" endpoint="storage/passwords" entity="_new">
  <input field="name">
    <label>Username</label>
    <type>text</type>
  </input>

  <input field="password">
    <label>Password</label>
    <type>password</type>
  </input>

  <!-- Remove the realm input field if your app is not using realm -->
  <input field="realm">
     <label>Realm</label>
     <type>text</type>
  </input>
</block>
</setup>

2. Write a python script that uses credentials

Here is the path to the example script: $SPLUNK_HOME/etc/apps/app_name/default/bin/MyInputScript.py.

MyInputScript.py

import splunk.entity as entity

. . .

# access the credentials in /servicesNS/nobody/app_name/admin/passwords
def getCredentials(sessionKey):
   myapp = 'name-of-your-app-here'
   try:
      # list all credentials
      entities = entity.getEntities(['admin', 'passwords'], namespace=myapp,
                                    owner='nobody', sessionKey=sessionKey)
   except Exception, e:
      raise Exception("Could not get %s credentials from splunk. Error: %s"
                      % (myapp, str(e)))

   # return first set of credentials
   for i, c in entities.items():
        return c['username'], c['clear_password']

   raise Exception("No credentials have been found")  

def main():
        # read session key sent from splunkd
        sessionKey = sys.stdin.readline().strip()

        if len(sessionKey) == 0:
           sys.stderr.write("Did not receive a session key from splunkd. " +
                            "Please enable passAuth in inputs.conf for this " +
                            "script\n")
           exit(2)

        # now get twitter credentials - might exit if no creds are available
        username, password = getCredentials(sessionKey)

        # use the credentials to access the data source
        . . .

3. Create a stanza in inputs.conf

Here is the path to inputs.conf for the example: $SPLUNK_HOME/etc/apps/app_name/default/inputs.conf.

Add the following stanza to inputs.conf:

[script://./bin/MyInputScript.py]
. . .
passAuth   = splunk-system-user