Exemple #1
0
 def step2_new(self, app, action, **params):
     owner = splunk.auth.getCurrentUser()['name']
     saved_search = SavedSearch.get(params.get('id'))
     dashboard = Dashboard(app, owner, None)
     dashboard.metadata.sharing = 'app'
     dashboards = Dashboard.filter_by_can_write_simple_xml(app)
     template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboards=dashboards, 
                          dashboard_action=None, panel_type='event', panel_title=None)
     return self.render_template('dashboardwizard/step2.html', template_args)
Exemple #2
0
 def step2_edit(self, app, action, **params):
     owner = splunk.auth.getCurrentUser()['name']
     saved_search = SavedSearch.get(params.get('id'))
     dashboard = Dashboard.get(params.get('dashboard_id'))
     dashboard_action = params.get('dashboard_action')
     if dashboard_action=='new':
         dashboard.delete()
     dashboards = Dashboard.filter_by_can_write_simple_xml()
     template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboards=dashboards, 
                          dashboard_action=dashboard_action)
     return self.render_template('dashboardwizard/step2.html', template_args)
Exemple #3
0
 def step2_edit(self, app, action, **params):
     owner = splunk.auth.getCurrentUser()['name']
     saved_search = SavedSearch.get(params.get('id'))
     dashboard = Dashboard.get(params.get('dashboard_id'))
     dashboard_action = params.get('dashboard_action')
     if dashboard_action=='new':
         dashboard.delete()
     dashboards = Dashboard.filter_by_can_write_simple_xml()
     template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboards=dashboards, 
                          dashboard_action=dashboard_action)
     return self.render_template('dashboardwizard/step2.html', template_args)
Exemple #4
0
    def step3_update(self, app, step, action, **params):
        # saved search models
        saved_search = SavedSearch.get(params.get('id'))
        schedule_type = params.get('schedule_type')
        saved_search.schedule.is_scheduled = True
        saved_search.is_disabled = False
        if schedule_type=='preset':
            alert_preset = params.get('alert_preset')
            if alert_preset=='cron':
                saved_search.schedule.cron_schedule = params.get('alert_cron')
            else:
                saved_search.schedule.cron_schedule = alert_preset
        elif schedule_type=='never':
            saved_search.schedule.is_scheduled = False
            saved_search.schedule.cron_schedule = None
        elif schedule_type=='continuous':
            saved_search.schedule.cron_schedule = '* * * * *'

        # dashboard model
        dashboard = Dashboard.get(params.get('dashboard_id'))
        panel_type = params.get('panel_type', 'event')
        dashboard.create_panel(panel_type, saved_search=saved_search.name, title=params.get('panel_title'))

        if saved_search.passive_save() and dashboard.passive_save():
            # update saved search only on save success         
            raise cherrypy.HTTPRedirect(self.make_url(['dashboardwizard', app, 'success'], _qs=dict(search_id=saved_search.id, dashboard_id=dashboard.id)), 303)
        template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboard_action=params.get('dashboard_action'))
        return self.render_template('dashboardwizard/step3.html', template_args)
Exemple #5
0
    def step3_update(self, app, step, action, **params):
        # saved search models
        saved_search = SavedSearch.get(params.get('id'))
        saved_search.auto_summarize.enabled = params.get('auto_summarize.enabled') == 'True'
        saved_search.auto_summarize.earliest_time = params.get('auto_summarize.earliest_time')
        saved_search.auto_summarize.timespan = params.get('auto_summarize.timespan')
        schedule_type = params.get('schedule_type')
        saved_search.schedule.is_scheduled = True
        saved_search.is_disabled = False
        if schedule_type=='preset':
            alert_preset = params.get('alert_preset')
            if alert_preset=='cron':
                saved_search.schedule.cron_schedule = params.get('alert_cron')
            else:
                saved_search.schedule.cron_schedule = alert_preset
        elif schedule_type=='never':
            saved_search.schedule.is_scheduled = False
            saved_search.schedule.cron_schedule = None
        elif schedule_type=='continuous':
            saved_search.schedule.cron_schedule = '* * * * *'

        # dashboard model
        dashboard = Dashboard.get(params.get('dashboard_id'))
        panel_type = params.get('panel_type', 'event')
        dashboard.create_panel(panel_type, saved_search=saved_search.name, title=params.get('panel_title'))

        if saved_search.passive_save() and dashboard.passive_save():
            # update saved search only on save success         
            raise cherrypy.HTTPRedirect(self.make_url(['dashboardwizard', app, 'success'], _qs=dict(search_id=saved_search.id, dashboard_id=dashboard.id)), 303)
        template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboard_action=params.get('dashboard_action'))
        return self.render_template('dashboardwizard/step3.html', template_args)
