示例#1
0
def parseSearchToXML(search, hostPath=None, sessionKey=None, parseOnly='t', namespace=None, owner=None):
    """
        Given a valid search string, return the XML from the splunk parsing endpoint that
        represents the search.
    """

    if search == None or len(search) == 0:
        return None
    
    if not owner: owner = auth.getCurrentUser()['name']
    
    uri = entity.buildEndpoint('/search/parser', namespace=namespace, owner=owner)
    if hostPath:
        uri = splunk.mergeHostPath(hostPath) + uri

    args = {
        'q'             : search,
        'parse_only'    : parseOnly
    }

    serverResponse, serverContent = rest.simpleRequest(uri, getargs=args, sessionKey=sessionKey)
    #print "SERVERCONTENT:", serverContent
    # normal messages from splunkd are propogated via SplunkdException;
    if 400 <= serverResponse.status < 500:
        root = et.fromstring(serverContent)
        extractedMessages = rest.extractMessages(root)
        for msg in extractedMessages:
            raise splunk.SearchException, msg['text']

    return serverContent
示例#2
0
def commitChanges(app, view, uglyXML, updateMetaData, fileNameForNewView=None):
    removeIdsFromAllModules(uglyXML)

    # plan A
    uglyXML = uglyXML.toxml()
    parser = et.XMLParser(remove_blank_text=True, strip_cdata=False)
    etXML = et.XML(uglyXML, parser)
    prettyXML = et.tostring(etXML, pretty_print=True)

    # plan B
    #prettyXML = uglyXML.toprettyxml(indent="  ")

    prettyXML = patchXMLForReadability(prettyXML)

    viewEntity = en.getEntity('data/ui/views', view, namespace=app)

    garbagePropertiesReturnedBySplunk6Beta = [
        "isDashboard", "isVisible", "label"
    ]
    for p in garbagePropertiesReturnedBySplunk6Beta:
        if (viewEntity.properties.get(p)):
            logger.warn(
                "Sideview Editor - garbage property detected in the getEntity response ("
                + p +
                "). We are deleting it here or else it will correctly trigger an error from splunkd when we try to post the modified entity back via setEntity"
            )
            del (viewEntity.properties[p])

    # in the create new cases, view will be "_new"
    if (fileNameForNewView):
        viewEntity.properties["name"] = fileNameForNewView

    viewEntity[en.EAI_DATA_KEY] = prettyXML

    currentUser = auth.getCurrentUser()['name']
    try:
        en.setEntity(viewEntity)

        ## remnants of some 4.X logging insanity where I never got a handle on root cause.
        try:
            logger.info("view updated by Sideview Editor. view=" + str(view) +
                        " user="******" " +
                        str(updateMetaData))
        except Exception, e:
            logger.error("exception trying to log view update. " + str(view) +
                         " user="******"exception trying to update view.  view=" + str(view) +
                     " user="******" message=" + str(e))
        logger.error(traceback.print_exc(e))
        return e
    def _hasReadPerms(self):
        '''
        Use services/server/settings as a proxy for read permissions.
        '''

        # NOTE:Due SPL-21113 BETA: unify ACL actions to read/write we cannot use the settings endpoint defer to user admin for now.
        return True if 'admin' == au.getCurrentUser()['name'] else False

        entity = None
        try:
            entity = en.getEntity('/server/', 'settings', namespace=splunk.getDefault('namespace'))
        except Exception, e:
            return False
示例#4
0
    def _hasReadPerms(self):
        '''
        Use services/server/settings as a proxy for read permissions.
        '''
        
        # NOTE:Due SPL-21113 BETA: unify ACL actions to read/write we cannot use the settings endpoint defer to user admin for now.
        return True if 'admin' == au.getCurrentUser()['name'] else False

        entity = None
        try:
            entity = en.getEntity('/server/', 'settings', namespace=splunk.getDefault('namespace'))
        except Exception, e:
            return False
