Splunk Enterprise 6.0.
3
Module System Reference
Generated: 4/22/2014 9:40 am
Copyright (c) 2014 Splunk Inc. All Rights Reserved
Table of Contents
Extension dictionary............................................................................................1
Extension dictionary..................................................................................1
Splunk APIs..........................................................................................................4
Splunk.Context..........................................................................................4
Splunk.Job................................................................................................8
Splunk.Search.........................................................................................40
Splunk.TimeRange..................................................................................75
Splunk.util................................................................................................93
Module APIs.....................................................................................................119
Splunk.Module......................................................................................119
Splunk.Module.DispatchingModule.......................................................164
Module Controller APIs...................................................................................168
ModuleController...................................................................................168
ModuleHandler......................................................................................169
Controller API...................................................................................................172
BaseController......................................................................................172
Model APIs........................................................................................................180
SplunkRESTModel................................................................................180
SplunkAppObjModel.............................................................................193
ObjectMetadataModel...........................................................................197
SplunkRESTManager...........................................................................200
SplunkQuerySet....................................................................................203
Decorators API.................................................................................................210
Decorators.............................................................................................210
Template API....................................................................................................215
Templates.............................................................................................215
App Server Util API..........................................................................................219
App Server Utilities................................................................................219
i
Extension dictionary
Extension dictionary
controllers.BaseController
Module System component: MVC controller
Parent: object
Mechanism: Subclass using the web.conf bootstrap name to hook into the
framework
Usage: Overriding existing methods is not recommended; If you need to override
the initialize() constructor, call the parent constructor using $super()
first to ensure the parent is initialized; add additional methods as needed
SplunkAppObjModel
Module System component: MVC model
Parent: SplunkRESTModel
Mechanism: Subclass to hook your model into the framework
Usage: Overriding existing methods is not recommended; If you need to override
the initialize() constructor, call the parent constructor using $super()
first to ensure the parent is initialized; add additional model-specific methods
lib.html
Module System component: MVC view (template)
Mechanism: Dynamic binding
Usage: Import; way to include Import custom/3rd party JavaScript and CSS
1
Splunk.Module
Module System component: module
Parent: object
Mechanism: Subclass using module name
Usage: Override methods
Most common methods to override:
applyContext()
getModifiedContext()
getResultParams()
getResultsCompleteHandler()
getResultsErrorHandler()
initialize()
isReadyForContextPush()
onBeforeJobDispatched()
onContextChange()
onLoadStatusChange()
onResultsRendered()
onViewDataChange()
renderResults()
requiresAsynchonousLoading()
requiresDispatch()
resetUI()
Splunk.Module.DispatchingModule
Module System component: module
Parent: Splunk.Module
Mechanism: Subclass using module name
Usage: Override methods
Most common methods to override:
onJobDone()
onJobProgress()
onJobStatusChange()
2
requiresTransformedResults()
module.ModuleHandler
Module System component: module controller
Parent: object
Mechanism: Subclass using module name
Usage: Override methods
Most common methods to override:
generateResults()
application.js
Module System component: module
Mechanism: Dynamic binding
Usage: Override with custom JavaScript
3
Splunk APIs
Splunk.Context
clone()
The clone() method gets an exact copy of a module context.
Synopsis
contextCopy = someContext.clone()
Return Value
Object Duplicate of the current context object.
Example
dupCurrentContext: function() {
var context = this.getContext()
return = context.clone();
enforceByValue()
The enforceByValue() method ensures that the get() and getAll()
methods return objects by value instead of by reference.
Note: This method usually does not need to be called because the getter and
setter methods already enforce return by-value.
Synopsis
eValue = enforceByValue( value )
Parameters
value Object Value to be checked for references.
4
Return Value
Object Enforced value.
See Also
get()
getAll()
set()
get()
The get() method is a generic getter that gets the value associated with the
named key, provided the key is defined for the context. A context is a
user-defined dictionary of name-value pairs.
Synopsis
value = get( name )
Parameters
name String Context dictionary key.
Return Value
Value corresponding to the name key. If name does not
exist, the method returns null.
Object
Note that this method returns a value and not a reference.
Example
getSearch: function() {
var context = this.getContext()
return context.get('search');
See Also
enforceByValue()
getAll()
set()
5
getAll()
The getAll() method is a generic getter that gets all values at or below the
name namespace.
For example, given charting.chart.stackMode and charting.chart keys, calling
getAll("charting") returns a map of hash values for the chart.stackMode
and chart keys.
Synopsis
hash = getAll( name )
Parameters
name String key name for which the corresponding values are returned.
Return Value
List of corresponding values at or below the name key. If
name had no matching values, null is returned.
Object
Note that this method returns values and not a references to
the values.
Example
getResultsDict: function() {
var context = this.getContext()
return context.getAll("results");
See Also
enforceByValue()
get()
set()
has()
The has() method checks if the context contains the name key.
6
Synopsis
status = has( name )
Parameters
name String Key name to test.
Return Value
Requested name key found indication:
Boolean true = Key with specified name exists.
false = Key with specified name does not exist.
Example
hasSearch: function() {
var context = this.getContext();
if (context.has("search")) {
return true;
else
return false;
}
set()
The set() method is a generic setter that stores the specified name - value
pair, by value, in the context.
The method never assigns a reference value but copies the referenced object.
Synopsis
set( name, value)
Parameters
name String Key name to associate with value.
Value to be set for key name.
value Object
Note that this method overwrites the current value if name
already exists.
7
Example
setBaseSearch: function(baseSearch) {
var context = this.getContext();
var search = context.get('search');
search.setBaseSearch(baseSearch);
context.set('search', search);
See Also
enforceByValue()
get()
getAll()
Splunk.Job
areResultsTransformed()
The areResultsTransformed() method indicates whether or not search
results are transformed. Results are transformed when search commands, such
as timechart and stats, have populated the results set with different data than the
events set. Use this method to determine whether to retrieve data from the job
events set or results set.
Synopsis
results = areResultsTransformed()
Return Value
Results endpoint returns transformed results indication:
Boolean true = Search results are transformed.
false = Search results are not transformed.
Example
var context = this.getContext(); var search = context.get('search'); var
entityName;
if (search.job.areResultsTransformed()) {
8
entityName = 'results';
} else {
entityName = 'events';
console.log(entityName);
See Also
getStatusBuckets()
canBeAutoCancelled()
The canBeAutoCancelled() method checks if the current job can be
auto-canceled. A job can be auto-canceled if it is not a real-time search or has
not been saved by calling save(). A job can also be auto-canceled if it has
been set to auto-cancelable, either at instantiation or by calling
setAsAutoCancellable().
Jobber attempts to automatically cancel a job when polling indicates that the job
has become inactive, after a defined time interval, or if the browser page closed.
Synopsis
cancel = canBeAutoCancelled()
Return Value
Job can be auto-canceled indication:
Boolean true = Job can be auto-canceled.
false = Job cannot be auto-canceled.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.canBeAutoCancelled()) {
console.log('job can be auto-canceled.');
} else {
9
console.log('job cannot be auto-canceled.');
See Also
isRealTimeSearch()
save()
setAsAutoCancellable()
cancel()
The cancel() method cancels the current job, if it has not already been
canceled. If the job is successfully canceled, the job SID is set to null.
Calling this method raises the jobCanceled and jobStatusChanged
events.
Synopsis
status = cancel( onSuccess, onFailure )
Parameters
(Optional) Function to be called on successful
onSuccess Function
cancellation.
(Optional) Function to be called on unsuccessful
onFailure Function
cancellation.
Return Value
Cancel request status:
Boolean Undefined = Job canceled.
False = Job already canceled or could not be canceled.
Throws
Error: "Cannot call the job endpoint if we dont have an sid yet"
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.cancel(function() {
10
console.log('Handle successful job cancellation.');
}, function() {
console.log('Handle failure to cancel job.');
}) == false)
console.log('job already canceled or could not be canceled.');
See Also
setAsAutoCancellable()
canBeAutoCancelled()
finalize()
If the current job has not yet finished, the finalize() method stops the job,
unpausing the job if it has been paused.
This method raises the jobFinalized and jobStatusChanged events.
Because we cannot predict when job polling will finish it is possible to request a
job be paused that, on the server, is actually done. The first time the server
indicates a job is paused or finalized, a jobPaused event is triggered. If the job
state is also set to done, jobProgress and jobDone events are also
triggered.
Synopsis
status = finalize( onSuccess, onFailure )
Parameters
(Optional) Function to be called on successful
onSuccess Function
finalization.
(Optional) Function to be called on unsuccessful
onFailure Function
finalization.
Return Value
Job finalization request status:
Boolean undefined = Finalize request made to the server.
false = Job has already finished.
11
Throws
Error: "Cannot call the job endpoint if we dont have an sid yet"
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.finalize(function() {
console.log('Handle successful job finalization.');
}, function() {
console.log('Handle failure to finalize job.');
}) == false)
console.log('Job has already completed.');
See Also
isDone()
isFinalized()
getCreateTime()
The getCreateTime() method gets the current job creation time. The job
creation time is set when the job is posted to the backend, and
getCreateTime() expects the date to be stored as seconds since 01.01.1970.
Note: The return value is undefined if the search didn't previously call
setCreateTime().
Synopsis
time = getCreateTime()
Return Value
false = Job creation time not previously set.
Date() object = Job creation time.
Example
var context = this.getContext(); var search = context.get('search');
search.job.setCreateTime(new Date().getTime()/1000); var createTime =
12
search.job.getCreateTime(); console.log('Job created at ' +
createTime.toString());
getCursorTime()
Cursor time is the time after which no events have been scanned. Cursor time
can be used to indicate job progress, where:
doneProgress = (latestTime - cursorTime) / (latestTime -
earliestTime)
The getCursorTime() method gets the current job cursor time.
Note: For searches distributed over multiple search heads, this is the latest
cursor time of all searches.
Synopsis
time = getCursorTime()
Return Value
false = Cursor time not yet set.
Date() object = Cursor time.
Example
var context = this.getContext(); var search = context.get('search'); var cursorTime
= search.job.getCursorTime();
if (cursorTime == false)
console.log('Job cursor time not set.');
else
console.log('Current job cursor time is ' + cursorTime.toString());
See Also
getDoneProgress()
13
getDoneProgress()
Job progress is calculated as:
doneProgress = (latestTime - cursorTime) / (latestTime -
earliestTime)
The getDoneProgress() method gets a value representing the percentage of
job completion, for the current job.
Synopsis
progress = getDoneProgress()
Return Value
Job progress from 0.0 to 1.0, representing zero percent to 100
Float
percent complete.
Example
var context = this.getContext(); var search = context.get('search'); var cursorTime
= search.job.getCursorTime(); var jobProgress =
Math.round(search.job.getDoneProgress() * 100);
console.log (sprintf(_('Job is %s%% complete'), jobProgress));
See Also
isDone()
getCursorTime()
getEventAvailableCount()
The getEventAvailableCount() method gets the number of events
available for export, for the current job.
Note: If there are no status buckets set for the current job, this method returns
the result count (see getResultCount() ). This is the main difference between this
method and getEventCount().
14
Synopsis
count = getEventAvailableCount()
Return Value
Integer Number of available events for the current job.
Example
var context = this.getContext(); var search = context.get('search'); var
availableEvents = search.job.getEventAvailableCount();
console.log('Available event count = ' + availableEvents.toString());
See Also
getEventCount()
getResultCount()
getScanCount()
getEventCount()
The getEventCount() method gets the number of events advertised for the
current job.
Note: This method and getEventAvailableCount() often return different
values. This method always returns the total number of events returned by the
current job.
Synopsis
count = getEventCount()
Return Value
Integer Number of available events for the current job.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Number of events in the current job = ' +
search.job.getEventCount().toString());
15
See Also
getEventAvailableCount()
getResultCount()
getScanCount()
getEventFieldCount()
The getEventFieldCount() method gets the number of unique fields
available within the current job. Jobs with zero status buckets always advertise
zero fields.
Synopsis
results = getEventFieldCount()
Return Value
Integer Number of available fields for the current job.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Number of unique fields in the current job = ' +
search.job.getEventFieldCount().toString());
getEventSearch()
The getEventSearch() method gets the part of the search string preceding
the first transforming command, such as stats or timechart commands.
Synopsis
eventSearch = getEventSearch()
Return Value
The part of the search string preceding the first transforming
String
command.
16
Example
var context = this.getContext(); var search = context.get('search');
console.log('Base search command: ' + search.job.getEventSearch());
See Also
getSearch()
getEventSorting()
The getEventSorting() method gets the event sorting order for the current
job.
Synopsis
sort = getEventSorting()
Return Value
Event sorting order:
desc = Descending order.
String
none = (Default) No sorting.
realtime = Recent events are prepended to the event set.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Event sorting order: ' + search.job.getEventSorting());
getResultCount()
The getResultCount() method gets the number of results for the current
job. If the job is preview-enabled, meaning that partial results are available before
the job is done, this method returns the number of partial results.
Synopsis
count = getResultCount()
17
Return Value
Integer Number of results within the current job.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Result count = ' + search.job.getResultCount().toString());
See Also
getEventAvailableCount()
getEventCount()
getScanCount()
getScanCount()
The getScanCount() method gets the number of events scanned by the
current job in compiling the event or result set.
Synopsis
count = getScanCount()
Return Value
Integer Number of scanned events.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Scan count = ' + search.job.getScanCount().toString());
See Also
getEventAvailableCount()
getEventCount()
getResultCount()
18
getSearch()
The getSearch() method gets the current job search string.
Synopsis
search = getSearch()
Return Value
String Current job search string.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Search string: ' + search.job.getSearch());
See Also
getSearchId()
getSID()
getSearchId()
The getSearchId() getter method gets the current job search identifier.
Synopsis
searchID = getSearchId()
Return Value
String Current job search identifier.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Search ID: ' + search.job.getSearchId());
19
See Also
getSearch()
getSID()
setSearchId()
setSID()
getSID()
The getSID() getter method gets the current job search identifier. This
method calls getSearchId().
Synopsis
searchID = getSID()
Return Value
String Current job search identifier.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Search ID: ' + search.job.getSID());
See Also
getSearch()
getSearchId()
setSID()
getStatusBuckets()
The getStatusBuckets() method gets the number of status buckets for the
current job.
Status buckets represent the status_buckets parameter in the Splunk REST API
endpoint /services/search/jobs. Essentially, if status_buckets is zero, raw events
are not persisted for the job. If status_buckets is greater than zero, raw events
persist for the job.
20
Synopsis
buckets = getStatusBuckets()
Return Value
Integer Number of status buckets requested for the current job.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Number of status buckets = ' +
search.job.getStatusBuckets().toString());
See Also
areResultsTransformed()
getTimeRange()
The getTimeRange() method gets a Splunk.TimeRange instance
representing the current job data absolute time range.
Synopsis
timeRange = getTimeRange()
Return Value
Splunk.TimeRange instance representing the absolute time range
Object
of the current job data.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Timerange: ' + search.job.getTimeRange().toString());
getTimeSinceLastProgress()
The getTimeSinceLastProgress() method gets the time interval since a
progress event was fired for the current job.
21
Synopsis
time = getTimeSinceLastProgress()
Return Value
A Date() object representing the time since a progress event was
Object
fired, in milliseconds.
Example
var context = this.getContext(); var search = context.get('search'); var idleTime =
search.job.getTimeSinceLastProgress();
console.log('it has been ' + idleTime.toString() + ' since the job last showed
progress');
See Also
setLastProgressTime()
isCanceled()
The isCanceled() method checks if the current job has been canceled.
Synopsis
status = isCanceled()
Return Value
Job canceled status:
Boolean true = Job is canceled.
false = Job is not canceled.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isCanceled()) {
console.log('job is cancelled!');
} else {
22
console.log('job is active!');
See Also
isDone()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
isSaved()
isDone()
The isDone() method checks if the current job has completed processing.
Synopsis
status = isDone()
Return Value
Processing complete status:
Boolean true = Processing is complete.
false = Processing is NOT complete.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isDone()) {
console.log('job has completed processing!');
} else {
console.log('job has not completed processing!');
23
See Also
getDoneProgress()
isCanceled()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
isSaved()
isEventStreaming()
The isEventStreaming() method checks if the current job permits partial
events and results retrieval.
Synopsis
status = isEventStreaming()
Return Value
Job permits retrieval of partial events and results indication:
Boolean true = Job permits partial event or result streaming.
false = Job does not permit partial event or result streaming.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isEventStreaming()) {
console.log('Job permits partial event streaming!');
} else {
console.log('Job does not permit partial event streaming!');
24
See Also
isCanceled()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
isSaved()
isFinalized()
The isFinalized() method checks the current job was stopped (finalized)
before it completed.
Synopsis
results = isFinalized()
Return Value
Job finalized state:
Boolean true = Job stopped before it completed.
false = Job was not stopped before it completed.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isFinalized()) {
console.log('job stopped before it completed!');
} else {
console.log('job was NOT stopped before it completed!');
See Also
isCanceled()
isDone()
25
isEventStreaming()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
isSaved()
isPaused()
The isPaused() method checks if the current job is paused. A job that has
completed is considered not paused.
Synopsis
results = isPaused()
Return Value
Job paused state:
Boolean true = Job is paused.
false = Job is not paused.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isPaused()) {
console.log('Current job is paused!');
} else {
console.log('Current job is NOT paused!');
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPreviewable()
isRealTimeSearch()
26
isRunning()
isSaved()
pause()
unpause()
isPreviewable()
The isPreviewable() method checks if results can be previewed for the
current job.
Synopsis
results = isPreviewable()
Return Value
Job preview permission: true = Job can be previewed. false =
Boolean
Job cannot be previewed.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isPreviewable()) {
console.log('Current job results are previewable!');
} else {
console.log('Current job results are NOT previewable!');
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPaused()
isRealTimeSearch()
isRunning()
isSaved()
setPreviewable()
27
isRealTimeSearch()
The isRealTimeSearch() method checks if the current job is a real-time
search.
Real-time search jobs cannot be auto-canceled.
See Search and report in real time for a discusion of real-time searches.
Synopsis
results = isRealTimeSearch()
Return Value
Search job type:
Boolean true = Job is a real-time search.
false = Job is not a real-time search.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isRealTimeSearch()) {
console.log('Current job is a real-time search!');
} else {
console.log('Current job is NOT a real-time search!');
See Also
canBeAutoCancelled()
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRunning()
isSaved()
28
isRunning()
The isRunning() method checks if the current job is done or paused. If the
job is not done or paused, the job is running.
Synopsis
results = isRunning()
Return Value
Job running state: true = Job is not done or paused
Boolean
(running). false = Job is done or paused (not running).
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isRunning()) {
console.log('Current job is running!');
} else {
console.log('Current job is NOT running!');
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isSaved()
pause()
isSaved()
The isSaved() method checks if the current job is saved. A saved job is not
29
auto-cancellable by the UI.
Synopsis
results = isSaved()
Return Value
Job saved state:
Boolean true = Job is saved.
false = Job is not saved.
Example
var context = this.getContext(); var search = context.get('search');
if (search.job.isSaved()) {
console.log('Current job is saved!');
} else {
console.log('Current job is NOT saved!');
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
save()
unsave()
makeWorldReadable()
The makeWorldReadable() method sets the current job access control to
world readable. No error is indicated, if job access control is already world
readable.
30
Synopsis
makeWorldReadable( onSuccess, onFailure)
Parameters
(Optional) Function to execute upon successful
onSuccess Function
operation.
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.makeWorldReadable(
function() { console.log('Current job access control set to world
readable.'); },
function() { console.log('Failed to set current job access
control to world readable.'); } );
See Also
undoWorldReadable()
pause()
The pause() method suspends processing for the current job until either
unpause(), save(), finalize(), or cancel() is requested.
Because you cannot predict when jobs are polled, it is possible to request that a
job be paused that has already completed. The first time the server detects a job
is paused triggers a jobPaused event. If the server also detects a job has
completed, jobProgress and jobDone events are triggered.
Synopsis
pause( onSuccess, onFailure)
Parameters
onSuccess Function
31
(Optional) Function to execute upon successful
operation.
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
if (!search.job.isDone()) {
search.job.pause(
function() { console.log('Current job successfully paused!'); },
function() { console.log('Failed to pause current job!'); } );
} else {
console.log('Current job has already completed!');
See Also
isDone()
isPaused()
isRunning()
unPause()
save()
The save() method saves the current job, which permits the job to persist,
indefinitely. Calling this method has no effect if the job has already completed,
although the save operation will be considered successful. A saved job cannot be
auto-canceled by the UI or by calling setAsAutoCancellable().
Synopsis
save( onSuccess, onFailure)
Parameters
(Optional) Function to execute upon successful
onSuccess Function
operation.
32
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.save(
function() { console.log('Current job successfully saved!'); },
function() { console.log('Failed to save the current job!'); } );
See Also
canBeAutoCancelled()
isSaved()
setAsAutoCancellable()
unsave()
setAsAutoCancellable()
The setAsAutoCancellable() method sets whether or not the current job
can be auto-canceled. Saving a job by calling save(), implicitly, prevents the job
from being canceled.
Splunk attempts to automatically cancel jobs when polling indicates that the job
has been inactive for a predefined time interval, or when the browser page is
closed. Some types of jobs, such as real-time or saved jobs, are not intended to
be canceled so this method must be called to prevent those types of jobs from
being canceled.
Synopsis
setAsAutoCancellable( cancelableFlag )
Parameters
Job auto-cancelable specification:
cancelableFlag Boolean true = Job is auto-cancelable.
false = Job is not auto-cancelable.
33
Example
var context = this.getContext(); var search = context.get('search');
search.job.setAsAutoCancellable(true);
See Also
canBeAutoCancelled()
save()
setLastProgressTime()
The setLastProgressTime() method sets the last progress time for the
current job to the current client browser time.
Synopsis
setLastProgressTime()
Example
var context = this.getContext(); var search = context.get('search');
search.job.setLastProgressTime();
See Also
getTimeSinceLastProgress()
setPreviewable()
The setPreviewable() method sets whether or not job results can be
previewed before the job completes.
Note: Setting preview mode impacts search performance, considerably.
Synopsis
setPreviewable( mode )
34
Parameters
Preview mode:
mode Boolean true = Job results can be previewed.
false = Job results cannot be previewed.
Example
var context = this.getContext(); var search = context.get('search');
search.job.setPreviewable(true);
See Also
isPreviewable()
setSearchId()
The setSearchId() method sets the current job search identifier to the
specified value.
Synopsis
setSearchId( searchID )
Parameters
searchID String Search identifier.
Example
var context = this.getContext(); var search = context.get('search');
search.job.setSearchId("TEST_HARNESS_MODE_ID_" +
(20000*Math.random()));
See Also
getSearchId()
getSID()
setSID()
35
setSID()
The setSID() method sets the current job search identifier to the specified
value. This method calls setSearchId().
Synopsis
setSID( searchID )
Parameters
searchID String Search identifier.
Example
var context = this.getContext(); var search = context.get('search');
search.job.setSID("TEST_HARNESS_MODE_ID_" + (20000*Math.random()));
See Also
getSearchId()
getSID()
setSearchId()
setTTL()
The setTTL() method sets the current job time-to-live to the specified value so
the job is not auto- canceled or expired. If successful, this generates a
jobStatusChanged event.
Synopsis
setTTL( onSuccess, onFailure, ttl)
Parameters
onSuccess Function Function to run on success of operation.
onFailure Function Function to run on failure of operation.
ttl Integer Current job time-to-live, in seconds.
36
Example
search.job.setTTL(
function() { console.log('Current job TTL successfully set.'); },
function() { console.log('Failed to set current job TTL.'); },
24*3600);
See Also
touch()
touch()
The touch() method touches the job, using the REST API, to refresh the
time-to-live so the job is not auto- canceled or expired. If successful, this
generates a jobStatusChanged event.
Synopsis
touch( onSuccess, onFailure)
Parameters
onSuccess Function (Optional) Function to run on successful operation.
(Optional) Function to run on unsuccessful
OnFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.touch();
See Also
setTTL()
undoWorldReadable()
The undoWorldReadable() method sets the current job access control to not
world-readable. An error is not indicated if the job is already set to not world
readable.
37
Synopsis
results = undoWorldReadable( onSuccess, onFailure)
Parameters
onSuccess Function (Optional) Function to call on successful operation.
(Optional) Function to call on unsuccessful
onFailure Function
operation.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get('search');
search.job.undoWorldReadable(
function() { console.log('Current job access control set to not
world readable.'); },
function() { console.log('Failed to set current job access
control to not world readable.'); } );
);
See Also
makeWorldReadable()
unpause()
The unpause() method unsuspends the current job.
Synopsis
unpause( onSuccess, onFailure)
Parameters
onSuccess Function (Optional) Function to call on successful operation.
onFailure Function
38
(Optional) Function to call on unsuccessful
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.unpause(function() { console.log('Successfully unpaused job.'); },
function() { console.log('Failed to unpause job.'); }
);
See Also
isPaused()
pause()
unsave()
The unsave() method sets the current job status to not saved, permitting the
job to be canceled.
Synopsis
unsave( onSuccess, onFailure)
Parameters
onSuccess Function (Optional) Function to call on successful operation.
(Optional) Function to call on unsuccessful
onFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.unsave(
function() { console.log('Current job successfully unsaved!'); },
function() { console.log('Failed to unsave the current job!'); } );
39
See Also
isSaved()
save()
Splunk.Search
abandonJob()
The abandonJob() method removes the search object Splunk.Job from
the view Splunk.Jobber queue so the job is no longer be touched by the
view. This eventually leads to the job expiring. This method is called by a module
when it no longer requires the current job within the context search object,
including any time there are search object changes that require a new job to be
dispatched.
Synopsis
abandonJob()
Return Value
Undefined
Example
var context = this.getContext();var search = context.get('search');
search.abandonJob();
See Also
dispatchJob()
isJobDispatched()
absorbIntentions()
The absorbIntentions() method uses the Parser REST endpoint to
flatten the baseSearch and intentions array into a flattened search string,
stored in fullSearchWithIntentions.
40
Synopsis
results = absorbIntentions( onSuccess, onFailure )
Parameters
(Optional) Function to call upon successful
onSuccess Function
operation.
(Optional) Function to call upon unsuccessful
onFailure Function
operation.
Return Value
Undefined
Throws
this._baseSearch + " is not a search"
Example
this.absorbIntentions();
See Also
addIntention()
clearIntentions()
dispatchJob()
getIntentionReference()
hasIntentions()
popIntention()
sendToView()
setIntentions()
addIntention()
The addIntention() method adds the specified intention dictionary to the
previous intentions list.
Synopsis
addIntention( intentionDict )
41
Parameters
intentionDict Object Dictionary of intentions.
Return Value
Undefined
Throws
"Assertion Failed - addIntention called for null intention"
Example
getModifiedContext: function() { var context = this.getContext();
var legacyTarget = this.getParam('settingToConvert');
var intention = $.extend(true, {}, this.getParam('intention'));
var search = context.get("search");
if (legacyTarget) {
var setting = context.get(legacyTarget);
if (!setting) setting = "";
intention = Splunk.util.replaceTokens(intention,
this._legacyIntentionReplace, setting);
} else {
for (var i=0; i<this._matches.length; i++) {
var key = this._matches[i]
var replacer = new RegExp("\\$" + key + "\\$");
intention = Splunk.util.replaceTokens(intention, replacer,
context.get(key));
}
}
search.addIntention(intention);
context.set("search", search);
return context;
See Also
absorbIntentions()
clearIntentions()
getIntentionReference()
hasIntentions()
popIntention()
42
setIntentions()
clearIntentions()
The clearIntentions() method empties the search object intentions list,
undefining savedSearchName if it is defined.
This method should be called by modules that call absorbIntentions(), if
leaving intentions could result in unexpected behavior in subsequent calls to
absorbIntentions().
Synopsis
clearIntentions()
Return Value
Undefined
Example
var context = this.getContext();var search = context.get('search');
search.absorbIntentions(); search.clearIntentions(); context.set('search', search);
return context;
See Also
absorbIntentions()
addIntention()
getIntentionReference()
hasIntentions()
popIntention()
setIntentions()
clearTimeRange()
The clearTimeRange() method resets the search TimeRange object to the
all time default and undefines savedSearchName, if it is defined.
43
Synopsis
this = clearTimeRange()
Return Value
Object Current object.
Example
var context = this.getContext();var search = context.get('search');
search.absorbIntentions(); search.clearIntentions(); context.set('search', search);
return context;
See Also
getTimeRange()
setTimeRange()
Splunk.TimeRange
clone()
The clone () method instantiates a search object identical to the current
context search object.
Synopsis
search = clone()
Return Value
Object Search object identical to the current context search object.
Example
var context = this.getContext();var search = context.get("search"); var newSearch
= this.newSearch.clone();
dispatchJob()
The dispatchJob() method handles job dispatch requests, dispatching a
search job and flattening intentions as needed, if the job is not already
44
dispatched.
Note: This method is called by pushContextToChildren() in modules
derived from AbstractModule and should not be called directly.
Synopsis
results = dispatchJob( onSuccess, onFailure ), group)
Parameters
onSuccess Object (Optional) Function to call on successful operation.
onFailure Object (Optional) Function to call on unsuccessful operation.
(Optional) group identifier for UI to display last
group String refreshed text at the top of the appropriate group
hierarchy.
Return Value
Job dispatch status:
Boolean True = Search job successfully dispatched.
False = Search job is already dispatched.
Example
search.dispatchJob(this._fireDispatchSuccessHandler.bind(this),
this._fireDispatchFailHandler.bind(this),
this.getGroupName());
See Also
abandonJob()
absorbIntentions()
isJobDispatched()
Splunk.Module.pushContextToChildren()
equalToSearch()
The equalToSearch() method tests if a context current search is equal to the
specified search, where the following properties are equivalent in both objects:
• Search string
45
• Job ID
• Dispatch state
• Intentions
• Time range
• Remote servers list
• Event count
• Post process
Synopsis
equal = equalToSearch( search )
Parameters
search Object Search object to compare to current context search object.
Return Value
Equivalent search object indication:
Boolean True = Search objects are equal.
False = Search objects are not equal.
Example
var context = this.getContext();var search = context.get('search');
if (search.equalToSearch(this._previousSearch)) {
alert('search has not changed!');
return true;
} else {
alert('search has changed!');
return false;
getBaseSearch()
The getBaseSearch() method gets the base search of the current context
search object.
46
Synopsis
baseSearch = getBaseSearch()
Return Value
String Current context base search object.
Example
var context = this.getContext();var search = context.get("search"); var
searchString = search.getBaseSearch();
alert('search = ' + escape(searchString));
See Also
setBaseSearch()
toString()
getDistributedServerList()
The getDistributedServerList() method gets the list of search peers for
distributing the current search.
List items are splunkd instance names, not host names, and the list is used as
the optional argument in the REST API remote_server_list set request.
Synopsis
remoteServerList = getDistributedServerList()
Return Value
Array List of search peers to distribute the current search to.
Example
var context = this.getContext();var search = context.get("search"); var serverList
= search.getDistributedServerList();
if ('https://amrit.splunk.com:8089' in serverList) {
alert('Amrit up in the heezy!');
47
}
See Also
setDistributedServerList()
getEventAvailableCount()
The getEventAvailableCount() method gets the number of events
available for export, for the current job.
Note: If there are no status buckets set for the current job, this method returns
the result count (see getResultCount() ). This is the main difference between this
method and getEventCount().
Synopsis
count = getEventAvailableCount()
Return Value
Integer Number of available events for the current job.
Example
var context = this.getContext(); var search = context.get('search'); var
availableEvents = search.job.getEventAvailableCount();
console.log('Available event count = ' + availableEvents.toString());
See Also
getEventCount()
getResultCount()
getScanCount()
getEventCount()
The getEventCount() method gets the number of events advertised for the
current job.
Note: This method and getEventAvailableCount() often return different
values. This method always returns the total number of events returned by the
48
current job.
Synopsis
count = getEventCount()
Return Value
Integer Number of available events for the current job.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Number of events in the current job = ' +
search.job.getEventCount().toString());
See Also
getEventAvailableCount()
getResultCount()
getScanCount()
getIntentionReference()
The getIntentionReference() method gets a reference to the intention
specified by the specified intentionName, as constrained by the optional
secondArgKey.
Synopsis
intention = getIntentionReference( intentionName,
secondArgKey )
Parameters
intentionName String Name of the intention to get.
(Optional) Secondary key, which must be present as
secondArgKey String an argument of intentionName for the reference
to be retrieved.
49
Return Value
Object Reference to the specified intention.
Example
var context = this.getContext();var search = context.get('search'); var
fieldsIntention = search.getIntentionReference('setfields');
if (fieldsIntention) {
alert('setfields exists');
} else {
alert('setfields does not exist');
See Also
absorbIntentions()
addIntention()
clearIntentions()
hasIntentions()
popIntention()
setIntentions()
getMaxCount()
The getMaxCount() method gets the search max count setting.
maxEvents maps to the splunkd REST API setting max_count, which is an
optional argument specifying the maximum number of results that each of a
search job's status buckets can contain. If the search is non-transforming,
operates on only raw events, maxEvents has precedence. If the search is
transforming, uses stats/timechart or similar, maxCount has precedence.
Synopsis
maxCount = getMaxCount()
50
Return Value
Maximum number of results that each of the search job status
Integer
buckets can contain.
Example
var context = this.getContext();var search = context.get("search"); var maxCount
= search.getMaxCount();
alert('maxCount = ' + escape(toString(maxCount)));
See Also
getMaxEvents()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getMaxEvents()
The getMaxEvents() method gets the maxEvents setting for a search.
maxEvents maps to the splunkd REST API setting max_count, which is an
optional argument specifying the maximum number of results that each of a
search job's status buckets can contain. If the search is non-transforming,
operates on only raw events, maxEvents has precedence. If the search is
transforming, uses stats/timechart or similar, maxCount has precedence.
Synopsis
maxEvents = getMaxEvents()
Return Value
Maximum number of events that each of the search job status
Integer
buckets can contain.
51
Example
var context = this.getContext();var search = context.get("search"); var maxEvents
= search.getMaxEvents();
alert('maxEvents = ' + escape(toString(maxEvents)));
See Also
getMaxCount()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getMaxTime()
The getMaxTime() method gets the maxTime setting for a search, the
number of seconds to run the search before finalizing.
Synopsis
maxTime = getMaxTime()
Return Value
Maximum time that the current context search job should run, in
Integer
seconds.
Example
var context = this.getContext();var search = context.get("search"); var maxTime =
search.getMaxTime();
if (maxTime > 300) {
alert('maxTime value seems high');
} else {
alert('maxTime value seems about right');
52
}
See Also
getMaxCount()
getMaxEvents()
getMinimumStatusBuckets()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getMinimumStatusBuckets()
The getMinimumStatusBuckets() method gets the value of the
statusBuckets setting for a search.
The needed number of status buckets is one of the parameters passed in the
POST to dispatch a job. You need to allocate buckets to store job event
information. Typically, allocating one status bucket is sufficient, while a module
like flashtimeline needs to explicitly allocate 300 buckets to handle the default
number of events it expects. By convention, a module only sets the number of
buckets it needs for itself, if any. Parent modules should not the set bucket count
for child modules.
The default minimum status buckets setting specified by SplunkWeb is 300.
Synopsis
minBuckets = getMinimumStatusBuckets()
Return Value
Minimum number of status huckets prepared by the current context
Integer
search job.
Example
var context = this.getContext();var search = context.get("search"); var
minBuckets = search.getMinimumStatusBuckets();
if (maxBuckets < 300) {
alert('maxBuckets value seems low');
53
} else {
alert('maxBuckets value seems about right');
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getPostProcess()
The getPostProcess() method gets the postProcess value of the current
search.
postProcess is an optional string stored in a search object, which is used by
the post process subsystem to perform work on completed search artifacts.
Synopsis
postProcessVal = getPostProcess()
Return Value
String Search post process string.
Example
var context = this.getContext();var search = context.get("search"); var
postProcess = search.getPostProcess();
if (postProcess) {
alert('postProcess = ' + escape(postProcess));
} else {
alert('this search does not have a value for postProcess');
54
}
See Also
getBaseSearch()
setBaseSearch()
setPostProcess()
getRequiredFieldList()
The getRequiredFieldList() method gets the requiredFieldList of
the current search. This is a list of fields that must be present in the result set,
even if empty. The default value is empty.
Synopsis
fieldList = getRequiredFieldList()
Return Value
Array Required field list.
Example
var context = this.getContext();var search = context.get("search"); var rfl =
search.getRequiredFieldList();
if (rfl) {
$.each(rfl, function(i, v) {
alert('requireField = ' + escape(v));
});
} else {
alert('this search has no required field list');
See Also
setRequiredFields()
55
getSavedSearchName()
The getSavedSearchName() method gets the savedSearchName of the
current search.
Synopsis
searchName = getSavedSearchName()
Return Value
String Saved search name. Default = undefined.
Example
var context = this.getContext();var search = context.get("search"); var
savedSearch = search.getSavedSearchName();
if (savedSearch) {
alert('savedSearch = ' + escape(savedSearch));
} else {
alert('this search object does not reference a saved search');
See Also
setSavedSearchName()
getTimeRange()
The getTimeRange() method gets a Splunk.TimeRange instance
representing the current job data absolute time range.
Synopsis
timeRange = getTimeRange()
56
Return Value
Splunk.TimeRange instance representing the absolute time range
Object
of the current job data.
Example
var context = this.getContext(); var search = context.get('search');
console.log('Timerange: ' + search.job.getTimeRange().toString());
See Also
getTimeRange()
Splunk.TimeRange
getUrl()
The getUrl() method gets the URI to access resources for the current search
job.
Synopsis
jobURI = getUrl( asset, optionalArgs)
Parameters
(Optional) asset type: results control summary events
asset String
timeline
optionalArgs Object (Not implemented)
Return Value
String Job URI.
Example
var context = this.getContext();var search = context.get("search"); var url =
search.getUrl();
alert('results url is ' + url);
57
getViewStateId()
The getViewStateId () method gets the current search object viewStateId
property. The viewStateId property is used by the Splunk view state
subsystem to maintain per-view preferences.
Synopsis
viewStateID = getViewStateId()
Parameters
Return Value
String Current search object viewStateId.
Example
var context = this.getContext();var search = context.get("search"); var id =
search.getViewStateId();
alert('vsid = ' + escape(id));
See Also
setViewStateId()
hasIntentions()
The hasIntentions() method indicates if the current search object has
intentions.
Synopsis
results = hasIntentions()
Return Value
Search object has intentions indication:
Boolean True = Search object has intentions.
False = Search object does not have intentions.
58
Example
var context = this.getContext();var search = context.get("search");
if (search.hasIntentions()) {
search.absorbIntentions();
context.set('search', search); return context;
See Also
absorbIntentions()
addIntention()
clearIntentions()
dispatchJob()
getIntentionReference()
popIntention()
setIntentions()
isJobDispatched()
The isJobDispatched() method indicates if the current job has been
dispatched.
Synopsis
status = isJobDispatched()
Return Value
Job dispatch status:
Boolean true = Current job has been dispatched.
false = Current job has not been dispatched.
Example
var context = this.getContext();var search = context.get("search");
if !(search.isJobDispatched()) {
search.setBaseSearch('search index=_internal sourcetype=splunkd');
59
} else {
alert('cannot set base search since search is already dispatched');
context.set('search', search); return context;
See Also
abandonJob()
dispatchJob()
popIntention()
The popIntention() method gets the specified intention, intentionName,
constrained by the optional secondArgKey parameter. The retrieved intention is
removed from the intentions list.
Synopsis
intention = popIntention( intentionName, secondArgKey)
Parameters
Name of intention to be retrieved and removed from
intentionName String
list.
(Optional) Secondary key that must be present as
secondArgKey String an argument of the intentionName for the reference
to be removed and returned.
Return Value
Object Requested intention.
Example
var context = this.getContext();var search = context.get('search');
if (search.getIntentionReference('setfields')) {
search.popIntention('setfields');
60
See Also
absorbIntentions()
addIntention()
clearIntentions()
getIntentionReference()
hasIntentions()
setIntentions()
resurrect()
The resurrect() method gets a search object containing a previously
dispatched job.
Synopsis
search = resurrect( paramsDict )
Parameters
Dictionary of URI name-value pair GET request
paramsDict String
params.
Return Value
Object JSON dictionary as generated by view.py resurrection code.
Example
this.savedSearch = Splunk.Search.resurrect(this._params['jsonSearch']);
sendToView()
The sendToView() method redirects the user and current search to the
specified view, performing redirection across views while retaining the current
search object.
Synopsis
results = sendToView( viewName, additionalArgs,
dispatchBeforeRedirect, openInPopup, options, appName)
61
Parameters
Dictionary of URI name-value pair GET request
viewName String
params.
additionalArgs Object (Optional) Not implemented.
Enable dispatching of search job before redirection:
dispatchBeforeRedirect Bool True = Enable.
False = Disable.
Enable opening of destination window as a popup:
openInPopup Bool True = Enable.
False = Disable.
(Optional) window features representation for
destination window object: windowFeatures
{String} standard XHR window options. Default:
"resizable=yes,status=no,scrollbars=yes,toolbar=no"
options Object
autosize {Bool} Enables destination window
autosizing:
True = Enable.
False = Disable (default)
(Optional) Name of app to redirect to. Default =
appName String
current app.
Return Value
Boolean Success
Example
var context = this.getContext(); var search = context.get("search"); var options =
{} var additionalArgs = {}
search.sendToView('charting', additionalArgs, false, true, options);
setBaseSearch()
The setBaseSearch() method replaces the current base search string with
the specified search string. This method is the primary interface for setting the
base search string. This method also undefines
fullSearchWithIntentions and savedSearchName.
Note: You should not call this method against a search where the job has already
been dispatched. Use isJobDispatched() to check the dispatch status.
62
Synopsis
setBaseSearch( search )
Parameters
search Object Search string to be set as new base search string.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setBaseSearch('search index=_internal head 100'); context.set('search',
search); return context;
See Also
getBaseSearch()
isJobDispatched()
setDistributedServerList()
The setDistributedServerList() method sets the list search peers to
which the context current search is distributed.
Note: This method is destructive, so preserve the existing list using
getDistributedServerList().
Synopsis
results = setDistributedServerList( serverList )
Parameters
serverList Array List of splunkd instance names.
63
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search"); var serverList
= ['https://foobar.splunk.com:8089', 'https://barfoo.splunk.com:8089'];
search.setDistributedServerList(serverList); context.set('search', search); return
context;
See Also
getDistributedServerList()
setIntentions()
The setIntentions() method replaces the current search intentions with the
specified intentions.
Synopsis
results = setIntentions( intentionsList )
Parameters
intentionsList Array Intentions list.
Return Value
Undefined
Example
setNewIntentions: function(intentionsList) {
var context = this.getContext();
var search = context.get('search');
search.setIntentions(intentionsList);
context.set('search', search);
},
64
See Also
absorbIntentions()
addIntention()
clearIntentions()
getIntentionReference()
hasIntentions()
popIntention()
setMaxCount()
The setMaxCount() method sets the search maxCount property, specifying
the maximum number of results that each of a search job status buckets can
contain.
Note: In general, the default maxCount value should not be changed. Also, if
the search is dispatched with status_buckets >= 1, the maxCount setting
are ignored by splunkd.
Synopsis
setMaxCount( maxCount )
Parameters
Maximum job status bucket results count. Default =
maxCount Integer
10,000.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setMaxCount(31337); context.set('search', search); return context;
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
65
getMinimumStatusBuckets()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
setMaxEvents()
The setMaxEvents() method sets the maxEvents property for a search,
specifying the maximum number of events that each of a search job status
buckets can contain.
Note: If the search is dispatched with status_buckets>=1, the maxEvents
setting is ignored by splunkd.
Synopsis
setMaxEvents( maxEvents )
Parameters
Maximum number of events in job status bucket.
maxEvents Integer
Default = 10,000.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setMaxEvents(31337); context.set('search', search); return context;
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
setMaxTime()
setMinimumStatusBuckets()
66
setMaxTime()
The setMaxTime() method sets the maximum time for a search.
Note: In general, the default value should not be changed.
Synopsis
setMaxTime( maxTime )
Parameters
Maximum search time, in seconds. Default = 0, no
maxTime Integer
constraint.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setMaxTime(31337); context.set('search', search); return context;
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
setMaxCount()
setMaxEvents()
setMinimumStatusBuckets()
The setMinimumStatusBuckets() method specifies the minimum number
of status buckets to generate for consumers, such as flashtimeline.
The needed number of status buckets is one of the parameters passed in the
POST to dispatch a job. You need to allocate buckets to store job event
information. Typically, allocating one status bucket is sufficient, while a module
like flashtimeline needs to explicitly allocate 300 buckets to handle the default
number of events it expects. By convention, a module only sets the number of
67
buckets it needs for itself, if any. Parent modules should not the set bucket count
for child modules.
If search consumers require access to raw events, specify a value between one
and 300. If statusBuckets is less than the current value, the current value is not
changed.
Synopsis
setMinimumStatusBuckets( statusBuckets )
Parameters
Minimum number of status buckets that should be
statusBuckets Integer
prepared by the current context search job.
Return Value
Undefined
Example
bucketFunction: function(statusBuckets) {
var context = this.getContext();
var search = context.get("search");
var minBuckets = search.getMinimumStatusBuckets();
if (parseInt(statusBuckets) <= minBuckets) {
alert('between you and me - this value is too low. did you read
the docs?');
} else {
search.setMinimumStatusBuckets(parseInt(statusBuckets));
}
context.set('search', search);
return context;
},
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
68
setMaxEvents()
setMaxTime()
setPostProcess()
The setPostProcess() method stores a post-processing string in the current
search.
Synopsis
setPostProcess( search )
Parameters
search String Post-processing search string.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search"); var
postProcess = search.getPostProcess();
if (postProcess) {
alert('There is already a postProcess!');
} else {
search.setPostProcess('stats count');
context.set('search', search); return context;
See Also
getBaseSearch()
69
setRequiredFields()
The setRequiredFields() method sets the fields that must be present in
the event or result set, including an empty list, for when your module needs to
render certain fields without re-dispatching.
Synopsis
setRequiredFields( requiredFieldList )
Parameters
List of fields that must be present in the event or
requiredFieldList Array
result set. Default = empty.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setRequiredFields(['src_ip', 'dest_ip']); context.set('search', search); return
context;
See Also
getRequiredFieldList()
setSavedSearchName()
The setSavedSearchName() method sets the current search saved search
name so the search object reference a particular saved search.
If a saved search name is defined, the baseSearch value is ignored.
Intentions are not compatible with search objects that reference a saved search.
Synopsis
setSavedSearchName( name )
70
Parameters
name String Saved search name.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setSavedSearchName('Errors in the last hour'); context.set('search',
search); return context;
See Also
getSavedSearchName()
setSelectedEventAvailableCount()
The setSelectedEventAvailableCount() method sets the search job
event available count to the specified value. You should use this method to select
a sub-range of the original time range for getEventAvailableCount() to
return accurate results.
Synopsis
setSelectedEventAvailableCount( count )
Parameters
count Integer Event available count.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setSelectedEventAvailableCount(totalEventsAvailable);
search.setSelectedEventCount(totalEvents); var range =
71
this.getSelectionRange(selectedBuckets); search.setTimeRange(range);
context.set("search", search); return context;
See Also
getEventAvailableCount()
getEventCount()
setSelectedEventCount()
setSelectedEventCount()
The setSelectedEventCount() method sets the current search job event
count. You should use this method to select a sub range of the original time
range for getEventCount() to return accurate results.
Synopsis
setSelectedEventCount( count )
Parameters
count Integer Event count.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setSelectedEventAvailableCount(totalEventsAvailable);
search.setSelectedEventCount(totalEvents); var range =
this.getSelectionRange(selectedBuckets); search.setTimeRange(range);
context.set("search", search); return context;
See Also
getEventAvailableCount()
getEventCount()
setSelectedEventAvailableCount()
72
setTimeRange()
The setTimeRange() method sets the current search time range to the
specified value.
Note: Providing a time range equivalent to the current time range causes the
saved search name to be undefined.
Synopsis
this = setTimeRange( range )
Parameters
range Object Time range of type Splunk.TimeRange.
Return Value
Object Calling namespace.
Example
var context = this.getContext(); var search = context.get("search"); var
timeRange = new Splunk.TimeRange('-1d', 'now');
search.setTimeRange(timeRange); context.set('search', search); return context;
See Also
clearTimeRange()
getTimeRange()
Splunk.TimeRange
setViewStateId()
The setViewStateId() method sets the search object view state to the
specified value.
Synopsis
setViewStateId( id )
73
Parameters
id String Desired search object view state.
Return Value
Undefined
Example
var context = this.getContext(); var search = context.get("search");
search.setViewStateId(null); context.set('search', search); return context;
See Also
getViewStateId()
toString()
The toString() method gets the current search as a string, for textual
representation of the search.
Synopsis
search = toString()
Return Value
String Current search, as either full search with intentions or base search.
Example
var context = this.getContext();var search = context.get("search");
alert(escape(search.toString()));
See Also
getBaseSearch()
74
Splunk.TimeRange
clone()
The clone() method gets a copy of the current time range.
Synopsis
range = clone()
Return Value
Splunk.TimeRange object, which is a copy of the current time
Object
range object.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange(); var cloned_range = range.clone();
containsRange()
The containsRange() method checks if the specified timeRange is
contained in the current time range, inclusive.
Note: This method is only accurate given absolute terms in both the specified
range and the current, stored time range. If relative or real-time terms are used,
the method always returns true.
Synopsis
contains = containsRange( timeRange )
Parameters
Splunk.TimeRange object to test against current time
timeRange Object
range.
Return Value
Boolean Time range included indication:
True = Specified timeRange is included in the current time range,
or there are relative or real-time terms in the current time range
75
object.
False = Specified timeRange is not included in the current time
range.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange(); var new_range = new Splunk.TimeRange('-15m', 'now');
if (range.containsRange(new_range)) {
alert('this will always fire since new_range is relative');
var new_range = new Splunk.TimeRange('1311695438', '1311695498'); if
(range.containsRange(new_range)) {
alert('this will fire only if range contains new_range or if range
contains real-time or relative terms');
See Also
containsTime()
equalToRange()
isAbsolute()
isRealTime()
isRelative()
containsTime()
The containsTime() method checks if the specified dateObj time is
contained in the current time range.
Note: This method is only accurate for absolute terms contained in the current
time range. If relative or real-time terms are used, the method always returns
true.
Synopsis
contains = containsTime( dateObj )
76
Parameters
dateObj Object Time, of type JavaScript Date() object.
Return Value
Time included indication:
True = Specified dateObj is included in current time range, or
Boolean
there are relative or real-time terms in the current time range object.
False = Specified dateObj is not included in current time range.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange(); var new_time = new Date();
if (range.isAbsolute() && range.containsTime(new_time)) {
alert('this will fire only if range is absolute and contains
new_time');
See Also
containsRange()
equalToRange()
isAbsolute()
isRealTime()
isRelative()
equalToRange()
The equalToRange() method checks if the specified range time range object
is equal to the current time range.
Synopsis
equals = equalToRange( range )
Parameters
TimeRange object to compare against the current time
range Object
range.
77
Return Value
Time range equality indication:
True = Specified range is equal to the current time range. Always
Boolean returns true for relative or real-time terms in current time range
object.
False = Specified range is not equal to the current time range.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange(); var new_range = new Splunk.TimeRange('-15m', 'now');
if (range.equalToRange(new_range)) {
alert('this fires only if range is equivalent to new_range');
See Also
containsRange()
containsTime()
isAbsolute()
isRealTime()
isRelative()
formatRelativeRange()
The formatRelativeRange() method gets a text-formated representation of
the current time range.
Synopsis
formattedRange = formatRelativeRange()
Return Value
String Text-formatted representation of the current time range.
78
Throws
"Assertion failed - we dont support cases where one side has
snapUnits and the other does not."
Example
var range = new Splunk.TimeRange('-15m', 'now');if (range.isRelative()) {
alert(range.formatRelativeRange());
See Also
isRelative()
getAbsoluteEarliestTime()
The getAbsoluteEarliestTime() method gets the absolute earliest time of
the current time range object.
Note: This is intended to be a private method.
Synopsis
time = getAbsoluteEarliestTime()
Return Value
Absolute earliest time, of JavaScript type Date(). False, if time
Object
is relative.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange(); if (range.isAbsolute()) {
alert(range.getAbsoluteEarliestTime().toString());
79
See Also
getAbsoluteLatestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeEarliestTime()
getRelativeLatestTime()
getAbsoluteLatestTime()
The getAbsoluteLatestTime() method gets the absolute latest time in the
current time range object.
Note: This method is intended to be a private method.
Synopsis
time = getAbsoluteLatestTime()
Return Value
Absolute latest time, of JavaScript type Date(). False, if the time is
Object
relative.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange();
if (range.isAbsolute()) {
alert(range.getAbsoluteEarliestTime().toString());
See Also
getAbsoluteEarliestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeEarliestTime()
getRelativeLatestTime()
80
getDuration()
The getDuration() method gets the interval between the absolute current
time range earliest and latest times.
Synopsis
duration = getDuration()
Return Value
Interval, in milliseconds, between the earliest and latest
Integer times in the current time range. Returns -1, if the current
time range is relative.
Example
if (timeRange.getDuration() == -1) {
this._activator.text(timeRange.toConciseString());
} else {
this._activator.text(this.CUSTOM_TIME_LABEL);
See Also
isAbsolute()
isRealTime()
isRelative()
getEarliestTimeTerms()
The getEarliestTimeTerms() method gets the earliest time since the
epoch, in seconds, for absolute current time, or a Splunk time string representing
the earliest time, for relative current time.
Synopsis
time = getEarliestTimeTerms()
81
Return Value
Absolute current time: Earliest time since the epoch, in seconds.
Integer,
Relative current time: Splunk time string representing earliest
String
time.
Example
updatePermalinks: function(event) { var context = this.getContext();
var search = context.get("search");
var args = {};
args["q"] = Splunk.util.addLeadingSearchCommand(search.toString());
var range = search.getTimeRange();
if (range) {
if (range.getEarliestTimeTerms()) {
args["earliest"] = range.getEarliestTimeTerms();
}
if (range.getLatestTimeTerms()) {
args["latest"] = range.getLatestTimeTerms();
}
}
$("li." + this.PERMALINK_SEARCH_CLASS + " a",
this.container).attr("href", "?" +
Splunk.util.propToQueryString(args));
$("li." + this.PERMALINK_SID_CLASS + " a",
this.container).attr("href", "?sid=" +
encodeURIComponent(search.job.getSearchId()));
},
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getLatestTimeTerms()
getRelativeEarliestTime()
getRelativeLatestTime()
getLatestTimeTerms()
The getLatestTimeTerms() method gets the latest time since the epoch, in
seconds, for absolute current time, or a Splunk time string representing the latest
time, for relative current time..
82
Synopsis
time = getLatestTimeTerms()
Return Value
Integer Absolute current time: Latest time since the epoch, in seconds.
String Relative current time: Splunk time string representing latest time.
Example
updatePermalinks: function(event) { var context = this.getContext();
var search = context.get("search");
var args = {};
args["q"] = Splunk.util.addLeadingSearchCommand(search.toString());
var range = search.getTimeRange();
if (range) {
if (range.getEarliestTimeTerms()) {
args["earliest"] = range.getEarliestTimeTerms();
}
if (range.getLatestTimeTerms()) {
args["latest"] = range.getLatestTimeTerms();
}
}
$("li." + this.PERMALINK_SEARCH_CLASS + " a",
this.container).attr("href", "?" +
Splunk.util.propToQueryString(args));
$("li." + this.PERMALINK_SID_CLASS + " a",
this.container).attr("href", "?sid=" +
encodeURIComponent(search.job.getSearchId()));
},
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getEarliestTimeTerms()
getRelativeEarliestTime()
getRelativeLatestTime()
getRelativeEarliestTime()
The getRelativeEarliestTime() method gets the earliest time of the
relative current time range.
83
Note: This method is intended to be private.
Synopsis
time = getRelativeEarliestTime()
Return Value
Splunk time representation of the earliest time in the current
String time range. Returns false for an absolute current time
range.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange();
if (range.isRelative()) {
alert(range.getRelativeEarliestTime().toString());
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeLatestTime()
getRelativeLatestTime()
The getRelativeLatestTime() method gets the latest time of the relative
current time range.
Note: This method is intended to be private.
Synopsis
time = getRelativeLatestTime()
84
Return Value
Splunk time representation of the latest time in the current time
String
range. Returns false for an absolute current time range.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange();
if (range.isRelative()) {
alert(range.getRelativeEarliestTime().toString());
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeEarliestTime()
getTimeFormat()
The getTimeFormat() method gets a formatted absolute time used by the
REST API. This method wraps Splunk.util.getConfigValue(
'DISPATCH_TIME_FORMAT' ).
Synopsis
formattedTime = getTimeFormat()
Return Value
String Server configured dispatch time format
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange();
alert(range.getTimeFormat());
85
See Also
Splunk.util.getConfigValue()
isAbsolute()
The isAbsolute() method tests if the earliest and latest times in the current
time range are absolute.
Synopsis
results = isAbsolute()
Return Value
Absolute time representation indication:
Boolean true = Time range is absolute.
false = Time range is not absolute.
Example
updateTimeHeader: function(range) {
var job = this.getContext().get("search").job;
var actualIndexRange = new
Splunk.TimeRange(job["_searchEarliestTime"], job["_searchLatestTime"]);
if (!actualIndexRange.isAllTime()) {
if (range.isAbsolute()) {
header = sprintf(_("%(humanReadableTime)s
(%(actualAbsoluteTime)s)"),
{humanReadableTime: header,
actualAbsoluteTime:
actualIndexRange.toConciseString()}); }
}
this._timeRangeHeader.text(header);
},
See Also
containsRange()
containsTime()
equalToRange()
getDuration()
isAllTime()
86
isRealTime()
isRelative()
isAllTime()
The isAllTime() method tests if the time range is "all time," unbounded
earliest and latest time.
Synopsis
allTime = isAllTime()
Return Value
"all time" time range indication:
Boolean true = Time range is "all time."
false = Time range is not "all time."
Example
updateTimeHeader: function(range) {
var header = this.getMatchingCustomHeader(range)
range.toConciseString();
var job = this.getContext().get("search").job;
var actualIndexRange = new
Splunk.TimeRange(job["_searchEarliestTime"], job["_searchLatestTime"]);
if (!actualIndexRange.isAllTime()) {
if (range.isAbsolute()) {
header = sprintf(_("%(humanReadableTime)s
(%(actualAbsoluteTime)s)"),
{humanReadableTime: header,
actualAbsoluteTime:
actualIndexRange.toConciseString()});
}
}
this._timeRangeHeader.text(header);
},
See Also
containsRange()
containsTime()
equalToRange()
isAbsolute()
87
isRealTime()
isRelative()
isRealTime()
The isRealTime() method tests if the current time range is a real-time
representation.
Synopsis
realTime = isRealTime()
Return Value
Real-time current time range indication:
Boolean true = Current time range is real-time.
false = Current time range is not real-time.
Example
onContextChange: function() { var context = this.getContext();
var search = context.get("search");
var range = search.getTimeRange();
var currentSID = search.job.getSearchId();
if (range.isRealTime() ) {
this.hide(this.PREVIEW_AND_REAL_TIME_CONFLICT);
}
else {
this.show(this.PREVIEW_AND_REAL_TIME_CONFLICT);
if (search.isJobDispatched() && !search.job.isDone() &&
currentSID != this.previousSID) {
search.job.setPreviewable(this.isChecked());
}
}
this.previousSID = currentSID;
},
See Also
containsRange()
containsTime()
equalToRange()
getDuration()
isAbsolute()
88
isAllTime()
isRelative()
isRelative()
The isRelative() method tests if the current time range is relative.
Synopsis
relative = isRelative()
Return Value
Relative time representation indication:
Boolean true = Time range is relative.
false = Time range is not relative.
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange();
if (range.isRelative()) {
alert(range.getRelativeLatestTime().toString());
See Also
containsRange()
containsTime()
equalToRange()
formatRelativeRange()
getDuration()
isAbsolute()
isAllTime()
isRealTime()
isSubRangeOfJob()
The isSubRangeOfJob() method checks if the current time range is a
sub-range of the underlying job. If setAsSubRangeOfJob( true ) was
89
previously called when selection part of the original time range to drill down, this
method may need to be called to determine if a new search needs to be
dispatched.
Synopsis
results = isSubRangeOfJob()
Return Value
Sub-range indication:
true = Current time range is a sub-range of the underlying job
Boolean time range.
false = Current time range is a not sub-range of the underlying
job time range.
Example
requiresDispatch: function(search) {
search = search new Splunk.Search();
if (this.requiresTransformedResults()) {
var range = search.getTimeRange();
if (range.isSubRangeOfJob()) {
return true;
}
}
},
See Also
setAsSubRangeOfJob()
setAsSubRangeOfJob()
The setAsSubRangeOfJob() method must be called to indicate that the
current time range is a subset of the underlying job time range.
If the Splunk.TimeRange instance attached to a Splunk.Search instance
was modified to represent a sub-range, with the start and end times
corresponding to boundaries on the timelineData structure in splunkd, the
client is required to call setAsSubRangeOfJob(). The time range is typically
changed when interacting with the REST API timeline endpoint, such that the
search time range becomes a sub-range of the job time range.
90
Synopsis
setAsSubRangeOfJob( isSubrange )
Parameters
Current time range is a sub-range indication:
true = Current time range is a sub-range of underlying
isSubrange Boolean job time range.
false = Current time range is not a sub-range of
underlying job time range.
Return Value
Undefined
Example
getSelectionRange: function(selectedBuckets) {
selectedBuckets = selectedBuckets
this.bridge.callMethod("getSelectedBuckets");
var numberOfBuckets = selectedBuckets.length;
if (numberOfBuckets==0) {
this.logger.error(this.moduleType,
" getSelectionRange returned an empty selectedBuckets");
return new Splunk.TimeRange();
}
var earliestBucket = selectedBuckets[0];
var latestBucket = selectedBuckets[numberOfBuckets-1];
var range = new Splunk.TimeRange(earliestBucket["earliestTime"],
latestBucket["latestTime"]);
range.setAsSubRangeOfJob(!this.isEntireRangeSelected);
return range;
},
See Also
isSubRangeOfJob()
toConciseString()
The toConciseString() method gets a compact, localized time range in
human-readable form.
91
Synopsis
timeRange = toConciseString()
Return Value
Boolean Success
Example
updateTimeHeader: function(range) { var header =
this.getMatchingCustomHeader(range) range.toConciseString();
var job = this.getContext().get("search").job;
var actualIndexRange = new
Splunk.TimeRange(job["_searchEarliestTime"],
job["_searchLatestTime"]);
if (!actualIndexRange.isAllTime()) {
if (range.isAbsolute()) {
header = sprintf(_("%(humanReadableTime)s
(%(actualAbsoluteTime)s)"),
{humanReadableTime: header,
actualAbsoluteTime:
actualIndexRange.toConciseString()}); }
}
this._timeRangeHeader.text(header);
},
See Also
toString()
toString()
The toString() method serializes the current time range.
Synopsis
timeRange = toString()
Return Value
String Serialized time range.
92
Example
var context = this.getContext();var search = context.get('search'); var range =
search.getTimeRange();
alert(range.toString());
See Also
toConciseString()
Splunk.util
addLeadingSearchCommand()
The addLeadingSearchCommand() method prefixes a search string to the
specified search string if it does not already begin with search or a pipe (¦)
symbol. This method is typically used to verify that user-provided search is
formatted correctly for the search API.
Synopsis
qSearch = Splunk.util.addLeadingSearchCommand( search,
isUserEntered )
Parameters
search String Search string to be qualified.
Unqualified search string indication:
true = The search parameter is expected to be
isUserEntered Boolean unqualified.
false = The search parameter is not expected to
be unqualified.
Return Value
String Qualified search string.
93
Example
getUserEnteredSearch: function() {
var q = this.input.attr('value') '*';
q = Splunk.util.addLeadingSearchCommand(q, true);
return q;
},
See Also
stripLeadingSearchCommand()
discoverReplacementTokens()
The discoverReplacementTokens() method gets an array of unique
replacement tokens found in the specified string or object fragment. If fragment is
an object, the method identifies tokens in both keys and values. Replacement
tokens are formatted as $token$.
Synopsis
results = Splunk.util.discoverReplacementTokens( fragment )
Parameters
fragment String, Object Fragment to examine for replacement tokens.
Return Value
Array List of unique replacement tokens.
Example
if (USE_AUTOMATIC_STRING_REPLACEMENT) {
var context = this.getContext();
var baseSearch = search.toString();
var tokens = Splunk.util.discoverReplacementTokens(baseSearch);
for (var i=0; i<tokens.length; i++) {
var replacer = new RegExp("\\$" + tokens[i] + "\\$");
baseSearch = Splunk.util.replaceTokens(baseSearch, replacer,
context.get(tokens[i]));
search.setBaseSearch(baseSearch);
}
94
}
See Also
replaceTokens()
escapeBackslash()
The escapeBackslash() method escapes backslash characters found in the
specified input string.
Synopsis
results = Splunk.util.escapeBackslash( input )
Parameters
input String String to search for backslash characters.
Return Value
String The input string with any backslash characters escaped.
Example
var input = "foo//bar"; var input = Splunk.util.escapeBackslash(input);
alert(input); // will be "foo////bar"
See Also
escapeHtml()
escapeHtml()
The escapeHtml() method escapes HTML entities in the specified input
string.
Note: This method should only be used as a convenience method, because
client-side escaping is not trustworthy.
95
Synopsis
results = Splunk.util.escapeHtml( input )
Parameters
input String String containing HTML entities.
Return Value
String The input string with HTML entities escaped.
Example
var input = '"<&bar&>"'; var input = Splunk.util.escapeHtml(input);
alert(input);
See Also
escapeBackslash()
fieldListToString()
The fieldListToString() method serializes a specified fieldArray array
into a comma-separated string.
Synopsis
results = Splunk.util.fieldListToString( fieldArray )
Parameters
fieldArray Array Array of fields to serialize.
Return Value
String Comma-separated field list.
Example
var fieldList = ['foo\bar ', ' "bar"', 'biz,']; var fieldString =
Splunk.util.fieldListToString(fieldList);
alert(fieldString);
96
See Also
stringToFieldList()
getCommaFormattedNumber()
The getCommaFormattedNumber() method converts numbers in the
specified input string to comma-notated format.
Synopsis
results = Splunk.util.getCommaFormattedNumber( input )
Parameters
input String String, possibly containing numbers.
Return Value
The input string with numbers converted to comma-notated
String
representations.
Example
var num = '10000000001';
numb = Splunk.util.getCommaFormattedNumber(numb); alert(num);
getComputedStyleHelper()
The getComputedStyleHelper() method gets the value of the specified
style for the specified element.
Synopsis
results = Splunk.util.getComputedStyleHelper( element,
styleProp )
Parameters
element Object Element to interrogate.
styleProp String Style property to interrogate.
97
Return Value
Value of the element style property, styleProp. Returns null, if
Boolean
element or styleProp do not exist.
Example
var myVal = Splunk.util.getComputedStyleHelper(myElement, 'display');
alert(myVal);
getConfigValue()
The getConfigValue() method gets SplunkWeb configuration values stored
in the DOM.
Synopsis
results = Splunk.util.getConfigValue( configKey,
optionalDefault )
Parameters
configKey String Configuration key to get.
(Optional) Fallback value if configKey does not exist
optionalDefault String
or has no value.
Return Value
String Value of specified configKey.
Throws
'getConfigValue - ' + configKey + ' not set, no default
provided'
Example
var f = Splunk.util.getConfigValue("SEARCH_RESULTS_TIME_==
getCurrentDisplayView()==
The getCurrentDisplayView() method gets the current displayView
name, which is the view label stored in the DOM.
98
Synopsis
name = Splunk.util.getCurrentDisplayView()
Return Value
Current displayView name if different from the view name.
String
Otherwise, the current view name.
Example
<code>
var displayView = Splunk.util.getCurrentDisplayView();
See Also
getCurrentApp()
getCurrentView()
getCurrentViewConfig()
FORMAT"); var f =
Splunk.util.getConfigValue("DEFAULT_SPACECAKE_VENDOR", "Barneys");
</code>
getCumlativeOffsetLeft()
The getCumlativeOffsetLeft() method gets the cumulative offset of the
specified DOM element property.
Synopsis
offset = Splunk.util.getCumlativeOffsetLeft( element )
Parameters
element Object DOM element: offsetLeft or offsetParent.
Return Value
Integer Cumulative offset value.
99
Example
var height = ($(window).height() + Splunk.util.getPageYOffset() +
pixelAdjustment) - \
Splunk.util.getCumlativeOffsetTop(this.container[0]);
See Also
getCumlativeOffsetTop()
getPageYOffset()
getCumlativeOffsetTop()
The getCumlativeOffsetTop() method gets the value of the specified
DOM element parameter.
Synopsis
offset = Splunk.util.getCumlativeOffsetTop( element )
Parameters
element Object DOM element: offsetTop or offsetParent.
Return Value
Integer Cumulative DOM element value.
Example
var height = ($(window).height() + Splunk.util.getPageYOffset() +
pixelAdjustment) - \
Splunk.util.getCumlativeOffsetTop(this.container[0]);
See Also
getCumlativeOffsetLeft()
getPageYOffset()
100
getCurrentApp()
The getCurrentApp() method gets the current app name as stored in the
DOM, which is not the friendly name, or label, of the current app.
Synopsis
app = Splunk.util.getCurrentApp()
Return Value
Current app name or UNKNOWN_APP, if app name is undefined in
String
the DOM.
Example
document.location = Splunk.util.make_url('app',
Splunk.util.getCurrentApp());
See Also
getCurrentDiplayView()
getCurrentView()
getCurrentViewConfig()
make_url()
getCurrentDisplayView()
The getCurrentDisplayView() method gets the current displayView
name, which is the view label stored in the DOM.
Synopsis
name = Splunk.util.getCurrentDisplayView()
Return Value
Current displayView name if different from the view
String
name. Otherwise, the current view name.
101
Example
var displayView = Splunk.util.getCurrentDisplayView();
See Also
getCurrentApp()
getCurrentView()
getCurrentViewConfig()
getCurrentView()
The getCurrentView() method gets the current view value, which is the
actual view name stored in the DOM.
Synopsis
results = Splunk.util.getCurrentView()
Return Value
Current view value, as stored in the DOM, or UNKNOWN_VIEW if
String
undefined.
Example
var view = Splunk.util.getCurrentView();
See Also
getCurrentApp()
getCurrentDisplayView()
getCurrentViewConfig()
getCurrentViewConfig()
The getCurrentViewConfig() method gets a dictionary of app, view, and
saved search configuration data in the DOM, for the current view.
Synopsis
config = Splunk.util.getCurrentViewConfig()
102
Return Value
The app, view, and saved search configuration data in the DOM, for
Object
the current view.
Example
var config = Splunk.util.getCurrentViewConfig();
See Also
getCurrentApp()
getCurrentDisplayView()
getCurrentView()
getEpochTimeFromISO()
The getEpochTimeFromISO() method gets an epoch time equivalent to the
specified ISO time.
Synopsis
epoch = Splunk.util.getEpochTimeFromISO( isoStr )
Parameters
isoStr String ISO-formatted time
Return Value
String Epoch time equivalent to isoStr, including milliseconds.
Example
getTimeRange: function() {
if (!this._earliestTime !this._latestTime) {
return new Splunk.TimeRange();
}
var startTime = Splunk.util.getEpochTimeFromISO(this._earliestTime);
var endTime = Splunk.util.getEpochTimeFromISO(this._latestTime);
if (isNaN(startTime)) {
startTime = this._earliestTime;
endTime = this._latestTime;
}
if (startTime == 0) startTime = null;
103
if (endTime == 0) endTime = null;
return new Splunk.TimeRange(startTime, endTime);
},
getHEX()
The getHEX() method gets the hexadecimal equivalent of the specified RGB
value.
Synopsis
hexVal = Splunk.util.getHEX( rgbVal )
Parameters
rgbVal String RGB value. Format: 'rgb(rrr, ggg, bbb)'
Return Value
String Hexadecimal equivalent of rgbVal, with preceding # symbol.
Example
var myHEX = Splunk.util.getHEX('rgb(255, 0, 0)');
alert(myHEX);
See Also
normalizeColor()
getPageYOffset()
The getPageYOffset() method gets the amount of content hidden by
scrolling down.
Synopsis
offset = Splunk.util.getPageYOffset()
104
Return Value
Number Amount of content hidden, vertically, by scrolling down, in pixels.
Example
var height = ($(window).height() + Splunk.util.getPageYOffset() +
pixelAdjustment) - \
Splunk.util.getCumlativeOffsetTop(this.container[0]);
See Also
getCumlativeOffsetLeft()
getCumlativeOffsetTop()
getParameter()
The getParameter() method gets the GET parameter from window.location
or an optional string.
Synopsis
getParam = Splunk.util.getParameter( paramVal, string )
Parameters
paramVal String Parameter value to get.
(Optional) String to search instead of
string String
window.location.search
Return Value
String Parameter value, or none if paramVal has no value.
Example
var fooVal = Splunk.util.getParameter('foo');
See Also
getPath()
105
getPath()
The getPath() method gets the current location path without the localization
segment.
Synopsis
results = Splunk.util.getPath()
Return Value
String Current location path without localization.
Example
var pathVal = Splunk.util.getPath();
See Also
getParameter()
make_url()
queryStringToProp()
getServerTimezoneOffset()
The getServerTimezoneOffset() method gets the current server timezone
offset.
Synopsis
offset = Splunk.util.getServerTimezoneOffset()
Return Value
String Current server timezone offset, in milliseconds.
Example
var serverOffsetSeconds = Splunk.util.getServerTimezoneOffset();
See Also
getTimezoneOffsetDelta()
106
getTimezoneOffsetDelta()
The getTimezoneOffsetDelta() method gets the time delta between the
specified offset and date.
Synopsis
offset = Splunk.util.getTimezoneOffsetDelta(
serverOffsetThen, date )
Parameters
serverOffsetThen Integer Timezone offset, in minutes.
JavaScript Date() object from which to
date Object
calculate offset.
Return Value
Integer Difference between serverOffsetThen and date, in milliseconds.
Example
var earliestDelta = \
Splunk.util.getTimezoneOffsetDelta(this.serverOffsetAtEarliest,
earliest);
var latestDelta = \
Splunk.util.getTimezoneOffsetDelta(this.serverOffsetAtLatest, latest);
See Also
getServerTimezoneOffset()
getWindowDimensions()
The getWindowDimensions() method gets the inner dimensions of the
current window.
Synopsis
dims = Splunk.util.getWindowDimensions()
107
Return Value
JSON-formatted height and width. Example: { 'height': 600,
Object
'width': 800 }
Example
var dimensions = Splunk.util.getWindowDimensions();
isInt()
The isInt() method tests if the specified value is an integer, implying it can
be parsed into an integer using the JavaScript parseInt() method.
Synopsis
status = Splunk.util.isInt( int )
Parameters
int String, Integer Value to test for an integer.
Return Value
Value is integer indication:
Boolean true = Value is an integer or can be converted to an integer.
false = Value is not an integer.
Example
var int1 = 42; var int2 = function() { return false; }; var int3 = '42'; var int4 = ['foo',
'bar']; var int5 = { the_answer_to_life_the_universe_and_everything: 42}
alert(Splunk.util.isInt(int1)); alert(Splunk.util.isInt(int2));
alert(Splunk.util.isInt(int3)); alert(Splunk.util.isInt(int4));
alert(Splunk.util.isInt(int5));
make_full_url()
The make_full_url() method builds a qualified query string given the
specified path and, optional, dictionary of options.
108
Synopsis
fullURL = Splunk.util.make_full_url( url, options)
Parameters
url String Endpoint path.
options Object Query string parameters dictionary.
Return Value
String Full URL created from url and options.
Example
var bounce_url = Splunk.util.make_full_url('/account/login', \
{ return_to: 'apps/search/'
});
See Also
make_url()
make_url
The make_url() function returns a URL for the specified path.
The method builds a URL from a relative or absolute URL with optional query
string. A relative URL is returned, if relative is set to True, otherwise, an absolute
URL is returned. The string /splunk or the configuration root_path is prefixed
to the URL unless translate is set to False.
Static paths are constructed with an embedded cache defeater segment :
/static/@<build_number>[.<push_number>]/
This results in static paths like the following example:
/static/@12345/js/foo/static/@12345.1/js/foo
Static assets for apps have an additional cache defeater number correlating to
the application build number as defined in the app.conf file:
109
/static/@12345.1:2/app/unix/static/foo.png
The URL handler in root.py strips out any requests having this schema.
Synopsis
targURL = make_url(target, _qs=None, translate=True,
relative=False, __app_cache={})
Parameters
target String
Query string as a list of tuples or a dictionary. Example:
_qs Object _qs=[('q', 'search val to quote')] (Default =
None )
Prefix the application server root path flag:
translate Boolean True = Prefix root path (Default).
False = Do not prefix root path.
Relative returned path indication:
relative Boolean True = Returned targetURL is relative.
False = Returned targetURL is absolute (Default)
Return Value
String The specified target as a full URL.
Raises
InvalidURLException "Illegal characters in URL"
'Illegal escape from parent directory
ValueError
"%s": %s' %(basepath, fullpath)
Example
from splunk.appserver.mrsparkle.lib import util
targetURL = '/en-US/api/search/jobs?job=1234&action=delete' example1URL =
util.make_url('/api/search/jobs', job=1234, action=delete) example2URL =
util.make_url('/api/search/jobs, _qs=dict(job=1234,action=delete))
110
See Also
strip_url()
url_has_valid_charset()
normalizeBoolean()
The normalizeBoolean() method normalizes various boolean syntax idioms
into a Boolean response.
Synopsis
results = Splunk.util.normalizeBoolean( test, strictMode)
Parameters
String, Integer,
test Item to be normalized.
Boolean
Notification on failure:
true = Throw exception if
strictMode Boolean normalization fails.
false = Do not throw exception if
normalization fails.
Return Value
Boolean Normalized test value.
Throws
TypeError Unable to cast value into boolean: < test >
Example
var myBool = Splunk.util.normalizeBoolean(1); var myBool =
Splunk.util.normalizeBoolean(0); var myBool =
Splunk.util.normalizeBoolean('Yes'); var myBool =
Splunk.util.normalizeBoolean('nO'); var myBool =
Splunk.util.normalizeBoolean('1');
var myBool = Splunk.util.normalizeBoolean('0'); var myBool =
Splunk.util.normalizeBoolean('on'); var myBool =
Splunk.util.normalizeBoolean('OFF'); var myBool =
Splunk.util.normalizeBoolean('foobar', true);
111
normalizeColor()
The normalizeColor() method converts an RGB or hexadecimal color value
to a fully-qualified hexadecimal equivalent.
Synopsis
hexColor = Splunk.util.normalizeColor( color )
Parameters
color String RGB or hexadecimal color value.
Return Value
Fully-qualified, six-digit hexadecimal color value with leading number
String
symbol ( # ), or null if color cannot be processed.
Example
getCSSColor: function(specificity, cssProperty){
var color;
for (var i=0; i<specificity.length; i++){
var computedColor = specificity[i].css(cssProperty);
color = Splunk.util.normalizeColor(computedColor);
if (color){
return color;
}
}
return null;
},
See Also
getHex()
objectSimilarity()
The objectSimilarity() method compares two objects.
112
Synopsis
similar = Splunk.util.objectSimilarity( obj1, obj2)
Parameters
obj1 Object Object to compare against obj2.
obj2 Object Object to compare against obj1.
Return Value
Object similarity indication:
Boolean true = obj1 and obj2 are similar.
false = obj1 and obj2 are not similar.
Example
haveResultParamsChanged: function() {
var currentResultParams = this.getResultParams();
return (!Splunk.util.objectSimilarity(this._previousResultParams, \
currentResultParams));
},
propToQueryString()
The propToQueryString() method serializes the specified properties
dictionary into an query string.
Synopsis
query = Splunk.util.propToQueryString( dictionary )
Parameters
dictionary String One-level properties dictionary.
Return Value
String Serialized query string representation of dictionary.
113
Example
var dictionary = {'foo': 'bar', 'fiz': 'baz'}; var qStr =
Splunk.util.propToQueryString(dictionary); alert(qStr);
See Also
getPath()
queryStringToProp()
queryStringToProp()
The queryStringToProp() method de-serializes the specified query string
into an object literal.
Synopsis
obj = Splunk.util.queryStringToProp( query )
Parameters
query String Query string to de-serialize.
Return Value
Object De-serialized query string, in JSON fomat.
Example
var qsDict = Splunk.util.queryStringToProp(document.location.search);
alert(qsDict['foo']);
See Also
getPath()
propToQueryString()
redirect_to()
The redirect_to() method is a window.document.location wrapper.
114
Synopsis
Splunk.util.redirect_to( uri, options, windowObj, focus)
Parameters
uri String Location to redirect to.
Redirection options:
sid = Attaches optional sid in valid format.
options Object s = Attaches optional saved search name.
q = Attaches optional search string in valid
format.
(Optional) Window object to target the location
windowObj Window Object
change.
Window receives focus indication:
focus Boolean true = New window receives focus.
false = New window does not receive focus.
Return Value
Undefined
Example
Splunk.util.redirect_to(['app', Splunk.util.getCurrentApp(), '@go'].join('/'), \
{'sid': '12345678901.123'});
See Also
make_url()
replaceTokens()
The replaceTokens() method performs regular expression-based token
replacement in the specified fragment. If the given fragment is an object,
replacement will be performed in both keys and values.
Synopsis
result = Splunk.util.replaceTokens( fragment, reg, val)
115
Parameters
fragment String, Object Fragment to perform replacement on.
reg String Regular expression used for replacement.
Value with which to replace tokens matching
val String
reg.
Return Value
String, Object Fragment with tokens replaced.
Example
if (USE_AUTOMATIC_STRING_REPLACEMENT) {
var context = this.getContext();
var baseSearch = search.toString();
var tokens = Splunk.util.discoverReplacementTokens(baseSearch);
for (var i=0; i<tokens.length; i++) {
var replacer = new RegExp("\\$" + tokens[i] + "\\$");
baseSearch = Splunk.util.replaceTokens(baseSearch, \
replacer, \
context.get(tokens[i]));
search.setBaseSearch(baseSearch);
}
See Also
discoverReplacementTokens()
smartTrim()
The smartTrim() method gets a string trimmed to a specified maxLength by
replacing characters in the middle of the string with ellipses.
Synopsis
trimString = Splunk.util.smartTrim( inString, maxLength)
Parameters
inString String String to trim.
116
maxLength Integer Maximum length of the field.
Return Value
String Trimmed representation of inString.
Example
var smartString = Splunk.util.smartTrim('1234567890', 5); alert(smartString);
stringToFieldList()
The stringToFieldList() method de-serializes a specified
comma-separated string into an array.
Synopsis
items = Splunk.util.stringToFieldList( strList )
Parameters
strList String String list to de-serialize.
Return Value
Array De-serialized representation of strList.
Example
var fieldStr = '"foo\bar","\"bar\"","biz,"'; var fieldList =
Splunk.util.stringToFieldList(fieldStr);
alert(fieldList);
See Also
fieldListToString()
stripLeadingSearchCommand()
The stripLeadingSearchCommand() method gets an unqualified search
string by stripping any leading search string from the specified string.
117
Synopsis
unqualified = Splunk.util.stripLeadingSearchCommand(
qSearch )
Parameters
qSearch String Search string to be unqualified.
Return Value
String Unqualified search string.
Example
onContextChange: function() {
var context = this.getContext();
var search = context.get("search");
search.absorbIntentions(function(newQ) {
this.setInputField(Splunk.util.stripLeadingSearchCommand(newQ));
}.bind(this));
},
See Also
addLeadingSearchCommand()
118
Module APIs
Splunk.Module
abortGetResults()
The abortGetResults() method destroys the previously submitted XHR
request within the current context.
Warning: Calling this method is discouraged because misuse can cause
unexpected behavior. Instead, you should call reset(). Also, overriding this
method when suclassing AbstractModule is not recommended.
Synopsis
results = abortGetResults()
Return Value
Undefined
See Also
reset()
addChild()
The addChild() method adds the specified module as a child of the current
instance. The child must not already have a parent.
Synopsis
status = addChild( child )
Parameters
child Object Module to be added as a child.
119
Return Value
Undefined
Example
var first_child = this._children[0]; var first_grandchild = first_child._children[0];
child.removeChild(first_grandchild); this.addChild(first_grandchild);
See Also
removeChild()
applyContext()
The applyContext() method handles context changes that flow from
descendants to ancestors, when a context change needs to traverse up the
hierarchy.
Upward traversal of a context can cause unexpected behavior and should be
avoided, if possible. This method
is not implemented, by default, and is intended to be overridden by modules that
subclass AbstractModule.
Synopsis
results = applyContext( context )
Parameters
context Object Context to be passed upstream.
Return Value
Undefined
Example
applyContext: function($super, context) {
if (this.isPageLoadComplete()) {
var search = context.get("search");
120
if (search.search(/\spony\W+/i) > -1) {
alert('I found the p0ny!');
} else {
alert('p0ny detection phail');
}
return $super(context);
}
},
See Also
getContext()
isPageLoadComplete()
onContextChange()
passContextToParent()
displayInlineErrorMessage()
The displayInlineErrorMessage() method displays the specified
message in the module.
Synopsis
results = displayInlineErrorMessage( message )
Parameters
message String Message to display.
Return Value
Undefined
Example
this.displayInlineErrorMessage('Game 0v3r!!1');
ensureFreshContexts()
The ensureFreshContexts() method propagates context changes
downstream for ancestors that have stale context that has not been propagated.
For example, when a user types into an input field, but submits the form by
clicking "enter" on another form field.
121
Synopsis
results = ensureFreshContexts()
Return Value
Error indication:
Boolean False = An ancestor context contains a search that has already
been dispatched.
Exceptions
TBD
Example
this.ensureFreshContexts();
See Also
getModifiedContext()
pushContextToChildren()
setChildContextFreshness()
withEachAncestor()
getAncestors()
The getAncestors() method gets an ordered list of calling module
ancestors.
Note: You should generally call the withEachAncestor() iterator instead of
this method.
Synopsis
ancestors = getAncestors()
Return Value
Array Ordered list of ancestors.
122
Example
alertEachAncestor: function() {
var ancestors = this.getAncestors();
$.each(ancestors, function(i, v) {
alert(v);
});
},
See Also
getDescendants()
getModulesInTree()
getRootAncestor()
withEachAncestor())
getContext()
The getContext() method gets the most current Splunk.Context search
context, which is the accumulated information from all module ancestors.
Note: This method should not be overridden.
Synopsis
context = getContext()
Return Value
Current context.
Object
null = Could not get a context object.
Throws
Message: "getContext was called by <this> (moduleId)s with
no baseContext. </this><this> (moduleId)s's parent returned
a null context. This should not happen." </this>
Example
var context = this.getContext(); var search = context.get('search');
123
See Also
applyContext()
getModifiedContext()
onContextChange()
getDescendants()
The getDescendants() method gets an ordered list of all module
descendants.
Note: This method should not be overridden.
Synopsis
results = getDescendants( self, **args )
Return Value
Array Ordered list of descendants.
Example
var descendants = this.getDescendants();
for (var i=0, len=descendants.length; i < len; i++) {
descendants[i].reset();
See Also
getAncestors()
getModulesInTree()
getRootAncestor()
getGroupName()
The getGroupName() method gets the current module group name. If a group
name does not exist for the module, it returns the parent group name.
124
Synopsis
group = getGroupName()
Return Value
Group name parameter of current module or parent module.
String
False = Group name not found.
Example
if (!this.getGroupName()) {
alert('Neither this module nor its parent has a 'group' param');
See Also
getParam()
getLoadState()
The getLoadState() method gets the module load state.
Synopsis
loadstate = getLoadState()
Return Value
Module load state:
WAITING_FOR_INITIALIZATION
Constant WAITING_FOR_HIERARCHY
WAITING_FOR_CONTEXT
HAS_CONTEXT
Example
if (this.getLoadState() < Splunk.util.moduleLoadStates.HAS_CONTEXT) {
return;
} else {
125
alert('I have a context and can proceed with some useful function');
See Also
setLoadState()
getModifiedContext()
The getModifiedContext() method provides a proxy for getContext(),
by default. This method is intended to be overridden to pass a modified context
to children. Modified contexts might include search, time range or other functional
changes.
Synopsis
results = getModifiedContext()
Return Value
Object Modified context.
Example
getModifiedContext: function() {
var context = this.getContext();
if (!this.isEmpty()) {
var search = context.get("search");
var searchTermStr = this._getUserEnteredSearch();
this.logger.info('getModifiedContext - got search=',
searchTermStr);
if (this.baseContext)
this.logger.warn(this.moduleType, "WARNING: clobbering base
search.");
search.abandonJob();
search.setBaseSearch(searchTermStr);
context.set("search", search);
}
return context;
},
126
See Also
ensureFreshContexts()
getContext()
onContextChange()
getModulesInTree()
The getModulesInTree() method gets a list of all modules in the current
module tree.
Synopsis
results = getModulesInTree()
Return Value
Array List of modules in current module tree.
Example
var modules = this.getModulesInTree();
for (var i=0; i<modules.length; i++) {
modules[i].reset();
See Also
getAncestors()
getDescendants()
getRootAncestor()
getParam()
The getParam() method gets the value for the specified parameter key. You
can specify a fallbackValue, if the module does not have a value explicitly set for
the key. The fallbackValue supercedes the value set in the .conf file.
127
Synopsis
param = getParam( key, fallbackValue )
Parameters
key String Parameter key.
Fallback parameter value, if the key parameter is not
fallbackValue String
set.
Return Value
The key or fallbackValue value, or Null if key or fallbackValue
Undefined
are not defined.
Throws
'getParam: Splunk cannot get param; null key name
Error
passed'
Example
var entityName = this.getParam("entityName", "events");
if (entityName === "results") {
alert('This module has been configured to operate on results');
} else {
alert('This module has not been configured to operate on results');
See Also
importParams()
setParam()
snapshotParamset()
getResultParams()
The getResultParams() method gets modified/refined/extended parameters
when called by functions such as getResults().
128
Note: This method is intended to be overridden and returns an empty object by
default.
Synopsis
param = getResultParams()
Return Value
Object Results params.
Example
getResultParams: function() {
var context = this.getContext();
var params = {
output_mode: this._params['outputMode'],
fields: [],
sort_key: this.sortBy,
sort_dir: this.sortDir,
count: context.get('results.count'),
offset: context.get('results.offset')
};
if (this._params['labelField']) params['fields'].push({'label':
this._params['labelField']});
if (this._params['valueField']) params['fields'].push({'label':
this._params['valueField']});
for (var i=0, j=params['fields'].length; i<j; i++) {
params['fields'][i] = JSON.stringify(params['fields'][i]);
}
return params;
},
See Also
getResults()
haveResultsParamsChanged()
getResults()
The getResults() method gets the calling module HTML content to render
from the server.
129
Upon successfully getting the data from the module controller, this method calls
renderResults(). Two callback functions are also bound to the completion
status of the ajax operation: getResultsCompleteHandler() and
getResultsErrorHandler().
Synopsis
results = getResults()
Return Value
Undefined
Example
onJobDone: function(event) {
if (this.getInferredEntityName()=="results") {
this.getResults();
}
},
See Also
getResultURL()
renderResults()
getResultsCompleteHandler()
getResultsErrorHandler()
getResultParams()
haveResultParamsChanged()
getResultsCompleteHandler()
The getResultsCompleteHandler() callback function handles AJAX
request completion initiated by a getResults() call.
This method is not implemented, by default, and should be overridden.
Synopsis
results = getResultsCompleteHandler( xhr, textStatus )
130
Parameters
XMLHTTPResponse object passed by the AJAX
xhr Object
response.
textStatus String Text status code passed by the AJAX response.
Return Value
Undefined
Example
getResultsCompleteHandler: function(xhr) {
var length = xhr.getResponseHeader('X-Splunk-List-Length');
var context = this.getContext();
var callback = context.get("results.totalCountCallback");
if (this.totalCountCallback == null && typeof callback ==
'function') {
this.totalCountCallback = callback;
}
if (length && this.length != length && this.totalCountCallback) {
this.length = length;
this.totalCountCallback(length);
}
var t = setTimeout(this._adjustLayout, 100);
},
See Also
getResults()
getResultsErrorHandler()
getResultsErrorHandler()
The getResultsErrorHandler() callback function handles an AJAX
request returning an error.
Note: This function is implemented by default but is intended to be overridden.
Synopsis
results = getResultsErrorHandler( xhr, textStatus,
exception )
131
Parameters
XMLHTTPResponse object passed by the AJAX
xhr Object
response.
textStatus String Text status code passed by the AJAX response.
exception Exception The type of exception to throw.
Return Value
Undefined
Throws
If exception is not ' undefined', exception.
Example
getResultsErrorHandler: function(xhr, textStatus, exception) {
if (xhr.status >= 404) {
var errorMsg = _('An error was returned: "%(statusText)s".');
var errorVars = {status: xhr.status, statusText: xhr.statusText};
this.displayInlineErrorMessage(sprintf(errorMsg, errorVars));
}
},
See Also
getResults()
getResultsCompleteHandler()
getResultURL()
The getResultURL() method gets the URI query string representing the path
to the calling module controller, which contains module content to be rendered.
Note: This method is called by getResults().
Synopsis
uri = getResultURL( params )
132
Parameters
params Object result params to add to the resultURL query string.
Return Value
URI and query string representing the path to the calling module
String
controller.
Example
var resultUrl = this.getResultURL(params);
if (!resultUrl) {
this.logger.warn("getResultsURL() appears to be unimplemented or
returning null for this instance.");
this.getResultsXHRObject = $.ajax({
type: "GET",
cache: ($.browser.msie ? false : true),
url: resultUrl,
... elided ...
});
See Also
getResults()
getRootAncestor()
The getRootAncestor() method gets the root module in the module tree.
Synopsis
resp = getRootAncestor()
Return Value
Splunk.Module object representing the module at the module tree
Object
root.
133
Example
getModulesInTree: function() {
var root = this.getRootAncestor();
return [root].concat(root.getDescendants());
},
See Also
getModulesInTree()
getAncestors()
getDescendants()
haveResultParamsChanged()
The haveResultParamsChanged() helper function determines if the current
result parameters have changed.
Synopsis
changed = haveResultParamsChanged()
Return Value
Result parameters changed indication:
Boolean true = Result parameters changed.
false = Result parameters did not change.
Example
onContextChange: function($super){
if(this.haveResultParamsChanged() && (search.job.isDone()
(search.job.getEventAvailableCount() > 0))){
this._pageComplete = false;
this.getResults();
}
},
134
See Also
getResults()
getResultParams()
onContextChange()
hide()
The hide() helper function sets the calling module invisibilityMode, hidden or
not hidden.
Note: This method is called by hideDescendants() and
showDescendants() and is not intended to be overridden.
Synopsis
results = hide( invisibilityMode )
Parameters
Dictionary of URI name-value pair GET request
invisibilityMode Constant
params.
Return Value
Undefined
Example
initialize: function($super, container){
$super(container);
$("a", this.container).click(function(event) {
var popup = Splunk.util.normalizeBoolean(this._params["popup"]);
this.sendToView({}, popup);
return false;
}.bind(this));
if
(!Splunk.util.normalizeBoolean(this._params["dispatchBeforeRedirect"]))
{
$("a", this.container).hide();
}
this.show(this.HIDDEN_MODULE_KEY);
},
135
See Also
hideDescendants()
show()
showDescendants()
hideDescendants()
The hideDescendants() method hides the calling module and all
descendant modules.
Note: This module is not intended to be overridden.
Synopsis
hideDescendants( invisibilityMode )
Parameters
invisibilityMode String Invisibility mode the current module should store.
Return Value
Undefined
Example
onContextChange: function($super) {
$super();
this._selection = null;
this.hideDescendants(this.DRILLDOWN_VISIBILITY_KEY + "_" +
this.moduleId);
this.renderedCount = -1;
var context = this.getContext();
if (this.haveResultParamsChanged()) {
var search = context.get("search");
if (search.job.isDone() (search.job.getEventAvailableCount() >
0)) {
this._pageComplete = false; this.getResults();
}
}
else if (context.has("results.dataOverlayMode")){
this.onResultsRendered();
}
136
},
See Also
hide()
showDescendants()
show()
importParams()
The importParams() method imports module startup parameters passed by
the module configuration system. Usually, configuration settings are static, so
this method should not be called after view initialization.
Note: This module is not intended to be overridden.
Synopsis
importParams()
Return Value
Undefined
Example
this.importParams(); if (this._params.hasOwnProperty('foobar')) {
alert('foobar was found!')
See Also
getParam()
setParam()
snapshotParamset()
isPageLoadComplete()
The isPageLoadComplete() method gets the page loaded status.
Note: This module is not intended to be overridden.
137
Synopsis
status = isPageLoadComplete()
Return Value
Page loaded status indication:
Boolean true = Page loading is complete.
false = Page loading is not complete.
Example
applyContext: function(context) {
if (this.isPageLoadComplete()) {
var search = context.get("search");
var fieldsIntention = search.getIntentionReference("setfields");
if (fieldsIntention) {
this.selectedFields = [];
var fields = fieldsIntention["arg"];
for (var i=0; i<fields.length; i++) {
var field = fields[i];
if (field.charAt(0)!=="_") {
this.selectedFields.push(field);
}
}
this.setSelectedFieldList(this.selectedFields);
this.pushContextToChildren();
return true;
}
}
},
See Also
markPageLoadComplete()
onLoadStatusChange()
applyContext()
isReadyForContextPush()
The isReadyForContextPush() method sets up the contract for
propagating the context to child modules when pushContextToChildren()
is called, depending on whether or not page load has completed.
138
Note: This module is intended to be overridden.
Synopsis
status = isReadyForContextPush()
Return Value
[Default] Module ready for context push indication:
Boolean true = Module is ready for a context push.
false = Module is not ready for a context push.
[Override] Module ready for context push indication:
CANCEL = No selected state, stop context pushes.
Integer
CONTINUE = Job is finished, push context.
DEFER = Job is not finished, do not push context.
Example
isReadyForContextPush: function($super) { if (!$super()) return false;
if (this.hasLoaded) return Splunk.Module.CONTINUE;
else return Splunk.Module.DEFER;
},
See Also
getLoadState()
markPageLoadComplete()
onLoadStatusChange()
pushContextToChildren()
markPageLoadComplete()
The markPageLoadComplete() method sets the page load completion
status.
Synopsis
results = markPageLoadComplete( self, **args )
139
Return Value
Undefined
Example
pushContextToChildren: function(explicitContext) {
var readiness = this.isReadyForContextPush()
if (readiness == Splunk.Module.CANCEL) {
if (!this.isPageLoadComplete()) {
var propagateLoadCompleteFlag = function(module) {
module.markPageLoadComplete();
module.withEachChild(function(child) {
propagateLoadCompleteFlag(child);
});
};
propagateLoadCompleteFlag(this);
}
return;
}
},
See Also
isPageLoadComplete()
onLoadStatusChange()
mergeLoadParamsIntoContext()
The mergeLoadParamsIntoContext() method pushes non-search
parameters to child modules.
Synopsis
results = mergeLoadParamsIntoContext( namespace,
paramNames)
Parameters
namespace String Namespace the params should retain.
paramNames Array Keys passed to child modules.
140
Return Value
Undefined
Example
initialize: function($super, container){
$super(container);
this.childEnforcement = Splunk.Module.NEVER_ALLOW;
this.logger = Splunk.Logger.getLogger("events_viewer.js");
this.mergeLoadParamsIntoContext("results", ["displayRowNumbers",
"segmentation"]);
},
See Also
importParams()
snapshotParamset()
onBeforeJobDispatched()
The onBeforeJobDispatched() method provides a mechanism for
changing job settings before the job is dispatched, typically to change result
parameters. The main purpose is to set the required_field_list and
status_buckets params on the POST which dispatches the job.
Note: This method is intended to be overridden.
Synopsis
onBeforeJobDispatched( search )
Parameters
search Object Splunk.Search object to be acted upon.
Return Value
Undefined
141
Example
onBeforeJobDispatched: function(search) {
var fields = this.getNormalizedFields();
if (this.entityName!="results") {
search.setMinimumStatusBuckets(1);
if (fields.length>0) {
search.setRequiredFields(fields);
}
}
},
onContextChange()
The onContextChange() method handles the context change event. The
method is called when the underlying context instance available in
this.getContext() ha s changed.
Note:This method is intended to be overridden.
Synopsis
onContextChange()
Return Value
Undefined
Example
onContextChange: function() {
var context = this.getContext();
var search = context.get('search');
var new_search = 'index=example sourcetype=documentation';
search.setBaseSearch(new_search);
context.set('search', new_search);
},
142
See Also
getContext()
getModifiedContext()
haveResultParamsChanged()
applyContext()
onLoadStatusChange()
The onLoadStatusChange() handler is invoked when the current module
load status changes, if the notification has not been suppressed by
setLoadState().
The default implementation of this method calls validateHierarchy(), if the
module has a context. This method is intended to be overridden.
Synopsis
onLoadStatusChange( status )
Parameters
status Integer New load status.
Return Value
Undefined
Example
onLoadStatusChange: function($super, statusInt) {
$super(statusInt);
if (statusInt == Splunk.util.moduleLoadStates.LOADED) {
var context = this.getContext();
if (context === null) {
this.logger.warn('getContext could not retrieve a context');
return;
}
if (context.get("results.dataOverlayMode")) {
this.onResultsRendered();
}
}
else if (statusInt ==
Splunk.util.moduleLoadStates.WAITING_FOR_HIERARCHY) {
this.hideDescendants(this.DRILLDOWN_VISIBILITY_KEY + "_" +
143
this.moduleId);
}
},
See Also
getLoadState()
setLoadState()
validateHierarchy()
onResultsRendered()
The onResultsRendered() event handler performs any actions required
after results are rendered. This method is called by renderResults().
Note: This method is not implemented, by default, so you must provide it.
Synopsis
onResultsRendered()
Return Value
Undefined
Example
onResultsRendered: function() {
var context = this.getContext();
if (!context.has("results.dataOverlayMode")) return false;
switch(context.get("results.dataOverlayMode")) {
case "none":
this.resetHeatMap(this.container);
this.decorateBounds(this.container, false, false);
break;
case "heatmap":
this.decorateBounds(this.container, false, false);
this.decorateHeatMap(this.container);
break;
case "highlow":
this.resetHeatMap(this.container);
this.decorateBounds(this.container, true, true);
break;
default:
144
this.logger.warn("Context contains unsupported
dataOverlayMode value of", context.get("results.dataOverlayMode"));
}
},
See Also
getResults()
renderResults()
onViewDataChange()
The onViewDataChange() handler is called by the app server to generate
module HTML content in response to a GET request.
Synopsis
results = onViewDataChange( event, data)
Parameters
event Object jQuery event.
Object literal representation of all templateArgs returned
data Object
from the view.py render method.
Return Value
Undefined
Example
onViewDataChange: function(event, data){
if(data.navConfig){
try{
var menuData = this.parseNavConfig(data.navConfig);
}catch(e){
this.logger.error("Unable to parse JSON navConfig for appbar
menu", e);
return;
}
this.removeMainMenus();
this.generateMainMenus(menuData);
this.logger.info("onViewDataChange fired, successfully reloaded
145
main menu data in AppBar");
}
},
passContextToParent()
The passContextToParent() method passes the current module context to
the parent module until a parent is found that accepts the context.
Note: Be careful using this method because of the inherent complexity of
contexts passing in both directions of the hierarchy.
Synopsis
results = passContextToParent( context )
Parameters
context Object Module context to pass to parent.
Return Value
Context accepted indication:
Boolean True = An upstream parent accepted the context.
False = No upstream parent accepted the context.
Example
onTimestampSelect: function(event) {
var em = $(event.target);
var epoch = em.attr(this.TIMESTAMP_EPOCH_TIME_ATTRIBUTE_NAME);
if (epoch) {
epoch = parseInt(epoch, 10);
var context = new Splunk.Context();
var search = new Splunk.Search();
var range = new Splunk.TimeRange(epoch, epoch+1);
search.setTimeRange(range);
context.set("search", search);
this.passContextToParent(context);
} else {
this.logger.error("cannot continue.");
}
return false;
},
146
See Also
applyContext()
onContextChange()
pushContextToChildren()
pushContextToChildren()
The pushContextToChildren() method passes the current module context
to all child modules.
Note: This method is not intended to be overridden. It is recommended that you
use onContextChange() to refine the context before it is passed to children.
Synopsis
results = pushContextToChildren( explicitContext )
Parameters
Explicit context to be passed to children. If omitted,
explicitContext Object
getContext() is called to provide the context.
Return Value
Undefined
Example
_onMenuClick: function(evt) {
var t = evt.target;
if ( $(t).parent('li').hasClass('timeRangePreset') ) {
this._setSelectedRangeToPreset($(t));
this.setParam('default', this._getRawLabel($(t).text()));
if
(Splunk.util.normalizeBoolean(this.getParam('searchWhenChanged'))) {
this.pushContextToChildren();
} else {
this.setChildContextFreshness(false);
}
$('.timeRangeActivator', this.container).text($(t).text());
}
},
147
See Also
applyContext()
ensureFreshContexts()
getContext()
getModifiedContext()
onContextChange()
passContextToParent()
pushViewDataChange()
The pushViewDataChange() method broadcasts that view data has been
changed by the controller. Because every module subclassed from
Splunk.Module has a listener on the viewDataChange event, it is unlikely
that this method needs to be called.
Note: This method is not intended to be overridden.
Synopsis
pushViewDataChange()
Return Value
Undefined
Example
this.pushViewDataChange();
removeChild()
The removeChild() method removes the specified child module from the
current module hierarchy. The childModule must exist and be a child of the caller.
Note: The removed child module is orphaned.
Synopsis
removeChild( childModule )
148
Parameters
args Object Splunk.Module object of the child to be removed.
Return Value
Undefined
Example
this.withEachChild( function(child) {
this.removeChild(child);
return false;
});
renderResults()
The renderResults() method inserts content into the module results
container within the DOM. The default implementation replaces the module
resultsContainer content with the htmlFragment passed to it, usually from
the module controller.
Synopsis
results = renderResults( htmlFragment, turbo)
Parameters
Dictionary of URI name-value pair GET request
htmlFragment String
params.
HTML injection directive:
True = Use shallow clone for faster html injection.
turbo Boolean (Caution: All event listeners will be lost in clone.)
False = Do not use shallow clone for faster html
injection.
Return Value
Undefined
149
Example
renderResults: function($super, htmlFragment) {
$super(htmlFragment);
if (this.getInferredEntityName()=="events") {
this.renderedCount = $("tr", this.container).length - 1;
}
},
See Also
getResults()
onResultsRendered()
requiresAsynchronousLoading()
The requiresAsynchronousLoading() method indicates whether or not
the module hierarchy must be complete before loading the current module. If the
module can be loaded asynchronously, the module must make sure the
corresponding moduleLoadStatusChange event is fired after loading.
Subclass this module to change the behavior to depend on your specific
configuration.
Synopsis
asyncLoad = requiresAsynchronousLoading()
Return Value
Asynchronous loading required indication:
True = This module does not depend on the module hierarchy to
Boolean be complete.
False = (Default) This module depends on the module hierarchy
to be complete.; WAITING_FOR_HIERARCHY
Example
requiresAsynchronousLoading: function() {return true;},
150
See Also
requiresDispatch()
requiresDispatch()
The requiresDispatch() method indicates whether or not the module
requires a context with dispatched search to function correctly.
Subclass this module to change the behavior to depend on your specific
configuration.
Synopsis
dispatch = requiresDispatch( search )
Parameters
search Object Splunk.Search object to be dispatched.
Return Value
Module requires context with dispatched search indication:
Boolean True = Module does not require a context.
False = (Default) Module requires a context.
Example
requiresDispatch: function() {return true;},
See Also
requiresAsynchronousLoading()
someChildrenRequireDispatch()
reset()
The reset() method resets the current module context and UI. The method
calls resetContext() and resetUI(), which may be overridden.
Synopsis
reset()
151
Return Value
Undefined
Example
this.withEachChild(function(child) {
child.reset();
});
See Also
abortGetResults()
resetContext()
resetUI()
resetContext()
The resetContext() method resets the current context, setting the current
context to null and removing the job from the job manifest..
Synopsis
resetContext()
Return Value
Undefined
Example
reset: function() {
this.abortGetResults();
this.resetContext();
this.resetUI();
},
152
See Also
abortGetResults()
reset()
resetUI()
resetUI()
The resetUI() method resets the module user interface to an initial state.
Note: This module is intended to be overridden with behavior specific to the
module.
Synopsis
resetUI()
Return Value
Undefined
Example
resetUI: function(){
this.resultsContainer.html("");
},
See Also
abortGetResults()
reset()
resetContext()
resizeWidthToParent()
The resizeWidthToParent() handler resizes the current module to be the
same width as parent module.
Note: This module should not be overridden.
153
Synopsis
resizeWidthToParent()
Return Value
Example
$(window).bind('resize', this.resizeWidthToParent.bind(this));
setChildContextFreshness()
The setChildContextFreshness() method marks the freshness of the
context held by child modules, permitting the calling module to validate or
invalidate child freshness without traversing the module tree.
Note: This module should not be overridden.
Synopsis
results = setChildContextFreshness( contextStatus )
Parameters
Status to set child module contexts to:
contextStatus Boolean True = Mark context as fresh.
False = Mark context as stale.
Return Value
Undefined
Example
pushContextToChildren: function(explicitContext) {
this.withEachChild(function(child) {
child.baseContext = childContext;
child.setLoadState(Splunk.util.moduleLoadStates.HAS_CONTEXT);
child.onContextChange();
child.pushContextToChildren();
if (!child.isPageLoadComplete()) {
child.markPageLoadComplete();
}
});
154
this.setChildContextFreshness(true);
},
See Also
ensureFreshContexts()
setLoadState()
The setLoadState() method changes the current module load state and,
optionally, invokes the onLoadStatusChange() event handler.
Synopsis
setLoadState( statusInt, suppressEvent)
Parameters
Dictionary of URI name-value pair GET request
statusInt Integer
params.
Invoke event handler indication:
suppressEvent Boolean True = Invoke event handler.
False = (Default) Do not invoke event handler.
Return Value
Undefined
Example
pushContextToChildren: function(explicitContext) {
this.withEachDescendant(function(module) {
module.setLoadState(Splunk.util.moduleLoadStates.WAITING_FOR_CONTEXT);
});
this.withEachChild(function(child) {
child.baseContext = childContext;
child.setLoadState(Splunk.util.moduleLoadStates.HAS_CONTEXT);
child.onContextChange();
child.pushContextToChildren();
if (!child.isPageLoadComplete()) {
child.markPageLoadComplete();
}
});
155
this.setChildContextFreshness(true);
},
See Also
getLoadState()
onLoadStatusChange()
setParam()
The setParam() method sets the value of the specified parameter and,
optionally, specifies the key - value persistence duration.
Synopsis
setParam( key, value, isSessionOnly)
Parameters
key String Name of parameter to persist.
value String Value of key.
Instance persistence indication:
True = Parameter value only persists for current
isSessionOnly Boolean instance.
False = (Default) Parameter value persists
independent of the current instance.
Return Value
Undefined
Throws
'... - Cannot build name; null key'
Example
this.setParam('label', 'Pony Rides per Day', True);
See Also
getParam()
importParams()
156
snapshotParamset()
show()
The show() method makes the current module visible and sets the visibility
mode.
Synopsis
show( invisibilityMode )
Parameters
Invisibility mode string. If a mode is not specified,
invisibilityMode String
the mode is set to "global."
Return Value
Undefined
Example
showDescendants: function(invisibilityMode) {
if (!this.isSwitcherLeaf) {
for (var i=0; i<this._children.length;i++) {
this._children[i].show(invisibilityMode);
this._children[i].showDescendants(invisibilityMode);
}
}
},
See Also
hide()
hideDescendants()
showDescendants()
showDescendants()
The showDescendants() method sets child modules to visible.
157
Synopsis
showDescendants( invisibilityMode )
Parameters
A common invisibility mode to be passed to child
invisibilityMode String
modules.
Return Value
Undefined
Example
onRowClick: function(evt) {
this.showDescendants(this.DRILLDOWN_VISIBILITY_KEY + "_" +
this.moduleId);
},
See Also
hide()
hideDescendants()
show()
snapshotParamset
The snapshotParamset() method gets a snapshot of the current state of
persistable module parameters.
Synopsis
snapshotParamset()
Return Value
Undefined
158
Example
var tempParams = this.snapshotParamset(); if ('fookey' in tempParams) {
delete tempParams.fookey;
See Also
getParam()
importParams()
setParam()
someChildrenRequireDispatch()
The someChildrenRequireDispatch() helper method determines if any
immediate children require a dispatched search in the context pushed to them.
Synopsis
status = someChildrenRequireDispatch( search )
Parameters
search Object Splunk.Search object.
Return Value
Dispatched search required indication:
True = At least one immediate child module requires a dispatched
Boolean
search.
False = No child modules require a dispatched search.
Example
pushContextToChildren: function(explicitContext) {
if (this.someChildrenRequireDispatch(search)) {
search.abandonJob();
this.withEachDescendant(function(module) {
module.onBeforeJobDispatched(search);
});
this._fireDispatch(search);
return;
159
}
},
See Also
requiresDispatch()
validateHierarchy()
The validateHierarchy() method validates the current module hierarchy
and displays one of the following error messages, if the hierarchy is invalid:
"This view has a %s module but it is configured with no child modules to push
its changes to. This represents a configuration error."
"This view has a %s module configured to push changes to downstream
modules. This module never has any changes to push so this represents a
configuration error."
"This view has a %s module but that module has no parent modules to receive
changes from. This module will not work in this configuration so this represents
a configuration error."
"This view has a %s module but that module receives changes from other
modules upstream. Since this module will ignore all such changes, this
represents a configuration error."
This method is called by the default implementation of
onLoadStatusChange().
The module uses the childEnforcement and parentEnforcement values to
perform validation. For example, if your module requires children to function
properly, set:
this.childEnforcement = Splunk.Module.ALWAYS_REQUIRE;
to ensure that anyone consuming your module receives a hierarchy validation
error.
In addition to providing error messaging, this method sets:
this._hierarchyValidated = true;
160
Synopsis
validateHierarchy()
Return Value
Undefined
Example
onLoadStatusChange: function(statusInt) {
if (!this._hierarchyValidated &&
(statusInt >=
Splunk.util.moduleLoadStates.WAITING_FOR_CONTEXT)) {
this.validateHierarchy();
}
},
See Also
onLoadStatusChange()
withEachAncestor()
The withEachAncestor() method passes each ancestor module of the
current module to the specified callback function.
Synopsis
status = withEachAncestor( fn, reverse )
Parameters
Function that acts on ancestor module passed as an
fn Function
argument.
Direction to traverse ancestor list:
True = Traverse ancestor list in the direction of root to
reverse Boolean child.
False = (Default) Traverse ancestor list in the
direction of child to root.
161
Return Value
Status indication:
True = Ancestors successfully traversed.
Boolean
False = The callback function, fn, returned False for one of the
ancestors; operation terminated.
Example
ensureFreshContexts: function() {
if (this.getContext().get('search').isJobDispatched()) {
return;
}
var stale = null;
this.withEachAncestor(function(module) {
if (module.getContext().get('search').isJobDispatched()) {
return false;
}
if (!module._childModulesHaveFreshContexts) {
stale = module;
}
}, true);
if (stale) {
stale.withEachDescendant(function (child) {
child.baseContext = null;
});
stale.setChildContextFreshness(true);
}
},
See Also
ensureFreshContexts()
getAncestors()
withEachChild()
withEachDescendant()
withEachChild()
The withEachChild() method passes each immediate child of the current
module to the specified callback function.
Note: Only immediate child modules are operated on, not grandchildren.
162
Synopsis
status = withEachChild( fn )
Parameters
fn Function Function that acts on child module passed as an argument.
Return Value
Status indication:
True = Child modules successfully traversed.
Boolean
False = The callback function, fn, returned False for one of the
children; operation terminated.
Example
someChildrenRequireDispatch: function(search) {
var requireDispatch = false;
this.withEachChild(function(child) {
if (child.requiresDispatch(search)) {
requireDispatch = true;
return false;
}
});
return requireDispatch;
},
See Also
someChildrenRequireDispatch()
withEachAncestor()
withEachDescendant()
withEachDescendant()
The withEachDescendant() method passes each descendant module of the
current module to the specified callback function.
Synopsis
status = withEachDescendant( callback )
163
Parameters
Function that acts on descendant module passed as an
callback Function
argument.
Return Value
Status indication:
True = Descendant modules successfully traversed.
Boolean
False = The callback function returned False for one of the
descendants; operation terminated.
Example
someChildrenRequireDispatch: function(search) {
var requireDispatch = false;
this.withEachChild(function(child) {
if (child.requiresDispatch(search)) {
requireDispatch = true;
return false;
}
});
return requireDispatch;
},
See Also
someChildrenRequireDispatch()
withEachAncestor()
withEachDescendant()
Splunk.Module.DispatchingModule
onJobDone()
The onJobDone() event handler provides global notification that the current
job has completed.
This method is typically used to call getResults(), because the results entity
is not available until the job has finished.
164
Note: By default, this method is not implemented and is intended to be
overridden.
Synopsis
onJobDone( event )
Parameters
event Object A jQuery event object passed to the handler.
Return Value
Undefined
Example
onJobDone: function(event) {
if (this.getInferredEntityName()=="results") {
this.getResults();
}
},
See Also
onJobProgress()
onJobStatusChange()
onJobProgress()
The onJobProgress () event handler provides global job progress notifications.
Note: By default, this method is not implemented and is intended to be
overridden.
Synopsis
onJobProgress( event )
165
Parameters
event String A jQuery event object.
Return Value
Undefined
Example
onJobProgress: function() {
var search = this.getContext().get("search");
var count = this.getEntityCount(search);
this.setCountHeader(count, search.job.isDone());
},
See Also
onJobProgress()
onJobStatusChange()
onJobStatusChange()
The onJobStatusChange() event handler provides global notification of job
status changes.
This method is typically used to call reset(), if a job is canceled.
Synopsis
onJobStatusChange( event, status)
Parameters
event Object A jQuery event object.
Job status:
status String
(Default) "cancel" = call reset().
166
Return Value
Undefined
Example
onJobStatusChange: function(event, status) {
if (status == 'cancel') {
this.reset();
}
See Also
onJobDone()
onJobProgress()
requiresTransformedResults()
The requiresTransformedResults() method checks if the current module
requires transformed results.
Synopsis
transform = requiresTransformedResults()
Return Value
Module requires transformed results indication:
Boolean true = Module requires transformed results.
false = (Default) Module does not require transformed results.
Example
requiresTransformedResults: function() {return true},
167
Module Controller APIs
ModuleController
renderJobStatusMessage()
For the current job, the renderJobStatusMessage() method renders status
information to display in search results containers, in response to a GET request.
Override renderJobStatusMessage() to generate custom job status
messages for your module.
By default, the method returns either HTML status information, such as "No
results found" and "Waiting for data" or an error message in response to an
exception.
Synopsis
results = renderJobStatusMessage(kwargs)
Parameters
kwargs Dict [optional] Dictionary of dictionary of keywords and values.
Return Value
Success: Status message.
Error messages:
• 'resultStatusMessage empty_results No matching events
String found. More info...'
• 'resultStatusMessage empty_results No results found. More
info...'
• 'resultStatusMessage empty_results Waiting for data...'
• 'resultStatusMessage empty_results unknown search state:
...'
168
Exceptions
User-defined
renderModule()
The renderModule () method registers a modules controller and exposes the
generateResults() method. Use generateResults() to control the
content rendered by the module.
Warning: renderModule() should not be called or overridden.
Synopsis
results = renderModule(self, host_app, module, action,
**args)
Parameters
host_app String App where the module resides. Default: system
Module String Current module name.
action String Requested action. The value is always render.
args Dict TBD
Return Value
String Content returned by the module controller, or any error message.
ModuleHandler
generateResults()
The generateResults() method is called by the app server to generate
module HTML content in response to a GET request.
The base class method is not implemented. Override generateResults() to
provide module-specific content information.
169
The args parameter is a dictionary of all URI query string parameters that can be
passed from the UI. The response HTML fragment is returned with the method
call.
By default, the getResults() method retrieves data produced by
generateResults(), using the @route() decorator.
Synopsis
results = generateResults(args)
Parameters
Dictionary of URI name-value pair GET request parameters.
args Dict
Example: args['host_app'] = host_app_value
Return Value
Success: The HTML fragment to render.
Error: Error message.
String
Default error message: ' This module does not have a
registered renderer.'
Exceptions
User-defined, as needed.
Example
Overridden
def generateResults(self, host_app=None, client_app=None,
savedSearchName=None):
if savedSearchName:
jsonSearch = None
owner = 'nobody'
try:
savedSearchObject =
splunk.search.getSavedSearch(label =
savedSearchName,
namespace = client_app,
owner = owner)
jsonSearch =
splunk.appserver.mrsparkle.util.resurrectFromSavedSearch(
savedSearchObject = savedSearchObject,
170
hostPath = splunk.mergeHostPath(),
namespace = client_app,
owner = owner)
job = splunk.search.getJobForSavedSearch(
savedSearchName,
namespace=client_app,
owner=owner,
search='name=scheduler*')
if (job):
jsonSearch["job"] =
job.toJsonable(timeFormat='unix')
return json.dumps(jsonSearch)
except Exception, e:
logger.exception(e)
return ""
else:
logger.warn('savedSearchName was not passed from the
caller')
return ""
171
Controller API
BaseController
conf()
Note: Beginning with Splunk version 4.2, use the Model API (class
SplunkAppObjModel), instead, to work with Splunk configuration objects.
Get a configuration key from the Splunk configuration.
Synopsis
value = conf( key, name, stanza, cast, default )
Parameters
key Configuration entity key value.
name String Default: web
stanza String Default: settings
cast Default: None
default Default: None
Return Value
Integer Configuration key.
Raises
Specified key does Your configuration may be corrupt or may
KeyError
not exist. require a restart.
make_route()
The make_route() method is a wrapper, returning a URL path for a given
route. The method returns a URL path for the specified, base_path, route.
Synopsis
route = make_route( base_path, **kwargs)
172
Parameters
base_path String Route
kwargs Object Name-value pair, list of tuples, or dictionary query string.
Return Value
String Relative URL for the specified base_path .
Examples
Example 1
make_route('/search/jobs', job_id=1234, action=delete)
Example 2
make_route('/search/jobs', job_id=1234, action=delete, _qs=[('q', 'search val to
quote')])
Example 3
make_route('/search/jobs', job_id=1234, action=delete, _qs=dict(q='search val to
quote'))
See Also
make_url()
make_url()
The make_url() method extends the specified path relative to the current app
server location, specifying a full path or a series of arguments representing path
segments.
Synopsis
results = Splunk.util.make_url(path)
path String Relative path to extend, or path segment arguments.
173
Return Value
String Qualified relative path.
Example
Full path argument
var path1 = Splunk.util.make_url('/static/foo.js'); alert(path1);
Path segment arguments
var path2 = Splunk.util.make_url('app', 'search', 'flashtimeline') alert(path2);
Common application
Load the myContent.html file located in the /appserver/static
directory of the current app.
<div id="sampleContent"></div>
<script>
var url = Splunk.util.make_url('/static/app/' +
Splunk.util.getCurrentApp() + '/myContent.html');
$("#sampleContent").load(url);
</script>
The example loads the content of myContent.html into the
sampleContent DIV. We recommend using the getCurrentApp() utility for
portability.
See Also
make_full_url()
push_version()
The push_version() method is a wrapper, forcing a version increment on
application server static assets and browsers to update cached static content.
The returned version is a local-to-installed-instance version number used in
combination with the build number to specify a revision of static resources in
174
$SPLUNK_HOME/etc/apps/<app>/appserver/static . This number
should be incremented by a POST to /_bump whenever a static resource has
been changed to force the client to fetch the new resource regardless of the
Expires headers that were sent with it.
Synopsis
version = push_version()
Return Value
Integer Incremented version number.
Example
return "Version bumped to %i" % self.push_version()
redirect_to_route()
The redirect_to_route() method is a convenience method,
wrapping a call to cherrypy.HTTPRedirect() with the URI provided
by make_route().
Synopsis
redirect_to_route( *target, **kwargs )
Parameters
target String Redirection target.
[OPTIONAL] keyword-value pair dictionary representing the
kwargs Object
query string to include with redirection.
Return Value
Undefined
Raises
cherrypy.HTTPRedirect(self.make_route( *target, **kwargs))
175
Example
self.redirect_to_route('/accounts',
username='someUser',
action='delete',
_qs=[ ('return_to', '/') ])
See Also
make_route()
redirect_to_url()
render_template()
cherrypy.HTTPRedirect()
redirect_to_url()
The redirect_to_url() method is a convenience method, wrapping a call
to cherrypy.HTTPRedirect() with the redirect URI.
Synopsis
redirect_to_url( *target, **kwargs)
Parameters
target String Redirection target.
[OPTIONAL] keyword-value pair dictionary representing the
kwargs Object
query string to include with redirection.
Return Value
Undefined
Raises
cherrypy.HTTPRedirect(self.make_url( *target, **kwargs))
Example
self.redirect_to_url('/api/search/jobs', job_id=1234)
176
See Also
render_template()
redirect_to_route()
cherrypy.HTTPRedirect()
render_json()
The render_json() method returns JSON-formatted response data.
Synopsis
response = render_json( response_data, set_mime)
Parameters
Data to return. If not JSON data, the data are
response_data String
parsed into JSON format.
[OPTIONAL] Mime type specified in the response.
set_mime String
Default: 'text/json'
Return Value
String JSON-formatted response_data with 256 bytes whitespace padding.
Exceptions
TBD
Examples
Example 1
output = {'foo': 'bar', 'fiz' : {'foobar': 1, 'fizbaz': 2 } }
self.render_json(output)
Example 2
self.render_json({'status': 'FIELD_ERRORS', 'fields': { key: 'Password error' },},
set_mime='text/html')
177
See Also
render_template()
render_template()
The render_template() method renders the specified Mako template. First,
the method creates a global instantiation of TemplateLookup named
mako_lookup() by calling setup_mako(). The specified template,
template_name, must exist within the lookup instance to be rendered. Template
arguments, template_args, are passed to the template to be rendered.
Synopsis
response = render_template( template_name, template_args)
Parameters
template_name String Mako template to be rendered.
[OPTIONAL] Dictionary of arguments passed to
template_args Objects
template_name.
Return Value
String Rendered template.
Raises
Exception 'unable to obtain template=%s' % template_name
See Also
render_json()
TemplateLookup
setup_mako()
setup_mako()
Initializes an instance of TemplateLookup. In general, this method is called by
render_template() and does not need to be called, explicitly. However,
setup_mako() can be overridden to provide additional lookup paths, imports, or
other options, which can be retrieved by calling mako_lookup().
178
Synopsis
setup_mako()
Parameters
None
Return Value
Undefined
See Also
render_template()
TemplateLookup
strip_url()
The strip_url() method returns a specified URL without the root endpoint or
i18n prefixes. Use this method to format a URL path fragment to pass to methods
such as make_url(), which can safely handle the root endpoint and i18n
prefixes on a per user basis.
The path parameter is a URL, and the method returns a URL with the root
endpoint and i18n prefixes stripped.
Synopsis
url = strip_url( path )
Parameters
path String URL to be stripped.
Return Value
String The path URL with the root endpoint and i18n prefixes stripped.
See Also
make_url()
179
Model APIs
SplunkRESTModel
all()
The all() method retrieves the entire set of model objects for all the models in
scope. This convenience method is a wrapper for SplunkQuerySet.all().
Use this method in combination with SplunkQuerySet.filter(),
SplunkQuerySet.filter_by_app(),
SplunkQuerySet.filter_by_user(), and SplunkQuerySet.search()
to populate lists or locate specific entities from the pool of models in scope.
Synopsis
qsObj = all()
Return Value
Object A SplunkQuerySet object containing a list of all models in scope.
Example
Example 1
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
def index(self):
apps = self.all()
class MyAppModel(SplunkRESTModel):
def index(self):
apps = self.all().filter(is_disabled=False)
Example 2
from splunk.models.base import SplunkRESTModel
180
class MyAppModel(SplunkRESTModel):
def index(self):
apps = self.all().filter(is_disabled=False)
build_id()
The build_id() method generates an ID string from the specified object
name and the resource URI path defined in the model.
Synopsis
resId = build_id( name, namespace, owner )
Parameters
name String Entity name.
namespace String Entity namespace, or application name.
owner String Entity owner.
Return Value
String Hierarchical URI path to the requested entity in the REST API.
Examples
Example 1
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
try:
id = MyAppModel.build_id(name='newsearch', namespace='search',
owner='admin')
except:
raise
Example 2
Without build_id() :
form_content[key] =
EventType.get('/servicesNS/%s/%s/saved/eventtypes/%s' %\
181
(user, 'webintelligence', key))
Alternative using build_id() :
et = Eventtype.build_id(key, 'webintelligence', user) form_content[key] =
EventType.get(et)
See Also
get()
create()
The create() method creates a new version of the current object from the
settings stored when the object was instantiated.
Synopsis
status = create()
Return Value
Object create status:
True = Object successfully created.
Boolean
False = Current object already has an ID, or unable to create a new
entity. Object not created.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel): if MyAppModel.create():
... elided ...
else:
... elided ...
See Also
delete()
182
delete()
The delete() method deletes the current entity.
Synopsis
status = delete()
Return Value
Entity delete request status:
True = Entity successfully deleted.
Boolean
False = Entity not deleted. Current object has invalid ID or non-200
HTTP error code returned.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel): if MyAppModel.delete():
... elided ...
else:
... elided ...
See Also
create()
from_entity()
The from_entity() method populates the current model with the specified
entity.
Synopsis
status = from_entity( entity )
183
Parameters
entity Object Entity from which to populate the current model.
Return Value
Populate model request status:
Boolean True = Model successfully populated.
False = Invalid entity ; module not populated.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel): def populateModel (entity):
try:
my_entity = Eventtype.all().filter(name='failed-logins')
except Exception, ex:
raise
my_instance = Eventtype('search', 'admin', 'failed-logins',
entity=my_entity)
if not my_instance.from_entity(my_instance.entity):
... elided ...
else:
... elided ...
See Also
get()
save()
get()
The get() method is a generic getter that gets the value associated with the
named key, provided the key is defined for the context. A context is a
user-defined dictionary of name-value pairs.
Synopsis
value = get( name )
Parameters
name String Context dictionary key.
184
Return Value
Value corresponding to the name key. If name does not
exist, the method returns null.
Object
Note that this method returns a value and not a reference.
Example
getSearch: function() {
var context = this.getContext()
return context.get('search');
See Also
enforceByValue()
getAll()
set()
get_mutable_fields()
The get_mutable_fields() method gets a list of field names that can be
modified using update().
Synopsis
results = get_mutable_fields( args, arg2)
Return Value
List List of keys of mutable fields for the current entity.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel): def getFieldsToChange ():
event_type = self.get(self.build_id('myeventtype', 'search',
'admin'))
return m_fields = self.get_mutable_fields()
185
See Also
update()
is_mutable()
The is_mutable() method tests for mutability of the attrname field.
Synopsis
status = is_mutable( attrname )
Parameters
attrname String Field name.
Return Value
Field mutability status:
String True = The attrname field is mutable.
False = The attrname field is not mutable.
Example
from splunk.models.base import SplunkRESTModel import cherrypy
class MyAppModel(SplunkRESTModel):
def generateResults(self, host_app=None, client_app=None,
savedSearchName=None):
from splunk.models.saved_search import SavedSearch
saved_search = SavedSearch(, cherrypy.session['user']['name'],
'newsearch')
return saved_search.is_mutable('alert.severity')
See Also
get_mutable_fields()
manager()
The manager() method instantiates a new SplunkRESTManager instance
based on the current SplunkRESTModel instance, which usually represents a
unique entity.
186
Synopsis
results = manager()
Return Value
Object A new SplunkRESTManager instance.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
def newInstance(owner, namespace):
entity = self.manager()._get_new_entity(namespace, owner)
return entity
See Also
SplunkRESTManager
order_by()
The order_by() method gets a clone of the current result set, ordered by the
specified model field and sorting order.
Synopsis
clone = order_by( key, direction)
Parameters
key String Key to sort on.
Sort dirrection:
direction String asc = Ascending order.
desc = Descending order.
Return Value
A clone of the current SplunkRESTModel object sorted by key and
Object
direction.
187
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
See Also
all()
search()
order_by()
parse_except_messages()
The parse_except_messages() method parses errors raised by
SplunkRESTModel operations into a flat list.
Note: In general, this method does not need to be called explicitly. It is used by
passive_save() to handle error messaging, usually to pass the error
messages to a template.
Synopsis
messages = parse_except_messages( e )
Parameters
e Object Exception message to parse.
Return Value
List List of error message strings.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
def errorMsgs(self):
self.errors = []
try:
... elided ...
except Exception, e:
self.errors =
188
[x.replace("In handler 'savedsearch':", ).lstrip() for x
in self.parse_except_messages(e)]
return False
else:
return True
See Also
passive_save()
passive_save()
The passive_save () method attempts to save the model without raising an
exception. The return value indicates if an exception occurred, and exception
messages are added to the instance member.
The method flushes errors instance member before adding messages to avoid
duplicate or stale entries.
Synopsis
eStatus = passive_save()
Return Value
Exception status:
Boolean True = An exception did not occur.
False = An exception occurred.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
@expose_page(must_login=True, trim_spaces=True, methods=['POST'])
def save(self, **params):
... elided ...
for key in form_content.keys():
if not form_content[key].passive_save():
return self.render_template(
'/myapp/templates/setup.html',
dict(name=key, form_content=form_content))
189
See Also
parse_except_messages()
save()
save()
The save() method saves the current job, which permits the job to persist,
indefinitely. Calling this method has no effect if the job has already completed,
although the save operation will be considered successful. A saved job cannot be
auto-canceled by the UI or by calling setAsAutoCancellable().
Synopsis
save( onSuccess, onFailure)
Parameters
(Optional) Function to execute upon successful
onSuccess Function
operation.
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.save(
function() { console.log('Current job successfully saved!'); },
function() { console.log('Failed to save the current job!'); } );
See Also
canBeAutoCancelled()
isSaved()
setAsAutoCancellable()
unsave()
search()
The search () method gets a clone of the current query set constrained by the
specified search_string. This method is used to perform free text search against
190
a SplunkQuerySet to limit the results returned.
Synopsis
clone = search( search_string )
Parameters
search_string String Search string by which to constrain the results.
Return Value
Clone of the current SplunkQuerySet with only members that
Object
match the specified search_string.
Example
from splunk.models.base import SplunkRESTModelfrom
splunk.models.fired_alert import FiredAlert, FiredAlertSummary
class MyAppModel(SplunkRESTModel):
def index(self, app, **params):
... elided ...
if not 'alerts_id' in params:
fired_alerts = FiredAlert.all()
else:
fired_alerts = FiredAlert.get_alerts(
urllib.unquote_plus(params.get('alerts_id')))
# augment query with search
if len(search_string) > 0:
fired_alerts = fired_alerts.search('
'.join(search_string))
... elided ...
See Also
all()
order_by()
set_entity_fields()
The set_entity_fields() method sets the current object entity fields to the
specified model fields.
Note: Generally, calling create() is preferred over calling this method.
191
Synopsis
status = set_entity_fields( entity )
Parameters
entity Object Entity from which to copy metadata fields.
Return Value
Set request status. This method always returns True, indicating
Boolean
the fields were successfully set.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
def from_entity(self, entity):
self._parse_id(entity)
self._parse_links(entity)
if not self.id:
return False
self.name = entity.name
if 'eai:acl' in entity:
self.owner = entity['eai:acl']['owner']
self.namespace = entity['eai:acl']['app' ]
return self.set_entity_fields(entity)
See Also
create()
update()
The update () method updates the current model fields with the specified
fields.
Synopsis
update( fields )
192
Parameters
fields List Collection of Field objects to set in the current model.
Return Value
Undefined
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
def step1_update(self, app, step, action, **params):
saved_search = SavedSearch.get(params.get('id'))
saved_search.update(params)
See Also
get_mutable_fields()
passive_save()
save()
SplunkAppObjModel
create()
The create() method creates a new version of the current object from the
settings stored when the object was instantiated. This method wraps
SplunkRESTModel.create(), and ensures that new instances of class
SplunkAppObjModel have an owner of nobody and default to fail-safe
metadata while retaining all other settings of the previous class
SplunkAppObjModel instance.
Synopsis
status = create()
193
Return Value
Object create status:
True = Object successfully created.
Boolean
False = Current object already has an ID, or unable to create a new
entity. Object not created.
Example
from splunk.models.base import SplunkAppObjModel
class MyAppModel(SplunkAppObjModel): if MyAppModel.create():
... elided ...
else:
... elided ...
from_entity()
The from_entity() method populates the current model with the specified
entity.
Synopsis
status = from_entity( entity )
Parameters
entity Object Entity from which to populate the current model.
Return Value
Populate model request status:
Boolean True = Model successfully populated.
False = Invalid entity ; module not populated.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel): def populateModel (entity):
194
try:
my_entity = Eventtype.all().filter(name='failed-logins')
except Exception, ex:
raise
my_instance = Eventtype('search', 'admin', 'failed-logins',
entity=my_entity)
if not my_instance.from_entity(my_instance.entity):
... elided ...
else:
... elided ...
See Also
get()
share_app()
The share_app() method sets the sharing level to app, making the
application visible to users who have permissions only within the current app
context.
Synopsis
status = share_app()
Return Value
Share request status:
String True = Successful share request.
False = Share request failed due to invalid ID, entity or metadata.
Example
from splunk.models.saved_search import SavedSearch
class AlertsWizardController(BaseController):
... elided ...
def step1_update(self, app, step, action, **params):
saved_search = SavedSearch.get(params.get('id'))
saved_search.update(params)
if params.get('sharing')=='app':
try:
saved_search.share_app()
except Exception:
saved_search.errors = [_('Search %s cannot be
shared.') \
195
% saved_search.name ]
See Also
share_global()
unshare()
share_global()
The share_global() method sets the sharing level to global, making the
application visible to users who have permissions across all apps.
Synopsis
status = share_global()
Return Value
Share request status:
String True = Successful share request.
False = Share request failed due to invalid ID, entity or metadata.
Example
from splunk.models.saved_search import SavedSearch
class AlertsWizardController(BaseController):
... elided ...
def step1_update(self, **params):
saved_search = SavedSearch.get(params.get('id'))
saved_search.update(params)
if params.get('sharing')=='global':
try:
saved_search.share_global()
except Exception:
saved_search.errors = [_('Search %s cannot be
shared.') \
% saved_search.name ]
See Also
share_app()
unshare()
196
unshare()
The unshare() method sets the sharing level to user, making the
application visible to only the current user.
Synopsis
status = unshare()
Return Value
Share request status:
String True = Successful share request.
False = Share request failed due to invalid ID, entity or metadata.
Example
from splunk.models.saved_search import SavedSearch
class AlertsWizardController(BaseController):
def step1_update(self, **params):
saved_search = SavedSearch.get(params.get('id'))
saved_search.update(params)
if params.get('sharing')=='app':
... eliced ...
else:
try:
saved_search.unshare()
except Exception:
saved_search.errors = [_('Search %s cannot be
shared.') \
% saved_search.name ]
See Also
share_app()
share_global()
ObjectMetadataModel
197
create()
The create() method creates a new version of the current object from the
settings stored when the object was instantiated.
Synopsis
status = create()
Return Value
Object create status:
True = Object successfully created.
Boolean
False = Current object already has an ID, or unable to create a new
entity. Object not created.
Example
from splunk.models.base import ObjectMetadataModel
class MyAppModel(ObjectMetadataModel): if MyAppModel.create():
... elided ...
else:
... elided ...
save()
The save() method saves the current job, which permits the job to persist,
indefinitely. Calling this method has no effect if the job has already completed,
although the save operation will be considered successful. A saved job cannot be
auto-canceled by the UI or by calling setAsAutoCancellable().
Synopsis
save( onSuccess, onFailure)
Parameters
(Optional) Function to execute upon successful
onSuccess Function
operation.
198
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
var context = this.getContext(); var search = context.get('search');
search.job.save(
function() { console.log('Current job successfully saved!'); },
function() { console.log('Failed to save the current job!'); } );
set_entity_fields()
The set_entity_fields() method sets the current object entity fields to the
specified model fields.
Note: Generally, calling SplunkRESTModel.create() is preferred over calling
this method.
Synopsis
status = set_entity_fields( entity )
Parameters
entity Object Entity from which to copy metadata fields.
Return Value
Set request status. This method always returns True, indicating
Boolean
the fields were successfully set.
Example
from splunk.models.base import SplunkRESTModel
class MyAppModel(SplunkRESTModel):
def from_entity(self, entity):
self._parse_id(entity)
self._parse_links(entity)
if not self.id:
return False
self.name = entity.name
if 'eai:acl' in entity:
199
self.owner = entity['eai:acl']['owner']
self.namespace = entity['eai:acl']['app' ]
return self.set_entity_fields(entity)
SplunkRESTManager
all()
The all() method gets the entire set of model objects for all models in scope.
Use this method in combination with SplunkQuerySet.filter(),
SplunkQuerySet.filter_by_app(),
SplunkQuerySet.filter_by_user(), and SplunkQuerySet.search()
to populate lists or locate specific entities from the pool of models in scope.
Synopsis
querySet = all()
Return Value
Object A SplunkQuerySet object containing a list of all models in scope.
get()
The get() method loads the model object for the specified REST entity. The
REST entity is specified using the entity URI. If id is not provided, the default
model resource is used. If there is no default resource or the entity cannot be
loaded, the method returns None.
This method is the most convenient and preferred way to load a single entity into
a model.
Synopsis
results = get( id )
Parameters
id String REST API entity path.
200
Return Value
Object
Model object for entity id, or None if the entity cannot be loaded.
None
Example
from splunk.models.base import SplunkRESTModel
required_keys = ['web-traffic', 'clientip-internal', 'internal-domain'] class
MyAppModel(SplunkRESTModel):
def show(self, **kwargs):
form_content = {}
for key in required_keys:
try:
form_content[key] = self.get(
'/servicesNS/%s/%s/saved/eventtypes/%s' \
% (user, 'myapp', key))
except:
form_content[key] = {'search': }
return form_content)
order_by()
The order_by() method gets a clone of the current result set, ordered by the
specified model field and sorting order.
Synopsis
clone = order_by( key, direction)
Parameters
key String Key to sort on.
Sort dirrection:
direction String asc = Ascending order.
desc = Descending order.
Return Value
A clone of the current SplunkRESTManager object sorted by key
Object
and direction.
201
Example
from splunk.models.base import SplunkRESTManager
class MyAppModel(SplunkRESTManager):
See Also
all()
search()
search()
The search() method gets a clone of the current query set constrained by the
specified search_string. This method is used to perform free text search against
a SplunkQuerySet to limit the results returned.
Synopsis
clone = search( search_string )
Parameters
search_string String Search string by which to constrain the results.
Return Value
Clone of the current SplunkQuerySet with only members that
Object
match the specified search_string.
Example
from splunk.models.base import SplunkRESTManager from
splunk.models.fired_alert import FiredAlert, FiredAlertSummary
class MyAppModel(SplunkRESTManager):
def index(self, app, **params):
... elided ...
if not 'alerts_id' in params:
fired_alerts = FiredAlert.all()
else:
fired_alerts = FiredAlert.get_alerts(
urllib.unquote_plus(params.get('alerts_id')))
# augment query with search
202
if len(search_string) > 0:
fired_alerts = fired_alerts.search('
'.join(search_string))
... elided ...
See Also
all()
order_by()
SplunkQuerySet
all()
The all() method gets the entire set of model objects for all models in scope.
Use this method in combination with filter(), filter_by_app(),
filter_by_user(), and search() to populate lists or locate specific entities
from the pool of models in scope.
Synopsis
querySet = all()
Return Value
Object A SplunkQuerySet object containing a list of all models in scope.
See Also
filter()
filter_by_app()
filter_by_user()
order_by()
search()
filter()
The filter() method gets a clone of the current query set, which is filtered by
the kwargs model field names.
203
Synopsis
clone = filter( **kwargs )
Parameters
Dictionary corresponding to model fields and values by
**kwargs Dict
which to filter the current result set.
Return Value
SplunkQuerySet object representing a filtered clone of the current
Object
result set.
Raises
Exception 'cannot filter on unknown field: %s' % arg
Example
from splunk.models.app import App
class AlertsController(BaseController):
def index(self, app, **params):
apps = App.all().filter(is_disabled=False)
See Also
all()
filter_by_app()
filter_by_user()
order_by()
search()
filter_by_app()
The filter_by_app() method provides app-based filtering by getting a clone
of the current query set.
Synopsis
clone = filter_by_app( app )
204
Parameters
app String App name to use for filtering.
Return Value
SplunkQuerySet object representing a filtered clone of the current
Object
result set.
Example
from splunk.models.fired_alert import FiredAlert, FiredAlertSummary
class AlertsController(BaseController):
... elided ...
def index(self, app, **params):
fired_alert_summary =
FiredAlertSummary.all().filter_by_app(alerts_app).
filter_by_user(alerts_user)
See Also
all()
filter()
filter_by_user()
order_by()
search()
filter_by_user()
The filter_by_user() method provides user-based filtering by getting a
clone of the current query set.
Synopsis
clone = filter_by_user( user )
Parameters
user String Object owner name used for filtering.
205
Return Value
SplunkQuerySet object representing a filtered clone of the current
Object
result set.
Example
from splunk.models.fired_alert import FiredAlert, FiredAlertSummaryclass
AlertsController(BaseController):
def index(self, app, **params):
fired_alert_summary =
FiredAlertSummary.all().filter_by_app(alerts_app).
filter_by_user(alerts_user)
See Also
all()
filter()
filter_by_app()
search()
get_entities()
The get_entities() wrapper creates Splunk Entity object sets of stored
Splunk configuration objects.
Note: This method is called by the iterator() during SplunkQuerySet
instantiation and, generally, does not need to be called directly.
Synopsis
entities = get_entities( **kwargs )
Parameters
**kwargs Dict De-serialized key-value pairs.
Return Value
Entity An Entities object containing zero or more entities.
206
See Also
iterator()
iterator()
The iterator() method iteratively gets resource entities, using an internal
count-per-request that is set when SplunkQuerySet is instantiated.
Note: This method does not need to be called directly, because it is used with the
built-in __iter__() method and accessed implicitly by calling
SplunkQuerySet.next(). Overriding this method is not recommended unless
the model has properties that require a special iterator.
Synopsis
model = iterator()
Yields
Generator function representing an iteration of
Function
SplunkQuerySet.
Raises
splunk.AuthenticationFailed
See Also
get_entities()
order_by()
The order_by() method gets a clone of the current result set, ordered by the
specified model field and sorting order.
Synopsis
clone = order_by( key, direction)
Parameters
key String Key to sort on.
207
Sort dirrection:
direction String asc = Ascending order.
desc = Descending order.
Return Value
A clone of the current SplunkQuerySet object sorted by key and
Object
direction.
Example
from splunk.models.base import SplunkQuerySet
class MyAppModel(SplunkRESTModel):
See Also
all()
filter()
filter_by_app()
filter_by_user()
search()
search()
The search() method gets a clone of the current query set constrained by the
specified search_string. This method is used to perform free text search against
a SplunkQuerySet to limit the results returned.
Synopsis
clone = search( search_string )
Parameters
search_string String Search string by which to constrain the results.
Return Value
Clone of the current SplunkQuerySet with only members that
Object
match the specified search_string.
208
Example
from splunk.models.base import SplunkQuerySet from splunk.models.fired_alert
import FiredAlert, FiredAlertSummary
class MyAppModel(SplunkQuerySet):
def index(self, app, **params):
... elided ...
if not 'alerts_id' in params:
fired_alerts = FiredAlert.all()
else:
fired_alerts = FiredAlert.get_alerts(
urllib.unquote_plus(params.get('alerts_id')))
# augment query with search
if len(search_string) > 0:
fired_alerts = fired_alerts.search('
'.join(search_string))
... elided ...
See Also
all()
filter()
filter_by_app()
filter_by_user()
order_by()
209
Decorators API
Decorators
@expose_page()
The @expose_page() decorator exposes the decorated method, providing
authentication, SSO verification, and CSRF protection. The @expose_page()
decorator is often used with the @route() decorator.
Note: Any controller method exposed to the user should use the
@expose_page() decorator. Very few methods should ever be exposed without
authentication.
Synopsis
@expose_page( must_login, handle_api, methods,
verify_session, verify_sso, trim_spaces )
Parameters
Login requirement control:
True = (Default) Must be logged in to
must_login Boolean
expose page.
False = Login not required.
API handler control:
True = Requests beginning with /api are
sent to the handler.
Boolean, False = (Default) All requests are sent to
handle_api
Constant the handler.
ONLY_API = Only requests
beginning with /api are sent to the
handler.
Comma-separated list of method names s to
methods String
apply the decorator to. Default = None.
POST verification control:
True = (Default) POSTs are verified to
verify_session Boolean
prevent CSRF.
False = POSTs are not verified.
210
SSO IP address verification control:
True = (Default) In SSO mode, verify the
verify_sso Boolean SSO IP address.
False = Not in SSO mode, do not verify
the SSO IP address.
Keyword and value trim spaces control:
True = Trim spaces from keywords and
trim_spaces Boolean values.
False = (Default) Do not trim spaces from
keywords and values.
Example
@route('/:namespace/:action=fields') @expose_page(must_login=True,
handle_api=True, methods=['GET', 'POST'])
def fields(self, namespace, action, operation=None, **kwargs):
return self.render_admin_template('admin/fields.html', {
'namespace' : namespace,
'breadcrumbs' : self.generateBreadcrumbs(namespace,
'fields'),
})
See Also
@route()
@lock_session()
Use the @lock_session() decorator to acquire an exclusive lock on a
CherryPy session for the duration of the current request. (See: CherryPy v3.2.0
documentation, Reference Manual.) This protects against deadlocks and race
conditions between methods concurrently making changes to session data.
Splunk implements custom session lock behaviour by default, where CherryPy
acquires a shared lock instead of an exclusive lock. A local shared lock protects
against race conditions between threads and a file level lock protects against
races between processes.
Synopsis
@lock_session
211
Example
@expose_page(must_login=False, methods=['GET','POST'],
verify_session=False)@lock_session @set_cache_level('never')
def login(self, username=None, password=None, return_to=None, cval=None,
**kwargs):
... elided ...
@route()
The @route() decorator permits URI targets to be routed to specific controller
methods. The @route() decorator is often used with the @expose_page()
decorator.
Note: Every controller method which needs to be exposed by the Splunk Web
hierarchy at a target, other than the method name itself, should be preceded by
an @route() decorator.
A route is specified using the following syntax:
<controller_name>/
The implied base path.
e.g. my_controller/
@route('/:var')
Any value for <controller_name> within 1 path segment
e.g. my_controller/setup
my_controller/foobar
my_controller/*
@route('/:action=setup', methods='GET')
Only requests that begin with /setup - the action kwarg will always be
'setup'
e.g. my_controller/setup?action=foobar
unittest.assertEqual(action, 'setup')
@route('/:var/*category/:action', methods='POST')
Adds a keyword argument called category that greedily matches path
segments, but only for the POST verb
212
e.g my_controller/setup/step1/confirm/areusure/doublecheck
unittest.assertEqual(var, 'setup')
unittest.assertEqual(category, '/step1/confirm/areusure')
unittest.assertEqual(action, 'doublecheck')
Synopsis
@route( route, methods, leave_exposed )
Parameters
route String Route to expose for this method. Default = None.
Comma-separated string of HTTP methods/verbs
methods String
to route for. Default = None.
Method exposure control:
True = Leave method exposed at method name.
leave_exposed Boolean
False = Do not leave method exposed at
method name.
Example
The controller config.py has several methods, but only two are accessible
using SplunkWeb:
• http://<splunk-server>:<splunk-port>/config
• http://<splunk-server>:<splunk-port>/config/<VAR>
where VAR is a valid key exposed by the config endpoint.
This is because of the use of the @route() decorator in the controller:
... elided ...
@route('/') @expose_page(must_login=False, methods='GET') def index(self,
autoload=False, namespace=None, asDict=False):
... elided ...
@route('/:var') @expose_page(methods='GET') def getvar(self, var, **kw):
... elided ...
The @route() decoration that precedes index() routes the root endpoint of
213
the controller to index(), while the @route() decorator that precedes
getvar() routes any target below the root endpoint to the getvar(). Note
that the var variable in the later decorator is passed to getvar() as a
keyword argument.
Thus, navigating to /en-US/config/VERSION_LABEL results in the getvar()
method being called with the parameter var='VERSION_LABEL' passed to it.
See Also
@expose_page()
@set_cache_level()
The @set_cache_level() decorator permits consumers to set specific cache
headers within responses. This decorator is typically used to either set cache
level to never, to defeat caching for certain controllers, or to etag to take
advantage of HTTP Response Code 304.
This decorator wraps the appserver/lib/util.set_cache_level() utility.
Synopsis
@set_cache_level( cache_level )
Parameters
Cache level literal:
never = Explicitly defeat client-side caching.
cache_level String
etag = Apply an ETag header by MD5 hashing the
body.
always = Set max caching.
Example
@route('/:namespace/*endpoint_path/',
methods=['GET'])@expose_page(must_login=True) @set_cache_level('never')
def listEntities(self, namespace, endpoint_path, **kwargs):
... elided ...
214
Template API
Templates
add_script_block()
The add_script_block() method is a convenience expression that wraps
the script_tags() template utility, which includes the contents of the caller
body within a script block. This method is used by consumers to include
template-specific JavaScript on template render.
Warning: Never inject user input into a call to add_script_block().
Synopsis
add_script_block()
Example
%page args="h"/><%namespace name="lib" file="//lib.html" import="*"/> <%call
expr="lib.add_script_block()">
alert('This alert will be included within a script block in this
template');
</%call>
See Also
script_tags()
csrf_hidden_input()
The csrf_hidden_input() method is called within any HTML form that
requires POST. This allows forms to comply with Splunk Web's CSRF protection
scheme.
Note: Forms that POST but do not use this method are rejected.
215
Synopsis
csrf_hidden_input()
Example
<%page args="h"/><%namespace name="lib" file="//lib.html" import="*"/> <form
action="${ make_url(someURI) }" method="post">
${csrf_hidden_input()}
... elided ...
css()
The css() method provides a convenience wrapper to the
stylesheet_tags() template utility, permitting stylesheets to be included by
the calling template. This method is used to include custom stylesheets to be
included in a view.
Note: Use parent.css() to preserve parent stylesheets.
Synopsis
css()
Example
<%page args="h"/><%inherit file="//layout/view.html"/> <%namespace
name="lib" file="//lib.html" import="*"/> <%def name="css()">
<% parent.css() %>
<%lib:stylesheet_tags files="${['/static/css/my_cool_styles1.css']}"
/>
</%def>
get_script_blocks()
The get_script_blocks() method renders any 'script_block' values within
the attributes passed to the template as an argument.
Warning: Never inject user input into script blocks.
216
Synopsis
get_script_blocks()
Example
<%page args="h"/><%inherit file="//layout/view.html"/> <%namespace
name="lib" file="//lib.html" import="*"/> <%lib:get_script_blocks /> <%doc>
if the template was passed attributes['script_blocks'] with a
list value, each value will be injected into a script block.
</%doc>
script_tags()
The script_tags() method includes each of the specified files passed as a
parameter. This method is most useful if your view requires custom or third-party
JavaScript.
Warning: Never inject user input into script_tag() calls.
Synopsis
script_tags( files, compile)
Parameters
files Array List of files to be included in script source tags.
compile Boolean Deprecated
Example
<%page args="h"/><%inherit file="//layout/view.html"/> <%namespace
name="lib" file="//lib.html" import="*"/>
<%lib:script_tags files="${['/static/js/foo.js', '/static/js/bar.js']}" />
See Also
add_script_block()
217
stylesheet_tags()
The stylesheet_tags() method includes each of the specified files in link
tags. This method is most useful if your view requires custom or third-party CSS.
Warning: Never inject user input into stylesheet_tags() calls.
Synopsis
stylesheet_tags( files, compile, media)
Parameters
files Array List of files to be included in link tags.
compile Boolean Deprectated
(Optional) Media type:
all
media String
screen
print
Example
<%page args="h"/><%inherit file="//layout/view.html"/> <%namespace
name="lib" file="//lib.html" import="*"/>
<%lib:stylesheet_tags files="${['/static/css/foo.css', '/static/css/bar.css']}" />
218
App Server Util API
App Server Utilities
check_restart_required()
The check_restart_required() function indicates if splunkd raised the
restart flag as a result of configuration changes. Use this function to detect if
changes made by a controller require a splunkd restart to be enabled.
Synopsis
restartF = check_restart_required()
Return Value
Restart flag status:
String True = Restart required flag is set.
False = Restart required flag is reset.
Example
from splunk.appserver.mrsparkle.lib import util
template_args = {
... elided ...
'requires_restart': util.check_restart_required()
return self.render_template('/licensing/self.html', template_args)
convert_to_bytes()
The convert_to_bytes() function converts byte string value notation,
containing a size specification, to an integer or float value, using base-2
computation.
219
Synopsis
numericValue = convert_to_bytes(byteValue)
Parameters
Byte string value with one of the following unit
specifications:
YB
ZB
EB
PB
TB
GB
MB
KB
YiB
ZiB
EiB
PiB
byteValue String
TiB
GiB
MiB
KiB
B Format specification examples: 10MB
1.4 GB
1000 YiB
1000YB Note that the value may not contain a
thousands separator comma, and uses a period (.) to
denote decimal. Examples:
convert_to_bytes('10MB') returns 102400000
convert_to_bytes('40 GB') returns
42949672960 convert_to_bytes('300') returns
300
Return Value
Integer/Float Integer or float representation of byteValue.
220
Exceptions
ValueError 'unrecognized units: %s' % units
ValueError 'cannot convert to bytes: %s' % byteValue
Example
from splunk.appserver.mrsparkle.lib import util
byteVal = '10000PB' try:
bytes = util.convert_to_bytes(byteVal)
except:
pass
current_url_path()
The current_url_path() convenience function returns the current URL
path. Optionally, the query string can be included, specifying include_qs, and is
encoded so it can be used safely in an HTML page.
Typical usage includes a controller using the current path in a redirection or
similar operation.
Synopsis
urlPath = current_url_path( include_qs )
Parameters
Include query string flag:
include_qs String True = Include query string. (Default)
False = Do not include query string.
Return Value
String Current URL path, including query string as specified by include_qs.
221
Example
import cherrypyfrom splunk.appserver.mrsparkle.lib import util
path = util.current_url_path(include_qs=False) raise
cherrypy.HTTPRedirect(path, '303')
deep_update_dict()
The deep_update_dict() function recursively updates a dictionary with
another dictionary. Dictionary key values in the original dictionary are recursively
merged with an overlay dictionary, if it exists.
Note: The original dictionary is modified by this function.
Synopsis
newDict = deep_update_dict( original, overlay )
Parameters
original Object Original dictionary.
overlay Object Dictionary to overlay on the original dictionary.
Return Value
Object The original dictionary overlayed with the overlay dictionary.
Example
from splunk.appserver.mrsparkle.lib import util
... elided ...
@route('/:namespace/*endpoint_base/:element=_element/:element_name',
methods=['POST','GET']) @expose_page(must_login=True) def
fetch_element(self, namespace, endpoint_base, element, element_name,
form_defaults=None, element_overlay=None,
entity_name=None, eai_attributes=None):
... elided ...
element = copy.deepcopy(uiHelper_flatten[element_name])
util.deep_update_dict(element, element_overlay)
... elided ...
222
get_active_controller()
The get_active_controller() convenience function returns the controller
class of the current request handler. This wraps a CherryPy request handler
object and can be used to identify the active controller, for logging or debugging.
Synopsis
name = get_active_controller()
Return Value
String Current request handler controller class name.
Example
from splunk.appserver.mrsparkle.lib import util
logger = logging.getLogger('splunk.appserver.mrsparkle.controller_test')
controller = util.get_active_controller()
logger.debug('controller=%s' % controller)
get_apps_dir()
The get_apps_dir() function gets the current root applications directory path
name.
Synopsis
path = get_apps_dir()
Return Value
String Current root applications directory path name.
Example
import osfrom splunk.appserver.mrsparkle.lib import util
apps_list = os.listdir(util.get_apps_dir())
223
get_time()
The get_time() function returns a time structure. Given specified time units
and values for hours, minutes, seconds, and microseconds,
Note: This function permits you to provide a number beyond the bounds of a
typical Python Time object and returns values that can then be used to
instantiate a Python Time object.
Synopsis
results = get_time( hours, minutes, seconds, microseconds)
Parameters
hours Float Number of hours (default = 0 ).
minutes Float Number of minutes (default = 0 ).
seconds Float Number of seconds (default = 0 ).
microseconds Float Number of microseconds (default = 0 ).
Return Value
Formatted time in the form {year, days, hours, minutes,
seconds}.
Struct{Float}
Example: Calling get_time(seconds=600) returns {
0.0, 0.0, 0.0, 10.0, 0.0 }.
Example
from splunk.appserver.mrsparkle.lib import util
my_time = util.get_time(seconds=86400)
in_sso_mode()
The in_sso_mode() function indicates if Splunk is operating in trusted
authority, Single Sign-on (SSO), mode.
224
Synopsis
ssoMode = in_sso_mode()
Return Value
Indicates if Splunk is operating in trusted authority mode:
Boolean True = In trusted authority mode.
False = Not in trusted authority mode.
Example
from splunk.appserver.mrsparkle.lib import util
... elided ...
def validate_ip(fn, self, *a, **kw):
if util.in_sso_mode():
... elided ...
is_api()
The is_api() function indicates if the current request was made to the /api
endpoint.
Synopsis
results = is_api()
Return Value
Current request made to /api endpoint flag:
Boolean True = Current request was made to the /api endpoint.
False = Current request was not made to the /api endpoint.
Example
from splunk.appserver.mrsparkle.lib import util
... elided ...
def check(fn, self, *a, **kw):
225
is_api = util.is_api()
if (is_api):
... elided ...
else
... elided ...
is_ie()
The is_ie() function indicates whether or not the Internet Explorer browser
was detected in the requesting user agent.
Synopsis
results = is_ie()
Return Value
Internet Explorer browser detected indication:
Boolean True = Browser is Internet Explorer.
False = Browser is not Internet Explorer.
Example
from splunk.appserver.mrsparkle.lib import util
if util.is_ie():
... elided ...
else
... elided ...
is_valid_cherrypy_session_id()
The is_valid_cherrypy_session_id() function indicates whether or not
the specified token is equivalent to the Splunk session token stored in the
CherryPy session.
The @expose_page decorator, uses this function as part of CSRF protection
on POST requests.
226
Synopsis
tokenIdF = is_valid_cherrypy_session_id( token )
Parameters
token String Token to compare to the Splunk session token.
Return Value
Token matches Splunk session token indication:
Boolean True = The token is equivalent to the Splunk session token.
False = The token is not equivalent to the Splunk session token.
Example
def expose_page(must_login=True, handle_api=False, methods=None,
verify_session=True, verify_sso=True, trim_spaces=False):
@decorator
def check(fn, self, *a, **kw):
is_api = util.is_api()
request = cherrypy.request
... elided ...
if verify_session and request.method == 'POST' and not
cherrypy.config.get('environment') == 'test_suite':
is_xhr = util.is_xhr()
session_id = request.headers.get('X-Splunk-Session') if is_xhr
else request.params.get('splunk_session_id')
if not util.is_valid_cherrypy_session_id(session_id):
if is_xhr:
logger.warn('CSRF: validation failed because client XHR
did not include proper header')
else:
logger.warn('CSRF: validation failed because HTTP POST
did not include expected parameter')
... elided ...
is_xhr()
The is_xhr() function indicates if the current request is an
XMLHttpRequest request. A request is an XMLHttpRequest request if the
X-Requested-With request Header is set to XMLHttpRequest. The
@expose_page decorator, uses this function for CSRF protection on
XMLHttpRequest POST requests.
227
Synopsis
results = is_xhr()
Return Value
Current request is XMLHttpRequest indication:
Boolean True = Current request is an XMLHttpRequest request.
False = Current request is not an XMLHttpRequest request.
Example
def expose_page(must_login=True, handle_api=False, methods=None,
verify_session=True, verify_sso=True, trim_spaces=False):
@decorator
def check(fn, self, *a, **kw):
is_api = util.is_api()
request = cherrypy.request
... elided ...
if verify_session and request.method == 'POST' and not
cherrypy.config.get('environment') == 'test_suite':
is_xhr = util.is_xhr()
session_id = request.headers.get('X-Splunk-Session') if
is_xhr else request.params.get('splunk_session_id')
if not util.is_valid_cherrypy_session_id(session_id):
if is_xhr:
logger.warn('CSRF: validation failed because client XHR did
not include proper header')
else:
logger.warn('CSRF: validation failed because HTTP POST did
not include expected parameter')
... elided ...
isEpochTimeArg()
The isEpochTimeArg() function indicates if the specified time can be
converted to a float datatype.
Synopsis
results = isEpochTimeArg( time )
228
Parameters
time String Time value.
Return Value
Indication if time can be converted to a float datatype:
Boolean True = time can be converted to float.
False = time cannot be converted to float.
Raises
ValueError,TypeError Value cannot be converted to float datatype.
Example
from splunk.appserver.mrsparkle.lib import util
... elided ...
def setTime(earliest, latest):
if (earliest) :
if (isEpochTimeArg(earliest)):
... elided ...
else
... elided ...
layPiping()
The layPiping() convenience function returns the specified search string,
beginning with a pipe ( ) symbol if it does not already begin with the term
search.
Synopsis
searchString = layPiping( q )
Parameters
q String Qualified search string to be piped.
229
Return Value
String Search string, q , piped as required.
Example
from splunk.appserver.mrsparkle.lib import util
q = 'search index=_internal
r = util.layPiping(q)
make_absolute()
The make_absolute() function converts the specified partial or relative path
to an absolute path within the Splunk path hierarchy.
Synopsis
fullpath = make_absolute(fn, postfix, basedir)
Parameters
fn String Partial or relative path to be converted.
[Optional] String to be inserted between the path route and
postfix String
fn.
[Optional] Base directory to use instead of SPLUNK_HOME
basedir String
(Default = SPLUNK_HOME ).
Return Value
String The specified fn path expressed as an absolute path.
Exceptions
TBD
Example
import osfrom splunk.appserver.mrsparkle.lib import util
SPLUNK_HOME = os.environ['SPLUNK_HOME'] path = '/etc/apps/search'
fullpath = util.make_absolute(path)
230
make_url
The make_url() function returns a URL for the specified path.
The method builds a URL from a relative or absolute URL with optional query
string. A relative URL is returned, if relative is set to True, otherwise, an absolute
URL is returned. The string /splunk or the configuration root_path is prefixed
to the URL unless translate is set to False.
Static paths are constructed with an embedded cache defeater segment :
/static/@<build_number>[.<push_number>]/
This results in static paths like the following example:
/static/@12345/js/foo/static/@12345.1/js/foo
Static assets for apps have an additional cache defeater number correlating to
the application build number as defined in the app.conf file:
/static/@12345.1:2/app/unix/static/foo.png
The URL handler in root.py strips out any requests having this schema.
Synopsis
targURL = make_url(target, _qs=None, translate=True,
relative=False, __app_cache={})
Parameters
target String
Query string as a list of tuples or a dictionary. Example:
_qs Object _qs=[('q', 'search val to quote')] (Default =
None )
Prefix the application server root path flag:
translate Boolean True = Prefix root path (Default).
False = Do not prefix root path.
Relative returned path indication:
relative Boolean True = Returned targetURL is relative.
False = Returned targetURL is absolute (Default)
231
Return Value
String The specified target as a full URL.
Raises
InvalidURLException "Illegal characters in URL"
'Illegal escape from parent directory
ValueError
"%s": %s' %(basepath, fullpath)
Example
from splunk.appserver.mrsparkle.lib import util
targetURL = '/en-US/api/search/jobs?job=1234&action=delete' example1URL =
util.make_url('/api/search/jobs', job=1234, action=delete) example2URL =
util.make_url('/api/search/jobs, _qs=dict(job=1234,action=delete))
See Also
strip_url()
url_has_valid_charset()
normalize_value()
The normalize_value () function converts a string to either an integer or
boolean value. If value cannot be cast to an integer the function tries to convert
the string to boolean.
Synopsis
normValue = normalize_value( value )
Parameters
value String Value to be converted to integer or boolean.
Return Value
Integer or Boolean Converted value.
232
Raises
The specified value could not be converted to an integer or
ValueError
boolean value.
Example
from splunk.appserver.mrsparkle.lib import util
intVal = util.normalize_value('42') boolVal = util.normalize_value('false')
push_version()
The push_version() method gets the current application push_version
value.
The push_version variable is a local-to-installed-instance version number,
which is combined with the build number to revise static resources in
%SPLUNK_HOME/etc/apps/<appName>/appserver/static. This number
is incremented by a POST to /_bump, forcing the client to fetch the new version
of any modified resource, regardless of the Expires headers that were sent with
it.
Synopsis
push_version = push_version()
Return Value
String Current push_version value.
Example
from splunk.appserver.mrsparkle.lib import util
def incr_push_version(self):
new_version = cherrypy.config['_push_version'] = util.push_version()
+ 1
f = open(util.make_absolute('var/run/splunk/push-version.txt'), 'w')
f.write(str(new_version))
f.close()
return new_version
233
restart_splunk()
The restart_splunk() function restarts the Splunk splunkd and splunkweb
processes.
Synopsis
results = restart_splunk()
Return Value
Undefined
Raises
SplunkRestartException Error encountered restarting Splunk.
Example
from splunk.appserver.mrsparkle.lib import util
util.restart_splunk()
set_cache_level()
The set_cache_level() function sets the HTTP caching headers to a preset
configuration.
Synopsis
results = set_cache_level( cache_level, response)
Parameters
Cache level literal:
never = Explicitly defeat client-side caching.
cache_level String
etag = Apply an ETag header by MD5 hashing the
body.
always = Set max caching.
234
response String Deprecated
Return Value
Undefined
Raises
ValueError 'Unrecognized cache level: %s' % cache_level
Example
from splunk.appserver.mrsparkle.lib import util
def renderExample():
try:
pageContent = '<p>Sample Content</p>'
except Exception, e:
pageContent = '<p class="moduleException"></p>'
if cherrypy.response.headers.get('Cache-Control') == None:
return util.set_cache_level('etag', pageContent)
return pageContent
strip_url()
The strip_url() function returns a URL, stripping the path root endpoint and
i18n prefixes. Call this function when intending to pass a pathname fragment to
methods, such as make_url(), that can safely handle the root endpoint and
i18n prefixes.
Synopsis
stripPath = strip_url( path )
Parameters
path String Pathname to be stripped.
Return Value
String Pathname with the root endpoint and i18n prefixes stripped.
235
Example
from splunk.appserver.mrsparkle.lib import util
util.strip_url('/en-US/app/search/foo')
util.strip_url('http://localhost:8000/en-GB/app/launcher/home')
See Also
make_url()
url_has_valid_charset()
url_has_valid_charset()
The url_has_valid_charset() function validates the URL character set
against RFC 3986.
Synopsis
results = url_has_valid_charset(url)
Parameters
url String URL to be validated.
Return Value
Valid URL indication:
Boolean True = The url is valid.
False = The url is invalid.
Example
from splunk.appserver.mrsparkle.lib import util
if (util.url_has_valid_charset('http://localhost:8000/en-US/account/login'))
... valid URL ...
else
... invalid URL ...
236
See Also
make_url()
strip_url()
237