Exemple #6
0
    def getPanel(self, namespace, view_id, panel_type, panel_sequence,
                 **unused):
        '''
        Returns a dashboard panel config
        
        GET /<namespace>/<view_id>/panel/<panel_sequence>
            --> panel config for panel at <panel_sequence>
            
            ==> returns a JSON response
        '''

        output = jsonresponse.JsonResponse()

        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS,
                                       view_id,
                                       namespace=namespace,
                                       owner=username)
            dashObject = Dashboard.get(dash_id)
            output.data = dashObject.get_panel(panel_sequence)

        except IndexError, e:
            cherrypy.response.status = 404
            output.success = False
            output.addError(
                _('Requested panel %s does not exist') % panel_sequence)
Exemple #7
0
 def step2_new(self, app, action, **params):
     owner = splunk.auth.getCurrentUser()['name']
     saved_search = SavedSearch.get(params.get('id'))
     dashboard = Dashboard(app, owner, None)
     dashboard.metadata.sharing = 'app'
     dashboards = Dashboard.filter_by_can_write_simple_xml(app)
     template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboards=dashboards, 
                          dashboard_action=None, panel_type='event', panel_title=None)
     return self.render_template('dashboardwizard/step2.html', template_args)
 def get(cls, id, intersect):
     """
     Retrieve a known panel with it's associated splunkd REST path and row/column intersection.
     
     id: The splunkd REST path for the resource.
     intersect: A tuple containing the row/column intersect (0 based).
     """
     dashboard = Dashboard.get(id)
     return DashboardPanel(None, intersect, dashboard=dashboard)
Exemple #9
0
 def get(cls, id, intersect):
     """
     Retrieve a known panel with it's associated splunkd REST path and row/column intersection.
     
     id: The splunkd REST path for the resource.
     intersect: A tuple containing the row/column intersect (0 based).
     """
     dashboard = Dashboard.get(id)
     return DashboardPanel(None, intersect, dashboard=dashboard)
Exemple #10
0
 def step3_edit(self, app, action, **params):
     owner = splunk.auth.getCurrentUser()['name']
     saved_search = SavedSearch.get(params.get('search_id'))
     dashboard = Dashboard.get(params.get('dashboard_id'))
     dashboard_action = params.get('dashboard_action')
     panel_type = 'event' 
     if saved_search.ui.display_view in ['charting', 'report_builder_format_report', 'report_builder_display']:
         panel_type = 'chart' 
     template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboard_action=dashboard_action, panel_type=panel_type, panel_title=None)
     return self.render_template('dashboardwizard/step3.html', template_args)
Exemple #11
0
 def step3_edit(self, app, action, **params):
     owner = splunk.auth.getCurrentUser()['name']
     saved_search = SavedSearch.get(params.get('search_id'))
     dashboard = Dashboard.get(params.get('dashboard_id'))
     dashboard_action = params.get('dashboard_action')
     panel_type = 'event' 
     if saved_search.ui.display_view in ['charting', 'report_builder_format_report', 'report_builder_display']:
         panel_type = 'chart' 
     template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboard_action=dashboard_action, panel_type=panel_type, panel_title=None)
     return self.render_template('dashboardwizard/step3.html', template_args)
