Splunk-6 0 3-ModuleRef
Splunk-6 0 3-ModuleRef
3
Module System Reference
Generated: 4/22/2014 9:40 am
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
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
i
Extension dictionary
Extension dictionary
controllers.BaseController
Parent: object
Mechanism: Subclass using the web.conf bootstrap name to hook into the
framework
SplunkAppObjModel
Parent: SplunkRESTModel
lib.html
Usage: Import; way to include Import custom/3rd party JavaScript and CSS
1
Splunk.Module
Parent: object
applyContext()
getModifiedContext()
getResultParams()
getResultsCompleteHandler()
getResultsErrorHandler()
initialize()
isReadyForContextPush()
onBeforeJobDispatched()
onContextChange()
onLoadStatusChange()
onResultsRendered()
onViewDataChange()
renderResults()
requiresAsynchonousLoading()
requiresDispatch()
resetUI()
Splunk.Module.DispatchingModule
Parent: Splunk.Module
2
requiresTransformedResults()
module.ModuleHandler
Parent: object
generateResults()
application.js
3
Splunk APIs
Splunk.Context
clone()
Synopsis
contextCopy = someContext.clone()
Return Value
dupCurrentContext: function() {
var context = this.getContext()
return = context.clone();
enforceByValue()
Note: This method usually does not need to be called because the getter and
setter methods already enforce return by-value.
Synopsis
Parameters
4
Return Value
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
Parameters
getSearch: function() {
See Also
enforceByValue()
getAll()
set()
5
getAll()
The getAll() method is a generic getter that gets all values at or below the
name namespace.
Synopsis
Parameters
name String key name for which the corresponding values are returned.
Return Value
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
Parameters
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
Parameters
7
Example
setBaseSearch: function(baseSearch) {
See Also
enforceByValue()
get()
getAll()
Splunk.Job
areResultsTransformed()
Synopsis
results = areResultsTransformed()
Return Value
if (search.job.areResultsTransformed()) {
8
entityName = 'results';
} else {
entityName = 'events';
console.log(entityName);
See Also
getStatusBuckets()
canBeAutoCancelled()
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
if (search.job.canBeAutoCancelled()) {
} 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.
Synopsis
Parameters
Error: "Cannot call the job endpoint if we dont have an sid yet"
Example
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.
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
Parameters
11
Throws
Error: "Cannot call the job endpoint if we dont have an sid yet"
Example
if (search.job.finalize(function() {
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
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:
Note: For searches distributed over multiple search heads, this is the latest
cursor time of all searches.
Synopsis
time = getCursorTime()
Return Value
if (cursorTime == false)
else
See Also
getDoneProgress()
13
getDoneProgress()
Synopsis
progress = getDoneProgress()
Return Value
See Also
isDone()
getCursorTime()
getEventAvailableCount()
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
See Also
getEventCount()
getResultCount()
getScanCount()
getEventCount()
The getEventCount() method gets the number of events advertised for the
current job.
Synopsis
count = getEventCount()
Return Value
15
See Also
getEventAvailableCount()
getResultCount()
getScanCount()
getEventFieldCount()
Synopsis
results = getEventFieldCount()
Return Value
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
16
Example
See Also
getSearch()
getEventSorting()
The getEventSorting() method gets the event sorting order for the current
job.
Synopsis
sort = getEventSorting()
Return Value
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
See Also
getEventAvailableCount()
getEventCount()
getScanCount()
getScanCount()
Synopsis
count = getScanCount()
Return Value
See Also
getEventAvailableCount()
getEventCount()
getResultCount()
18
getSearch()
Synopsis
search = getSearch()
Return Value
See Also
getSearchId()
getSID()
getSearchId()
The getSearchId() getter method gets the current job search identifier.
Synopsis
searchID = getSearchId()
Return Value
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
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
See Also
areResultsTransformed()
getTimeRange()
Synopsis
timeRange = getTimeRange()
Return Value
getTimeSinceLastProgress()
21
Synopsis
time = getTimeSinceLastProgress()
Return Value
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
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
if (search.job.isDone()) {
} else {
23
See Also
getDoneProgress()
isCanceled()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
isSaved()
isEventStreaming()
Synopsis
status = isEventStreaming()
Return Value
if (search.job.isEventStreaming()) {
} else {
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
if (search.job.isFinalized()) {
} else {
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
if (search.job.isPaused()) {
} else {
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPreviewable()
isRealTimeSearch()
26
isRunning()
isSaved()
pause()
unpause()
isPreviewable()
Synopsis
results = isPreviewable()
Return Value
if (search.job.isPreviewable()) {
} else {
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPaused()
isRealTimeSearch()
isRunning()
isSaved()
setPreviewable()
27
isRealTimeSearch()
See Search and report in real time for a discusion of real-time searches.
Synopsis
results = isRealTimeSearch()
Return Value
if (search.job.isRealTimeSearch()) {
} else {
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
if (search.job.isRunning()) {
} else {
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
if (search.job.isSaved()) {
} else {
See Also
isCanceled()
isDone()
isEventStreaming()
isFinalized()
isPaused()
isPreviewable()
isRealTimeSearch()
isRunning()
save()
unsave()
makeWorldReadable()
30
Synopsis
Parameters
search.job.makeWorldReadable(
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
Parameters
onSuccess Function
31
(Optional) Function to execute upon successful
operation.
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
if (!search.job.isDone()) {
search.job.pause(
function() { console.log('Current job successfully paused!'); },
function() { console.log('Failed to pause current job!'); } );
} else {
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
Parameters
32
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
search.job.save(
See Also
canBeAutoCancelled()
isSaved()
setAsAutoCancellable()
unsave()
setAsAutoCancellable()
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
33
Example
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
search.job.setLastProgressTime();
See Also
getTimeSinceLastProgress()
setPreviewable()
Synopsis
setPreviewable( mode )
34
Parameters
Preview mode:
mode Boolean true = Job results can be previewed.
false = Job results cannot be previewed.
Example
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
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
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
Parameters
36
Example
search.job.setTTL(
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
Parameters
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
Parameters
Undefined
Example
search.job.undoWorldReadable(
);
See Also
makeWorldReadable()
unpause()
Synopsis
Parameters
38
(Optional) Function to call on unsuccessful
operation.
Example
See Also
isPaused()
pause()
unsave()
The unsave() method sets the current job status to not saved, permitting the
job to be canceled.
Synopsis
Parameters
search.job.unsave(
39
See Also
isSaved()
save()
Splunk.Search
abandonJob()
Synopsis
abandonJob()
Return Value
Undefined
Example
See Also
dispatchJob()
isJobDispatched()
absorbIntentions()
40
Synopsis
Parameters
Undefined
Throws
Example
this.absorbIntentions();
See Also
addIntention()
clearIntentions()
dispatchJob()
getIntentionReference()
hasIntentions()
popIntention()
sendToView()
setIntentions()
addIntention()
Synopsis
addIntention( intentionDict )
41
Parameters
Undefined
Throws
Example
if (legacyTarget) {
See Also
absorbIntentions()
clearIntentions()
getIntentionReference()
hasIntentions()
popIntention()
42
setIntentions()
clearIntentions()
Synopsis
clearIntentions()
Return Value
Undefined
Example
See Also
absorbIntentions()
addIntention()
getIntentionReference()
hasIntentions()
popIntention()
setIntentions()
clearTimeRange()
43
Synopsis
this = clearTimeRange()
Return Value
return context;
See Also
getTimeRange()
setTimeRange()
Splunk.TimeRange
clone()
Synopsis
search = clone()
Return Value
dispatchJob()
44
dispatched.
Synopsis
Parameters
search.dispatchJob(this._fireDispatchSuccessHandler.bind(this),
this._fireDispatchFailHandler.bind(this),
this.getGroupName());
See Also
abandonJob()
absorbIntentions()
isJobDispatched()
Splunk.Module.pushContextToChildren()
equalToSearch()
• Search string
45
• Job ID
• Dispatch state
• Intentions
• Time range
• Remote servers list
• Event count
• Post process
Synopsis
Parameters
if (search.equalToSearch(this._previousSearch)) {
} else {
getBaseSearch()
The getBaseSearch() method gets the base search of the current context
search object.
46
Synopsis
baseSearch = getBaseSearch()
Return Value
See Also
setBaseSearch()
toString()
getDistributedServerList()
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
if ('https://amrit.splunk.com:8089' in serverList) {
47
}
See Also
setDistributedServerList()
getEventAvailableCount()
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
See Also
getEventCount()
getResultCount()
getScanCount()
getEventCount()
The getEventCount() method gets the number of events advertised for the
current job.
48
current job.
Synopsis
count = getEventCount()
Return Value
See Also
getEventAvailableCount()
getResultCount()
getScanCount()
getIntentionReference()
Synopsis
Parameters
49
Return Value
if (fieldsIntention) {
alert('setfields exists');
} else {
See Also
absorbIntentions()
addIntention()
clearIntentions()
hasIntentions()
popIntention()
setIntentions()
getMaxCount()
Synopsis
maxCount = getMaxCount()
50
Return Value
See Also
getMaxEvents()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getMaxEvents()
Synopsis
maxEvents = getMaxEvents()
Return Value
51
Example
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
} else {
52
}
See Also
getMaxCount()
getMaxEvents()
getMinimumStatusBuckets()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getMinimumStatusBuckets()
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.
Synopsis
minBuckets = getMinimumStatusBuckets()
Return Value
53
} else {
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
setMaxCount()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
getPostProcess()
Synopsis
postProcessVal = getPostProcess()
Return Value
if (postProcess) {
} else {
54
}
See Also
getBaseSearch()
setBaseSearch()
setPostProcess()
getRequiredFieldList()
Synopsis
fieldList = getRequiredFieldList()
Return Value
if (rfl) {
$.each(rfl, function(i, v) {
alert('requireField = ' + escape(v));
});
} else {
See Also
setRequiredFields()
55
getSavedSearchName()
Synopsis
searchName = getSavedSearchName()
Return Value
if (savedSearch) {
} else {
See Also
setSavedSearchName()
getTimeRange()
Synopsis
timeRange = getTimeRange()
56
Return Value
See Also
getTimeRange()
Splunk.TimeRange
getUrl()
The getUrl() method gets the URI to access resources for the current search
job.
Synopsis
Parameters
57
getViewStateId()
Synopsis
viewStateID = getViewStateId()
Parameters
Return Value
See Also
setViewStateId()
hasIntentions()
Synopsis
results = hasIntentions()
Return Value
58
Example
if (search.hasIntentions()) {
search.absorbIntentions();
See Also
absorbIntentions()
addIntention()
clearIntentions()
dispatchJob()
getIntentionReference()
popIntention()
setIntentions()
isJobDispatched()
Synopsis
status = isJobDispatched()
Return Value
if !(search.isJobDispatched()) {
59
} else {
See Also
abandonJob()
dispatchJob()
popIntention()
Synopsis
Parameters
if (search.getIntentionReference('setfields')) {
search.popIntention('setfields');
60
See Also
absorbIntentions()
addIntention()
clearIntentions()
getIntentionReference()
hasIntentions()
setIntentions()
resurrect()
Synopsis
Parameters
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
61
Parameters
Boolean Success
Example
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
Undefined
Example
See Also
getBaseSearch()
isJobDispatched()
setDistributedServerList()
Synopsis
Parameters
63
Return Value
Undefined
Example
See Also
getDistributedServerList()
setIntentions()
The setIntentions() method replaces the current search intentions with the
specified intentions.
Synopsis
Parameters
Undefined
Example
setNewIntentions: function(intentionsList) {
search.setIntentions(intentionsList);
context.set('search', search);
},
64
See Also
absorbIntentions()
addIntention()
clearIntentions()
getIntentionReference()
hasIntentions()
popIntention()
setMaxCount()
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
Undefined
Example
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
65
getMinimumStatusBuckets()
setMaxEvents()
setMaxTime()
setMinimumStatusBuckets()
setMaxEvents()
Synopsis
setMaxEvents( maxEvents )
Parameters
Undefined
Example
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
setMaxTime()
setMinimumStatusBuckets()
66
setMaxTime()
Synopsis
setMaxTime( maxTime )
Parameters
Undefined
Example
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
setMaxCount()
setMaxEvents()
setMinimumStatusBuckets()
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
Undefined
Example
bucketFunction: function(statusBuckets) {
context.set('search', search);
return context;
},
See Also
getMaxCount()
getMaxEvents()
getMaxTime()
getMinimumStatusBuckets()
setMaxCount()
68
setMaxEvents()
setMaxTime()
setPostProcess()
Synopsis
setPostProcess( search )
Parameters
Undefined
Example
if (postProcess) {
} else {
search.setPostProcess('stats count');
See Also
getBaseSearch()
69
setRequiredFields()
Synopsis
setRequiredFields( requiredFieldList )
Parameters
Undefined
Example
See Also
getRequiredFieldList()
setSavedSearchName()
Intentions are not compatible with search objects that reference a saved search.
Synopsis
setSavedSearchName( name )
70
Parameters
Undefined
Example
See Also
getSavedSearchName()
setSelectedEventAvailableCount()
Synopsis
setSelectedEventAvailableCount( count )
Parameters
Undefined
Example
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()
Synopsis
setSelectedEventCount( count )
Parameters
Undefined
Example
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
Parameters
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
Undefined
Example
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
See Also
getBaseSearch()
74
Splunk.TimeRange
clone()
Synopsis
range = clone()
Return Value
containsRange()
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
Parameters
75
object.
False = Specified timeRange is not included in the current time
range.
Example
if (range.containsRange(new_range)) {
See Also
containsTime()
equalToRange()
isAbsolute()
isRealTime()
isRelative()
containsTime()
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
76
Parameters
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
Parameters
77
Return Value
if (range.equalToRange(new_range)) {
See Also
containsRange()
containsTime()
isAbsolute()
isRealTime()
isRelative()
formatRelativeRange()
Synopsis
formattedRange = formatRelativeRange()
Return Value
78
Throws
Example
alert(range.formatRelativeRange());
See Also
isRelative()
getAbsoluteEarliestTime()
Synopsis
time = getAbsoluteEarliestTime()
Return Value
alert(range.getAbsoluteEarliestTime().toString());
79
See Also
getAbsoluteLatestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeEarliestTime()
getRelativeLatestTime()
getAbsoluteLatestTime()
Synopsis
time = getAbsoluteLatestTime()
Return Value
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
if (timeRange.getDuration() == -1) {
this._activator.text(timeRange.toConciseString());
} else {
this._activator.text(this.CUSTOM_TIME_LABEL);
See Also
isAbsolute()
isRealTime()
isRelative()
getEarliestTimeTerms()
Synopsis
time = getEarliestTimeTerms()
81
Return Value
},
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
},
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getEarliestTimeTerms()
getRelativeEarliestTime()
getRelativeLatestTime()
getRelativeEarliestTime()
83
Note: This method is intended to be private.
Synopsis
time = getRelativeEarliestTime()
Return Value
if (range.isRelative()) {
alert(range.getRelativeEarliestTime().toString());
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeLatestTime()
getRelativeLatestTime()
Synopsis
time = getRelativeLatestTime()
84
Return Value
if (range.isRelative()) {
alert(range.getRelativeEarliestTime().toString());
See Also
getAbsoluteEarliestTime()
getAbsoluteLatestTime()
getEarliestTimeTerms()
getLatestTimeTerms()
getRelativeEarliestTime()
getTimeFormat()
Synopsis
formattedTime = getTimeFormat()
Return Value
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
updateTimeHeader: function(range) {
},
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
updateTimeHeader: function(range) {
},
See Also
containsRange()
containsTime()
equalToRange()
isAbsolute()
87
isRealTime()
isRelative()
isRealTime()
Synopsis
realTime = isRealTime()
Return Value
},
See Also
containsRange()
containsTime()
equalToRange()
getDuration()
isAbsolute()
88
isAllTime()
isRelative()
isRelative()
Synopsis
relative = isRelative()
Return Value
if (range.isRelative()) {
alert(range.getRelativeLatestTime().toString());
See Also
containsRange()
containsTime()
equalToRange()
formatRelativeRange()
getDuration()
isAbsolute()
isAllTime()
isRealTime()
isSubRangeOfJob()
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) {
},
See Also
setAsSubRangeOfJob()
setAsSubRangeOfJob()
90
Synopsis
setAsSubRangeOfJob( isSubrange )
Parameters
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");
},
See Also
isSubRangeOfJob()
toConciseString()
91
Synopsis
timeRange = toConciseString()
Return Value
Boolean Success
Example
},
See Also
toString()
toString()
Synopsis
timeRange = toString()
Return Value
92
Example
alert(range.toString());
See Also
toConciseString()
Splunk.util
addLeadingSearchCommand()
Synopsis
Parameters
93
Example
getUserEnteredSearch: function() {
},
See Also
stripLeadingSearchCommand()
discoverReplacementTokens()
Synopsis
Parameters
if (USE_AUTOMATIC_STRING_REPLACEMENT) {
94
}
See Also
replaceTokens()
escapeBackslash()
Synopsis
Parameters
See Also
escapeHtml()
escapeHtml()
95
Synopsis
Parameters
alert(input);
See Also
escapeBackslash()
fieldListToString()
Synopsis
Parameters
alert(fieldString);
96
See Also
stringToFieldList()
getCommaFormattedNumber()
Synopsis
Parameters
getComputedStyleHelper()
Synopsis
Parameters
97
Return Value
getConfigValue()
Synopsis
Parameters
Example
var f = Splunk.util.getConfigValue("SEARCH_RESULTS_TIME_==
getCurrentDisplayView()==
98
Synopsis
name = Splunk.util.getCurrentDisplayView()
Return Value
<code>
See Also
getCurrentApp()
getCurrentView()
getCurrentViewConfig()
FORMAT"); var f =
Splunk.util.getConfigValue("DEFAULT_SPACECAKE_VENDOR", "Barneys");
</code>
getCumlativeOffsetLeft()
Synopsis
Parameters
99
Example
Splunk.util.getCumlativeOffsetTop(this.container[0]);
See Also
getCumlativeOffsetTop()
getPageYOffset()
getCumlativeOffsetTop()
Synopsis
Parameters
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
document.location = Splunk.util.make_url('app',
Splunk.util.getCurrentApp());
See Also
getCurrentDiplayView()
getCurrentView()
getCurrentViewConfig()
make_url()
getCurrentDisplayView()
Synopsis
name = Splunk.util.getCurrentDisplayView()
Return Value
101
Example
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
See Also
getCurrentApp()
getCurrentDisplayView()
getCurrentViewConfig()
getCurrentViewConfig()
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
See Also
getCurrentApp()
getCurrentDisplayView()
getCurrentView()
getEpochTimeFromISO()
Synopsis
Parameters
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
Parameters
alert(myHEX);
See Also
normalizeColor()
getPageYOffset()
Synopsis
offset = Splunk.util.getPageYOffset()
104
Return Value
Splunk.util.getCumlativeOffsetTop(this.container[0]);
See Also
getCumlativeOffsetLeft()
getCumlativeOffsetTop()
getParameter()
Synopsis
Parameters
See Also
getPath()
105
getPath()
The getPath() method gets the current location path without the localization
segment.
Synopsis
results = Splunk.util.getPath()
Return Value
See Also
getParameter()
make_url()
queryStringToProp()
getServerTimezoneOffset()
Synopsis
offset = Splunk.util.getServerTimezoneOffset()
Return Value
See Also
getTimezoneOffsetDelta()
106
getTimezoneOffsetDelta()
Synopsis
offset = Splunk.util.getTimezoneOffsetDelta(
serverOffsetThen, date )
Parameters
var earliestDelta = \
Splunk.util.getTimezoneOffsetDelta(this.serverOffsetAtEarliest,
earliest);
var latestDelta = \
Splunk.util.getTimezoneOffsetDelta(this.serverOffsetAtLatest, latest);
See Also
getServerTimezoneOffset()
getWindowDimensions()
Synopsis
dims = Splunk.util.getWindowDimensions()
107
Return Value
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
Parameters
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()
108
Synopsis
Parameters
{ return_to: 'apps/search/'
});
See Also
make_url()
make_url
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/@<build_number>[.<push_number>]/
/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
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
110
See Also
strip_url()
url_has_valid_charset()
normalizeBoolean()
Synopsis
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
111
normalizeColor()
Synopsis
Parameters
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()
112
Synopsis
Parameters
haveResultParamsChanged: function() {
},
propToQueryString()
Synopsis
Parameters
113
Example
See Also
getPath()
queryStringToProp()
queryStringToProp()
Synopsis
Parameters
See Also
getPath()
propToQueryString()
redirect_to()
114
Synopsis
Parameters
Undefined
Example
{'sid': '12345678901.123'});
See Also
make_url()
replaceTokens()
Synopsis
115
Parameters
if (USE_AUTOMATIC_STRING_REPLACEMENT) {
See Also
discoverReplacementTokens()
smartTrim()
Synopsis
Parameters
116
maxLength Integer Maximum length of the field.
Return Value
stringToFieldList()
Synopsis
Parameters
alert(fieldList);
See Also
fieldListToString()
stripLeadingSearchCommand()
117
Synopsis
unqualified = Splunk.util.stripLeadingSearchCommand(
qSearch )
Parameters
onContextChange: function() {
},
See Also
addLeadingSearchCommand()
118
Module APIs
Splunk.Module
abortGetResults()
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
Parameters
119
Return Value
Undefined
Example
child.removeChild(first_grandchild); this.addChild(first_grandchild);
See Also
removeChild()
applyContext()
Synopsis
Parameters
Undefined
Example
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()
Synopsis
Parameters
Undefined
Example
this.displayInlineErrorMessage('Game 0v3r!!1');
ensureFreshContexts()
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()
Synopsis
ancestors = getAncestors()
Return Value
122
Example
alertEachAncestor: function() {
},
See Also
getDescendants()
getModulesInTree()
getRootAncestor()
withEachAncestor())
getContext()
Synopsis
context = getContext()
Return Value
Current context.
Object
null = Could not get a context object.
Throws
Example
123
See Also
applyContext()
getModifiedContext()
onContextChange()
getDescendants()
Synopsis
Return Value
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
if (!this.getGroupName()) {
See Also
getParam()
getLoadState()
Synopsis
loadstate = getLoadState()
Return Value
return;
} else {
125
alert('I have a context and can proceed with some useful function');
See Also
setLoadState()
getModifiedContext()
Synopsis
results = getModifiedContext()
Return Value
getModifiedContext: function() {
},
126
See Also
ensureFreshContexts()
getContext()
onContextChange()
getModulesInTree()
Synopsis
results = getModulesInTree()
Return Value
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
Parameters
} else {
See Also
importParams()
setParam()
snapshotParamset()
getResultParams()
128
Note: This method is intended to be overridden and returns an empty object by
default.
Synopsis
param = getResultParams()
Return Value
getResultParams: function() {
},
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()
Synopsis
130
Parameters
Undefined
Example
getResultsCompleteHandler: function(xhr) {
},
See Also
getResults()
getResultsErrorHandler()
getResultsErrorHandler()
Synopsis
131
Parameters
Undefined
Throws
Example
},
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.
Synopsis
132
Parameters
URI and query string representing the path to the calling module
String
controller.
Example
if (!resultUrl) {
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
133
Example
getModulesInTree: function() {
},
See Also
getModulesInTree()
getAncestors()
getDescendants()
haveResultParamsChanged()
Synopsis
changed = haveResultParamsChanged()
Return Value
onContextChange: function($super){
},
134
See Also
getResults()
getResultParams()
onContextChange()
hide()
The hide() helper function sets the calling module invisibilityMode, hidden or
not hidden.
Synopsis
Parameters
Undefined
Example
$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()
Synopsis
hideDescendants( invisibilityMode )
Parameters
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()
Synopsis
importParams()
Return Value
Undefined
Example
this.importParams(); if (this._params.hasOwnProperty('foobar')) {
See Also
getParam()
setParam()
snapshotParamset()
isPageLoadComplete()
137
Synopsis
status = isPageLoadComplete()
Return Value
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()
138
Note: This module is intended to be overridden.
Synopsis
status = isReadyForContextPush()
Return Value
See Also
getLoadState()
markPageLoadComplete()
onLoadStatusChange()
pushContextToChildren()
markPageLoadComplete()
Synopsis
139
Return Value
Undefined
Example
pushContextToChildren: function(explicitContext) {
},
See Also
isPageLoadComplete()
onLoadStatusChange()
mergeLoadParamsIntoContext()
Synopsis
Parameters
140
Return Value
Undefined
Example
$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()
Synopsis
onBeforeJobDispatched( search )
Parameters
Undefined
141
Example
onBeforeJobDispatched: function(search) {
},
onContextChange()
Synopsis
onContextChange()
Return Value
Undefined
Example
onContextChange: function() {
},
142
See Also
getContext()
getModifiedContext()
haveResultParamsChanged()
applyContext()
onLoadStatusChange()
Synopsis
onLoadStatusChange( status )
Parameters
Undefined
Example
$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()
Note: This method is not implemented, by default, so you must provide it.
Synopsis
onResultsRendered()
Return Value
Undefined
Example
onResultsRendered: function() {
144
this.logger.warn("Context contains unsupported
dataOverlayMode value of", context.get("results.dataOverlayMode"));
}
},
See Also
getResults()
renderResults()
onViewDataChange()
Synopsis
Parameters
Undefined
Example
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()
Synopsis
Parameters
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()
Synopsis
Parameters
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()
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.
Synopsis
removeChild( childModule )
148
Parameters
Undefined
Example
this.withEachChild( function(child) {
this.removeChild(child);
return false;
});
renderResults()
Synopsis
Parameters
Undefined
149
Example
$super(htmlFragment);
if (this.getInferredEntityName()=="events") {
this.renderedCount = $("tr", this.container).length - 1;
}
},
See Also
getResults()
onResultsRendered()
requiresAsynchronousLoading()
Synopsis
asyncLoad = requiresAsynchronousLoading()
Return Value
150
See Also
requiresDispatch()
requiresDispatch()
Synopsis
Parameters
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.
Synopsis
resetUI()
Return Value
Undefined
Example
resetUI: function(){
this.resultsContainer.html("");
},
See Also
abortGetResults()
reset()
resetContext()
resizeWidthToParent()
153
Synopsis
resizeWidthToParent()
Return Value
Example
$(window).bind('resize', this.resizeWidthToParent.bind(this));
setChildContextFreshness()
Synopsis
Parameters
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
Parameters
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
Parameters
Undefined
Throws
Example
See Also
getParam()
importParams()
156
snapshotParamset()
show()
The show() method makes the current module visible and sets the visibility
mode.
Synopsis
show( invisibilityMode )
Parameters
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()
157
Synopsis
showDescendants( invisibilityMode )
Parameters
Undefined
Example
onRowClick: function(evt) {
this.showDescendants(this.DRILLDOWN_VISIBILITY_KEY + "_" +
this.moduleId);
},
See Also
hide()
hideDescendants()
show()
snapshotParamset
Synopsis
snapshotParamset()
Return Value
Undefined
158
Example
delete tempParams.fookey;
See Also
getParam()
importParams()
setParam()
someChildrenRequireDispatch()
Synopsis
Parameters
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()
"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().
this.childEnforcement = Splunk.Module.ALWAYS_REQUIRE;
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()
Synopsis
Parameters
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()
Note: Only immediate child modules are operated on, not grandchildren.
162
Synopsis
status = withEachChild( fn )
Parameters
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) {
},
See Also
someChildrenRequireDispatch()
withEachAncestor()
withEachDescendant()
withEachDescendant()
Synopsis
163
Parameters
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) {
},
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
Undefined
Example
onJobDone: function(event) {
if (this.getInferredEntityName()=="results") {
this.getResults();
}
},
See Also
onJobProgress()
onJobStatusChange()
onJobProgress()
Synopsis
onJobProgress( event )
165
Parameters
Undefined
Example
onJobProgress: function() {
},
See Also
onJobProgress()
onJobStatusChange()
onJobStatusChange()
Synopsis
Parameters
166
Return Value
Undefined
Example
if (status == 'cancel') {
this.reset();
}
See Also
onJobDone()
onJobProgress()
requiresTransformedResults()
Synopsis
transform = requiresTransformedResults()
Return Value
167
Module Controller APIs
ModuleController
renderJobStatusMessage()
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
Error messages:
168
Exceptions
User-defined
renderModule()
Synopsis
Parameters
ModuleHandler
generateResults()
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.
Synopsis
results = generateResults(args)
Parameters
User-defined, as needed.
Example
Overridden
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.
Synopsis
Parameters
Synopsis
172
Parameters
Example 1
Example 2
Example 3
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)
173
Return Value
Common application
<div id="sampleContent"></div>
<script>
</script>
See Also
make_full_url()
push_version()
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
redirect_to_route()
Synopsis
Parameters
Undefined
Raises
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()
Synopsis
Parameters
Undefined
Raises
Example
self.redirect_to_url('/api/search/jobs', job_id=1234)
176
See Also
render_template()
redirect_to_route()
cherrypy.HTTPRedirect()
render_json()
Synopsis
Parameters
TBD
Examples
Example 1
self.render_json(output)
Example 2
set_mime='text/html')
177
See Also
render_template()
render_template()
Synopsis
Parameters
render_json()
TemplateLookup
setup_mako()
setup_mako()
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
Parameters
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().
Synopsis
qsObj = all()
Return Value
Example 1
class MyAppModel(SplunkRESTModel):
def index(self):
apps = self.all()
class MyAppModel(SplunkRESTModel):
def index(self):
apps = self.all().filter(is_disabled=False)
Example 2
180
class MyAppModel(SplunkRESTModel):
def index(self):
apps = self.all().filter(is_disabled=False)
build_id()
Synopsis
Parameters
String Hierarchical URI path to the requested entity in the REST API.
Examples
Example 1
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))
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
else:
See Also
delete()
182
delete()
Synopsis
status = delete()
Return Value
else:
See Also
create()
from_entity()
The from_entity() method populates the current model with the specified
entity.
Synopsis
183
Parameters
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
Parameters
184
Return Value
getSearch: function() {
See Also
enforceByValue()
getAll()
set()
get_mutable_fields()
Synopsis
Return Value
185
See Also
update()
is_mutable()
Synopsis
Parameters
class MyAppModel(SplunkRESTModel):
See Also
get_mutable_fields()
manager()
186
Synopsis
results = manager()
Return Value
class MyAppModel(SplunkRESTModel):
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
Parameters
187
Example
class MyAppModel(SplunkRESTModel):
See Also
all()
search()
order_by()
parse_except_messages()
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
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 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
class MyAppModel(SplunkRESTModel):
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
Parameters
search.job.save(
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
Parameters
class MyAppModel(SplunkRESTModel):
See Also
all()
order_by()
set_entity_fields()
The set_entity_fields() method sets the current object entity fields to the
specified model fields.
191
Synopsis
Parameters
class MyAppModel(SplunkRESTModel):
See Also
create()
update()
The update () method updates the current model fields with the specified
fields.
Synopsis
update( fields )
192
Parameters
Undefined
Example
class MyAppModel(SplunkRESTModel):
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
else:
from_entity()
The from_entity() method populates the current model with the specified
entity.
Synopsis
Parameters
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
class AlertsWizardController(BaseController):
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
class AlertsWizardController(BaseController):
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
class AlertsWizardController(BaseController):
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
else:
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
Parameters
198
(Optional) Function to execute upon unsuccessful
onFailure Function
operation.
Example
search.job.save(
set_entity_fields()
The set_entity_fields() method sets the current object entity fields to the
specified model fields.
Synopsis
Parameters
class MyAppModel(SplunkRESTModel):
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.
Synopsis
querySet = all()
Return Value
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
200
Return Value
Object
Model object for entity id, or None if the entity cannot be loaded.
None
Example
order_by()
The order_by() method gets a clone of the current result set, ordered by the
specified model field and sorting order.
Synopsis
Parameters
201
Example
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
Parameters
class MyAppModel(SplunkRESTManager):
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.
Synopsis
querySet = all()
Return Value
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
Parameters
class AlertsController(BaseController):
See Also
all()
filter_by_app()
filter_by_user()
order_by()
search()
filter_by_app()
Synopsis
204
Parameters
class AlertsController(BaseController):
See Also
all()
filter()
filter_by_user()
order_by()
search()
filter_by_user()
Synopsis
Parameters
205
Return Value
See Also
all()
filter()
filter_by_app()
search()
get_entities()
Synopsis
Parameters
206
See Also
iterator()
iterator()
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
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
Parameters
207
Sort dirrection:
direction String asc = Ascending order.
desc = Descending order.
Return Value
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
Parameters
208
Example
class MyAppModel(SplunkQuerySet):
See Also
all()
filter()
filter_by_app()
filter_by_user()
order_by()
209
Decorators API
Decorators
@expose_page()
Note: Any controller method exposed to the user should use the
@expose_page() decorator. Very few methods should ever be exposed without
authentication.
Synopsis
Parameters
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'])
return self.render_admin_template('admin/fields.html', {
'namespace' : namespace,
'breadcrumbs' : self.generateBreadcrumbs(namespace,
'fields'),
})
See Also
@route()
@lock_session()
Synopsis
@lock_session
211
Example
@expose_page(must_login=False, methods=['GET','POST'],
verify_session=False)@lock_session @set_cache_level('never')
@route()
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.
<controller_name>/
@route('/:var')
@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')
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
Parameters
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>
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.
See Also
@expose_page()
@set_cache_level()
Synopsis
@set_cache_level( cache_level )
Parameters
@route('/:namespace/*endpoint_path/',
methods=['GET'])@expose_page(must_login=True) @set_cache_level('never')
def listEntities(self, namespace, endpoint_path, **kwargs):
214
Template API
Templates
add_script_block()
Synopsis
add_script_block()
Example
</%call>
See Also
script_tags()
csrf_hidden_input()
Note: Forms that POST but do not use this method are rejected.
215
Synopsis
csrf_hidden_input()
Example
${csrf_hidden_input()}
... elided ...
css()
Synopsis
css()
Example
</%def>
get_script_blocks()
216
Synopsis
get_script_blocks()
Example
</%doc>
script_tags()
Synopsis
Parameters
See Also
add_script_block()
217
stylesheet_tags()
Synopsis
Parameters
218
App Server Util API
Synopsis
restartF = check_restart_required()
Return Value
template_args = {
convert_to_bytes()
219
Synopsis
numericValue = convert_to_bytes(byteValue)
Parameters
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:
220
Exceptions
bytes = util.convert_to_bytes(byteVal)
except:
pass
current_url_path()
Synopsis
Parameters
221
Example
deep_update_dict()
Synopsis
Parameters
@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()
Synopsis
name = get_active_controller()
Return Value
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
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
Parameters
my_time = util.get_time(seconds=86400)
in_sso_mode()
224
Synopsis
ssoMode = in_sso_mode()
Return Value
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
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
if util.is_ie():
else
is_valid_cherrypy_session_id()
226
Synopsis
Parameters
is_xhr()
227
Synopsis
results = is_xhr()
Return Value
@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()
Synopsis
228
Parameters
if (earliest) :
if (isEpochTimeArg(earliest)):
... elided ...
else
... elided ...
layPiping()
Synopsis
searchString = layPiping( q )
Parameters
229
Return Value
q = 'search index=_internal
r = util.layPiping(q)
make_absolute()
Synopsis
Parameters
TBD
Example
230
make_url
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/@<build_number>[.<push_number>]/
/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
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
See Also
strip_url()
url_has_valid_charset()
normalize_value()
Synopsis
Parameters
232
Raises
push_version()
Synopsis
push_version = push_version()
Return Value
def incr_push_version(self):
233
restart_splunk()
Synopsis
results = restart_splunk()
Return Value
Undefined
Raises
util.restart_splunk()
set_cache_level()
Synopsis
Parameters
234
response String Deprecated
Return Value
Undefined
Raises
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
Parameters
String Pathname with the root endpoint and i18n prefixes stripped.
235
Example
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()
Synopsis
results = url_has_valid_charset(url)
Parameters
if (util.url_has_valid_charset('http://localhost:8000/en-US/account/login'))
else
236
See Also
make_url()
strip_url()
237