<%! import splunk import logging import hashlib import os.path import splunk.appserver.mrsparkle.lib.i18n as i18n import splunk.appserver.mrsparkle.lib.filechain as filechain import cherrypy from mako.exceptions import RichTraceback from splunk.appserver.mrsparkle.lib import util from splunk.appserver.mrsparkle.lib.eai import cpQuoteEntity logger = logging.getLogger('splunk.appserver.templates.lib') import splunk.appserver.mrsparkle.lib.module as module modules = module.moduleMapper.getInstalledModules() isLite = splunk.util.normalizeBoolean(cherrypy.config['product_type'] == 'lite' or cherrypy.config['product_type'] == 'lite_free') %> <%namespace name="helpers" file="//view/_helpers.html" import="*"/> <%def name="add_script_block()"> <% if attributes.get('script_blocks', None) is None: attributes['script_blocks'] = [] attributes['script_blocks'].append(capture(caller.body)) %> <%def name="fillform(form_defaults, form_errors)"> <% from formencode import htmlfill context.write(htmlfill.render(capture(caller.body), form_defaults, form_errors, auto_insert_errors=False)) %> <%def name="get_script_blocks()"> % if attributes.get('script_blocks'): % endif ## DO NOT USE compile flag - here only to maintain compatibility with customer templates <%def name="script_tags(files, compile=False)"> <% seen = attributes.setdefault('script_tags_seen', set()) %> <% disable_messenger = cherrypy.session.get('sessionKey', None) is None minify_js = splunk.util.normalizeBoolean(cherrypy.config.get('minify_js')) %> % for file in files: % if minify_js and not file.startswith('/static/app/') and not file.startswith('/config?') and not file.endswith('init.js') and not file.endswith('highcharts.js'): % if 'common.min.js' not in seen: % if disable_messenger: % endif \ <% seen.add('common.min.js') %> % endif % if '/modules/' in file: <% basename = 'modules-' + filechain.generate_file_list_hash(files) + '.min.js' %> % if basename not in seen: <% filechain.chain_modules_js(files) %> \ <% seen.add(basename) %> % endif % endif % elif file not in seen: \ <% seen.add(file) %> % endif % endfor ## DO NOT USE compile flag - here only to maintain compatibility with customer templates <%def name="stylesheet_tags(files, compile=False, media=None)"> <% seen = attributes.setdefault('stylesheet_tags_seen', set()) minify_css = splunk.util.normalizeBoolean(cherrypy.config.get('minify_css')) %> % for file in files: % if minify_css and '/modules/' in file: <% basename = 'modules-' + filechain.generate_file_list_hash(files) + '.min.css' %> % if basename not in seen: <% filechain.chain_modules_css(files) %> \ <% seen.add(basename) %> % endif % elif file not in seen: \ <% seen.add(file) %> % endif % endfor <%def name="traceback(header=None, parent_element_class_name='traceback', row_highlight_class_name='active', max_lines=5)"> <% tback = RichTraceback() line = tback.lineno if tback.source: lines = tback.source.split('\n') else: lines = None %>

${header if header else "Error!"}

${str(tback.error.__class__.__name__)|h}: ${str(tback.error)|h}