Exemple #12
0
    def setPanel(self,
                 namespace,
                 view_id,
                 panel_type,
                 panel_sequence,
                 panel_class=None,
                 action='edit',
                 **panel_definition):
        '''
        Provides management for view panel objects
        
        The HTTP signature for this method expects standard form params to match
        the property names used in the panel objects.  All form params are
        inserted into a dict and passed into the panel object for processing
        
        POST /<namespace>/<view_id>/panel/<panel_sequence>
            &action=edit
            --> updates the existing panel at <panel_sequence>
            &action=delete
            --> deletes the panel at <panel_sequence>
            
            ==> returns JSON response
        '''

        output = jsonresponse.JsonResponse()

        self.collatePanelOptions(panel_definition)

        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS,
                                       view_id,
                                       namespace=namespace,
                                       owner=username)
            dashObject = Dashboard.get(dash_id)

            if action == 'edit':
                dashObject.set_panel(panel_sequence, panel_class,
                                     **panel_definition)

            elif action == 'delete':
                dashObject.delete_panel(panel_sequence)

            else:
                raise ValueError, 'Unknown action requested: %s' % action

            dashObject.save()
            output.addInfo(_('Successfully updated %s' % view_id))

        except Exception, e:
            logger.exception(e)
            output.success = False
            output.addError(
                _('Unable to update panel at sequence %s: %s') %
                (panel_sequence, e))
    def searchedit(self, app, action, row, column, **params):
        row = int(row)
        column = int(column)
        dashboard = Dashboard.get(params.get('id'))
        dashboard_panel = DashboardPanel(None, (row, column),
                                         dashboard=dashboard)
        saved_searches = SavedSearch.all().filter_by_app(app)
        saved_search_id = params.get('saved_search_id')
        owner = splunk.auth.getCurrentUser()['name']
        inline_search = SavedSearch(app, owner, None)
        ui_search_mode = dashboard_panel.panel_model.searchMode
        # set the saved_search object
        if saved_search_id:
            saved_search = SavedSearch.get(saved_search_id)
            ui_search_mode = 'saved'
        # otherwise defer to the first saved search item if it exists or an empty one
        else:
            saved_search_query = SavedSearch.all()
            if len(saved_search_query) > 0:
                saved_search = saved_search_query[0]
            else:
                saved_search = SavedSearch(app, owner, None)

        # based on search mode pre-populate an active saved_search and the inline_search accordingly
        if dashboard_panel.panel_model.searchMode == 'saved' and not saved_search_id:
            saved_search_query = SavedSearch.all().filter_by_app(None).search(
                'name=%s' % util.fieldListToString(
                    [dashboard_panel.panel_model.searchCommand]))
            if len(saved_search_query) > 0:
                saved_search = saved_search_query[0]
            # invalid/non-existant saved search reference, revert to empty saved search model
            else:
                saved_search.search = dashboard_panel.panel_model.searchCommand
                saved_search.dispatch.earliest_time = dashboard_panel.panel_model.searchEarliestTime
                saved_search.dispatch.latest_time = dashboard_panel.panel_model.searchLatestTime
        elif dashboard_panel.panel_model.searchMode == 'string':
            inline_search.search = dashboard_panel.panel_model.searchCommand
            inline_search.dispatch.earliest_time = dashboard_panel.panel_model.searchEarliestTime
            inline_search.dispatch.latest_time = dashboard_panel.panel_model.searchLatestTime

        template_args = dict(app=app,
                             dashboard=dashboard,
                             dashboard_panel=dashboard_panel,
                             saved_searches=saved_searches,
                             saved_search=saved_search,
                             ui_search_mode=ui_search_mode,
                             inline_search=inline_search)
        return self.render_template('paneleditor/searchedit.html',
                                    template_args)
Exemple #14
0
    def step2_create(self, app, step, action, **params):
        # saved search models
        saved_search = SavedSearch.get(params.get('id'))
        # dashboard model
        dashboard_action = params.get('dashboard.action')
        owner = splunk.auth.getCurrentUser()['name']
        if dashboard_action=='get':
            try:
                dashboard = Dashboard.get(params.get('dashboard.id'))
            except:
                dashboard = Dashboard(app, owner, None)
                dashboard.errors = [_('Please choose an existing dashboard.')]
        else:
            dashboard_name = params.get('dashboard.name', '')
            try:
                dashboard_name.encode('ascii')
            except:
                date = str(splunk.util.dt2epoch(datetime.datetime.now())).replace('.', '_')
                dashboard_name = '%s_%s' % (splunk.auth.getCurrentUser()['name'], date)
            dashboard = Dashboard(app, owner, dashboard_name)
            dashboard.label = params.get('dashboard.label')
            dashboard.metadata.sharing = params.get('sharing', 'user')

        if not dashboard.errors and saved_search.passive_save() and dashboard.passive_save():
            # update saved search only on save success
            if dashboard.metadata.sharing=='app':
                try:
                    saved_search.share_app()
                except Exception:
                    saved_search.errors = [_('Search %s cannot be shared because it already exists. Try using another search name in the previous step.') % saved_search.name ]
            else:
                try:
                    saved_search.unshare()
                except Exception:
                    saved_search.errors = [_('Search %s cannot be private because it already exists. Try using another search name in the previous step.') % saved_search.name]
            if not saved_search.errors:
                raise cherrypy.HTTPRedirect(self.make_url(['dashboardwizard', app, 'step3'], _qs=dict(search_id=saved_search.id, dashboard_id=dashboard.id, dashboard_action=dashboard_action)), 303)
        dashboards = Dashboard.filter_by_can_write_simple_xml()
        template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboards=dashboards, dashboard_action=dashboard_action)
        return self.render_template('dashboardwizard/step2.html', template_args)
