Splunk Dev

reliable way for custom python code to edit a savedsearch

sideview
SplunkTrust
SplunkTrust

I'm trying to get a python endpoint on a custom module that can basically take an existing savedsearch and make some simple edits to it. I actually had such a thing working for a long time but it seems that at some point (possibly 5.0), the getEntity/setEntity methods starting behaving inconsistently.

When I run this code in 5.0, if the user does not have the ability to create alerts, then even if it's a search that they themselves saved, when the same entity comes back through setEntity it generates an error that "action.email" is not a valid argument. This error message is implying that the user has attempted to save an alert, but it's no more an alert than it was when it came out of getEntity.

# Copyright (C) 2010-2013 Sideview LLC.  All Rights Reserved.
import cherrypy, logging
import controllers.module as module
import splunk.auth as auth
import splunk.entity as entity
import urllib, json
import splunk

#logger = logging.getLogger('splunk.modules.CustomRESTForSavedSearch.foo')

SAVED_SEARCHES_PATH = 'saved/searches'

class CustomRESTForSavedSearch(module.ModuleHandler):

    def generateResults(self,app,savedSearchName,serializedContext,editView, **args):

        response = {}

        currentUser = auth.getCurrentUser()['name']
        sessionKey  = cherrypy.session['sessionKey']
        try :
            ss = entity.getEntity(SAVED_SEARCHES_PATH, savedSearchName, namespace=app, owner=currentUser, sessionKey=sessionKey)
        except Exception, e:
            response["hypothesis"] = "saved search name incorrect"
            response["message"] = str(e)
            response["success"] = False
            return json.dumps(response)

        ss["search"] = ss["search"]
        ss["request.ui_context"] = serializedContext
        ss["request.ui_edit_view"] = editView

        try :
            response["success"] = str(entity.setEntity(ss))
        except Exception, e:
            response["message"] = str(e)
            response["success"] = False

        return json.dumps(response)

I see this sort of thing looks very easy in the Python SDK, and there's a good set of examples http://dev.splunk.com/view/SP-CAAAEK2 . Unfortunately it seems that the way you connect to Splunk in the Python SDK requires hardcoding username and password which wont work. ( http://dev.splunk.com/view/SP-CAAAEE4 )

Can anybody shed some light on a nice simple direction to pull down an existing savedsearch and make an edit and save it? Or can anyone point me in the right direction on how to make my existing code work? I'm really sick of the Entity class and I'd be happy to get rid of it, but if I can make it work I'll also happily stick with it.

Thanks in advance.

PS. In entity.py, there's this line logger.debug("entity.setEntity() is deprecated") but unfortunately it doesn't leave anyone the wiser as to what to use instead of setEntity.

Tags (2)

sideview
SplunkTrust
SplunkTrust

I've posted the solution I ended up finding, in case it helps someone else.

I ended up using the Splunk model classes because the base SavedSearch model makes great efforts to avoid this specific problem around saving savedsearches. Interestingly, although setEntity is marked as deprecated, its used by the Splunk model code as well and I was unable to find anything that might be used to replace it, save using the REST API directly. Since everything in Splunk that touches manager entities uses either setEntity or model objects, the deprecation of setEntity seems a bit arguable. Also I was able to establish that the cause of the problem has nothing to do with setEntity per se, but rather with the actual REST API for savedsearches. Thus even if you were to use the REST API directly you'd hit the same problem.

# Copyright (C) 2010-2013 Sideview LLC.  All Rights Reserved.
import cherrypy, logging
import controllers.module as module
import splunk.auth as auth
import splunk.entity as entity

from splunk.models.saved_search import *

import json



class SideviewUI(UI):

    dispatch_view = Field('request.ui_dispatch_view')
    display_view  = Field('displayview')
    vsid          = None
    ui_context    = Field('request.ui_context')
    edit_view     = Field('request.ui_edit_view')

logger = logging.getLogger('splunk.appserver')


class SideviewSavedSearch(SavedSearch):
    resource = 'saved/searches'
    search      = Field()
    description = Field()
    dispatch    = DispatchField()
    schedule    = ScheduleField()
    action      = ActionField()
    alert       = AlertField()
    is_disabled = BoolField('disabled')
    ui          = SideviewUI()

    # AutoSummarization is a 5.0 only feature
    # this is sufficient to maintain support on 4.3.X
    try: 
        auto_summarize = AutoSummarizeField()
    except NameError,e:
        pass

SAVED_SEARCHES_PATH = 'saved/searches'

class CustomRESTForSavedSearch(module.ModuleHandler):

    def generateResults(self,app,savedSearchName,serializedContext,editView, **args):

        response = {}

        currentUser = auth.getCurrentUser()['name']
        sessionKey  = cherrypy.session['sessionKey']

        try :
            ssEntity = entity.getEntity(SAVED_SEARCHES_PATH, savedSearchName, namespace=app, owner=currentUser, sessionKey=sessionKey)
        except Exception, e:
            response["hypothesis"] = "is the saved search name incorrect?"
            response["message"] = str(e)
            response["success"] = False
            return json.dumps(response)

        params = {}
        params['name'] = savedSearchName
        ssModel = SideviewSavedSearch(app, currentUser, **params)

        ssModel.from_entity(ssEntity)

        ssModel.ui.ui_context = serializedContext
        ssModel.ui.edit_view = editView

        if ssModel.passive_save():
            response["success"] = True
        else :
            response["success"] = False
            response["message"] = "Error: we failed to inject the extra Sideview keys needed to correctly reload the savedsearch in this view."

        return json.dumps(response)
Get Updates on the Splunk Community!

.conf24 | Registration Open!

Hello, hello! I come bearing good news: Registration for .conf24 is now open!   conf is Splunk’s rad annual ...

ICYMI - Check out the latest releases of Splunk Edge Processor

Splunk is pleased to announce the latest enhancements to Splunk Edge Processor.  HEC Receiver authorization ...

Introducing the 2024 SplunkTrust!

Hello, Splunk Community! We are beyond thrilled to announce our newest group of SplunkTrust members!  The ...