示例#5
0
文件: models.py 项目: TPLink32/spnk1
 def all(cls, namespace=None, default_owner='-', *args, **kwargs):
     """
     Gets us SOLNQuerySets instead of SplunkQuerySets as per normal
     Note that the kwargs allow for host_path and sessionKey to be set for remote hosts
     """
     manager = SOLNRESTManager(cls, **kwargs)
     sqs = SOLNQuerySet(manager, **kwargs)
     # can set namespace='-' here so that stanzas in different namespace will not be merged
     sqs._namespace = namespace
     sqs._owner = auth.getCurrentUser()['name']
     if sqs._owner == 'UNDEFINED_USERNAME':
         sqs._owner = default_owner
     return sqs.all(*args, **kwargs)
示例#6
0
    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)
 def reset(self, **kwargs):
     '''
     Resets the user space to a clean state; usually used for testingm
     '''
     has_perms = True if 'admin'==au.getCurrentUser()['name'] else False
     jobs_cancelled = []
     if has_perms and cherrypy.request.method=='POST':
         jobs = se.listJobs()
         for job in jobs:
             try:
                 j = se.getJob(job['sid'])
                 j.cancel()
                 jobs_cancelled.append(job['sid'])
             except splunk.ResourceNotFound:
                 continue
     return self.render_template('debug/reset.html', {
         'has_perms': has_perms,
         'method': cherrypy.request.method,
         'jobs_cancelled': jobs_cancelled
     })
示例#8
0
 def reset(self, **kwargs):
     '''
     Resets the user space to a clean state; usually used for testingm
     '''
     has_perms = True if 'admin'==au.getCurrentUser()['name'] else False
     jobs_cancelled = []
     if has_perms and cherrypy.request.method=='POST':
         jobs = se.listJobs()
         for job in jobs:
             try:
                 j = se.getJob(job['sid'])
                 j.cancel()
                 jobs_cancelled.append(job['sid'])
             except splunk.ResourceNotFound:
                 continue
     return self.render_template('debug/reset.html', {
         'has_perms': has_perms,
         'method': cherrypy.request.method,
         'jobs_cancelled': jobs_cancelled
     })
示例#9
0
def parseSearchToXML(search,
                     hostPath=None,
                     sessionKey=None,
                     parseOnly='t',
                     timeline=None,
                     namespace=None,
                     owner=None):
    """
        Given a valid search string, return the XML from the splunk parsing endpoint that
        represents the search.
    """

    if search == None or len(search) == 0:
        return None

    if not owner: owner = auth.getCurrentUser()['name']

    uri = entity.buildEndpoint('/search/parser',
                               namespace=namespace,
                               owner=owner)
    if hostPath:
        uri = splunk.mergeHostPath(hostPath) + uri

    args = {'q': search, 'parse_only': parseOnly}

    if timeline is not None:
        args['timeline'] = timeline

    serverResponse, serverContent = rest.simpleRequest(uri,
                                                       getargs=args,
                                                       sessionKey=sessionKey)
    #print "SERVERCONTENT:", serverContent
    # normal messages from splunkd are propogated via SplunkdException;
    if 400 <= serverResponse.status < 500:
        root = et.fromstring(serverContent)
        extractedMessages = rest.extractMessages(root)
        for msg in extractedMessages:
            raise splunk.SearchException, msg['text']

    return serverContent
        Use services/server/settings as a proxy for read permissions.
        '''

        # NOTE:Due SPL-21113 BETA: unify ACL actions to read/write we cannot use the settings endpoint defer to user admin for now.
        return True if 'admin' == au.getCurrentUser()['name'] else False

        entity = None
        try:
            entity = en.getEntity('/server/', 'settings', namespace=splunk.getDefault('namespace'))
        except Exception, e:
            return False
        if not entity['eai:acl']:
            return False
        if not entity['eai:acl']['perms']:
            return False
        if au.getCurrentUser()['name'] in entity['eai:acl']['perms'].get('read', []):
            return True
        else:
            return False

    def find_unittests(self, path, ext='.html', staticBase=True):
        relativePath = path.strip('/\\')
        extension = ext

        if staticBase:
            testFileDir = os.path.join(cherrypy.config['staticdir'], relativePath)
        else:
            testFileDir = os.path.join(self.get_qunit_base_path(), relativePath)
        logger.debug('Fetching HTML test files from: %s' % testFileDir)

        output = []
示例#11
0
        Use services/server/settings as a proxy for read permissions.
        '''
        
        # NOTE:Due SPL-21113 BETA: unify ACL actions to read/write we cannot use the settings endpoint defer to user admin for now.
        return True if 'admin' == au.getCurrentUser()['name'] else False

        entity = None
        try:
            entity = en.getEntity('/server/', 'settings', namespace=splunk.getDefault('namespace'))
        except Exception, e:
            return False
        if not entity['eai:acl']:
            return False
        if not entity['eai:acl']['perms']:
            return False
        if au.getCurrentUser()['name'] in entity['eai:acl']['perms'].get('read', []):
            return True
        else:
            return False
        
    def find_unittests(self, path, ext='.html', staticBase=True):
        relativePath = path.strip('/\\')
        extension = ext
        
        if staticBase:
            testFileDir = os.path.join(cherrypy.config['staticdir'], relativePath)
        else:
            testFileDir = os.path.join(util.make_absolute(cherrypy.config.get('templates', 'share/splunk/search_mrsparkle/templates')), relativePath)
        logger.debug('Fetching HTML test files from: %s' % testFileDir)
        
        output = []