Exemple #15
0
 def __init__(self, dashboard_id, intersect, dashboard=None):
     """
     dashboard_id: The splunkd REST path for the resource.
     intersect: A tuple contain the row/column intersect (0 base).
     dashboard: Optional dashboard model object to short-circuit additional Dashboard fetch.
     """
     self.intersect = intersect
     self.errors = []
     if dashboard is None:
         self._dashboard = Dashboard.get(dashboard_id)
         self.panel_model = None
         if len(self._dashboard._obj.rows)-1 < intersect[0]:
             self._dashboard._obj.rows.insert(intersect[0], [])
         self._dashboard._obj.rows[intersect[0]].insert(intersect[0], None)
     else:
         self._dashboard = dashboard
         self.panel_model = self._dashboard._obj.rows[self.intersect[0]][self.intersect[1]]
     self.id = (self._dashboard.id, intersect)
    def setPanel(self, namespace, view_id, panel_type, panel_sequence, panel_class=None, action='edit', **panel_definition):
        '''
        Provides management for view panel objects
        
        The HTTP signature for this method expects standard form params to match
        the property names used in the panel objects.  All form params are
        inserted into a dict and passed into the panel object for processing
        
        POST /<namespace>/<view_id>/panel/<panel_sequence>
            &action=edit
            --> updates the existing panel at <panel_sequence>
            &action=delete
            --> deletes the panel at <panel_sequence>
            
            ==> returns JSON response
        '''

        output = jsonresponse.JsonResponse()

        self.collatePanelOptions(panel_definition)

        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS, view_id, namespace=namespace, owner=username)
            dashObject = Dashboard.get(dash_id)
        
            if action == 'edit':
                dashObject.set_panel(panel_sequence, panel_class, **panel_definition)
        
            elif action == 'delete':
                dashObject.delete_panel(panel_sequence)

            else:
                raise ValueError, 'Unknown action requested: %s' % action

            dashObject.save()
            output.addInfo(_('Successfully updated %s' % view_id))

        except Exception, e:
            logger.exception(e)
            output.success = False
            output.addError(_('Unable to update panel at sequence %s: %s') % (panel_sequence, e))
Exemple #17
0
    def createPanel(self, namespace, view_id, panel_type, panel_class,
                    **panel_definition):
        '''
        Create a new panel to add to an existing dashboard
        
        POST /<namespace>/<view_id>/<panel_type=panel>
            &panel_class={table | chart | html | event | list}
            &<panel_property>=<property_value>
                --> creates a new panel
                
            the <panel_property> is a direct map to the panel XML data
            
            ==> returns a JSON response
        '''

        output = jsonresponse.JsonResponse()

        try:

            if panel_type != 'panel':
                raise ValueError, 'Only panel type "panel" is currently supported'

            # support all options
            self.collatePanelOptions(panel_definition)

            # get dashboard and create panel
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS,
                                       view_id,
                                       namespace=namespace,
                                       owner=username)
            dashObject = Dashboard.get(dash_id)

            dashObject.create_panel(type=panel_class, **panel_definition)

            dashObject.save()

        except Exception, e:
            logger.exception(e)
            output.success = False
            output.addError(_('Unable to add panel: %s') % e)
Exemple #18
0
    def searchedit(self, app, action, row, column, **params):
        row = int(row)
        column = int(column)
        dashboard = Dashboard.get(params.get('id'))
        dashboard_panel = DashboardPanel(None, (row, column), dashboard=dashboard)
        saved_searches = SavedSearch.all().filter_by_app(app)
        saved_search_id = params.get('saved_search_id')
        owner = splunk.auth.getCurrentUser()['name']
        inline_search = SavedSearch(app, owner, None)
        ui_search_mode = dashboard_panel.panel_model.searchMode
        # set the saved_search object
        if saved_search_id:
            saved_search = SavedSearch.get(saved_search_id)
            ui_search_mode = 'saved' 
        # otherwise defer to the first saved search item if it exists or an empty one
        else:
            saved_search_query = SavedSearch.all()
            if len(saved_search_query)>0:
                saved_search = saved_search_query[0]
            else:
                saved_search = SavedSearch(app, owner, None)
        
        # based on search mode pre-populate an active saved_search and the inline_search accordingly
        if dashboard_panel.panel_model.searchMode=='saved' and not saved_search_id:
            saved_search_query = SavedSearch.all().filter_by_app(None).search('name=%s' % util.fieldListToString([dashboard_panel.panel_model.searchCommand]))
            if len(saved_search_query)>0:
                saved_search = saved_search_query[0]
            # invalid/non-existant saved search reference, revert to empty saved search model
            else:
                saved_search.search = dashboard_panel.panel_model.searchCommand
                saved_search.dispatch.earliest_time = dashboard_panel.panel_model.searchEarliestTime
                saved_search.dispatch.latest_time = dashboard_panel.panel_model.searchLatestTime
        elif dashboard_panel.panel_model.searchMode=='string':
            inline_search.search = dashboard_panel.panel_model.searchCommand
            inline_search.dispatch.earliest_time = dashboard_panel.panel_model.searchEarliestTime
            inline_search.dispatch.latest_time = dashboard_panel.panel_model.searchLatestTime

        template_args = dict(app=app, dashboard=dashboard, dashboard_panel=dashboard_panel, saved_searches=saved_searches, saved_search=saved_search, 
                             ui_search_mode=ui_search_mode, inline_search=inline_search)
        return self.render_template('paneleditor/searchedit.html', template_args)
    def getPanel(self, namespace, view_id, panel_type, panel_sequence, **unused):
        '''
        Returns a dashboard panel config
        
        GET /<namespace>/<view_id>/panel/<panel_sequence>
            --> panel config for panel at <panel_sequence>
            
            ==> returns a JSON response
        '''
        
        output = jsonresponse.JsonResponse()

        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS, view_id, namespace=namespace, owner=username)
            dashObject = Dashboard.get(dash_id)
            output.data = dashObject.get_panel(panel_sequence)

        except IndexError, e:
            cherrypy.response.status = 404
            output.success = False
            output.addError(_('Requested panel %s does not exist') % panel_sequence)
    def createPanel(self, namespace, view_id, panel_type, panel_class, **panel_definition):
        '''
        Create a new panel to add to an existing dashboard
        
        POST /<namespace>/<view_id>/<panel_type=panel>
            &panel_class={table | chart | html | event | list}
            &<panel_property>=<property_value>
                --> creates a new panel
                
            the <panel_property> is a direct map to the panel XML data
            
            ==> returns a JSON response
        '''
        
        output = jsonresponse.JsonResponse()

        try:
            
            if panel_type != 'panel':
                raise ValueError, 'Only panel type "panel" is currently supported'
                
            # support all options
            self.collatePanelOptions(panel_definition)

            # get dashboard and create panel
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS, view_id, namespace=namespace, owner=username)
            dashObject = Dashboard.get(dash_id)

            dashObject.create_panel(
                type=panel_class,
                **panel_definition)

            dashObject.save()

        except Exception, e:
            logger.exception(e)
            output.success = False
            output.addError(_('Unable to add panel: %s') % e)