% if lines: % for index in range(max(0, line-(max_lines-1)), min(len(lines), line+max_lines)): % endfor
${index + 1}
${lines[index] | h}
% endif
% for (filename, lineno, function, line) in tback.reverse_traceback:
${filename}, line ${lineno}:
${line | h}
% endfor
<%def name="generate_select_options(optionArray, selectedValue=None)"> % for pair in optionArray: <% sel = ' selected="1"' if selectedValue != None and unicode(pair[0], 'utf-8') == unicode(selectedValue, 'utf-8') else '' %> \ \ % endfor <%def name="generate_radio_options(optionArray, formName, disabled=None, selectedValue=None)"> % for pair in optionArray: <% sel = ' checked ' if selectedValue != None and pair[0] == selectedValue else '' %> \ ${pair[1] | h}
% endfor <%def name="getSavedSearch(module, savedSearchName, useHistory=False, namespace=None, owner=None, nativeObjectMode=None)"> <% jsonSearch = None jobNotFoundMessage = 'Module %(module)s: Could not find a previously run search for saved search "%(savedSearchName)s".' savedSearchNotFoundMessage = 'Module %(module)s: Could not find a saved search named "%(savedSearchName)s".' quoteExceededMessage = 'Module %(module)s: There are too many searches running; unable to dispatch "%(savedSearchName)s".' try : savedSearchObject = splunk.search.getSavedSearch( label = savedSearchName, namespace = namespace, owner = owner ) # if decomp isn't supported, return decomp fail if not splunk.util.normalizeBoolean(cherrypy.config.get('support_decomposition')): q = util.layPiping(savedSearchObject["qualifiedSearch"]) jsonSearch = { "fullSearch" : q, "baseSearch" : q, "intentions": [], "decompositionFailed": True, "s": savedSearchObject.getLink('alternate'), "name": savedSearchObject.name, "earliest": savedSearchObject.get('dispatch.earliest_time'), "latest": savedSearchObject.get('dispatch.latest_time') } else: jsonSearch = splunk.appserver.mrsparkle.util.resurrectFromSavedSearch( savedSearchObject = savedSearchObject, hostPath = splunk.mergeHostPath(), namespace = namespace, owner = owner ) useHistory = unicode(useHistory).capitalize() if (useHistory in ["Auto", "None", "True"]) : if useHistory == "None": logger.warn("useHistory == None is being depreciated, please use Auto instead.") historySearch = 'name=scheduler* OR name=rt_scheduler*' # for real-time, not scheduled searches try to use an already running instance of the search if not splunk.util.normalizeBoolean(savedSearchObject.get('is_scheduled')) and \ savedSearchObject.get('dispatch.earliest_time') and \ savedSearchObject.get('dispatch.earliest_time').startswith('rt') : historySearch = 'isDone=0 AND isRealTimeSearch=1 AND isZombie=0 AND isFinalized=0' try: # Note that we never submit anything other than useHistory="true". # this is because its problematic to let the python dispatch the search for us. # instead if there's no job run by the scheduler, we return the other context data and let the # client dispatch the search itself. job = splunk.search.getJobForSavedSearch( savedSearchName, useHistory="True", namespace=namespace, owner=owner, search=historySearch, historyURI= savedSearchObject.getLink("history") ) if (job) : jsonSearch["job"] = job.toJsonable(timeFormat='unix') elif useHistory == "True": helpers.message('error', jobNotFoundMessage % {'savedSearchName': savedSearchName, 'module': module['id']}) except splunk.RESTException, e: # Payment Required! # Get a job by using useHistory = True if e.statusCode == 402: logger.warn("Could not retrieve the job history for the saved search '%s' because the current license does not allow it." % savedSearchName) helpers.message("info", _("This view references scheduled searches that do not run automatically in Free Splunk. Please wait while they run now.")) else: raise e except splunk.BadRequest, e: logger.exception(e) if len(e.extendedMessages) > 0: for msg in e.extendedMessages: logger.error(msg['text']) helpers.message(msg['type'].lower(), msg['text']) else: helpers.message('error', jobNotFoundMessage % {'savedSearchName': savedSearchName, 'module': module['id']}) except splunk.ResourceNotFound, e: logger.exception(e) if nativeObjectMode!='SimpleDashboard': helpers.message('error', savedSearchNotFoundMessage % {'savedSearchName': savedSearchName, 'module': module['id']}) except splunk.QuotaExceededException, e: logger.warn(str(e)) helpers.message('warn', quoteExceededMessage % {'searchName': savedSearchName, 'module': module['id']}) %> <%call expr="add_script_block()"> % if jsonSearch: Splunk.Module.loadParams.${module['id']}.jsonSearch = ${json_decode(jsonSearch)}; % else: Splunk.Module.loadParams.${module['id']}.jsonSearch = null; % endif <%def name="csrf_hidden_input()"> <%def name="render_exception(e)"> ${e.msg if hasattr(e, 'msg') else e | h} % if hasattr(e, 'extendedMessages') and e.extendedMessages: — % for item in e.extendedMessages: ${item['text'] | h} % endfor % endif <%def name="manager_save_search_link(namespace, id, name, label=None)"> ${label or name | h}. <%def name="wizard_errors(header, errors)"> % if len(errors)>0:

${header|h}

