def getEntity(entityPath, entityName, uri=None, namespace=None, owner=None, sessionKey=None, hostPath=None, **kwargs): ''' Retrieves a generic Splunkd entity from the REST endpoint @param entityPath: the class of objects to retrieve @param entityName: the specific name of the entity to retrieve @param namespace: the namespace within which to look for the entities. if None, then pull from merged @param owner: the owner within which to look for the entity. defaults to current user ''' # get default params if not owner: owner = auth.getCurrentUser()['name'] if not uri: if not entityName: raise ValueError, "entityName cannot be empty" uri = buildEndpoint(entityPath, entityName=entityName, namespace=namespace, owner=owner, hostPath=hostPath) serverResponse, serverContent = rest.simpleRequest(uri, getargs=kwargs, sessionKey=sessionKey, raiseAllErrors=True) if serverResponse.status != 200: logger.warn('getEntity - unexpected HTTP status=%s while fetching "%s"' % (serverResponse.status, uri)) atomEntry = rest.format.parseFeedDocument(serverContent) if isinstance(atomEntry, rest.format.AtomFeed): try: atomEntry = atomEntry[0] except IndexError, e: # Handle cases where no entry is found return None
def get(self): user = auth.getCurrentUser() name = "Web" if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() try: device = models.getDevice("%s/%s" % (user.email(), name)) except models.DeviceDoesNotExistError: device = models.DeviceData(user=user_data, name=name).save() over_quota = False try: channel = channels.Channel(device.address, override_quota=user_data.immune()) channel_token = channel.token except channels.OverQuotaError: over_quota = True channel_token = "overquota" template_values = { "channel_id": channel_token, "device": device.address, "device_name": device.name, "devices": user_data.getDevices(), "over_quota": over_quota, } path = os.path.join(os.path.dirname(__file__), "devlinks_index.html") self.response.out.write(template.render(path, template_values)) else: self.redirect(users.create_login_url(self.request.uri))
def add(apikey, body): currentUser = getCurrentUser() print('current user is {cu}'.format(cu=currentUser)) for thing in body: thing.update({'user': currentUser}) print('body is {a}'.format(a=body)) return buildResponse(addRows(__tablename, body))
def get(self, name=False): self.response.headers.add_header("Access-Control-Allow-Origin", "*") user = auth.getCurrentUser() response = {} if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() if not name: name = "Chrome" try: device = models.getDevice("%s/%s" % (user.email(), name)) except models.DeviceDoesNotExistError: device = models.DeviceData(user=user_data, name=name).save() try: channel = channels.Channel(device.address, override_quota=user_data.immune()) response['token'] = channel.token if channel.cached: response['code'] = 304 else: response['code'] = 200 except channels.OverQuotaError: response['code'] = 503 response['token'] = 'overquota' response['message'] = "Server is over quota." else: response['code'] = 401 response['message'] = 'Not logged in.' self.response.out.write(simplejson.dumps(response))
def get(self): user = auth.getCurrentUser() name = "Web" if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() try: device = models.getDevice("%s/%s" % (user.email(), name)) except models.DeviceDoesNotExistError: device = models.DeviceData(user=user_data, name=name).save() over_quota = False try: channel = channels.Channel(device.address, override_quota=user_data.immune()) channel_token = channel.token except channels.OverQuotaError: over_quota = True channel_token = 'overquota' template_values = { 'channel_id': channel_token, 'device': device.address, 'device_name': device.name, 'devices': user_data.getDevices(), 'over_quota': over_quota } path = os.path.join(os.path.dirname(__file__), 'devlinks_index.html') self.response.out.write(template.render(path, template_values)) else: self.redirect(users.create_login_url(self.request.uri))
def get(self, name=False): self.response.headers.add_header("Access-Control-Allow-Origin", "*") user = auth.getCurrentUser() response = {} if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() if not name: name = "Chrome" try: device = models.getDevice("%s/%s" % (user.email(), name)) except models.DeviceDoesNotExistError: device = models.DeviceData(user=user_data, name=name).save() try: channel = channels.Channel(device.address, override_quota=user_data.immune()) response["token"] = channel.token if channel.cached: response["code"] = 304 else: response["code"] = 200 except channels.OverQuotaError: response["code"] = 503 response["token"] = "overquota" response["message"] = "Server is over quota." else: response["code"] = 401 response["message"] = "Not logged in." self.response.out.write(simplejson.dumps(response))
def _getEntitiesAtomFeed(entityPath, namespace=None, owner=None, search=None, count=None, offset=0, sort_key=None, sort_dir=None , sessionKey=None, uri=None, hostPath=None, **kwargs): # fallback to currently authed user if not owner: owner = auth.getCurrentUser()['name'] # construct URI to get entities if not uri: uri = buildEndpoint(entityPath, namespace=namespace, owner=owner, hostPath=hostPath) if search: kwargs["search"] = search if count != None: kwargs["count"] = count if offset: kwargs["offset"] = offset if sort_key: kwargs["sort_key"] = sort_key if sort_dir: kwargs["sort_dir"] = sort_dir # fetch list of entities serverResponse, serverContent = rest.simpleRequest(uri, getargs=kwargs, sessionKey=sessionKey, raiseAllErrors=True) if serverResponse.status != 200: raise splunk.RESTException, (serverResponse.status, serverResponse.messages) atomFeed = rest.format.parseFeedDocument(serverContent) return atomFeed
def process_request(self, request): assert hasattr(request, 'session'), "The Django authentication middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'." from auth import getCurrentUser request.user = getCurrentUser() from google.appengine.api import users request.is_admin = users.is_current_user_admin() return None
def getConf(confName, sessionKey=None, namespace=None, owner=None, overwriteStanzas=False, hostPath=None): ''' Parses a logical bundle file and returns a Conf() object If namespace=None, then the behavior is 3.2-style, where all writes are done to conf files in etc/system/local. All reads will merge every conf file that is accessible in etc/system and etc/apps/*. If a namespace is provided, then writes are done in etc/apps/<namespace>/local/, and reads are restricted to values in etc/apps/<namespace>/(default|local). If overwriteStanzas is true, old keys in edited stanzas will not be preserved. For the 3.2-style reading, the endpoint uses the following priority: system/local apps/<namespace>/local apps/<namespace>/default system/default ''' # fallback to current user if not owner: owner = auth.getCurrentUser()['name'] uri = entity.buildEndpoint(entityClass='properties', entityName=confName, namespace=namespace, owner=owner, hostPath=hostPath) # the fillcontents arg will push all stanza keys down in 1 request instead # of iterating over all stanzas serverResponse, serverContent = rest.simpleRequest(uri, getargs={'fillcontents':1}, sessionKey=sessionKey) if serverResponse.status != 200: logger.info('getConf - server returned status=%s when asked for conf=%s' % (serverResponse.status, confName)) # convert the atom feed into dict confFeed = rest.format.parseFeedDocument(serverContent) stanzas = confFeed.toPrimitive() # create Conf/Stanzas output = Conf(confName, namespace=namespace, owner=owner, overwriteStanzas=overwriteStanzas) output.sessionKey = sessionKey output.isImportMode = True for name in stanzas: stanza = output.createStanza(name) stanza.needsPopulation = False for k in stanzas[name]: if stanzas[name][k] == None: stanza[k] = '' else: stanza[k] = stanzas[name][k] output.isImportMode = False return output
def _getEntitiesAtomFeed(entityPath, namespace=None, owner=None, search=None, count=None, offset=0, sort_key=None, sort_dir=None, sessionKey=None, uri=None, hostPath=None, **kwargs): # fallback to currently authed user if not owner: owner = auth.getCurrentUser()['name'] # construct URI to get entities if not uri: uri = buildEndpoint(entityPath, namespace=namespace, owner=owner, hostPath=hostPath) if search: kwargs["search"] = search if count != None: kwargs["count"] = count if offset: kwargs["offset"] = offset if sort_key: kwargs["sort_key"] = sort_key if sort_dir: kwargs["sort_dir"] = sort_dir # fetch list of entities serverResponse, serverContent = rest.simpleRequest(uri, getargs=kwargs, sessionKey=sessionKey, raiseAllErrors=True) if serverResponse.status != 200: raise splunk.RESTException, (serverResponse.status, serverResponse.messages) atomFeed = rest.format.parseFeedDocument(serverContent) return atomFeed
def post(self): user = auth.getCurrentUser() response = {} if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() payment_data = models.PaymentData( date=timestamp.now(), user=user_data, item=self.request.get("item_id"), order_number=self.request.get("order_number"), status="unconfirmed") payment_data.save()
def getEntity(entityPath, entityName, uri=None, namespace=None, owner=None, sessionKey=None, hostPath=None, **kwargs): ''' Retrieves a generic Splunkd entity from the REST endpoint @param entityPath: the class of objects to retrieve @param entityName: the specific name of the entity to retrieve @param namespace: the namespace within which to look for the entities. if None, then pull from merged @param owner: the owner within which to look for the entity. defaults to current user ''' # get default params if not owner: owner = auth.getCurrentUser()['name'] if not uri: if not entityName: raise ValueError, "entityName cannot be empty" uri = buildEndpoint(entityPath, entityName=entityName, namespace=namespace, owner=owner, hostPath=hostPath) serverResponse, serverContent = rest.simpleRequest(uri, getargs=kwargs, sessionKey=sessionKey, raiseAllErrors=True) if serverResponse.status != 200: logger.warn( 'getEntity - unexpected HTTP status=%s while fetching "%s"' % (serverResponse.status, uri)) atomEntry = rest.format.parseFeedDocument(serverContent) if isinstance(atomEntry, rest.format.AtomFeed): try: atomEntry = atomEntry[0] except IndexError, e: # Handle cases where no entry is found return None
def post(self): user = auth.getCurrentUser() response = {} if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() payment_data = models.PaymentData( date=timestamp.now(), user=user_data, item=self.request.get("item_id"), order_number=self.request.get("order_number"), status="unconfirmed", ) payment_data.save()
def post(self): self.response.headers.add_header("Access-Control-Allow-Origin", "*") user = auth.getCurrentUser() response = {} if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() name = self.request.get('name') if not name: name = "Chrome" try: device = models.getDevice("%s/%s" % (user.email(), name)) except models.DeviceDoesNotExistError: device = models.DeviceData(name=name, user=user_data).save() receiver = None if self.request.get("receiver"): try: receiver = models.getDevice( "%s/%s" % (user.email(), self.request.get("receiver"))) except models.DeviceDoesNotExistError: receiver = models.DeviceData( name=self.request.get("receiver"), user=user_data).save() if receiver == None: receiver = device link = models.LinkData(url=self.request.get('link'), sender=device, receiver=receiver).save() if models.getQuota().amount >= models.getStats( 'channels').count or user_data.immune(): channel = channels.Channel(receiver.address, False) channel.sendLink(link) response['code'] = 200 response['link'] = link.url else: response['code'] = 503 response['link'] = link.url else: response['code'] = 401 response['link'] = self.request.get('link') self.response.out.write(simplejson.dumps(response))
def post(self, name="Chrome"): self.response.headers.add_header("Access-Control-Allow-Origin", "*") user = auth.getCurrentUser() device = None if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() try: device = models.getDevice("%s/%s" % (user.email(), name)) except: device = models.DeviceData(user=user_data, name=name).save() last_links = models.getUnreadLinks(device) channel = channels.Channel(device.address, False) for link in last_links: channel.queueLink(link) channel.send() stats.record("user_connected", simplejson.dumps({"user": user.email()})) self.response.out.write(device.address)
def post(self): self.response.headers.add_header("Access-Control-Allow-Origin", "*") user = auth.getCurrentUser() response = {} if user: try: user_data = models.getUser(user) except models.UserDoesNotExistError: user_data = models.UserData(user=user).save() name = self.request.get("name") if not name: name = "Chrome" try: device = models.getDevice("%s/%s" % (user.email(), name)) except models.DeviceDoesNotExistError: device = models.DeviceData(name=name, user=user_data).save() receiver = None if self.request.get("receiver"): try: receiver = models.getDevice("%s/%s" % (user.email(), self.request.get("receiver"))) except models.DeviceDoesNotExistError: receiver = models.DeviceData(name=self.request.get("receiver"), user=user_data).save() if receiver == None: receiver = device link = models.LinkData(url=self.request.get("link"), sender=device, receiver=receiver).save() if models.getQuota().amount >= models.getStats("channels").count or user_data.immune(): channel = channels.Channel(receiver.address, False) channel.sendLink(link) response["code"] = 200 response["link"] = link.url else: response["code"] = 503 response["link"] = link.url else: response["code"] = 401 response["link"] = self.request.get("link") self.response.out.write(simplejson.dumps(response))
def setEntity(entity, sessionKey=None, uri=None, msgObj=None): ''' Commits the properties of a generic entity object ''' if not entity: raise Exception, 'Cannot set entity; no entity provided' if not entity.path: raise Exception, 'Entity does not have path defined' if not entity.name: raise Exception, 'Entity does not have name defined' if not entity.namespace: raise Exception, 'Cannot set entity without a namespace; %s' % entity.name # if editing entities that were owned by the system name, then convert to # to current user if not entity.owner: entity.owner = auth.getCurrentUser()['name'] if not uri: # This is where we determine edit / create behavior. WoNkY! if len(entity.links) > 0: for action, link in entity.links: if action == 'edit': uri = link if uri == None: uri = entity.getFullPath() postargs = entity.getCommitProperties() """ logger.debug("*" * 25) logger.debug("entity: %s." % entity) logger.debug("uri: %s." % uri) logger.debug("postargs: %s." % postargs) logger.debug("*" * 25) """ if not postargs: logger.warn('setEntity - tried to commit empty entity') raise Exception, 'setEntity - tried to commit empty entity' # if exists, then update by POST to own endpoint if rest.checkResourceExists(uri, sessionKey=sessionKey): # EAI sets entity.name to new for the new template... # so it will exist and not fall into the else case # do any of the endpoints used by Entity post back to # a nonexistent name for the create action? # EAI posts to the basePath. if entity.name == '_new': logger.debug("setting properties to create a new guy.") uri = entity.getBasePath() createName = entity.properties['name'] logger.debug("creating %s on %s." % (createName, uri)) entity.name = createName serverResponse, serverContent = rest.simpleRequest( uri, sessionKey=sessionKey, postargs=postargs, raiseAllErrors=True) if (serverResponse.status == 201): if msgObj: msgObj['messages'] = serverResponse.messages if serverResponse.status not in [200, 201]: logger.warn("Server did not return status 200 or 201.") else: try: atomFeed = rest.format.parseFeedDocument(serverContent) entity.id = atomFeed[0].id except Exception, e: pass return True
def getEntities(entityPath, namespace=None, owner=None, search=None, count=None, offset=0, sort_key=None, sort_dir=None, sessionKey=None, uri=None, unique_key='title', hostPath=None, **kwargs): ''' Retrieves generic entities from the Splunkd endpoint, restricted to a namespace and owner context. @param entityPath: the class of objects to retrieve @param namespace: the namespace within which to look for the entities. default set by splunk.getDefault('namespace') @param owner: the owner within which to look for the entity. defaults to current user @param search: simple key=value filter @param offset: the starting index of the first item to return. defaults to 0 @param count: the maximum number of entities to return. defaults to -1 (all) @param sort_key: the key to sort against @param sort_dir: the direction to sort (asc or desc) @param uri: force a specific path to the objects @param unique_key: specify the uniquifying key ''' # fallback to currently authed user if not owner: owner = auth.getCurrentUser()['name'] # construct URI to get entities if not uri: uri = buildEndpoint(entityPath, namespace=namespace, owner=owner, hostPath=hostPath) if search: kwargs["search"] = search if count != None: kwargs["count"] = count if offset: kwargs["offset"] = offset if sort_key: kwargs["sort_key"] = sort_key if sort_dir: kwargs["sort_dir"] = sort_dir # fetch list of entities serverResponse, serverContent = rest.simpleRequest(uri, getargs=kwargs, sessionKey=sessionKey, raiseAllErrors=True) if serverResponse.status != 200: raise splunk.RESTException, (serverResponse.status, serverResponse.messages) atomFeed = rest.format.parseFeedDocument(serverContent) offset = int(atomFeed.os_startIndex or -1) totalResults = int(atomFeed.os_totalResults or -1) itemsPerPage = int(atomFeed.os_itemsPerPage or -1) links = atomFeed.links messages = atomFeed.messages # preserves order of returned elements # EntityCollection is a new subclass or util.OrderedDict, it still preserves # the order, but it allows some additional params to be added on. collection = EntityCollection(None, search, count, offset, totalResults, itemsPerPage, sort_key, sort_dir, links, messages) for atomEntry in atomFeed: contents = atomEntry.toPrimitive() entity = Entity(entityPath, atomEntry.title, contents, namespace) entity.owner = atomEntry.author entity.createTime = atomEntry.published entity.updateTime = atomEntry.updated entity.summary = atomEntry.summary entity.links = atomEntry.links entity.id = atomEntry.id entity.hostPath = hostPath # use the same semantics as in the C++ code: make the first item in the # list win if two stanzas with the same name exist attr = getattr(atomEntry, unique_key) if attr not in collection: collection[attr] = entity return collection
def getConf(confName, sessionKey=None, namespace=None, owner=None, overwriteStanzas=False, hostPath=None): ''' Parses a logical bundle file and returns a Conf() object If namespace=None, then the behavior is 3.2-style, where all writes are done to conf files in etc/system/local. All reads will merge every conf file that is accessible in etc/system and etc/apps/*. If a namespace is provided, then writes are done in etc/apps/<namespace>/local/, and reads are restricted to values in etc/apps/<namespace>/(default|local). If overwriteStanzas is true, old keys in edited stanzas will not be preserved. For the 3.2-style reading, the endpoint uses the following priority: system/local apps/<namespace>/local apps/<namespace>/default system/default ''' # fallback to current user if not owner: owner = auth.getCurrentUser()['name'] uri = entity.buildEndpoint(entityClass='properties', entityName=confName, namespace=namespace, owner=owner, hostPath=hostPath) # the fillcontents arg will push all stanza keys down in 1 request instead # of iterating over all stanzas serverResponse, serverContent = rest.simpleRequest( uri, getargs={'fillcontents': 1}, sessionKey=sessionKey) if serverResponse.status != 200: logger.info( 'getConf - server returned status=%s when asked for conf=%s' % (serverResponse.status, confName)) # convert the atom feed into dict confFeed = rest.format.parseFeedDocument(serverContent) stanzas = confFeed.toPrimitive() # create Conf/Stanzas output = Conf(confName, namespace=namespace, owner=owner, overwriteStanzas=overwriteStanzas) output.sessionKey = sessionKey output.isImportMode = True for name in stanzas: stanza = output.createStanza(name) stanza.needsPopulation = False for k in stanzas[name]: if stanzas[name][k] == None: stanza[k] = '' else: stanza[k] = stanzas[name][k] output.isImportMode = False return output
def setEntity(entity, sessionKey=None, uri=None, msgObj=None, strictCreate=False, filterArguments=None): ''' Commits the properties of a generic entity object ''' logger.debug("entity.setEntity() is deprecated") if not entity: raise Exception, 'Cannot set entity; no entity provided' if not entity.path: raise Exception, 'Entity does not have path defined' if not entity.name: raise Exception, 'Entity does not have name defined' if not entity.namespace: raise Exception, 'Cannot set entity without a namespace; %s' % entity.name # if editing entities that were owned by the system name, then convert to # to current user if not entity.owner: entity.owner = auth.getCurrentUser()['name'] #check if we should filter arguments based on optional/required/wildcardFields #only enabled for datamodel and data/ui/views for now if filterArguments is None: filterArguments = False if entity.path.startswith("data/models") or re.match( "^\/?data\/ui\/views(\/|$)", entity.path) or re.match( "^\/?saved\/searches(\/|$)", entity.path): filterArguments = True tmpEntity = None if not uri: # This is where we determine edit / create behavior. WoNkY! if len(entity.links) > 0: for action, link in entity.links: if action == 'edit': uri = link if uri == None: uri = entity.getFullPath() if filterArguments: tmpEntity = getEntity(entity.path, None, uri=uri + "/_new", sessionKey=sessionKey) if filterArguments and tmpEntity == None: tmpEntity = getEntity(entity.path, entity.name, uri=uri, sessionKey=sessionKey) if filterArguments: postargs = entity.getCommitProperties( optionalFields=tmpEntity.optionalFields, requiredFields=tmpEntity.requiredFields, wildcardFields=tmpEntity.wildcardFields, isACL=uri.endswith('/acl'), filterArguments=filterArguments) else: postargs = entity.getCommitProperties() """ logger.debug("*" * 25) logger.debug("entity: %s." % entity) logger.debug("uri: %s." % uri) logger.debug("postargs: %s." % postargs) logger.debug("*" * 25) """ if not postargs: logger.warn('setEntity - tried to commit empty entity') raise Exception, 'setEntity - tried to commit empty entity' # if exists, then update by POST to own endpoint if rest.checkResourceExists(uri, sessionKey=sessionKey) and not strictCreate: # EAI sets entity.name to new for the new template... # so it will exist and not fall into the else case # do any of the endpoints used by Entity post back to # a nonexistent name for the create action? # EAI posts to the basePath. if entity.name == '_new': logger.debug("setting properties to create a new guy.") uri = entity.getBasePath() createName = entity.properties['name'] logger.debug("creating %s on %s." % (createName, uri)) entity.name = createName serverResponse, serverContent = rest.simpleRequest( uri, sessionKey=sessionKey, postargs=postargs, raiseAllErrors=True) if (serverResponse.status == 201): if msgObj: msgObj['messages'] = serverResponse.messages if serverResponse.status not in [200, 201]: logger.warn("Server did not return status 200 or 201.") else: try: atomFeed = rest.format.parseFeedDocument(serverContent) entity.id = atomFeed[0].id except Exception, e: pass return True
def setEntity(entity, sessionKey=None, uri=None, msgObj=None, strictCreate=False, filterArguments=None): ''' Commits the properties of a generic entity object ''' logger.debug("entity.setEntity() is deprecated") if not entity: raise Exception, 'Cannot set entity; no entity provided' if not entity.path: raise Exception, 'Entity does not have path defined' if not entity.name: raise Exception, 'Entity does not have name defined' if not entity.namespace: raise Exception, 'Cannot set entity without a namespace; %s' % entity.name # if editing entities that were owned by the system name, then convert to # to current user if not entity.owner: entity.owner = auth.getCurrentUser()['name'] #check if we should filter arguments based on optional/required/wildcardFields #only enabled for datamodel and data/ui/views for now if filterArguments is None: filterArguments = False if entity.path.startswith("data/models") or re.match("^\/?data\/ui\/views(\/|$)", entity.path) or re.match("^\/?saved\/searches(\/|$)", entity.path): filterArguments = True tmpEntity = None if not uri: # This is where we determine edit / create behavior. WoNkY! if len(entity.links) > 0: for action, link in entity.links: if action == 'edit': uri = link if uri == None: uri = entity.getFullPath() if filterArguments: tmpEntity = getEntity(entity.path, None, uri=uri + "/_new", sessionKey=sessionKey) if filterArguments and tmpEntity == None: tmpEntity = getEntity(entity.path, entity.name, uri=uri, sessionKey=sessionKey) if filterArguments: postargs = entity.getCommitProperties(optionalFields=tmpEntity.optionalFields, requiredFields=tmpEntity.requiredFields, wildcardFields=tmpEntity.wildcardFields, isACL=uri.endswith('/acl'), filterArguments=filterArguments) else: postargs = entity.getCommitProperties() """ logger.debug("*" * 25) logger.debug("entity: %s." % entity) logger.debug("uri: %s." % uri) logger.debug("postargs: %s." % postargs) logger.debug("*" * 25) """ if not postargs: logger.warn('setEntity - tried to commit empty entity') raise Exception, 'setEntity - tried to commit empty entity' # if exists, then update by POST to own endpoint if rest.checkResourceExists(uri, sessionKey=sessionKey) and not strictCreate: # EAI sets entity.name to new for the new template... # so it will exist and not fall into the else case # do any of the endpoints used by Entity post back to # a nonexistent name for the create action? # EAI posts to the basePath. if entity.name == '_new': logger.debug("setting properties to create a new guy.") uri = entity.getBasePath() createName = entity.properties['name'] logger.debug("creating %s on %s." % (createName,uri)) entity.name = createName serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, postargs=postargs, raiseAllErrors=True) if (serverResponse.status == 201): if msgObj: msgObj['messages'] = serverResponse.messages if serverResponse.status not in [200, 201]: logger.warn("Server did not return status 200 or 201.") else: try: atomFeed = rest.format.parseFeedDocument(serverContent) entity.id = atomFeed[0].id except Exception, e: pass return True
def getEntities(entityPath, namespace=None, owner=None, search=None, count=None, offset=0, sort_key=None, sort_dir=None , sessionKey=None, uri=None, unique_key='title', hostPath=None, **kwargs): ''' Retrieves generic entities from the Splunkd endpoint, restricted to a namespace and owner context. @param entityPath: the class of objects to retrieve @param namespace: the namespace within which to look for the entities. default set by splunk.getDefault('namespace') @param owner: the owner within which to look for the entity. defaults to current user @param search: simple key=value filter @param offset: the starting index of the first item to return. defaults to 0 @param count: the maximum number of entities to return. defaults to -1 (all) @param sort_key: the key to sort against @param sort_dir: the direction to sort (asc or desc) @param uri: force a specific path to the objects @param unique_key: specify the uniquifying key ''' # fallback to currently authed user if not owner: owner = auth.getCurrentUser()['name'] # construct URI to get entities if not uri: uri = buildEndpoint(entityPath, namespace=namespace, owner=owner, hostPath=hostPath) if search: kwargs["search"] = search if count != None: kwargs["count"] = count if offset: kwargs["offset"] = offset if sort_key: kwargs["sort_key"] = sort_key if sort_dir: kwargs["sort_dir"] = sort_dir # fetch list of entities serverResponse, serverContent = rest.simpleRequest(uri, getargs=kwargs, sessionKey=sessionKey, raiseAllErrors=True) if serverResponse.status != 200: raise splunk.RESTException, (serverResponse.status, serverResponse.messages) atomFeed = rest.format.parseFeedDocument(serverContent) offset = int(atomFeed.os_startIndex or -1) totalResults = int(atomFeed.os_totalResults or -1) itemsPerPage = int(atomFeed.os_itemsPerPage or -1) links = atomFeed.links messages = atomFeed.messages # preserves order of returned elements # EntityCollection is a new subclass or util.OrderedDict, it still preserves # the order, but it allows some additional params to be added on. collection = EntityCollection(None, search, count, offset, totalResults, itemsPerPage, sort_key, sort_dir, links, messages) for atomEntry in atomFeed: contents = atomEntry.toPrimitive() entity = Entity(entityPath, atomEntry.title, contents, namespace) entity.owner = atomEntry.author entity.createTime = atomEntry.published entity.updateTime = atomEntry.updated entity.summary = atomEntry.summary entity.links = atomEntry.links entity.id = atomEntry.id entity.hostPath = hostPath # use the same semantics as in the C++ code: make the first item in the # list win if two stanzas with the same name exist attr = getattr(atomEntry, unique_key) if attr not in collection: collection[attr] = entity return collection
def setEntity(entity, sessionKey=None, uri=None, msgObj=None): ''' Commits the properties of a generic entity object ''' if not entity: raise Exception, 'Cannot set entity; no entity provided' if not entity.path: raise Exception, 'Entity does not have path defined' if not entity.name: raise Exception, 'Entity does not have name defined' if not entity.namespace: raise Exception, 'Cannot set entity without a namespace; %s' % entity.name # if editing entities that were owned by the system name, then convert to # to current user if not entity.owner: entity.owner = auth.getCurrentUser()['name'] if not uri: # This is where we determine edit / create behavior. WoNkY! if len(entity.links) > 0: for action, link in entity.links: if action == 'edit': uri = link if uri == None: uri = entity.getFullPath() postargs = entity.getCommitProperties() """ logger.debug("*" * 25) logger.debug("entity: %s." % entity) logger.debug("uri: %s." % uri) logger.debug("postargs: %s." % postargs) logger.debug("*" * 25) """ if not postargs: logger.warn('setEntity - tried to commit empty entity') raise Exception, 'setEntity - tried to commit empty entity' # if exists, then update by POST to own endpoint if rest.checkResourceExists(uri, sessionKey=sessionKey): # EAI sets entity.name to new for the new template... # so it will exist and not fall into the else case # do any of the endpoints used by Entity post back to # a nonexistent name for the create action? # EAI posts to the basePath. if entity.name == '_new': logger.debug("setting properties to create a new guy.") uri = entity.getBasePath() createName = entity.properties['name'] logger.debug("creating %s on %s." % (createName,uri)) entity.name = createName serverResponse, serverContent = rest.simpleRequest(uri, sessionKey=sessionKey, postargs=postargs, raiseAllErrors=True) if (serverResponse.status == 201): if msgObj: msgObj['messages'] = serverResponse.messages if serverResponse.status not in [200, 201]: logger.warn("Server did not return status 200 or 201.") else: try: atomFeed = rest.format.parseFeedDocument(serverContent) entity.id = atomFeed[0].id except Exception, e: pass return True