Exemple #21
0
    def step2_create(self, app, step, action, **params):
        # saved search models
        saved_search = SavedSearch.get(params.get('id'))
        # dashboard model
        dashboard_action = params.get('dashboard.action')
        owner = splunk.auth.getCurrentUser()['name']
        if dashboard_action=='get':
            try:
                dashboard = Dashboard.get(params.get('dashboard.id'))
            except:
                dashboard = Dashboard(app, owner, None)
                dashboard.errors = [_('Please choose an existing dashboard.')]
        else:
            dashboard_name = params.get('dashboard.name', '')
            try:
                dashboard_name.encode('ascii')
            except:
                date = str(splunk.util.dt2epoch(datetime.datetime.now())).replace('.', '_')
                dashboard_name = '%s_%s' % (splunk.auth.getCurrentUser()['name'], date)
            dashboard = Dashboard(app, owner, dashboard_name)
            dashboard.label = params.get('dashboard.label')
            dashboard.metadata.sharing = params.get('sharing', 'user')

        if not dashboard.errors and saved_search.passive_save() and dashboard.passive_save():
            # update saved search only on save success
            if dashboard.metadata.sharing=='app':
                try:
                    saved_search.share_app()
                except Exception:
                    saved_search.errors = [_('Search %s cannot be shared because it already exists. Try using another search name in the previous step.') % saved_search.name ]
            else:
                try:
                    saved_search.unshare()
                except Exception:
                    saved_search.errors = [_('Search %s cannot be private because it already exists. Try using another search name in the previous step.') % saved_search.name]
            if not saved_search.errors:
                raise cherrypy.HTTPRedirect(self.make_url(['dashboardwizard', app, 'step3'], _qs=dict(search_id=saved_search.id, dashboard_id=dashboard.id, dashboard_action=dashboard_action)), 303)
        dashboards = Dashboard.filter_by_can_write_simple_xml()
        template_args = dict(app=app, saved_search=saved_search, dashboard=dashboard, dashboards=dashboards, dashboard_action=dashboard_action)
        return self.render_template('dashboardwizard/step2.html', template_args)
Exemple #22
0
    def setContainer(self, namespace, view_id, action, view_json=None):
        '''
        Provides support to modify dashboard configs
        
        POST /<namespace>/<view_id>
            &action=delete
                --> deletes the current view
            &action=edit
                --> updates the current view config (view JSON object)
                
            ==> returns a JSON response
        '''

        output = jsonresponse.JsonResponse()

        try:

            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS,
                                       view_id,
                                       namespace=namespace,
                                       owner=username)
            dashObject = Dashboard.get(dash_id)

            if action == 'delete':
                dashObject.delete()
                output.addInfo(_('Successfully deleted %s') % view_id)

            elif action == 'edit':

                # convert incoming JSON to native struct; clean strings,
                view_json = json.loads(view_json)

                if view_json.get('label'):
                    dashObject.label = view_json['label'].strip()
                if view_json.get('refresh'):
                    dashObject.refresh = int(view_json['refresh'].strip())

                # handle panel reordering; wrap number of columns to the max
                # column constraint
                newPanelDefinition = []
                for row in view_json['new_panel_sequence']:
                    newRow = []
                    for seq in row:
                        newRow.append(dashObject._obj.getPanelBySequence(seq))
                        if len(
                                newRow
                        ) >= splunk.models.dashboard.MAX_DASHBOARD_ROW_SIZE:
                            newPanelDefinition.append(newRow)
                            newRow = []
                    if len(row) > 0:
                        newPanelDefinition.append(newRow)
                dashObject._obj.rows = newPanelDefinition

                # ensure that the row grouping array is synced
                if len(dashObject._obj.rowGrouping) < len(
                        dashObject._obj.rows):
                    dashObject._obj.rowGrouping.extend(
                        [None] * (len(dashObject._obj.rows) -
                                  len(dashObject._obj.rowGrouping)))

                # commit
                dashObject.save()
                output.addInfo(_('Successfully updated %s') % view_id)

            else:
                output.success = False
                output.addError(
                    _('Unrecognized dashboard action: %s; cannot process') %
                    action)
                logger.error(
                    'Unrecognized dashboard action: %s; cannot process' %
                    action)

        except splunk.ResourceNotFound:
            cherrypy.response.status = 404
            output.addWarn(_('"%s" was not found; no action taken') % view_id)

        except Exception, e:
            output.success = False
            output.addError(_('Unable to update view %s: %s') % (view_id, e))
            logger.exception(e)