% endif <%def name="wizard_save_search_form(app, saved_search, display_share=True, display_acceleration=False)"> <%self:wizard_errors header="${_('Your search could not be saved.')}" errors='${saved_search.errors}'/> <%self:csrf_hidden_input/> % if saved_search.id: % endif % if display_share: % endif % if display_acceleration and saved_search.auto_summarize.enabled is not None and saved_search.auto_summarize.can_summarize: % endif
${_('Share')}
  • ${_('Additional permission settings available in
    Settings » Searches, reports, and alerts')}
<%self:acceleration_options/>
<%self:add_script_block> $(document).ready(function(){ var searchName = $('#name')[0]; if(searchName.disabled==false){ searchName.focus(); }else{ $('#search').focus(); } }); <%def name="acceleration_options()">
${_('Acceleration')}

${_('May increase storage and processing costs')} ${_('Learn more.')}

<% timespan_options = [{'value':'1m', 'label':'1 min'}, {'value':'1h', 'label':'1 hour'}, {'value':'1d', 'label':'1 day'}, {'value':'7d', 'label':'1 week'}] earliest_time_options = [{'value':'-1d@h', 'label':'1 Day'}, {'value':'-7d@d', 'label':'7 Days'}, {'value':'-1mon@d', 'label':'1 Month'}, {'value':'-3mon@d', 'label':'3 Months'}, {'value':'-1y@d', 'label':'1 Year'}, {'value':'0', 'label':'All Time'}] %>


% if not saved_search.auto_summarize.is_good_summarization_candidate:
Warning: Splunkd has determined that turning on acceleration will likely not benefit this search.
% endif
<%self:add_script_block> $(document).ready(function(){ $('#auto_summarize').click(toggle_autosummarize); toggle_autosummarize(); }); function toggle_autosummarize(){ if ($('#auto_summarize').attr('checked')) { $('#auto_summarize_options').show(); } else { $('#auto_summarize_options').hide(); } } <%def name="get_summarization_status(tsum)"> <% from splunk.appserver.mrsparkle.lib import util complete = int(float(tsum.complete)*100) completeString = _('%s%% Complete') % complete mod_time = util.timeToAgoStr(int(tsum.mod_time)) mod_time_string = " " + _('Updated: ') + mod_time + "" if mod_time else '' mod_time_seconds =util.timeToAgoSeconds(int(tsum.mod_time)) isUpdatedALongTimeAgo = util.timeToAgoSeconds(int(tsum.mod_time)) > 600 if tsum.is_inprogress: completeString = "
" + _('Building summary - ') + str(complete) + "%
" else: isNotStarted = len(tsum.run_stats) == 0 and not tsum.is_inprogress isNotEnoughData = int(tsum.size) == 0 and len(tsum.run_stats) > 0 and len(tsum.last_error) == 0 if isNotStarted: completeString = _('Summarization not started') elif isNotEnoughData: completeString = ' ' + _("Not enough data to summarize.") elif tsum.is_suspended: completeString = ' ' + _("Suspended.") elif isUpdatedALongTimeAgo: completeString = _('Pending') elif complete == 100: completeString = _('Complete') completeString += mod_time_string return completeString %> <%def name="wizard_steps(items, active)">
<%def name="wizard_cancel_delete(action, id, dashboard_id=None)">
${csrf_hidden_input()} % if dashboard_id: % endif
<%def name="wizard_schedules()"> <% return [ ('* * * * *', _('minute')), ('*/5 * * * *', _('5 minutes')), ('*/15 * * * *', _('15 minutes')), ('*/30 * * * *', _('30 minutes')), ('0 * * * *', _('hour')), ('0 */4 * * *', _('4 hours')), ('0 */12 * * *', _('12 hours')), ('0 0 * * *', _('day at midnight')), ('0 18 * * *', _('day at 6pm')), ('0 0 * * 6', _('Saturday at midnight')) ] %> <%def name="wizard_ok()"> <%def name="summarization_verification_form(verifyLink, estimated_verify_time_fast, estimated_verify_time_thorough, selectedValue='', error=None)">
${_('Verification tests a percentage of the summary to ensure the data is valid. ')} ${_('Learn more.')}

<%self:csrf_hidden_input/> <%self:wizard_errors header="${_('Your verification could not be started.')}" errors='${error if error else []}'/>



<%def name="prettyInt(num)"> <% s = '%d' % num groups = [] while s and s[-1].isdigit(): groups.append(s[-3:]) s = s[:-3] return s + ','.join(reversed(groups)) %> <%def name="timeToDateStr(num)"> <% import time if not num: return '' num = int(num) dateStr = time.ctime(num) if num > 0 else 'N/A' return dateStr %> <%def name="secondsToFormattedTime(t)"> <% result = 'Never' if t > 0: result = '' if t > 60: if t/86400 >= 1: days = int(t/86400) result = "%dd " % (days) t = t % 86400 hours = int(t/3600) mins = int( (t%3600)/60) if len(result) > 0 or hours > 0: result += ("%dh " % (hours)) result += ("%dm " % (mins)) else: result = "< 1 min" return result %> <%def name="summarization_verification_form_step2(verifyLink, max_buckets, max_time, max_ratio, auto_delete, total_buckets, error)">
<%self:csrf_hidden_input/> <%self:wizard_errors header="${_('Your verification could not be started.')}" errors='${error if error else []}'/>
This summary spans ${total_buckets} buckets.



<%def name="sort_link(label, url, params, sort_by)"> <% css_class = 'splSortNone' qs = {} qs.update(params) if qs.get('sort_by') == sort_by: if qs.get('sort_dir') is None or qs.get('sort_dir') == 'desc': qs['sort_dir'] = 'asc' css_class = 'splSortAsc' else: qs['sort_dir'] = 'desc' css_class = 'splSortDesc' else: qs['sort_by'] = sort_by qs['sort_dir'] = 'desc' %> ${label|h} <%def name="get_application_css(app)"> <% from lib.apps import local_apps css = None local_app = local_apps.apps.get(app, None) if local_app: local_app.setdefault('static', {}).setdefault('css', []) if local_app['static']['css'].count('application.css')>0: css = '/static/app/%s/application.css' % app %> % if css: % endif <% appPatches = local_apps[app]['patch'].get('css', []) %> % for patch in appPatches: % endfor <%def name="pretty_bucket_search_state(searchState)"> % if searchState == "Searchable": ${_("Raw data and Index files")} % else: ${_("Raw data only")} % endif <%def name="generate_slave_pagination(countPerPage, offset, numItems, search, ns, pwnr)"> ## EAI pagination <% import copy import splunk.appserver.mrsparkle.lib.paginator as paginator try: count = int(countPerPage) except Exception, e: count = 25 try: offset = int(offset) except Exception, e: offset = 0 try: totalResults = int(numItems) except Exception, e: totalResults = 0 newOffset = count + offset prevOffset = 0 if ( (offset - count) < 0 ) else (offset - count) spanStart = 1 if offset == 0 else (offset + 1) spanEnd = ( offset + count ) sel = "" resPerPage = [10, 25, 50, 100] if (spanEnd > totalResults): lastPage = True spanEnd = totalResults max_pages = 10 pager = paginator.Google(totalResults, count, max_pages=max_pages, item_offset=offset) page_range = [] for page in pager.page_range: page_range.append( { 'number':page, 'offset':pager.page_item_offset(page), 'active':pager.is_active_page(page) } ) %>
% if totalResults > 0:

${ungettext('Showing %(first)s-%(last)s of %(total)s item', 'Showing %(first)s-%(last)s of %(total)s items', totalResults) % dict(first=spanStart, last=spanEnd, total=totalResults)}

% endif
<% page_opts = {'search':search, 'count':countPerPage, 'offset':offset, 'ns':ns, 'pwnr':pwnr}%>
<%def name="generate_master_pagination(countPerPage, offset, numItems, search, ns, pwnr)">
## EAI pagination <% import copy import splunk.appserver.mrsparkle.lib.paginator as paginator try: count = int(countPerPage) except Exception, e: count = 25 try: offset = int(offset) except Exception, e: offset = 0 try: totalResults = int(numItems) except Exception, e: totalResults = 0 newOffset = count + offset prevOffset = 0 if ( (offset - count) < 0 ) else (offset - count) spanStart = 1 if offset == 0 else (offset + 1) spanEnd = ( offset + count ) sel = "" resPerPage = [10, 25, 50, 100] if (spanEnd > totalResults): lastPage = True spanEnd = totalResults max_pages = 10 pager = paginator.Google(totalResults, count, max_pages=max_pages, item_offset=offset) page_range = [] for page in pager.page_range: page_range.append( { 'number':page, 'offset':pager.page_item_offset(page), 'active':pager.is_active_page(page) } ) %>
% if totalResults > 0:

${ungettext('Showing %(first)s-%(last)s of %(total)s item', 'Showing %(first)s-%(last)s of %(total)s items', totalResults) % dict(first=spanStart, last=spanEnd, total=totalResults)}

% endif
<% page_opts = {'search':search, 'count':countPerPage, 'offset':offset, 'ns':ns, 'pwnr':pwnr}%>
<%def name="generate_searchbar(search, ns, countPerPage, appOptionList, pwnrOptionList, pwnr)">
<% nss = appOptionList pwnrs = pwnrOptionList %>
% if nss is not None and len(nss) > 0: % endif
% if pwnrs is not None and len(pwnrs) > 0:
% endif
<%def name="generate_splunk_header()">