示例#12
0
        try:
            return handleShowConf(restArgList['name'], sessionKey, namespace,
                                  owner)
        except splunk.ResourceNotFound:
            #can throw this error if we try and show a non-existent config
            displayResourceError(cmd=cmd,
                                 obj=obj,
                                 uri=restArgList['name'],
                                 serverContent=None)
            return
    #show:default-index has already been done for us, reuse it
    elif '%s:%s' % (cmd, obj) == 'show:default-index':
        defIndexList = []
        try:
            #first get the role associated with this user
            roles = auth.getUser(auth.getCurrentUser()['name'],
                                 sessionKey=sessionKey)['roles']
            #get details of each role
            for role in roles:
                indexes = auth.getRole(
                    role, sessionKey=sessionKey)['srchIndexesDefault']
                for index in indexes:
                    defIndexList.append(index)
        except:
            pass
        DISPLAY_CHARS[endpoint](cmd=cmd,
                                obj=obj,
                                sessionKey=sessionKey,
                                defIndex=defIndexList)

    #handle sync/async search
示例#13
0
 if cmd == 'help':
    return handleHelp(endpoint, restArgList)
 #extraction of properties has already been written for us, so reuse it
 elif '%s:%s' % (cmd,obj) == 'show:config':
    try:
       return handleShowConf(restArgList['name'], sessionKey, namespace, owner)
    except splunk.ResourceNotFound:
       #can throw this error if we try and show a non-existent config
       displayResourceError(cmd=cmd, obj=obj, uri=restArgList['name'], serverContent=None)
       return 
 #show:default-index has already been done for us, reuse it
 elif '%s:%s' % (cmd,obj) == 'show:default-index':
    defIndexList = []
    try:
       #first get the role associated with this user
       roles = auth.getUser(auth.getCurrentUser()['name'], sessionKey=sessionKey)['roles']
       #get details of each role
       for role in roles:
          indexes = auth.getRole(role, sessionKey=sessionKey)['srchIndexesDefault']
          for index in indexes:
             defIndexList.append(index)
    except:
       pass  
    DISPLAY_CHARS[endpoint](cmd=cmd, obj=obj, sessionKey=sessionKey, defIndex=defIndexList)
    
 #handle sync/async search
 elif cmd in ['search', 'dispatch']:
    if not restArgList['terms'].strip():
      displayGenericError(cmd=cmd, terms='') 
      return  
    if restArgList.has_key('detach') and restArgList['detach'] == 'true':