Exemple #23
0
    def getContainer(self, namespace, view_id, mode='', **unused):
        '''
        Renders the dashboard edit page
        
        GET /<namespace>/<view_id>
            ==> HTML form page with dashboard edit form (labels, panels) and
                master panel edit form (hidden)
            
        GET /api/<namespace>/<view_id>
            ==> JSON structure of dashboard config (unused?)
        '''

        # serve data feed
        output = jsonresponse.JsonResponse()

        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS,
                                       view_id,
                                       namespace=namespace,
                                       owner=username)
            dashObject = Dashboard.get(dash_id)
            output.data = dashObject._obj.toJsonable()

        except splunk.ResourceNotFound:
            cherrypy.response.status = 404
            output.success = False
            output.addError(_('View %s was not found') % view_id)
            return self.render_json(output)

        # serve template page
        if cherrypy.request.is_api:
            return self.render_json(output)
        else:
            cherrypy.response.headers['content-type'] = MIME_HTML

            # get supporting assets

            savedSearches = en.getEntities('saved/searches',
                                           namespace=namespace,
                                           count=-1,
                                           search="is_visible=1")

            for savedSearch in savedSearches:
                acl = savedSearches[savedSearch]['eai:acl']
                if dashObject.metadata.sharing == 'user':
                    continue
                if dashObject.metadata.sharing == 'app' and acl[
                        'sharing'] == 'user':
                    savedSearches[savedSearch]['dq'] = True
                    continue
                if dashObject.metadata.sharing == 'global' and acl[
                        'sharing'] != 'global':
                    savedSearches[savedSearch]['dq'] = True
                    continue
                if dashObject.metadata.perms['read'].count(
                        '*') > 0 and acl['perms']['read'].count('*') == 0:
                    savedSearches[savedSearch]['dq'] = True
                    continue

            #dashboardObject = splunk.entity.getEntity('data/ui/views', view_id, namespace=APP['id'], owner=cherrypy.session['user'].get('name'))
            #dashOwner = dashboardObject['eai:acl'].get('owner', 'nobody')

            editLink = self.make_url(
                ['manager', namespace, 'data/ui/views', view_id],
                _qs=dict(action='edit',
                         url=self.make_url(['app', namespace, view_id]),
                         redirect_override="/app/%s/%s" %
                         (namespace, view_id)))

            permissionsLink = self.make_url(
                [
                    'manager', 'permissions', namespace, 'data/ui/views',
                    view_id
                ],
                _qs=dict(
                    uri=en.buildEndpoint('data/ui/views',
                                         view_id,
                                         namespace=namespace,
                                         owner=dashObject.metadata.owner)))

            return self.render_template(
                'viewmaster/edit_dashboard.html', {
                    'namespace': namespace,
                    'view_id': view_id,
                    'view_object': dashObject._obj,
                    'APP': {
                        'id': namespace
                    },
                    'savedSearches': savedSearches,
                    'editLink': editLink,
                    'permissionsLink': permissionsLink,
                    'mode': mode,
                })
Exemple #24
0
    def createContainer(self,
                        namespace,
                        view_id='',
                        view_label='',
                        container_type='dashboard'):
        '''
        Handles dashboard creation
        
        GET /<namespace>
            ==> HTML template form to input create data
            
        POST /<namespace>
            ==> Saves the HTML input values from GET
            
            == returns JSON response
        '''

        #
        # serve template
        #

        if cherrypy.request.method == 'GET':
            return self.render_template('viewmaster/create_dashboard.html',
                                        {'namespace': namespace})

        #
        # handle create view
        #

        output = jsonresponse.JsonResponse()

        # clean inputs
        view_id = re.sub(r'[^\w]', '', view_id)
        view_label = view_label.strip() or view_id

        if view_id == '':
            output.success = False
            output.addError(_('Dashboard ID cannot be empty'))
            return self.render_json(output)

        # check that view doesn't already exist
        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS,
                                       view_id,
                                       namespace=namespace,
                                       owner=username)
            Dashboard.get(dash_id)
            output.success = False
            output.addError(
                _('Cannot create new %(container_type)s: %(view_id)s already exists') \
                % {'container_type': container_type, 'view_id': view_id})
            return self.render_json(output)

        except splunk.ResourceNotFound:
            pass

        # generate new
        try:
            view = Dashboard(namespace, username, view_id)
            view.label = view_label
            view.save()

            output.data = {'view_id': view_id, 'view_label': view_label}
            output.addInfo(_('Successfully created new %(container_type)s: %(view_id)s') \
                % {'container_type': container_type, 'view_id': view_id})
            logger.info('Created new %s: namespace=%s id=%s label=%s' %
                        (container_type, namespace, view_id, view_label))

        except Exception, e:
            logger.exception(e)
            output.success = False
            output.addError(_('Unable to create dashboard: %s') % e)
    def setContainer(self, namespace, view_id, action, view_json=None):
        '''
        Provides support to modify dashboard configs
        
        POST /<namespace>/<view_id>
            &action=delete
                --> deletes the current view
            &action=edit
                --> updates the current view config (view JSON object)
                
            ==> returns a JSON response
        '''

        output = jsonresponse.JsonResponse()

        try:

            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS, view_id, namespace=namespace, owner=username)
            dashObject = Dashboard.get(dash_id)

            if action == 'delete':
                dashObject.delete()
                output.addInfo(_('Successfully deleted %s') % view_id)

            elif action == 'edit':

                # convert incoming JSON to native struct; clean strings, 
                view_json = json.loads(view_json)

                if view_json.get('label'):
                    dashObject.label = view_json['label'].strip()
                if view_json.get('refresh'):
                    dashObject.refresh = int(view_json['refresh'].strip())
                    
                # handle panel reordering; wrap number of columns to the max
                # column constraint
                newPanelDefinition = []
                for row in view_json['new_panel_sequence']:
                    newRow = []
                    for seq in row:
                        newRow.append(dashObject._obj.getPanelBySequence(seq))
                        if len(newRow) >= splunk.models.dashboard.MAX_DASHBOARD_ROW_SIZE:
                            newPanelDefinition.append(newRow)
                            newRow = []
                    if len(row) > 0:
                        newPanelDefinition.append(newRow)
                dashObject._obj.rows = newPanelDefinition
                
                # ensure that the row grouping array is synced
                if len(dashObject._obj.rowGrouping) < len(dashObject._obj.rows):
                    dashObject._obj.rowGrouping.extend([None] * (len(dashObject._obj.rows) - len(dashObject._obj.rowGrouping)))

                # commit
                dashObject.save()
                output.addInfo(_('Successfully updated %s') % view_id)

            else:
                output.success = False
                output.addError(_('Unrecognized dashboard action: %s; cannot process') % action)
                logger.error('Unrecognized dashboard action: %s; cannot process' % action)

        except splunk.ResourceNotFound:
            cherrypy.response.status = 404
            output.addWarn(_('"%s" was not found; no action taken') % view_id)

        except Exception, e:
            output.success = False
            output.addError(_('Unable to update view %s: %s') % (view_id, e))
            logger.exception(e)
    def getContainer(self, namespace, view_id, mode='', **unused):
        '''
        Renders the dashboard edit page
        
        GET /<namespace>/<view_id>
            ==> HTML form page with dashboard edit form (labels, panels) and
                master panel edit form (hidden)
            
        GET /api/<namespace>/<view_id>
            ==> JSON structure of dashboard config (unused?)
        '''
        
        # serve data feed
        output = jsonresponse.JsonResponse()

        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS, view_id, namespace=namespace, owner=username)
            dashObject = Dashboard.get(dash_id)
            output.data = dashObject._obj.toJsonable()

        except splunk.ResourceNotFound:
            cherrypy.response.status = 404
            output.success = False
            output.addError(_('View %s was not found') % view_id)
            return self.render_json(output)


        # serve template page
        if cherrypy.request.is_api:
            return self.render_json(output)
        else:
            cherrypy.response.headers['content-type'] = MIME_HTML

            # get supporting assets
            
            savedSearches = en.getEntities('saved/searches', 
                namespace=namespace, 
                count=-1, 
                search="is_visible=1")
            
            for savedSearch in savedSearches:
                acl = savedSearches[savedSearch]['eai:acl']
                if dashObject.metadata.sharing=='user':
                    continue
                if dashObject.metadata.sharing=='app' and acl['sharing']=='user':
                    savedSearches[savedSearch]['dq'] = True
                    continue
                if dashObject.metadata.sharing=='global' and acl['sharing']!='global':
                    savedSearches[savedSearch]['dq'] = True
                    continue
                if hasattr(dashObject.metadata.perms, 'read') and hasattr(acl['perms'], 'read'):
                    if dashObject.metadata.perms['read'].count('*')>0 and acl['perms']['read'].count('*')==0:
                        savedSearches[savedSearch]['dq'] = True
                        continue
                  
            #dashboardObject = splunk.entity.getEntity('data/ui/views', view_id, namespace=APP['id'], owner=cherrypy.session['user'].get('name'))
            #dashOwner = dashboardObject['eai:acl'].get('owner', 'nobody')

            editLink = self.make_url(
                ['manager', namespace, 'data/ui/views', view_id], 
                _qs=dict(
                    action='edit', 
                    url=self.make_url(['app', namespace, view_id]), 
                    redirect_override="/app/%s/%s" % (namespace, view_id)
                )
            )
            
            permissionsLink = self.make_url(
                ['manager', 'permissions', namespace, 'data/ui/views', view_id], 
                _qs=dict(
                    uri=en.buildEndpoint('data/ui/views', view_id, namespace=namespace, 
                    owner=dashObject.metadata.owner)
                )
            ) 

            return self.render_template('viewmaster/edit_dashboard.html', 
                {
                    'namespace': namespace,
                    'view_id': view_id,
                    'view_object': dashObject._obj,
                    'APP': {'id': namespace},
                    'savedSearches': savedSearches,
                    'editLink': editLink,
                    'permissionsLink': permissionsLink,
                    'mode': mode,
                })
Exemple #27
0
 def delete(self, app, action, **params):
     SavedSearch.get(params.get('id')).delete()
     dashboard_id = params.get('dashboard_id')
     if dashboard_id:
         Dashboard.get(dashboard_id).delete()
     raise cherrypy.HTTPRedirect(self.make_url(['dashboardwizard', app, 'step1', 'new']), 303) 
Exemple #28
0
 def delete(self, app, action, **params):
     SavedSearch.get(params.get('id')).delete()
     dashboard_id = params.get('dashboard_id')
     if dashboard_id:
         Dashboard.get(dashboard_id).delete()
     raise cherrypy.HTTPRedirect(self.make_url(['dashboardwizard', app, 'step1', 'new']), 303) 
Exemple #29
0
 def success(self, app, action, **params):
     saved_search = SavedSearch.get(params.get('search_id'))
     dashboard = Dashboard.get(params.get('dashboard_id'))
     return self.render_template('dashboardwizard/success.html', dict(app=app, saved_search=saved_search, dashboard=dashboard))
    def createContainer(self, namespace, view_id='', view_label='', container_type='dashboard'):
        '''
        Handles dashboard creation
        
        GET /<namespace>
            ==> HTML template form to input create data
            
        POST /<namespace>
            ==> Saves the HTML input values from GET
            
            == returns JSON response
        '''

        #
        # serve template
        #
        
        if cherrypy.request.method == 'GET':
            return self.render_template('viewmaster/create_dashboard.html', {'namespace': namespace})
        
            
        #
        # handle create view
        #
        
        output = jsonresponse.JsonResponse()

        # clean inputs
        view_id = re.sub(r'[^\w]', '', view_id)
        view_label = view_label.strip() or view_id
        
        if view_id == '':
            output.success = False
            output.addError(_('Dashboard ID cannot be empty'))
            return self.render_json(output)
            
        # check that view doesn't already exist
        try:
            username = cherrypy.session['user'].get('name')
            dash_id = en.buildEndpoint(VIEW_ENTITY_CLASS, view_id, namespace=namespace, owner=username)
            Dashboard.get(dash_id)
            output.success = False
            output.addError(
                _('Cannot create new %(container_type)s: %(view_id)s already exists') \
                % {'container_type': container_type, 'view_id': view_id})
            return self.render_json(output)

        except splunk.ResourceNotFound:
            pass

        # generate new
        try:
            view = Dashboard(namespace, username, view_id)
            view.label = view_label
            view.save()

            output.data = {'view_id': view_id, 'view_label': view_label}
            output.addInfo(_('Successfully created new %(container_type)s: %(view_id)s') \
                % {'container_type': container_type, 'view_id': view_id})
            logger.info('Created new %s: namespace=%s id=%s label=%s' % (container_type, namespace, view_id, view_label))

        except Exception, e:
            logger.exception(e)
            output.success = False
            output.addError(_('Unable to create dashboard: %s') % e)
Exemple #31
0
 def success(self, app, action, **params):
     saved_search = SavedSearch.get(params.get('search_id'))
     dashboard = Dashboard.get(params.get('dashboard_id'))
     return self.render_template('dashboardwizard/success.html', dict(app=app, saved_search=saved_search, dashboard=dashboard))