id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
235,900
splunk/splunk-sdk-python
examples/job.py
Program.preview
def preview(self, argv): """Retrieve the preview for the specified search jobs.""" opts = cmdline(argv, FLAGS_RESULTS) self.foreach(opts.args, lambda job: output(job.preview(**opts.kwargs)))
python
def preview(self, argv): opts = cmdline(argv, FLAGS_RESULTS) self.foreach(opts.args, lambda job: output(job.preview(**opts.kwargs)))
[ "def", "preview", "(", "self", ",", "argv", ")", ":", "opts", "=", "cmdline", "(", "argv", ",", "FLAGS_RESULTS", ")", "self", ".", "foreach", "(", "opts", ".", "args", ",", "lambda", "job", ":", "output", "(", "job", ".", "preview", "(", "*", "*", ...
Retrieve the preview for the specified search jobs.
[ "Retrieve", "the", "preview", "for", "the", "specified", "search", "jobs", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L176-L180
235,901
splunk/splunk-sdk-python
examples/job.py
Program.run
def run(self, argv): """Dispatch the given command.""" command = argv[0] handlers = { 'cancel': self.cancel, 'create': self.create, 'events': self.events, 'finalize': self.finalize, 'list': self.list, 'pause': self.pause, 'preview': self.preview, 'results': self.results, 'searchlog': self.searchlog, 'summary': self.summary, 'perf': self.perf, 'timeline': self.timeline, 'touch': self.touch, 'unpause': self.unpause, } handler = handlers.get(command, None) if handler is None: error("Unrecognized command: %s" % command, 2) handler(argv[1:])
python
def run(self, argv): command = argv[0] handlers = { 'cancel': self.cancel, 'create': self.create, 'events': self.events, 'finalize': self.finalize, 'list': self.list, 'pause': self.pause, 'preview': self.preview, 'results': self.results, 'searchlog': self.searchlog, 'summary': self.summary, 'perf': self.perf, 'timeline': self.timeline, 'touch': self.touch, 'unpause': self.unpause, } handler = handlers.get(command, None) if handler is None: error("Unrecognized command: %s" % command, 2) handler(argv[1:])
[ "def", "run", "(", "self", ",", "argv", ")", ":", "command", "=", "argv", "[", "0", "]", "handlers", "=", "{", "'cancel'", ":", "self", ".", "cancel", ",", "'create'", ":", "self", ".", "create", ",", "'events'", ":", "self", ".", "events", ",", ...
Dispatch the given command.
[ "Dispatch", "the", "given", "command", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L209-L231
235,902
splunk/splunk-sdk-python
examples/job.py
Program.searchlog
def searchlog(self, argv): """Retrieve the searchlog for the specified search jobs.""" opts = cmdline(argv, FLAGS_SEARCHLOG) self.foreach(opts.args, lambda job: output(job.searchlog(**opts.kwargs)))
python
def searchlog(self, argv): opts = cmdline(argv, FLAGS_SEARCHLOG) self.foreach(opts.args, lambda job: output(job.searchlog(**opts.kwargs)))
[ "def", "searchlog", "(", "self", ",", "argv", ")", ":", "opts", "=", "cmdline", "(", "argv", ",", "FLAGS_SEARCHLOG", ")", "self", ".", "foreach", "(", "opts", ".", "args", ",", "lambda", "job", ":", "output", "(", "job", ".", "searchlog", "(", "*", ...
Retrieve the searchlog for the specified search jobs.
[ "Retrieve", "the", "searchlog", "for", "the", "specified", "search", "jobs", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/job.py#L233-L237
235,903
splunk/splunk-sdk-python
examples/handlers/handler_certs.py
handler
def handler(ca_file=None): """Returns an HTTP request handler configured with the given ca_file.""" def request(url, message, **kwargs): scheme, host, port, path = spliturl(url) if scheme != "https": ValueError("unsupported scheme: %s" % scheme) connection = HTTPSConnection(host, port, ca_file) try: body = message.get('body', "") headers = dict(message.get('headers', [])) connection.request(message['method'], path, body, headers) response = connection.getresponse() finally: connection.close() return { 'status': response.status, 'reason': response.reason, 'headers': response.getheaders(), 'body': BytesIO(response.read()) } return request
python
def handler(ca_file=None): def request(url, message, **kwargs): scheme, host, port, path = spliturl(url) if scheme != "https": ValueError("unsupported scheme: %s" % scheme) connection = HTTPSConnection(host, port, ca_file) try: body = message.get('body', "") headers = dict(message.get('headers', [])) connection.request(message['method'], path, body, headers) response = connection.getresponse() finally: connection.close() return { 'status': response.status, 'reason': response.reason, 'headers': response.getheaders(), 'body': BytesIO(response.read()) } return request
[ "def", "handler", "(", "ca_file", "=", "None", ")", ":", "def", "request", "(", "url", ",", "message", ",", "*", "*", "kwargs", ")", ":", "scheme", ",", "host", ",", "port", ",", "path", "=", "spliturl", "(", "url", ")", "if", "scheme", "!=", "\"...
Returns an HTTP request handler configured with the given ca_file.
[ "Returns", "an", "HTTP", "request", "handler", "configured", "with", "the", "given", "ca_file", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/handlers/handler_certs.py#L90-L115
235,904
splunk/splunk-sdk-python
examples/index.py
Program.list
def list(self, argv): """List available indexes if no names provided, otherwise list the properties of the named indexes.""" def read(index): print(index.name) for key in sorted(index.content.keys()): value = index.content[key] print(" %s: %s" % (key, value)) if len(argv) == 0: for index in self.service.indexes: count = index['totalEventCount'] print("%s (%s)" % (index.name, count)) else: self.foreach(argv, read)
python
def list(self, argv): def read(index): print(index.name) for key in sorted(index.content.keys()): value = index.content[key] print(" %s: %s" % (key, value)) if len(argv) == 0: for index in self.service.indexes: count = index['totalEventCount'] print("%s (%s)" % (index.name, count)) else: self.foreach(argv, read)
[ "def", "list", "(", "self", ",", "argv", ")", ":", "def", "read", "(", "index", ")", ":", "print", "(", "index", ".", "name", ")", "for", "key", "in", "sorted", "(", "index", ".", "content", ".", "keys", "(", ")", ")", ":", "value", "=", "index...
List available indexes if no names provided, otherwise list the properties of the named indexes.
[ "List", "available", "indexes", "if", "no", "names", "provided", "otherwise", "list", "the", "properties", "of", "the", "named", "indexes", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/index.py#L101-L116
235,905
splunk/splunk-sdk-python
examples/index.py
Program.foreach
def foreach(self, argv, func): """Apply the function to each index named in the argument vector.""" opts = cmdline(argv) if len(opts.args) == 0: error("Command requires an index name", 2) for name in opts.args: if name not in self.service.indexes: error("Index '%s' does not exist" % name, 2) index = self.service.indexes[name] func(index)
python
def foreach(self, argv, func): opts = cmdline(argv) if len(opts.args) == 0: error("Command requires an index name", 2) for name in opts.args: if name not in self.service.indexes: error("Index '%s' does not exist" % name, 2) index = self.service.indexes[name] func(index)
[ "def", "foreach", "(", "self", ",", "argv", ",", "func", ")", ":", "opts", "=", "cmdline", "(", "argv", ")", "if", "len", "(", "opts", ".", "args", ")", "==", "0", ":", "error", "(", "\"Command requires an index name\"", ",", "2", ")", "for", "name",...
Apply the function to each index named in the argument vector.
[ "Apply", "the", "function", "to", "each", "index", "named", "in", "the", "argument", "vector", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/index.py#L134-L143
235,906
splunk/splunk-sdk-python
examples/index.py
Program.update
def update(self, argv): """Update an index according to the given argument vector.""" if len(argv) == 0: error("Command requires an index name", 2) name = argv[0] if name not in self.service.indexes: error("Index '%s' does not exist" % name, 2) index = self.service.indexes[name] # Read index metadata and construct command line parser rules that # correspond to each editable field. # Request editable fields fields = self.service.indexes.itemmeta().fields.optional # Build parser rules rules = dict([(field, {'flags': ["--%s" % field]}) for field in fields]) # Parse the argument vector opts = cmdline(argv, rules) # Execute the edit request index.update(**opts.kwargs)
python
def update(self, argv): if len(argv) == 0: error("Command requires an index name", 2) name = argv[0] if name not in self.service.indexes: error("Index '%s' does not exist" % name, 2) index = self.service.indexes[name] # Read index metadata and construct command line parser rules that # correspond to each editable field. # Request editable fields fields = self.service.indexes.itemmeta().fields.optional # Build parser rules rules = dict([(field, {'flags': ["--%s" % field]}) for field in fields]) # Parse the argument vector opts = cmdline(argv, rules) # Execute the edit request index.update(**opts.kwargs)
[ "def", "update", "(", "self", ",", "argv", ")", ":", "if", "len", "(", "argv", ")", "==", "0", ":", "error", "(", "\"Command requires an index name\"", ",", "2", ")", "name", "=", "argv", "[", "0", "]", "if", "name", "not", "in", "self", ".", "serv...
Update an index according to the given argument vector.
[ "Update", "an", "index", "according", "to", "the", "given", "argument", "vector", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/index.py#L145-L169
235,907
splunk/splunk-sdk-python
splunklib/modularinput/argument.py
Argument.add_to_document
def add_to_document(self, parent): """Adds an ``Argument`` object to this ElementTree document. Adds an <arg> subelement to the parent element, typically <args> and sets up its subelements with their respective text. :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement :returns: An ``ET.Element`` object representing this argument. """ arg = ET.SubElement(parent, "arg") arg.set("name", self.name) if self.title is not None: ET.SubElement(arg, "title").text = self.title if self.description is not None: ET.SubElement(arg, "description").text = self.description if self.validation is not None: ET.SubElement(arg, "validation").text = self.validation # add all other subelements to this Argument, represented by (tag, text) subelements = [ ("data_type", self.data_type), ("required_on_edit", self.required_on_edit), ("required_on_create", self.required_on_create) ] for name, value in subelements: ET.SubElement(arg, name).text = str(value).lower() return arg
python
def add_to_document(self, parent): arg = ET.SubElement(parent, "arg") arg.set("name", self.name) if self.title is not None: ET.SubElement(arg, "title").text = self.title if self.description is not None: ET.SubElement(arg, "description").text = self.description if self.validation is not None: ET.SubElement(arg, "validation").text = self.validation # add all other subelements to this Argument, represented by (tag, text) subelements = [ ("data_type", self.data_type), ("required_on_edit", self.required_on_edit), ("required_on_create", self.required_on_create) ] for name, value in subelements: ET.SubElement(arg, name).text = str(value).lower() return arg
[ "def", "add_to_document", "(", "self", ",", "parent", ")", ":", "arg", "=", "ET", ".", "SubElement", "(", "parent", ",", "\"arg\"", ")", "arg", ".", "set", "(", "\"name\"", ",", "self", ".", "name", ")", "if", "self", ".", "title", "is", "not", "No...
Adds an ``Argument`` object to this ElementTree document. Adds an <arg> subelement to the parent element, typically <args> and sets up its subelements with their respective text. :param parent: An ``ET.Element`` to be the parent of a new <arg> subelement :returns: An ``ET.Element`` object representing this argument.
[ "Adds", "an", "Argument", "object", "to", "this", "ElementTree", "document", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/argument.py#L72-L103
235,908
splunk/splunk-sdk-python
examples/export/export.py
get_event_start
def get_event_start(event_buffer, event_format): """ dispatch event start method based on event format type """ if event_format == "csv": return get_csv_event_start(event_buffer) elif event_format == "xml": return get_xml_event_start(event_buffer) else: return get_json_event_start(event_buffer)
python
def get_event_start(event_buffer, event_format): if event_format == "csv": return get_csv_event_start(event_buffer) elif event_format == "xml": return get_xml_event_start(event_buffer) else: return get_json_event_start(event_buffer)
[ "def", "get_event_start", "(", "event_buffer", ",", "event_format", ")", ":", "if", "event_format", "==", "\"csv\"", ":", "return", "get_csv_event_start", "(", "event_buffer", ")", "elif", "event_format", "==", "\"xml\"", ":", "return", "get_xml_event_start", "(", ...
dispatch event start method based on event format type
[ "dispatch", "event", "start", "method", "based", "on", "event", "format", "type" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/export/export.py#L217-L225
235,909
splunk/splunk-sdk-python
examples/export/export.py
recover
def recover(options): """ recover from an existing export run. We do this by finding the last time change between events, truncate the file and restart from there """ event_format = options.kwargs['omode'] buffer_size = 64*1024 fpd = open(options.kwargs['output'], "r+") fpd.seek(0, 2) # seek to end fptr = max(fpd.tell() - buffer_size, 0) fptr_eof = 0 while (fptr > 0): fpd.seek(fptr) event_buffer = fpd.read(buffer_size) (event_start, next_event_start, last_time) = \ get_event_start(event_buffer, event_format) if (event_start != -1): fptr_eof = event_start + fptr break fptr = fptr - buffer_size if fptr < 0: # didn't find a valid event, so start over fptr_eof = 0 last_time = 0 # truncate file here fpd.truncate(fptr_eof) fpd.seek(fptr_eof) fpd.write("\n") fpd.close() return last_time
python
def recover(options): event_format = options.kwargs['omode'] buffer_size = 64*1024 fpd = open(options.kwargs['output'], "r+") fpd.seek(0, 2) # seek to end fptr = max(fpd.tell() - buffer_size, 0) fptr_eof = 0 while (fptr > 0): fpd.seek(fptr) event_buffer = fpd.read(buffer_size) (event_start, next_event_start, last_time) = \ get_event_start(event_buffer, event_format) if (event_start != -1): fptr_eof = event_start + fptr break fptr = fptr - buffer_size if fptr < 0: # didn't find a valid event, so start over fptr_eof = 0 last_time = 0 # truncate file here fpd.truncate(fptr_eof) fpd.seek(fptr_eof) fpd.write("\n") fpd.close() return last_time
[ "def", "recover", "(", "options", ")", ":", "event_format", "=", "options", ".", "kwargs", "[", "'omode'", "]", "buffer_size", "=", "64", "*", "1024", "fpd", "=", "open", "(", "options", ".", "kwargs", "[", "'output'", "]", ",", "\"r+\"", ")", "fpd", ...
recover from an existing export run. We do this by finding the last time change between events, truncate the file and restart from there
[ "recover", "from", "an", "existing", "export", "run", ".", "We", "do", "this", "by", "finding", "the", "last", "time", "change", "between", "events", "truncate", "the", "file", "and", "restart", "from", "there" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/export/export.py#L227-L261
235,910
splunk/splunk-sdk-python
examples/export/export.py
cleanup_tail
def cleanup_tail(options): """ cleanup the tail of a recovery """ if options.kwargs['omode'] == "csv": options.kwargs['fd'].write("\n") elif options.kwargs['omode'] == "xml": options.kwargs['fd'].write("\n</results>\n") else: options.kwargs['fd'].write("\n]\n")
python
def cleanup_tail(options): if options.kwargs['omode'] == "csv": options.kwargs['fd'].write("\n") elif options.kwargs['omode'] == "xml": options.kwargs['fd'].write("\n</results>\n") else: options.kwargs['fd'].write("\n]\n")
[ "def", "cleanup_tail", "(", "options", ")", ":", "if", "options", ".", "kwargs", "[", "'omode'", "]", "==", "\"csv\"", ":", "options", ".", "kwargs", "[", "'fd'", "]", ".", "write", "(", "\"\\n\"", ")", "elif", "options", ".", "kwargs", "[", "'omode'",...
cleanup the tail of a recovery
[ "cleanup", "the", "tail", "of", "a", "recovery" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/export/export.py#L263-L271
235,911
splunk/splunk-sdk-python
splunklib/modularinput/scheme.py
Scheme.to_xml
def to_xml(self): """Creates an ``ET.Element`` representing self, then returns it. :returns root, an ``ET.Element`` representing this scheme. """ root = ET.Element("scheme") ET.SubElement(root, "title").text = self.title # add a description subelement if it's defined if self.description is not None: ET.SubElement(root, "description").text = self.description # add all other subelements to this Scheme, represented by (tag, text) subelements = [ ("use_external_validation", self.use_external_validation), ("use_single_instance", self.use_single_instance), ("streaming_mode", self.streaming_mode) ] for name, value in subelements: ET.SubElement(root, name).text = str(value).lower() endpoint = ET.SubElement(root, "endpoint") args = ET.SubElement(endpoint, "args") # add arguments as subelements to the <args> element for arg in self.arguments: arg.add_to_document(args) return root
python
def to_xml(self): root = ET.Element("scheme") ET.SubElement(root, "title").text = self.title # add a description subelement if it's defined if self.description is not None: ET.SubElement(root, "description").text = self.description # add all other subelements to this Scheme, represented by (tag, text) subelements = [ ("use_external_validation", self.use_external_validation), ("use_single_instance", self.use_single_instance), ("streaming_mode", self.streaming_mode) ] for name, value in subelements: ET.SubElement(root, name).text = str(value).lower() endpoint = ET.SubElement(root, "endpoint") args = ET.SubElement(endpoint, "args") # add arguments as subelements to the <args> element for arg in self.arguments: arg.add_to_document(args) return root
[ "def", "to_xml", "(", "self", ")", ":", "root", "=", "ET", ".", "Element", "(", "\"scheme\"", ")", "ET", ".", "SubElement", "(", "root", ",", "\"title\"", ")", ".", "text", "=", "self", ".", "title", "# add a description subelement if it's defined", "if", ...
Creates an ``ET.Element`` representing self, then returns it. :returns root, an ``ET.Element`` representing this scheme.
[ "Creates", "an", "ET", ".", "Element", "representing", "self", "then", "returns", "it", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/scheme.py#L55-L85
235,912
splunk/splunk-sdk-python
splunklib/modularinput/event_writer.py
EventWriter.write_xml_document
def write_xml_document(self, document): """Writes a string representation of an ``ElementTree`` object to the output stream. :param document: An ``ElementTree`` object. """ self._out.write(ET.tostring(document)) self._out.flush()
python
def write_xml_document(self, document): self._out.write(ET.tostring(document)) self._out.flush()
[ "def", "write_xml_document", "(", "self", ",", "document", ")", ":", "self", ".", "_out", ".", "write", "(", "ET", ".", "tostring", "(", "document", ")", ")", "self", ".", "_out", ".", "flush", "(", ")" ]
Writes a string representation of an ``ElementTree`` object to the output stream. :param document: An ``ElementTree`` object.
[ "Writes", "a", "string", "representation", "of", "an", "ElementTree", "object", "to", "the", "output", "stream", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/event_writer.py#L74-L81
235,913
splunk/splunk-sdk-python
examples/conf.py
Program.create
def create(self, opts): """Create a conf stanza.""" argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # however, we must have a conf and stanza. cpres = True if count > 0 else False spres = True if count > 1 else False kpres = True if count > 2 else False if kpres: kvpair = argv[2].split("=") if len(kvpair) != 2: error("Creating a k/v pair requires key and value", 2) else: key, value = kvpair if not cpres and not spres: error("Conf name and stanza name is required for create", 2) name = argv[0] stan = argv[1] conf = self.service.confs[name] if not kpres: # create stanza conf.create(stan) return # create key/value pair under existing stanza stanza = conf[stan] stanza.submit({key: value})
python
def create(self, opts): argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # however, we must have a conf and stanza. cpres = True if count > 0 else False spres = True if count > 1 else False kpres = True if count > 2 else False if kpres: kvpair = argv[2].split("=") if len(kvpair) != 2: error("Creating a k/v pair requires key and value", 2) else: key, value = kvpair if not cpres and not spres: error("Conf name and stanza name is required for create", 2) name = argv[0] stan = argv[1] conf = self.service.confs[name] if not kpres: # create stanza conf.create(stan) return # create key/value pair under existing stanza stanza = conf[stan] stanza.submit({key: value})
[ "def", "create", "(", "self", ",", "opts", ")", ":", "argv", "=", "opts", ".", "args", "count", "=", "len", "(", "argv", ")", "# unflagged arguments are conf, stanza, key. In this order", "# however, we must have a conf and stanza.", "cpres", "=", "True", "if", "cou...
Create a conf stanza.
[ "Create", "a", "conf", "stanza", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/conf.py#L39-L72
235,914
splunk/splunk-sdk-python
examples/conf.py
Program.delete
def delete(self, opts): """Delete a conf stanza.""" argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # however, we must have a conf and stanza. cpres = True if count > 0 else False spres = True if count > 1 else False kpres = True if count > 2 else False if not cpres: error("Conf name is required for delete", 2) if not cpres and not spres: error("Conf name and stanza name is required for delete", 2) if kpres: error("Cannot delete individual keys from a stanza", 2) name = argv[0] stan = argv[1] conf = self.service.confs[name] conf.delete(stan)
python
def delete(self, opts): argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # however, we must have a conf and stanza. cpres = True if count > 0 else False spres = True if count > 1 else False kpres = True if count > 2 else False if not cpres: error("Conf name is required for delete", 2) if not cpres and not spres: error("Conf name and stanza name is required for delete", 2) if kpres: error("Cannot delete individual keys from a stanza", 2) name = argv[0] stan = argv[1] conf = self.service.confs[name] conf.delete(stan)
[ "def", "delete", "(", "self", ",", "opts", ")", ":", "argv", "=", "opts", ".", "args", "count", "=", "len", "(", "argv", ")", "# unflagged arguments are conf, stanza, key. In this order", "# however, we must have a conf and stanza.", "cpres", "=", "True", "if", "cou...
Delete a conf stanza.
[ "Delete", "a", "conf", "stanza", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/conf.py#L75-L99
235,915
splunk/splunk-sdk-python
examples/conf.py
Program.list
def list(self, opts): """List all confs or if a conf is given, all the stanzas in it.""" argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # but all are optional cpres = True if count > 0 else False spres = True if count > 1 else False kpres = True if count > 2 else False if not cpres: # List out the available confs for conf in self.service.confs: print(conf.name) else: # Print out detail on the requested conf # check for optional stanza, or key requested (or all) name = argv[0] conf = self.service.confs[name] for stanza in conf: if (spres and argv[1] == stanza.name) or not spres: print("[%s]" % stanza.name) for key, value in six.iteritems(stanza.content): if (kpres and argv[2] == key) or not kpres: print("%s = %s" % (key, value)) print()
python
def list(self, opts): argv = opts.args count = len(argv) # unflagged arguments are conf, stanza, key. In this order # but all are optional cpres = True if count > 0 else False spres = True if count > 1 else False kpres = True if count > 2 else False if not cpres: # List out the available confs for conf in self.service.confs: print(conf.name) else: # Print out detail on the requested conf # check for optional stanza, or key requested (or all) name = argv[0] conf = self.service.confs[name] for stanza in conf: if (spres and argv[1] == stanza.name) or not spres: print("[%s]" % stanza.name) for key, value in six.iteritems(stanza.content): if (kpres and argv[2] == key) or not kpres: print("%s = %s" % (key, value)) print()
[ "def", "list", "(", "self", ",", "opts", ")", ":", "argv", "=", "opts", ".", "args", "count", "=", "len", "(", "argv", ")", "# unflagged arguments are conf, stanza, key. In this order", "# but all are optional", "cpres", "=", "True", "if", "count", ">", "0", "...
List all confs or if a conf is given, all the stanzas in it.
[ "List", "all", "confs", "or", "if", "a", "conf", "is", "given", "all", "the", "stanzas", "in", "it", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/conf.py#L101-L129
235,916
splunk/splunk-sdk-python
examples/analytics/bottle.py
tob
def tob(data, enc='utf8'): """ Convert anything to bytes """ return data.encode(enc) if isinstance(data, six.text_type) else bytes(data)
python
def tob(data, enc='utf8'): return data.encode(enc) if isinstance(data, six.text_type) else bytes(data)
[ "def", "tob", "(", "data", ",", "enc", "=", "'utf8'", ")", ":", "return", "data", ".", "encode", "(", "enc", ")", "if", "isinstance", "(", "data", ",", "six", ".", "text_type", ")", "else", "bytes", "(", "data", ")" ]
Convert anything to bytes
[ "Convert", "anything", "to", "bytes" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L91-L93
235,917
splunk/splunk-sdk-python
examples/analytics/bottle.py
make_default_app_wrapper
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
python
def make_default_app_wrapper(name): ''' Return a callable that relays calls to the current default app. ''' @functools.wraps(getattr(Bottle, name)) def wrapper(*a, **ka): return getattr(app(), name)(*a, **ka) return wrapper
[ "def", "make_default_app_wrapper", "(", "name", ")", ":", "@", "functools", ".", "wraps", "(", "getattr", "(", "Bottle", ",", "name", ")", ")", "def", "wrapper", "(", "*", "a", ",", "*", "*", "ka", ")", ":", "return", "getattr", "(", "app", "(", ")...
Return a callable that relays calls to the current default app.
[ "Return", "a", "callable", "that", "relays", "calls", "to", "the", "current", "default", "app", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1644-L1649
235,918
splunk/splunk-sdk-python
examples/analytics/bottle.py
load_app
def load_app(target): """ Load a bottle application based on a target string and return the application object. If the target is an import path (e.g. package.module), the application stack is used to isolate the routes defined in that module. If the target contains a colon (e.g. package.module:myapp) the module variable specified after the colon is returned instead. """ tmp = app.push() # Create a new "default application" rv = _load(target) # Import the target module app.remove(tmp) # Remove the temporary added default application return rv if isinstance(rv, Bottle) else tmp
python
def load_app(target): tmp = app.push() # Create a new "default application" rv = _load(target) # Import the target module app.remove(tmp) # Remove the temporary added default application return rv if isinstance(rv, Bottle) else tmp
[ "def", "load_app", "(", "target", ")", ":", "tmp", "=", "app", ".", "push", "(", ")", "# Create a new \"default application\"", "rv", "=", "_load", "(", "target", ")", "# Import the target module", "app", ".", "remove", "(", "tmp", ")", "# Remove the temporary a...
Load a bottle application based on a target string and return the application object. If the target is an import path (e.g. package.module), the application stack is used to isolate the routes defined in that module. If the target contains a colon (e.g. package.module:myapp) the module variable specified after the colon is returned instead.
[ "Load", "a", "bottle", "application", "based", "on", "a", "target", "string", "and", "return", "the", "application", "object", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1935-L1947
235,919
splunk/splunk-sdk-python
examples/analytics/bottle.py
run
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, **kargs): """ Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter. """ app = app or default_app() if isinstance(app, six.string_types): app = load_app(app) if isinstance(server, six.string_types): server = server_names.get(server) if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise RuntimeError("Server must be a subclass of ServerAdapter") server.quiet = server.quiet or quiet if not server.quiet and not os.environ.get('BOTTLE_CHILD'): print("Bottle server starting up (using %s)..." % repr(server)) print("Listening on http://%s:%d/" % (server.host, server.port)) print("Use Ctrl-C to quit.") print() try: if reloader: interval = min(interval, 1) if os.environ.get('BOTTLE_CHILD'): _reloader_child(server, app, interval) else: _reloader_observer(server, app, interval) else: server.run(app) except KeyboardInterrupt: pass if not server.quiet and not os.environ.get('BOTTLE_CHILD'): print("Shutting down...")
python
def run(app=None, server='wsgiref', host='127.0.0.1', port=8080, interval=1, reloader=False, quiet=False, **kargs): app = app or default_app() if isinstance(app, six.string_types): app = load_app(app) if isinstance(server, six.string_types): server = server_names.get(server) if isinstance(server, type): server = server(host=host, port=port, **kargs) if not isinstance(server, ServerAdapter): raise RuntimeError("Server must be a subclass of ServerAdapter") server.quiet = server.quiet or quiet if not server.quiet and not os.environ.get('BOTTLE_CHILD'): print("Bottle server starting up (using %s)..." % repr(server)) print("Listening on http://%s:%d/" % (server.host, server.port)) print("Use Ctrl-C to quit.") print() try: if reloader: interval = min(interval, 1) if os.environ.get('BOTTLE_CHILD'): _reloader_child(server, app, interval) else: _reloader_observer(server, app, interval) else: server.run(app) except KeyboardInterrupt: pass if not server.quiet and not os.environ.get('BOTTLE_CHILD'): print("Shutting down...")
[ "def", "run", "(", "app", "=", "None", ",", "server", "=", "'wsgiref'", ",", "host", "=", "'127.0.0.1'", ",", "port", "=", "8080", ",", "interval", "=", "1", ",", "reloader", "=", "False", ",", "quiet", "=", "False", ",", "*", "*", "kargs", ")", ...
Start a server instance. This method blocks until the server terminates. :param app: WSGI application or target string supported by :func:`load_app`. (default: :func:`default_app`) :param server: Server adapter to use. See :data:`server_names` keys for valid names or pass a :class:`ServerAdapter` subclass. (default: `wsgiref`) :param host: Server address to bind to. Pass ``0.0.0.0`` to listens on all interfaces including the external one. (default: 127.0.0.1) :param port: Server port to bind to. Values below 1024 require root privileges. (default: 8080) :param reloader: Start auto-reloading server? (default: False) :param interval: Auto-reloader interval in seconds (default: 1) :param quiet: Suppress output to stdout and stderr? (default: False) :param options: Options passed to the server adapter.
[ "Start", "a", "server", "instance", ".", "This", "method", "blocks", "until", "the", "server", "terminates", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1950-L1995
235,920
splunk/splunk-sdk-python
examples/analytics/bottle.py
Router.build
def build(self, _name, *anon, **args): ''' Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.''' if _name not in self.named: raise RouteBuildError("No route with that name.", _name) rule, pairs = self.named[_name] if not pairs: token = self.syntax.split(rule) parts = [p.replace('\\:',':') for p in token[::3]] names = token[1::3] if len(parts) > len(names): names.append(None) pairs = list(zip(parts, names)) self.named[_name] = (rule, pairs) try: anon = list(anon) url = [s if k is None else s+str(args.pop(k)) if k else s+str(anon.pop()) for s, k in pairs] except IndexError: msg = "Not enough arguments to fill out anonymous wildcards." raise RouteBuildError(msg) except KeyError as e: raise RouteBuildError(*e.args) if args: url += ['?', urlencode(args)] return ''.join(url)
python
def build(self, _name, *anon, **args): ''' Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.''' if _name not in self.named: raise RouteBuildError("No route with that name.", _name) rule, pairs = self.named[_name] if not pairs: token = self.syntax.split(rule) parts = [p.replace('\\:',':') for p in token[::3]] names = token[1::3] if len(parts) > len(names): names.append(None) pairs = list(zip(parts, names)) self.named[_name] = (rule, pairs) try: anon = list(anon) url = [s if k is None else s+str(args.pop(k)) if k else s+str(anon.pop()) for s, k in pairs] except IndexError: msg = "Not enough arguments to fill out anonymous wildcards." raise RouteBuildError(msg) except KeyError as e: raise RouteBuildError(*e.args) if args: url += ['?', urlencode(args)] return ''.join(url)
[ "def", "build", "(", "self", ",", "_name", ",", "*", "anon", ",", "*", "*", "args", ")", ":", "if", "_name", "not", "in", "self", ".", "named", ":", "raise", "RouteBuildError", "(", "\"No route with that name.\"", ",", "_name", ")", "rule", ",", "pairs...
Return a string that matches a named route. Use keyword arguments to fill out named wildcards. Remaining arguments are appended as a query string. Raises RouteBuildError or KeyError.
[ "Return", "a", "string", "that", "matches", "a", "named", "route", ".", "Use", "keyword", "arguments", "to", "fill", "out", "named", "wildcards", ".", "Remaining", "arguments", "are", "appended", "as", "a", "query", "string", ".", "Raises", "RouteBuildError", ...
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L278-L304
235,921
splunk/splunk-sdk-python
examples/analytics/bottle.py
Router._match_path
def _match_path(self, environ): ''' Optimized PATH_INFO matcher. ''' path = environ['PATH_INFO'] or '/' # Assume we are in a warm state. Search compiled rules first. match = self.static.get(path) if match: return match, {} for combined, rules in self.dynamic: match = combined.match(path) if not match: continue gpat, match = rules[match.lastindex - 1] return match, gpat.match(path).groupdict() if gpat else {} # Lazy-check if we are really in a warm state. If yes, stop here. if self.static or self.dynamic or not self.routes: return None, {} # Cold state: We have not compiled any rules yet. Do so and try again. if not environ.get('wsgi.run_once'): self._compile() return self._match_path(environ) # For run_once (CGI) environments, don't compile. Just check one by one. epath = path.replace(':','\\:') # Turn path into its own static rule. match = self.routes.get(epath) # This returns static rule only. if match: return match, {} for rule in self.rules: #: Skip static routes to reduce re.compile() calls. if rule.count(':') < rule.count('\\:'): continue match = self._compile_pattern(rule).match(path) if match: return self.routes[rule], match.groupdict() return None, {}
python
def _match_path(self, environ): ''' Optimized PATH_INFO matcher. ''' path = environ['PATH_INFO'] or '/' # Assume we are in a warm state. Search compiled rules first. match = self.static.get(path) if match: return match, {} for combined, rules in self.dynamic: match = combined.match(path) if not match: continue gpat, match = rules[match.lastindex - 1] return match, gpat.match(path).groupdict() if gpat else {} # Lazy-check if we are really in a warm state. If yes, stop here. if self.static or self.dynamic or not self.routes: return None, {} # Cold state: We have not compiled any rules yet. Do so and try again. if not environ.get('wsgi.run_once'): self._compile() return self._match_path(environ) # For run_once (CGI) environments, don't compile. Just check one by one. epath = path.replace(':','\\:') # Turn path into its own static rule. match = self.routes.get(epath) # This returns static rule only. if match: return match, {} for rule in self.rules: #: Skip static routes to reduce re.compile() calls. if rule.count(':') < rule.count('\\:'): continue match = self._compile_pattern(rule).match(path) if match: return self.routes[rule], match.groupdict() return None, {}
[ "def", "_match_path", "(", "self", ",", "environ", ")", ":", "path", "=", "environ", "[", "'PATH_INFO'", "]", "or", "'/'", "# Assume we are in a warm state. Search compiled rules first.", "match", "=", "self", ".", "static", ".", "get", "(", "path", ")", "if", ...
Optimized PATH_INFO matcher.
[ "Optimized", "PATH_INFO", "matcher", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L324-L350
235,922
splunk/splunk-sdk-python
examples/analytics/bottle.py
Router._compile
def _compile(self): ''' Prepare static and dynamic search structures. ''' self.static = {} self.dynamic = [] def fpat_sub(m): return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:' for rule in self.rules: target = self.routes[rule] if not self.syntax.search(rule): self.static[rule.replace('\\:',':')] = target continue gpat = self._compile_pattern(rule) fpat = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, gpat.pattern) gpat = gpat if gpat.groupindex else None try: combined = '%s|(%s)' % (self.dynamic[-1][0].pattern, fpat) self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1]) self.dynamic[-1][1].append((gpat, target)) except (AssertionError, IndexError) as e: # AssertionError: Too many groups self.dynamic.append((re.compile('(^%s$)'%fpat), [(gpat, target)])) except re.error as e: raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e))
python
def _compile(self): ''' Prepare static and dynamic search structures. ''' self.static = {} self.dynamic = [] def fpat_sub(m): return m.group(0) if len(m.group(1)) % 2 else m.group(1) + '(?:' for rule in self.rules: target = self.routes[rule] if not self.syntax.search(rule): self.static[rule.replace('\\:',':')] = target continue gpat = self._compile_pattern(rule) fpat = re.sub(r'(\\*)(\(\?P<[^>]*>|\((?!\?))', fpat_sub, gpat.pattern) gpat = gpat if gpat.groupindex else None try: combined = '%s|(%s)' % (self.dynamic[-1][0].pattern, fpat) self.dynamic[-1] = (re.compile(combined), self.dynamic[-1][1]) self.dynamic[-1][1].append((gpat, target)) except (AssertionError, IndexError) as e: # AssertionError: Too many groups self.dynamic.append((re.compile('(^%s$)'%fpat), [(gpat, target)])) except re.error as e: raise RouteSyntaxError("Could not add Route: %s (%s)" % (rule, e))
[ "def", "_compile", "(", "self", ")", ":", "self", ".", "static", "=", "{", "}", "self", ".", "dynamic", "=", "[", "]", "def", "fpat_sub", "(", "m", ")", ":", "return", "m", ".", "group", "(", "0", ")", "if", "len", "(", "m", ".", "group", "("...
Prepare static and dynamic search structures.
[ "Prepare", "static", "and", "dynamic", "search", "structures", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L352-L374
235,923
splunk/splunk-sdk-python
examples/analytics/bottle.py
Router._compile_pattern
def _compile_pattern(self, rule): ''' Return a regular expression with named groups for each wildcard. ''' out = '' for i, part in enumerate(self.syntax.split(rule)): if i%3 == 0: out += re.escape(part.replace('\\:',':')) elif i%3 == 1: out += '(?P<%s>' % part if part else '(?:' else: out += '%s)' % (part or '[^/]+') return re.compile('^%s$'%out)
python
def _compile_pattern(self, rule): ''' Return a regular expression with named groups for each wildcard. ''' out = '' for i, part in enumerate(self.syntax.split(rule)): if i%3 == 0: out += re.escape(part.replace('\\:',':')) elif i%3 == 1: out += '(?P<%s>' % part if part else '(?:' else: out += '%s)' % (part or '[^/]+') return re.compile('^%s$'%out)
[ "def", "_compile_pattern", "(", "self", ",", "rule", ")", ":", "out", "=", "''", "for", "i", ",", "part", "in", "enumerate", "(", "self", ".", "syntax", ".", "split", "(", "rule", ")", ")", ":", "if", "i", "%", "3", "==", "0", ":", "out", "+=",...
Return a regular expression with named groups for each wildcard.
[ "Return", "a", "regular", "expression", "with", "named", "groups", "for", "each", "wildcard", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L376-L383
235,924
splunk/splunk-sdk-python
examples/analytics/bottle.py
Bottle.mount
def mount(self, app, prefix, **options): ''' Mount an application to a specific URL prefix. The prefix is added to SCIPT_PATH and removed from PATH_INFO before the sub-application is called. :param app: an instance of :class:`Bottle`. :param prefix: path prefix used as a mount-point. All other parameters are passed to the underlying :meth:`route` call. ''' if not isinstance(app, Bottle): raise TypeError('Only Bottle instances are supported for now.') prefix = '/'.join([_f for _f in prefix.split('/') if _f]) if not prefix: raise TypeError('Empty prefix. Perhaps you want a merge()?') for other in self.mounts: if other.startswith(prefix): raise TypeError('Conflict with existing mount: %s' % other) path_depth = prefix.count('/') + 1 options.setdefault('method', 'ANY') options.setdefault('skip', True) self.mounts[prefix] = app @self.route('/%s/:#.*#' % prefix, **options) def mountpoint(): request.path_shift(path_depth) return app._handle(request.environ)
python
def mount(self, app, prefix, **options): ''' Mount an application to a specific URL prefix. The prefix is added to SCIPT_PATH and removed from PATH_INFO before the sub-application is called. :param app: an instance of :class:`Bottle`. :param prefix: path prefix used as a mount-point. All other parameters are passed to the underlying :meth:`route` call. ''' if not isinstance(app, Bottle): raise TypeError('Only Bottle instances are supported for now.') prefix = '/'.join([_f for _f in prefix.split('/') if _f]) if not prefix: raise TypeError('Empty prefix. Perhaps you want a merge()?') for other in self.mounts: if other.startswith(prefix): raise TypeError('Conflict with existing mount: %s' % other) path_depth = prefix.count('/') + 1 options.setdefault('method', 'ANY') options.setdefault('skip', True) self.mounts[prefix] = app @self.route('/%s/:#.*#' % prefix, **options) def mountpoint(): request.path_shift(path_depth) return app._handle(request.environ)
[ "def", "mount", "(", "self", ",", "app", ",", "prefix", ",", "*", "*", "options", ")", ":", "if", "not", "isinstance", "(", "app", ",", "Bottle", ")", ":", "raise", "TypeError", "(", "'Only Bottle instances are supported for now.'", ")", "prefix", "=", "'/...
Mount an application to a specific URL prefix. The prefix is added to SCIPT_PATH and removed from PATH_INFO before the sub-application is called. :param app: an instance of :class:`Bottle`. :param prefix: path prefix used as a mount-point. All other parameters are passed to the underlying :meth:`route` call.
[ "Mount", "an", "application", "to", "a", "specific", "URL", "prefix", ".", "The", "prefix", "is", "added", "to", "SCIPT_PATH", "and", "removed", "from", "PATH_INFO", "before", "the", "sub", "-", "application", "is", "called", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L424-L449
235,925
splunk/splunk-sdk-python
examples/analytics/bottle.py
Bottle.uninstall
def uninstall(self, plugin): ''' Uninstall plugins. Pass an instance to remove a specific plugin. Pass a type object to remove all plugins that match that type. Subclasses are not removed. Pass a string to remove all plugins with a matching ``name`` attribute. Pass ``True`` to remove all plugins. The list of affected plugins is returned. ''' removed, remove = [], plugin for i, plugin in list(enumerate(self.plugins))[::-1]: if remove is True or remove is plugin or remove is type(plugin) \ or getattr(plugin, 'name', True) == remove: removed.append(plugin) del self.plugins[i] if hasattr(plugin, 'close'): plugin.close() if removed: self.reset() return removed
python
def uninstall(self, plugin): ''' Uninstall plugins. Pass an instance to remove a specific plugin. Pass a type object to remove all plugins that match that type. Subclasses are not removed. Pass a string to remove all plugins with a matching ``name`` attribute. Pass ``True`` to remove all plugins. The list of affected plugins is returned. ''' removed, remove = [], plugin for i, plugin in list(enumerate(self.plugins))[::-1]: if remove is True or remove is plugin or remove is type(plugin) \ or getattr(plugin, 'name', True) == remove: removed.append(plugin) del self.plugins[i] if hasattr(plugin, 'close'): plugin.close() if removed: self.reset() return removed
[ "def", "uninstall", "(", "self", ",", "plugin", ")", ":", "removed", ",", "remove", "=", "[", "]", ",", "plugin", "for", "i", ",", "plugin", "in", "list", "(", "enumerate", "(", "self", ".", "plugins", ")", ")", "[", ":", ":", "-", "1", "]", ":...
Uninstall plugins. Pass an instance to remove a specific plugin. Pass a type object to remove all plugins that match that type. Subclasses are not removed. Pass a string to remove all plugins with a matching ``name`` attribute. Pass ``True`` to remove all plugins. The list of affected plugins is returned.
[ "Uninstall", "plugins", ".", "Pass", "an", "instance", "to", "remove", "a", "specific", "plugin", ".", "Pass", "a", "type", "object", "to", "remove", "all", "plugins", "that", "match", "that", "type", ".", "Subclasses", "are", "not", "removed", ".", "Pass"...
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L467-L481
235,926
splunk/splunk-sdk-python
examples/analytics/bottle.py
Bottle.close
def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
python
def close(self): ''' Close the application and all installed plugins. ''' for plugin in self.plugins: if hasattr(plugin, 'close'): plugin.close() self.stopped = True
[ "def", "close", "(", "self", ")", ":", "for", "plugin", "in", "self", ".", "plugins", ":", "if", "hasattr", "(", "plugin", ",", "'close'", ")", ":", "plugin", ".", "close", "(", ")", "self", ".", "stopped", "=", "True" ]
Close the application and all installed plugins.
[ "Close", "the", "application", "and", "all", "installed", "plugins", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L493-L497
235,927
splunk/splunk-sdk-python
examples/analytics/bottle.py
Bottle._build_callback
def _build_callback(self, config): ''' Apply plugins to a route and return a new callable. ''' wrapped = config['callback'] plugins = self.plugins + config['apply'] skip = config['skip'] try: for plugin in reversed(plugins): if True in skip: break if plugin in skip or type(plugin) in skip: continue if getattr(plugin, 'name', True) in skip: continue if hasattr(plugin, 'apply'): wrapped = plugin.apply(wrapped, config) else: wrapped = plugin(wrapped) if not wrapped: break functools.update_wrapper(wrapped, config['callback']) return wrapped except RouteReset: # A plugin may have changed the config dict inplace. return self._build_callback(config)
python
def _build_callback(self, config): ''' Apply plugins to a route and return a new callable. ''' wrapped = config['callback'] plugins = self.plugins + config['apply'] skip = config['skip'] try: for plugin in reversed(plugins): if True in skip: break if plugin in skip or type(plugin) in skip: continue if getattr(plugin, 'name', True) in skip: continue if hasattr(plugin, 'apply'): wrapped = plugin.apply(wrapped, config) else: wrapped = plugin(wrapped) if not wrapped: break functools.update_wrapper(wrapped, config['callback']) return wrapped except RouteReset: # A plugin may have changed the config dict inplace. return self._build_callback(config)
[ "def", "_build_callback", "(", "self", ",", "config", ")", ":", "wrapped", "=", "config", "[", "'callback'", "]", "plugins", "=", "self", ".", "plugins", "+", "config", "[", "'apply'", "]", "skip", "=", "config", "[", "'skip'", "]", "try", ":", "for", ...
Apply plugins to a route and return a new callable.
[ "Apply", "plugins", "to", "a", "route", "and", "return", "a", "new", "callable", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L520-L538
235,928
splunk/splunk-sdk-python
examples/analytics/bottle.py
Bottle.hook
def hook(self, name): """ Return a decorator that attaches a callback to a hook. """ def wrapper(func): self.hooks.add(name, func) return func return wrapper
python
def hook(self, name): def wrapper(func): self.hooks.add(name, func) return func return wrapper
[ "def", "hook", "(", "self", ",", "name", ")", ":", "def", "wrapper", "(", "func", ")", ":", "self", ".", "hooks", ".", "add", "(", "name", ",", "func", ")", "return", "func", "return", "wrapper" ]
Return a decorator that attaches a callback to a hook.
[ "Return", "a", "decorator", "that", "attaches", "a", "callback", "to", "a", "hook", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L624-L629
235,929
splunk/splunk-sdk-python
examples/analytics/bottle.py
Request.bind
def bind(self, environ): """ Bind a new WSGI environment. This is done automatically for the global `bottle.request` instance on every request. """ self.environ = environ # These attributes are used anyway, so it is ok to compute them here self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/') self.method = environ.get('REQUEST_METHOD', 'GET').upper()
python
def bind(self, environ): self.environ = environ # These attributes are used anyway, so it is ok to compute them here self.path = '/' + environ.get('PATH_INFO', '/').lstrip('/') self.method = environ.get('REQUEST_METHOD', 'GET').upper()
[ "def", "bind", "(", "self", ",", "environ", ")", ":", "self", ".", "environ", "=", "environ", "# These attributes are used anyway, so it is ok to compute them here", "self", ".", "path", "=", "'/'", "+", "environ", ".", "get", "(", "'PATH_INFO'", ",", "'/'", ")"...
Bind a new WSGI environment. This is done automatically for the global `bottle.request` instance on every request.
[ "Bind", "a", "new", "WSGI", "environment", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L787-L796
235,930
splunk/splunk-sdk-python
examples/analytics/bottle.py
Request._body
def _body(self): """ The HTTP request body as a seekable file-like object. This property returns a copy of the `wsgi.input` stream and should be used instead of `environ['wsgi.input']`. """ maxread = max(0, self.content_length) stream = self.environ['wsgi.input'] body = BytesIO() if maxread < MEMFILE_MAX else TemporaryFile(mode='w+b') while maxread > 0: part = stream.read(min(maxread, MEMFILE_MAX)) if not part: break body.write(part) maxread -= len(part) self.environ['wsgi.input'] = body body.seek(0) return body
python
def _body(self): maxread = max(0, self.content_length) stream = self.environ['wsgi.input'] body = BytesIO() if maxread < MEMFILE_MAX else TemporaryFile(mode='w+b') while maxread > 0: part = stream.read(min(maxread, MEMFILE_MAX)) if not part: break body.write(part) maxread -= len(part) self.environ['wsgi.input'] = body body.seek(0) return body
[ "def", "_body", "(", "self", ")", ":", "maxread", "=", "max", "(", "0", ",", "self", ".", "content_length", ")", "stream", "=", "self", ".", "environ", "[", "'wsgi.input'", "]", "body", "=", "BytesIO", "(", ")", "if", "maxread", "<", "MEMFILE_MAX", "...
The HTTP request body as a seekable file-like object. This property returns a copy of the `wsgi.input` stream and should be used instead of `environ['wsgi.input']`.
[ "The", "HTTP", "request", "body", "as", "a", "seekable", "file", "-", "like", "object", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L953-L969
235,931
splunk/splunk-sdk-python
examples/analytics/bottle.py
Response.bind
def bind(self): """ Resets the Response object to its factory defaults. """ self._COOKIES = None self.status = 200 self.headers = HeaderDict() self.content_type = 'text/html; charset=UTF-8'
python
def bind(self): self._COOKIES = None self.status = 200 self.headers = HeaderDict() self.content_type = 'text/html; charset=UTF-8'
[ "def", "bind", "(", "self", ")", ":", "self", ".", "_COOKIES", "=", "None", "self", ".", "status", "=", "200", "self", ".", "headers", "=", "HeaderDict", "(", ")", "self", ".", "content_type", "=", "'text/html; charset=UTF-8'" ]
Resets the Response object to its factory defaults.
[ "Resets", "the", "Response", "object", "to", "its", "factory", "defaults", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1022-L1027
235,932
splunk/splunk-sdk-python
examples/analytics/bottle.py
Response.delete_cookie
def delete_cookie(self, key, **kwargs): ''' Delete a cookie. Be sure to use the same `domain` and `path` parameters as used to create the cookie. ''' kwargs['max_age'] = -1 kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs)
python
def delete_cookie(self, key, **kwargs): ''' Delete a cookie. Be sure to use the same `domain` and `path` parameters as used to create the cookie. ''' kwargs['max_age'] = -1 kwargs['expires'] = 0 self.set_cookie(key, '', **kwargs)
[ "def", "delete_cookie", "(", "self", ",", "key", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'max_age'", "]", "=", "-", "1", "kwargs", "[", "'expires'", "]", "=", "0", "self", ".", "set_cookie", "(", "key", ",", "''", ",", "*", "*", "kwarg...
Delete a cookie. Be sure to use the same `domain` and `path` parameters as used to create the cookie.
[ "Delete", "a", "cookie", ".", "Be", "sure", "to", "use", "the", "same", "domain", "and", "path", "parameters", "as", "used", "to", "create", "the", "cookie", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1110-L1115
235,933
splunk/splunk-sdk-python
examples/analytics/bottle.py
HooksPlugin.add
def add(self, name, func): ''' Attach a callback to a hook. ''' if name not in self.hooks: raise ValueError("Unknown hook name %s" % name) was_empty = self._empty() self.hooks[name].append(func) if self.app and was_empty and not self._empty(): self.app.reset()
python
def add(self, name, func): ''' Attach a callback to a hook. ''' if name not in self.hooks: raise ValueError("Unknown hook name %s" % name) was_empty = self._empty() self.hooks[name].append(func) if self.app and was_empty and not self._empty(): self.app.reset()
[ "def", "add", "(", "self", ",", "name", ",", "func", ")", ":", "if", "name", "not", "in", "self", ".", "hooks", ":", "raise", "ValueError", "(", "\"Unknown hook name %s\"", "%", "name", ")", "was_empty", "=", "self", ".", "_empty", "(", ")", "self", ...
Attach a callback to a hook.
[ "Attach", "a", "callback", "to", "a", "hook", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L1170-L1176
235,934
splunk/splunk-sdk-python
examples/analytics/bottle.py
BaseTemplate.global_config
def global_config(cls, key, *args): ''' This reads or sets the global settings stored in class.settings. ''' if args: cls.settings[key] = args[0] else: return cls.settings[key]
python
def global_config(cls, key, *args): ''' This reads or sets the global settings stored in class.settings. ''' if args: cls.settings[key] = args[0] else: return cls.settings[key]
[ "def", "global_config", "(", "cls", ",", "key", ",", "*", "args", ")", ":", "if", "args", ":", "cls", ".", "settings", "[", "key", "]", "=", "args", "[", "0", "]", "else", ":", "return", "cls", ".", "settings", "[", "key", "]" ]
This reads or sets the global settings stored in class.settings.
[ "This", "reads", "or", "sets", "the", "global", "settings", "stored", "in", "class", ".", "settings", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/analytics/bottle.py#L2137-L2142
235,935
splunk/splunk-sdk-python
splunklib/modularinput/script.py
Script.service
def service(self): """ Returns a Splunk service object for this script invocation. The service object is created from the Splunkd URI and session key passed to the command invocation on the modular input stream. It is available as soon as the :code:`Script.stream_events` method is called. :return: :class:splunklib.client.Service. A value of None is returned, if you call this method before the :code:`Script.stream_events` method is called. """ if self._service is not None: return self._service if self._input_definition is None: return None splunkd_uri = self._input_definition.metadata["server_uri"] session_key = self._input_definition.metadata["session_key"] splunkd = urlsplit(splunkd_uri, allow_fragments=False) self._service = Service( scheme=splunkd.scheme, host=splunkd.hostname, port=splunkd.port, token=session_key, ) return self._service
python
def service(self): if self._service is not None: return self._service if self._input_definition is None: return None splunkd_uri = self._input_definition.metadata["server_uri"] session_key = self._input_definition.metadata["session_key"] splunkd = urlsplit(splunkd_uri, allow_fragments=False) self._service = Service( scheme=splunkd.scheme, host=splunkd.hostname, port=splunkd.port, token=session_key, ) return self._service
[ "def", "service", "(", "self", ")", ":", "if", "self", ".", "_service", "is", "not", "None", ":", "return", "self", ".", "_service", "if", "self", ".", "_input_definition", "is", "None", ":", "return", "None", "splunkd_uri", "=", "self", ".", "_input_def...
Returns a Splunk service object for this script invocation. The service object is created from the Splunkd URI and session key passed to the command invocation on the modular input stream. It is available as soon as the :code:`Script.stream_events` method is called. :return: :class:splunklib.client.Service. A value of None is returned, if you call this method before the :code:`Script.stream_events` method is called.
[ "Returns", "a", "Splunk", "service", "object", "for", "this", "script", "invocation", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/script.py#L113-L144
235,936
splunk/splunk-sdk-python
examples/random_numbers/random_numbers.py
MyScript.validate_input
def validate_input(self, validation_definition): """In this example we are using external validation to verify that min is less than max. If validate_input does not raise an Exception, the input is assumed to be valid. Otherwise it prints the exception as an error message when telling splunkd that the configuration is invalid. When using external validation, after splunkd calls the modular input with --scheme to get a scheme, it calls it again with --validate-arguments for each instance of the modular input in its configuration files, feeding XML on stdin to the modular input to do validation. It is called the same way whenever a modular input's configuration is edited. :param validation_definition: a ValidationDefinition object """ # Get the parameters from the ValidationDefinition object, # then typecast the values as floats minimum = float(validation_definition.parameters["min"]) maximum = float(validation_definition.parameters["max"]) if minimum >= maximum: raise ValueError("min must be less than max; found min=%f, max=%f" % minimum, maximum)
python
def validate_input(self, validation_definition): # Get the parameters from the ValidationDefinition object, # then typecast the values as floats minimum = float(validation_definition.parameters["min"]) maximum = float(validation_definition.parameters["max"]) if minimum >= maximum: raise ValueError("min must be less than max; found min=%f, max=%f" % minimum, maximum)
[ "def", "validate_input", "(", "self", ",", "validation_definition", ")", ":", "# Get the parameters from the ValidationDefinition object,", "# then typecast the values as floats", "minimum", "=", "float", "(", "validation_definition", ".", "parameters", "[", "\"min\"", "]", "...
In this example we are using external validation to verify that min is less than max. If validate_input does not raise an Exception, the input is assumed to be valid. Otherwise it prints the exception as an error message when telling splunkd that the configuration is invalid. When using external validation, after splunkd calls the modular input with --scheme to get a scheme, it calls it again with --validate-arguments for each instance of the modular input in its configuration files, feeding XML on stdin to the modular input to do validation. It is called the same way whenever a modular input's configuration is edited. :param validation_definition: a ValidationDefinition object
[ "In", "this", "example", "we", "are", "using", "external", "validation", "to", "verify", "that", "min", "is", "less", "than", "max", ".", "If", "validate_input", "does", "not", "raise", "an", "Exception", "the", "input", "is", "assumed", "to", "be", "valid...
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/random_numbers/random_numbers.py#L73-L93
235,937
splunk/splunk-sdk-python
splunklib/modularinput/event.py
Event.write_to
def write_to(self, stream): """Write an XML representation of self, an ``Event`` object, to the given stream. The ``Event`` object will only be written if its data field is defined, otherwise a ``ValueError`` is raised. :param stream: stream to write XML to. """ if self.data is None: raise ValueError("Events must have at least the data field set to be written to XML.") event = ET.Element("event") if self.stanza is not None: event.set("stanza", self.stanza) event.set("unbroken", str(int(self.unbroken))) # if a time isn't set, let Splunk guess by not creating a <time> element if self.time is not None: ET.SubElement(event, "time").text = str(self.time) # add all other subelements to this Event, represented by (tag, text) subelements = [ ("source", self.source), ("sourcetype", self.sourceType), ("index", self.index), ("host", self.host), ("data", self.data) ] for node, value in subelements: if value is not None: ET.SubElement(event, node).text = value if self.done: ET.SubElement(event, "done") stream.write(ET.tostring(event)) stream.flush()
python
def write_to(self, stream): if self.data is None: raise ValueError("Events must have at least the data field set to be written to XML.") event = ET.Element("event") if self.stanza is not None: event.set("stanza", self.stanza) event.set("unbroken", str(int(self.unbroken))) # if a time isn't set, let Splunk guess by not creating a <time> element if self.time is not None: ET.SubElement(event, "time").text = str(self.time) # add all other subelements to this Event, represented by (tag, text) subelements = [ ("source", self.source), ("sourcetype", self.sourceType), ("index", self.index), ("host", self.host), ("data", self.data) ] for node, value in subelements: if value is not None: ET.SubElement(event, node).text = value if self.done: ET.SubElement(event, "done") stream.write(ET.tostring(event)) stream.flush()
[ "def", "write_to", "(", "self", ",", "stream", ")", ":", "if", "self", ".", "data", "is", "None", ":", "raise", "ValueError", "(", "\"Events must have at least the data field set to be written to XML.\"", ")", "event", "=", "ET", ".", "Element", "(", "\"event\"", ...
Write an XML representation of self, an ``Event`` object, to the given stream. The ``Event`` object will only be written if its data field is defined, otherwise a ``ValueError`` is raised. :param stream: stream to write XML to.
[ "Write", "an", "XML", "representation", "of", "self", "an", "Event", "object", "to", "the", "given", "stream", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/event.py#L72-L108
235,938
splunk/splunk-sdk-python
splunklib/client.py
Service.capabilities
def capabilities(self): """Returns the list of system capabilities. :return: A ``list`` of capabilities. """ response = self.get(PATH_CAPABILITIES) return _load_atom(response, MATCH_ENTRY_CONTENT).capabilities
python
def capabilities(self): response = self.get(PATH_CAPABILITIES) return _load_atom(response, MATCH_ENTRY_CONTENT).capabilities
[ "def", "capabilities", "(", "self", ")", ":", "response", "=", "self", ".", "get", "(", "PATH_CAPABILITIES", ")", "return", "_load_atom", "(", "response", ",", "MATCH_ENTRY_CONTENT", ")", ".", "capabilities" ]
Returns the list of system capabilities. :return: A ``list`` of capabilities.
[ "Returns", "the", "list", "of", "system", "capabilities", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L423-L429
235,939
splunk/splunk-sdk-python
splunklib/client.py
Service.modular_input_kinds
def modular_input_kinds(self): """Returns the collection of the modular input kinds on this Splunk instance. :return: A :class:`ReadOnlyCollection` of :class:`ModularInputKind` entities. """ if self.splunk_version >= (5,): return ReadOnlyCollection(self, PATH_MODULAR_INPUTS, item=ModularInputKind) else: raise IllegalOperationException("Modular inputs are not supported before Splunk version 5.")
python
def modular_input_kinds(self): if self.splunk_version >= (5,): return ReadOnlyCollection(self, PATH_MODULAR_INPUTS, item=ModularInputKind) else: raise IllegalOperationException("Modular inputs are not supported before Splunk version 5.")
[ "def", "modular_input_kinds", "(", "self", ")", ":", "if", "self", ".", "splunk_version", ">=", "(", "5", ",", ")", ":", "return", "ReadOnlyCollection", "(", "self", ",", "PATH_MODULAR_INPUTS", ",", "item", "=", "ModularInputKind", ")", "else", ":", "raise",...
Returns the collection of the modular input kinds on this Splunk instance. :return: A :class:`ReadOnlyCollection` of :class:`ModularInputKind` entities.
[ "Returns", "the", "collection", "of", "the", "modular", "input", "kinds", "on", "this", "Splunk", "instance", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L506-L514
235,940
splunk/splunk-sdk-python
splunklib/client.py
Service.restart_required
def restart_required(self): """Indicates whether splunkd is in a state that requires a restart. :return: A ``boolean`` that indicates whether a restart is required. """ response = self.get("messages").body.read() messages = data.load(response)['feed'] if 'entry' not in messages: result = False else: if isinstance(messages['entry'], dict): titles = [messages['entry']['title']] else: titles = [x['title'] for x in messages['entry']] result = 'restart_required' in titles return result
python
def restart_required(self): response = self.get("messages").body.read() messages = data.load(response)['feed'] if 'entry' not in messages: result = False else: if isinstance(messages['entry'], dict): titles = [messages['entry']['title']] else: titles = [x['title'] for x in messages['entry']] result = 'restart_required' in titles return result
[ "def", "restart_required", "(", "self", ")", ":", "response", "=", "self", ".", "get", "(", "\"messages\"", ")", ".", "body", ".", "read", "(", ")", "messages", "=", "data", ".", "load", "(", "response", ")", "[", "'feed'", "]", "if", "'entry'", "not...
Indicates whether splunkd is in a state that requires a restart. :return: A ``boolean`` that indicates whether a restart is required.
[ "Indicates", "whether", "splunkd", "is", "in", "a", "state", "that", "requires", "a", "restart", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L580-L596
235,941
splunk/splunk-sdk-python
splunklib/client.py
Service.splunk_version
def splunk_version(self): """Returns the version of the splunkd instance this object is attached to. The version is returned as a tuple of the version components as integers (for example, `(4,3,3)` or `(5,)`). :return: A ``tuple`` of ``integers``. """ if self._splunk_version is None: self._splunk_version = tuple([int(p) for p in self.info['version'].split('.')]) return self._splunk_version
python
def splunk_version(self): if self._splunk_version is None: self._splunk_version = tuple([int(p) for p in self.info['version'].split('.')]) return self._splunk_version
[ "def", "splunk_version", "(", "self", ")", ":", "if", "self", ".", "_splunk_version", "is", "None", ":", "self", ".", "_splunk_version", "=", "tuple", "(", "[", "int", "(", "p", ")", "for", "p", "in", "self", ".", "info", "[", "'version'", "]", ".", ...
Returns the version of the splunkd instance this object is attached to. The version is returned as a tuple of the version components as integers (for example, `(4,3,3)` or `(5,)`). :return: A ``tuple`` of ``integers``.
[ "Returns", "the", "version", "of", "the", "splunkd", "instance", "this", "object", "is", "attached", "to", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L656-L667
235,942
splunk/splunk-sdk-python
splunklib/client.py
Endpoint.get
def get(self, path_segment="", owner=None, app=None, sharing=None, **query): """Performs a GET operation on the path segment relative to this endpoint. This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus at most two additional round trips if the ``autologin`` field of :func:`connect` is set to ``True``. If *owner*, *app*, and *sharing* are omitted, this method takes a default namespace from the :class:`Service` object for this :class:`Endpoint`. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Service`` is not logged in. :raises HTTPError: Raised when an error in the request occurs. :param path_segment: A path segment relative to this endpoint. :type path_segment: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode for the namespace (optional). :type sharing: "global", "system", "app", or "user" :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` **Example**:: import splunklib.client s = client.service(...) apps = s.apps apps.get() == \\ {'body': ...a response reader object..., 'headers': [('content-length', '26208'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 16:30:35 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} apps.get('nonexistant/path') # raises HTTPError s.logout() apps.get() # raises AuthenticationError """ # self.path to the Endpoint is relative in the SDK, so passing # owner, app, sharing, etc. along will produce the correct # namespace in the final request. if path_segment.startswith('/'): path = path_segment else: path = self.service._abspath(self.path + path_segment, owner=owner, app=app, sharing=sharing) # ^-- This was "%s%s" % (self.path, path_segment). # That doesn't work, because self.path may be UrlEncoded. return self.service.get(path, owner=owner, app=app, sharing=sharing, **query)
python
def get(self, path_segment="", owner=None, app=None, sharing=None, **query): # self.path to the Endpoint is relative in the SDK, so passing # owner, app, sharing, etc. along will produce the correct # namespace in the final request. if path_segment.startswith('/'): path = path_segment else: path = self.service._abspath(self.path + path_segment, owner=owner, app=app, sharing=sharing) # ^-- This was "%s%s" % (self.path, path_segment). # That doesn't work, because self.path may be UrlEncoded. return self.service.get(path, owner=owner, app=app, sharing=sharing, **query)
[ "def", "get", "(", "self", ",", "path_segment", "=", "\"\"", ",", "owner", "=", "None", ",", "app", "=", "None", ",", "sharing", "=", "None", ",", "*", "*", "query", ")", ":", "# self.path to the Endpoint is relative in the SDK, so passing", "# owner, app, shari...
Performs a GET operation on the path segment relative to this endpoint. This method is named to match the HTTP method. This method makes at least one roundtrip to the server, one additional round trip for each 303 status returned, plus at most two additional round trips if the ``autologin`` field of :func:`connect` is set to ``True``. If *owner*, *app*, and *sharing* are omitted, this method takes a default namespace from the :class:`Service` object for this :class:`Endpoint`. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Service`` is not logged in. :raises HTTPError: Raised when an error in the request occurs. :param path_segment: A path segment relative to this endpoint. :type path_segment: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode for the namespace (optional). :type sharing: "global", "system", "app", or "user" :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` **Example**:: import splunklib.client s = client.service(...) apps = s.apps apps.get() == \\ {'body': ...a response reader object..., 'headers': [('content-length', '26208'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 16:30:35 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} apps.get('nonexistant/path') # raises HTTPError s.logout() apps.get() # raises AuthenticationError
[ "Performs", "a", "GET", "operation", "on", "the", "path", "segment", "relative", "to", "this", "endpoint", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L697-L759
235,943
splunk/splunk-sdk-python
splunklib/client.py
Entity._run_action
def _run_action(self, path_segment, **kwargs): """Run a method and return the content Record from the returned XML. A method is a relative path from an Entity that is not itself an Entity. _run_action assumes that the returned XML is an Atom field containing one Entry, and the contents of Entry is what should be the return value. This is right in enough cases to make this method useful. """ response = self.get(path_segment, **kwargs) data = self._load_atom_entry(response) rec = _parse_atom_entry(data) return rec.content
python
def _run_action(self, path_segment, **kwargs): response = self.get(path_segment, **kwargs) data = self._load_atom_entry(response) rec = _parse_atom_entry(data) return rec.content
[ "def", "_run_action", "(", "self", ",", "path_segment", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "get", "(", "path_segment", ",", "*", "*", "kwargs", ")", "data", "=", "self", ".", "_load_atom_entry", "(", "response", ")", "rec"...
Run a method and return the content Record from the returned XML. A method is a relative path from an Entity that is not itself an Entity. _run_action assumes that the returned XML is an Atom field containing one Entry, and the contents of Entry is what should be the return value. This is right in enough cases to make this method useful.
[ "Run", "a", "method", "and", "return", "the", "content", "Record", "from", "the", "returned", "XML", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L958-L970
235,944
splunk/splunk-sdk-python
splunklib/client.py
Entity._proper_namespace
def _proper_namespace(self, owner=None, app=None, sharing=None): """Produce a namespace sans wildcards for use in entity requests. This method tries to fill in the fields of the namespace which are `None` or wildcard (`'-'`) from the entity's namespace. If that fails, it uses the service's namespace. :param owner: :param app: :param sharing: :return: """ if owner is None and app is None and sharing is None: # No namespace provided if self._state is not None and 'access' in self._state: return (self._state.access.owner, self._state.access.app, self._state.access.sharing) else: return (self.service.namespace['owner'], self.service.namespace['app'], self.service.namespace['sharing']) else: return (owner,app,sharing)
python
def _proper_namespace(self, owner=None, app=None, sharing=None): if owner is None and app is None and sharing is None: # No namespace provided if self._state is not None and 'access' in self._state: return (self._state.access.owner, self._state.access.app, self._state.access.sharing) else: return (self.service.namespace['owner'], self.service.namespace['app'], self.service.namespace['sharing']) else: return (owner,app,sharing)
[ "def", "_proper_namespace", "(", "self", ",", "owner", "=", "None", ",", "app", "=", "None", ",", "sharing", "=", "None", ")", ":", "if", "owner", "is", "None", "and", "app", "is", "None", "and", "sharing", "is", "None", ":", "# No namespace provided", ...
Produce a namespace sans wildcards for use in entity requests. This method tries to fill in the fields of the namespace which are `None` or wildcard (`'-'`) from the entity's namespace. If that fails, it uses the service's namespace. :param owner: :param app: :param sharing: :return:
[ "Produce", "a", "namespace", "sans", "wildcards", "for", "use", "in", "entity", "requests", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L972-L994
235,945
splunk/splunk-sdk-python
splunklib/client.py
Entity.refresh
def refresh(self, state=None): """Refreshes the state of this entity. If *state* is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the :meth:`read` method of ``self``) to fetch an updated state, plus at most two additional round trips if the ``autologin`` field of :func:`connect` is set to ``True``. :param state: Entity-specific arguments (optional). :type state: ``dict`` :raises EntityDeletedException: Raised if the entity no longer exists on the server. **Example**:: import splunklib.client as client s = client.connect(...) search = s.apps['search'] search.refresh() """ if state is not None: self._state = state else: self._state = self.read(self.get()) return self
python
def refresh(self, state=None): if state is not None: self._state = state else: self._state = self.read(self.get()) return self
[ "def", "refresh", "(", "self", ",", "state", "=", "None", ")", ":", "if", "state", "is", "not", "None", ":", "self", ".", "_state", "=", "state", "else", ":", "self", ".", "_state", "=", "self", ".", "read", "(", "self", ".", "get", "(", ")", "...
Refreshes the state of this entity. If *state* is provided, load it as the new state for this entity. Otherwise, make a roundtrip to the server (by calling the :meth:`read` method of ``self``) to fetch an updated state, plus at most two additional round trips if the ``autologin`` field of :func:`connect` is set to ``True``. :param state: Entity-specific arguments (optional). :type state: ``dict`` :raises EntityDeletedException: Raised if the entity no longer exists on the server. **Example**:: import splunklib.client as client s = client.connect(...) search = s.apps['search'] search.refresh()
[ "Refreshes", "the", "state", "of", "this", "entity", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1008-L1033
235,946
splunk/splunk-sdk-python
splunklib/client.py
Entity.disable
def disable(self): """Disables the entity at this endpoint.""" self.post("disable") if self.service.restart_required: self.service.restart(120) return self
python
def disable(self): self.post("disable") if self.service.restart_required: self.service.restart(120) return self
[ "def", "disable", "(", "self", ")", ":", "self", ".", "post", "(", "\"disable\"", ")", "if", "self", ".", "service", ".", "restart_required", ":", "self", ".", "service", ".", "restart", "(", "120", ")", "return", "self" ]
Disables the entity at this endpoint.
[ "Disables", "the", "entity", "at", "this", "endpoint", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1052-L1057
235,947
splunk/splunk-sdk-python
splunklib/client.py
ReadOnlyCollection._entity_path
def _entity_path(self, state): """Calculate the path to an entity to be returned. *state* should be the dictionary returned by :func:`_parse_atom_entry`. :func:`_entity_path` extracts the link to this entity from *state*, and strips all the namespace prefixes from it to leave only the relative path of the entity itself, sans namespace. :rtype: ``string`` :return: an absolute path """ # This has been factored out so that it can be easily # overloaded by Configurations, which has to switch its # entities' endpoints from its own properties/ to configs/. raw_path = urllib.parse.unquote(state.links.alternate) if 'servicesNS/' in raw_path: return _trailing(raw_path, 'servicesNS/', '/', '/') elif 'services/' in raw_path: return _trailing(raw_path, 'services/') else: return raw_path
python
def _entity_path(self, state): # This has been factored out so that it can be easily # overloaded by Configurations, which has to switch its # entities' endpoints from its own properties/ to configs/. raw_path = urllib.parse.unquote(state.links.alternate) if 'servicesNS/' in raw_path: return _trailing(raw_path, 'servicesNS/', '/', '/') elif 'services/' in raw_path: return _trailing(raw_path, 'services/') else: return raw_path
[ "def", "_entity_path", "(", "self", ",", "state", ")", ":", "# This has been factored out so that it can be easily", "# overloaded by Configurations, which has to switch its", "# entities' endpoints from its own properties/ to configs/.", "raw_path", "=", "urllib", ".", "parse", ".",...
Calculate the path to an entity to be returned. *state* should be the dictionary returned by :func:`_parse_atom_entry`. :func:`_entity_path` extracts the link to this entity from *state*, and strips all the namespace prefixes from it to leave only the relative path of the entity itself, sans namespace. :rtype: ``string`` :return: an absolute path
[ "Calculate", "the", "path", "to", "an", "entity", "to", "be", "returned", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1291-L1312
235,948
splunk/splunk-sdk-python
splunklib/client.py
ReadOnlyCollection.itemmeta
def itemmeta(self): """Returns metadata for members of the collection. Makes a single roundtrip to the server, plus two more at most if the ``autologin`` field of :func:`connect` is set to ``True``. :return: A :class:`splunklib.data.Record` object containing the metadata. **Example**:: import splunklib.client as client import pprint s = client.connect(...) pprint.pprint(s.apps.itemmeta()) {'access': {'app': 'search', 'can_change_perms': '1', 'can_list': '1', 'can_share_app': '1', 'can_share_global': '1', 'can_share_user': '1', 'can_write': '1', 'modifiable': '1', 'owner': 'admin', 'perms': {'read': ['*'], 'write': ['admin']}, 'removable': '0', 'sharing': 'user'}, 'fields': {'optional': ['author', 'configured', 'description', 'label', 'manageable', 'template', 'visible'], 'required': ['name'], 'wildcard': []}} """ response = self.get("_new") content = _load_atom(response, MATCH_ENTRY_CONTENT) return _parse_atom_metadata(content)
python
def itemmeta(self): response = self.get("_new") content = _load_atom(response, MATCH_ENTRY_CONTENT) return _parse_atom_metadata(content)
[ "def", "itemmeta", "(", "self", ")", ":", "response", "=", "self", ".", "get", "(", "\"_new\"", ")", "content", "=", "_load_atom", "(", "response", ",", "MATCH_ENTRY_CONTENT", ")", "return", "_parse_atom_metadata", "(", "content", ")" ]
Returns metadata for members of the collection. Makes a single roundtrip to the server, plus two more at most if the ``autologin`` field of :func:`connect` is set to ``True``. :return: A :class:`splunklib.data.Record` object containing the metadata. **Example**:: import splunklib.client as client import pprint s = client.connect(...) pprint.pprint(s.apps.itemmeta()) {'access': {'app': 'search', 'can_change_perms': '1', 'can_list': '1', 'can_share_app': '1', 'can_share_global': '1', 'can_share_user': '1', 'can_write': '1', 'modifiable': '1', 'owner': 'admin', 'perms': {'read': ['*'], 'write': ['admin']}, 'removable': '0', 'sharing': 'user'}, 'fields': {'optional': ['author', 'configured', 'description', 'label', 'manageable', 'template', 'visible'], 'required': ['name'], 'wildcard': []}}
[ "Returns", "metadata", "for", "members", "of", "the", "collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1351-L1388
235,949
splunk/splunk-sdk-python
splunklib/client.py
ReadOnlyCollection.iter
def iter(self, offset=0, count=None, pagesize=None, **kwargs): """Iterates over the collection. This method is equivalent to the :meth:`list` method, but it returns an iterator and can load a certain number of entities at a time from the server. :param offset: The index of the first entity to return (optional). :type offset: ``integer`` :param count: The maximum number of entities to return (optional). :type count: ``integer`` :param pagesize: The number of entities to load (optional). :type pagesize: ``integer`` :param kwargs: Additional arguments (optional): - "search" (``string``): The search query to filter responses. - "sort_dir" (``string``): The direction to sort returned items: "asc" or "desc". - "sort_key" (``string``): The field to use for sorting (optional). - "sort_mode" (``string``): The collating sequence for sorting returned items: "auto", "alpha", "alpha_case", or "num". :type kwargs: ``dict`` **Example**:: import splunklib.client as client s = client.connect(...) for saved_search in s.saved_searches.iter(pagesize=10): # Loads 10 saved searches at a time from the # server. ... """ assert pagesize is None or pagesize > 0 if count is None: count = self.null_count fetched = 0 while count == self.null_count or fetched < count: response = self.get(count=pagesize or count, offset=offset, **kwargs) items = self._load_list(response) N = len(items) fetched += N for item in items: yield item if pagesize is None or N < pagesize: break offset += N logging.debug("pagesize=%d, fetched=%d, offset=%d, N=%d, kwargs=%s", pagesize, fetched, offset, N, kwargs)
python
def iter(self, offset=0, count=None, pagesize=None, **kwargs): assert pagesize is None or pagesize > 0 if count is None: count = self.null_count fetched = 0 while count == self.null_count or fetched < count: response = self.get(count=pagesize or count, offset=offset, **kwargs) items = self._load_list(response) N = len(items) fetched += N for item in items: yield item if pagesize is None or N < pagesize: break offset += N logging.debug("pagesize=%d, fetched=%d, offset=%d, N=%d, kwargs=%s", pagesize, fetched, offset, N, kwargs)
[ "def", "iter", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "None", ",", "pagesize", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "pagesize", "is", "None", "or", "pagesize", ">", "0", "if", "count", "is", "None", ":", "co...
Iterates over the collection. This method is equivalent to the :meth:`list` method, but it returns an iterator and can load a certain number of entities at a time from the server. :param offset: The index of the first entity to return (optional). :type offset: ``integer`` :param count: The maximum number of entities to return (optional). :type count: ``integer`` :param pagesize: The number of entities to load (optional). :type pagesize: ``integer`` :param kwargs: Additional arguments (optional): - "search" (``string``): The search query to filter responses. - "sort_dir" (``string``): The direction to sort returned items: "asc" or "desc". - "sort_key" (``string``): The field to use for sorting (optional). - "sort_mode" (``string``): The collating sequence for sorting returned items: "auto", "alpha", "alpha_case", or "num". :type kwargs: ``dict`` **Example**:: import splunklib.client as client s = client.connect(...) for saved_search in s.saved_searches.iter(pagesize=10): # Loads 10 saved searches at a time from the # server. ...
[ "Iterates", "over", "the", "collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1390-L1440
235,950
splunk/splunk-sdk-python
splunklib/client.py
ReadOnlyCollection.list
def list(self, count=None, **kwargs): """Retrieves a list of entities in this collection. The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. There is no caching--every call makes at least one round trip. :param count: The maximum number of entities to return (optional). :type count: ``integer`` :param kwargs: Additional arguments (optional): - "offset" (``integer``): The offset of the first item to return. - "search" (``string``): The search query to filter responses. - "sort_dir" (``string``): The direction to sort returned items: "asc" or "desc". - "sort_key" (``string``): The field to use for sorting (optional). - "sort_mode" (``string``): The collating sequence for sorting returned items: "auto", "alpha", "alpha_case", or "num". :type kwargs: ``dict`` :return: A ``list`` of entities. """ # response = self.get(count=count, **kwargs) # return self._load_list(response) return list(self.iter(count=count, **kwargs))
python
def list(self, count=None, **kwargs): # response = self.get(count=count, **kwargs) # return self._load_list(response) return list(self.iter(count=count, **kwargs))
[ "def", "list", "(", "self", ",", "count", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# response = self.get(count=count, **kwargs)", "# return self._load_list(response)", "return", "list", "(", "self", ".", "iter", "(", "count", "=", "count", ",", "*", "*...
Retrieves a list of entities in this collection. The entire collection is loaded at once and is returned as a list. This function makes a single roundtrip to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. There is no caching--every call makes at least one round trip. :param count: The maximum number of entities to return (optional). :type count: ``integer`` :param kwargs: Additional arguments (optional): - "offset" (``integer``): The offset of the first item to return. - "search" (``string``): The search query to filter responses. - "sort_dir" (``string``): The direction to sort returned items: "asc" or "desc". - "sort_key" (``string``): The field to use for sorting (optional). - "sort_mode" (``string``): The collating sequence for sorting returned items: "auto", "alpha", "alpha_case", or "num". :type kwargs: ``dict`` :return: A ``list`` of entities.
[ "Retrieves", "a", "list", "of", "entities", "in", "this", "collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1443-L1472
235,951
splunk/splunk-sdk-python
splunklib/client.py
Collection.delete
def delete(self, name, **params): """Deletes a specified entity from the collection. :param name: The name of the entity to delete. :type name: ``string`` :return: The collection. :rtype: ``self`` This method is implemented for consistency with the REST API's DELETE method. If there is no *name* entity on the server, a ``KeyError`` is thrown. This function always makes a roundtrip to the server. **Example**:: import splunklib.client as client c = client.connect(...) saved_searches = c.saved_searches saved_searches.create('my_saved_search', 'search * | head 1') assert 'my_saved_search' in saved_searches saved_searches.delete('my_saved_search') assert 'my_saved_search' not in saved_searches """ name = UrlEncoded(name, encode_slash=True) if 'namespace' in params: namespace = params.pop('namespace') params['owner'] = namespace.owner params['app'] = namespace.app params['sharing'] = namespace.sharing try: self.service.delete(_path(self.path, name), **params) except HTTPError as he: # An HTTPError with status code 404 means that the entity # has already been deleted, and we reraise it as a # KeyError. if he.status == 404: raise KeyError("No such entity %s" % name) else: raise return self
python
def delete(self, name, **params): name = UrlEncoded(name, encode_slash=True) if 'namespace' in params: namespace = params.pop('namespace') params['owner'] = namespace.owner params['app'] = namespace.app params['sharing'] = namespace.sharing try: self.service.delete(_path(self.path, name), **params) except HTTPError as he: # An HTTPError with status code 404 means that the entity # has already been deleted, and we reraise it as a # KeyError. if he.status == 404: raise KeyError("No such entity %s" % name) else: raise return self
[ "def", "delete", "(", "self", ",", "name", ",", "*", "*", "params", ")", ":", "name", "=", "UrlEncoded", "(", "name", ",", "encode_slash", "=", "True", ")", "if", "'namespace'", "in", "params", ":", "namespace", "=", "params", ".", "pop", "(", "'name...
Deletes a specified entity from the collection. :param name: The name of the entity to delete. :type name: ``string`` :return: The collection. :rtype: ``self`` This method is implemented for consistency with the REST API's DELETE method. If there is no *name* entity on the server, a ``KeyError`` is thrown. This function always makes a roundtrip to the server. **Example**:: import splunklib.client as client c = client.connect(...) saved_searches = c.saved_searches saved_searches.create('my_saved_search', 'search * | head 1') assert 'my_saved_search' in saved_searches saved_searches.delete('my_saved_search') assert 'my_saved_search' not in saved_searches
[ "Deletes", "a", "specified", "entity", "from", "the", "collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1572-L1613
235,952
splunk/splunk-sdk-python
splunklib/client.py
Collection.get
def get(self, name="", owner=None, app=None, sharing=None, **query): """Performs a GET request to the server on the collection. If *owner*, *app*, and *sharing* are omitted, this method takes a default namespace from the :class:`Service` object for this :class:`Endpoint`. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Service`` is not logged in. :raises HTTPError: Raised when an error in the request occurs. :param path_segment: A path segment relative to this endpoint. :type path_segment: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode for the namespace (optional). :type sharing: "global", "system", "app", or "user" :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` Example: import splunklib.client s = client.service(...) saved_searches = s.saved_searches saved_searches.get("my/saved/search") == \\ {'body': ...a response reader object..., 'headers': [('content-length', '26208'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 16:30:35 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} saved_searches.get('nonexistant/search') # raises HTTPError s.logout() saved_searches.get() # raises AuthenticationError """ name = UrlEncoded(name, encode_slash=True) return super(Collection, self).get(name, owner, app, sharing, **query)
python
def get(self, name="", owner=None, app=None, sharing=None, **query): name = UrlEncoded(name, encode_slash=True) return super(Collection, self).get(name, owner, app, sharing, **query)
[ "def", "get", "(", "self", ",", "name", "=", "\"\"", ",", "owner", "=", "None", ",", "app", "=", "None", ",", "sharing", "=", "None", ",", "*", "*", "query", ")", ":", "name", "=", "UrlEncoded", "(", "name", ",", "encode_slash", "=", "True", ")",...
Performs a GET request to the server on the collection. If *owner*, *app*, and *sharing* are omitted, this method takes a default namespace from the :class:`Service` object for this :class:`Endpoint`. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Service`` is not logged in. :raises HTTPError: Raised when an error in the request occurs. :param path_segment: A path segment relative to this endpoint. :type path_segment: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode for the namespace (optional). :type sharing: "global", "system", "app", or "user" :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` Example: import splunklib.client s = client.service(...) saved_searches = s.saved_searches saved_searches.get("my/saved/search") == \\ {'body': ...a response reader object..., 'headers': [('content-length', '26208'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 16:30:35 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} saved_searches.get('nonexistant/search') # raises HTTPError s.logout() saved_searches.get() # raises AuthenticationError
[ "Performs", "a", "GET", "request", "to", "the", "server", "on", "the", "collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1615-L1661
235,953
splunk/splunk-sdk-python
splunklib/client.py
Stanza.submit
def submit(self, stanza): """Adds keys to the current configuration stanza as a dictionary of key-value pairs. :param stanza: A dictionary of key-value pairs for the stanza. :type stanza: ``dict`` :return: The :class:`Stanza` object. """ body = _encode(**stanza) self.service.post(self.path, body=body) return self
python
def submit(self, stanza): body = _encode(**stanza) self.service.post(self.path, body=body) return self
[ "def", "submit", "(", "self", ",", "stanza", ")", ":", "body", "=", "_encode", "(", "*", "*", "stanza", ")", "self", ".", "service", ".", "post", "(", "self", ".", "path", ",", "body", "=", "body", ")", "return", "self" ]
Adds keys to the current configuration stanza as a dictionary of key-value pairs. :param stanza: A dictionary of key-value pairs for the stanza. :type stanza: ``dict`` :return: The :class:`Stanza` object.
[ "Adds", "keys", "to", "the", "current", "configuration", "stanza", "as", "a", "dictionary", "of", "key", "-", "value", "pairs", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1757-L1767
235,954
splunk/splunk-sdk-python
splunklib/client.py
Indexes.delete
def delete(self, name): """ Deletes a given index. **Note**: This method is only supported in Splunk 5.0 and later. :param name: The name of the index to delete. :type name: ``string`` """ if self.service.splunk_version >= (5,): Collection.delete(self, name) else: raise IllegalOperationException("Deleting indexes via the REST API is " "not supported before Splunk version 5.")
python
def delete(self, name): if self.service.splunk_version >= (5,): Collection.delete(self, name) else: raise IllegalOperationException("Deleting indexes via the REST API is " "not supported before Splunk version 5.")
[ "def", "delete", "(", "self", ",", "name", ")", ":", "if", "self", ".", "service", ".", "splunk_version", ">=", "(", "5", ",", ")", ":", "Collection", ".", "delete", "(", "self", ",", "name", ")", "else", ":", "raise", "IllegalOperationException", "(",...
Deletes a given index. **Note**: This method is only supported in Splunk 5.0 and later. :param name: The name of the index to delete. :type name: ``string``
[ "Deletes", "a", "given", "index", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1913-L1925
235,955
splunk/splunk-sdk-python
splunklib/client.py
Index.attached_socket
def attached_socket(self, *args, **kwargs): """Opens a raw socket in a ``with`` block to write data to Splunk. The arguments are identical to those for :meth:`attach`. The socket is automatically closed at the end of the ``with`` block, even if an exception is raised in the block. :param host: The host value for events written to the stream. :type host: ``string`` :param source: The source value for events written to the stream. :type source: ``string`` :param sourcetype: The sourcetype value for events written to the stream. :type sourcetype: ``string`` :returns: Nothing. **Example**:: import splunklib.client as client s = client.connect(...) index = s.indexes['some_index'] with index.attached_socket(sourcetype='test') as sock: sock.send('Test event\\r\\n') """ try: sock = self.attach(*args, **kwargs) yield sock finally: sock.shutdown(socket.SHUT_RDWR) sock.close()
python
def attached_socket(self, *args, **kwargs): try: sock = self.attach(*args, **kwargs) yield sock finally: sock.shutdown(socket.SHUT_RDWR) sock.close()
[ "def", "attached_socket", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "sock", "=", "self", ".", "attach", "(", "*", "args", ",", "*", "*", "kwargs", ")", "yield", "sock", "finally", ":", "sock", ".", "shutdown", ...
Opens a raw socket in a ``with`` block to write data to Splunk. The arguments are identical to those for :meth:`attach`. The socket is automatically closed at the end of the ``with`` block, even if an exception is raised in the block. :param host: The host value for events written to the stream. :type host: ``string`` :param source: The source value for events written to the stream. :type source: ``string`` :param sourcetype: The sourcetype value for events written to the stream. :type sourcetype: ``string`` :returns: Nothing. **Example**:: import splunklib.client as client s = client.connect(...) index = s.indexes['some_index'] with index.attached_socket(sourcetype='test') as sock: sock.send('Test event\\r\\n')
[ "Opens", "a", "raw", "socket", "in", "a", "with", "block", "to", "write", "data", "to", "Splunk", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L1977-L2008
235,956
splunk/splunk-sdk-python
splunklib/client.py
Index.clean
def clean(self, timeout=60): """Deletes the contents of the index. This method blocks until the index is empty, because it needs to restore values at the end of the operation. :param timeout: The time-out period for the operation, in seconds (the default is 60). :type timeout: ``integer`` :return: The :class:`Index`. """ self.refresh() tds = self['maxTotalDataSizeMB'] ftp = self['frozenTimePeriodInSecs'] was_disabled_initially = self.disabled try: if (not was_disabled_initially and \ self.service.splunk_version < (5,)): # Need to disable the index first on Splunk 4.x, # but it doesn't work to disable it on 5.0. self.disable() self.update(maxTotalDataSizeMB=1, frozenTimePeriodInSecs=1) self.roll_hot_buckets() # Wait until event count goes to 0. start = datetime.now() diff = timedelta(seconds=timeout) while self.content.totalEventCount != '0' and datetime.now() < start+diff: sleep(1) self.refresh() if self.content.totalEventCount != '0': raise OperationError("Cleaning index %s took longer than %s seconds; timing out." % (self.name, timeout)) finally: # Restore original values self.update(maxTotalDataSizeMB=tds, frozenTimePeriodInSecs=ftp) if (not was_disabled_initially and \ self.service.splunk_version < (5,)): # Re-enable the index if it was originally enabled and we messed with it. self.enable() return self
python
def clean(self, timeout=60): self.refresh() tds = self['maxTotalDataSizeMB'] ftp = self['frozenTimePeriodInSecs'] was_disabled_initially = self.disabled try: if (not was_disabled_initially and \ self.service.splunk_version < (5,)): # Need to disable the index first on Splunk 4.x, # but it doesn't work to disable it on 5.0. self.disable() self.update(maxTotalDataSizeMB=1, frozenTimePeriodInSecs=1) self.roll_hot_buckets() # Wait until event count goes to 0. start = datetime.now() diff = timedelta(seconds=timeout) while self.content.totalEventCount != '0' and datetime.now() < start+diff: sleep(1) self.refresh() if self.content.totalEventCount != '0': raise OperationError("Cleaning index %s took longer than %s seconds; timing out." % (self.name, timeout)) finally: # Restore original values self.update(maxTotalDataSizeMB=tds, frozenTimePeriodInSecs=ftp) if (not was_disabled_initially and \ self.service.splunk_version < (5,)): # Re-enable the index if it was originally enabled and we messed with it. self.enable() return self
[ "def", "clean", "(", "self", ",", "timeout", "=", "60", ")", ":", "self", ".", "refresh", "(", ")", "tds", "=", "self", "[", "'maxTotalDataSizeMB'", "]", "ftp", "=", "self", "[", "'frozenTimePeriodInSecs'", "]", "was_disabled_initially", "=", "self", ".", ...
Deletes the contents of the index. This method blocks until the index is empty, because it needs to restore values at the end of the operation. :param timeout: The time-out period for the operation, in seconds (the default is 60). :type timeout: ``integer`` :return: The :class:`Index`.
[ "Deletes", "the", "contents", "of", "the", "index", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2010-L2053
235,957
splunk/splunk-sdk-python
splunklib/client.py
Index.submit
def submit(self, event, host=None, source=None, sourcetype=None): """Submits a single event to the index using ``HTTP POST``. :param event: The event to submit. :type event: ``string`` :param `host`: The host value of the event. :type host: ``string`` :param `source`: The source value of the event. :type source: ``string`` :param `sourcetype`: The sourcetype value of the event. :type sourcetype: ``string`` :return: The :class:`Index`. """ args = { 'index': self.name } if host is not None: args['host'] = host if source is not None: args['source'] = source if sourcetype is not None: args['sourcetype'] = sourcetype # The reason we use service.request directly rather than POST # is that we are not sending a POST request encoded using # x-www-form-urlencoded (as we do not have a key=value body), # because we aren't really sending a "form". self.service.post(PATH_RECEIVERS_SIMPLE, body=event, **args) return self
python
def submit(self, event, host=None, source=None, sourcetype=None): args = { 'index': self.name } if host is not None: args['host'] = host if source is not None: args['source'] = source if sourcetype is not None: args['sourcetype'] = sourcetype # The reason we use service.request directly rather than POST # is that we are not sending a POST request encoded using # x-www-form-urlencoded (as we do not have a key=value body), # because we aren't really sending a "form". self.service.post(PATH_RECEIVERS_SIMPLE, body=event, **args) return self
[ "def", "submit", "(", "self", ",", "event", ",", "host", "=", "None", ",", "source", "=", "None", ",", "sourcetype", "=", "None", ")", ":", "args", "=", "{", "'index'", ":", "self", ".", "name", "}", "if", "host", "is", "not", "None", ":", "args"...
Submits a single event to the index using ``HTTP POST``. :param event: The event to submit. :type event: ``string`` :param `host`: The host value of the event. :type host: ``string`` :param `source`: The source value of the event. :type source: ``string`` :param `sourcetype`: The sourcetype value of the event. :type sourcetype: ``string`` :return: The :class:`Index`.
[ "Submits", "a", "single", "event", "to", "the", "index", "using", "HTTP", "POST", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2063-L2087
235,958
splunk/splunk-sdk-python
splunklib/client.py
Index.upload
def upload(self, filename, **kwargs): """Uploads a file for immediate indexing. **Note**: The file must be locally accessible from the server. :param filename: The name of the file to upload. The file can be a plain, compressed, or archived file. :type filename: ``string`` :param kwargs: Additional arguments (optional). For more about the available parameters, see `Index parameters <http://dev.splunk.com/view/SP-CAAAEE6#indexparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`Index`. """ kwargs['index'] = self.name path = 'data/inputs/oneshot' self.service.post(path, name=filename, **kwargs) return self
python
def upload(self, filename, **kwargs): kwargs['index'] = self.name path = 'data/inputs/oneshot' self.service.post(path, name=filename, **kwargs) return self
[ "def", "upload", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'index'", "]", "=", "self", ".", "name", "path", "=", "'data/inputs/oneshot'", "self", ".", "service", ".", "post", "(", "path", ",", "name", "=", "file...
Uploads a file for immediate indexing. **Note**: The file must be locally accessible from the server. :param filename: The name of the file to upload. The file can be a plain, compressed, or archived file. :type filename: ``string`` :param kwargs: Additional arguments (optional). For more about the available parameters, see `Index parameters <http://dev.splunk.com/view/SP-CAAAEE6#indexparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`Index`.
[ "Uploads", "a", "file", "for", "immediate", "indexing", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2090-L2107
235,959
splunk/splunk-sdk-python
splunklib/client.py
Input.update
def update(self, **kwargs): """Updates the server with any changes you've made to the current input along with any additional arguments you specify. :param kwargs: Additional arguments (optional). For more about the available parameters, see `Input parameters <http://dev.splunk.com/view/SP-CAAAEE6#inputparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The input this method was called on. :rtype: class:`Input` """ # UDP and TCP inputs require special handling due to their restrictToHost # field. For all other inputs kinds, we can dispatch to the superclass method. if self.kind not in ['tcp', 'splunktcp', 'tcp/raw', 'tcp/cooked', 'udp']: return super(Input, self).update(**kwargs) else: # The behavior of restrictToHost is inconsistent across input kinds and versions of Splunk. # In Splunk 4.x, the name of the entity is only the port, independent of the value of # restrictToHost. In Splunk 5.0 this changed so the name will be of the form <restrictToHost>:<port>. # In 5.0 and 5.0.1, if you don't supply the restrictToHost value on every update, it will # remove the host restriction from the input. As of 5.0.2 you simply can't change restrictToHost # on an existing input. # The logic to handle all these cases: # - Throw an exception if the user tries to set restrictToHost on an existing input # for *any* version of Splunk. # - Set the existing restrictToHost value on the update args internally so we don't # cause it to change in Splunk 5.0 and 5.0.1. to_update = kwargs.copy() if 'restrictToHost' in kwargs: raise IllegalOperationException("Cannot set restrictToHost on an existing input with the SDK.") elif 'restrictToHost' in self._state.content and self.kind != 'udp': to_update['restrictToHost'] = self._state.content['restrictToHost'] # Do the actual update operation. return super(Input, self).update(**to_update)
python
def update(self, **kwargs): # UDP and TCP inputs require special handling due to their restrictToHost # field. For all other inputs kinds, we can dispatch to the superclass method. if self.kind not in ['tcp', 'splunktcp', 'tcp/raw', 'tcp/cooked', 'udp']: return super(Input, self).update(**kwargs) else: # The behavior of restrictToHost is inconsistent across input kinds and versions of Splunk. # In Splunk 4.x, the name of the entity is only the port, independent of the value of # restrictToHost. In Splunk 5.0 this changed so the name will be of the form <restrictToHost>:<port>. # In 5.0 and 5.0.1, if you don't supply the restrictToHost value on every update, it will # remove the host restriction from the input. As of 5.0.2 you simply can't change restrictToHost # on an existing input. # The logic to handle all these cases: # - Throw an exception if the user tries to set restrictToHost on an existing input # for *any* version of Splunk. # - Set the existing restrictToHost value on the update args internally so we don't # cause it to change in Splunk 5.0 and 5.0.1. to_update = kwargs.copy() if 'restrictToHost' in kwargs: raise IllegalOperationException("Cannot set restrictToHost on an existing input with the SDK.") elif 'restrictToHost' in self._state.content and self.kind != 'udp': to_update['restrictToHost'] = self._state.content['restrictToHost'] # Do the actual update operation. return super(Input, self).update(**to_update)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# UDP and TCP inputs require special handling due to their restrictToHost", "# field. For all other inputs kinds, we can dispatch to the superclass method.", "if", "self", ".", "kind", "not", "in", "[", "'tcp'", ...
Updates the server with any changes you've made to the current input along with any additional arguments you specify. :param kwargs: Additional arguments (optional). For more about the available parameters, see `Input parameters <http://dev.splunk.com/view/SP-CAAAEE6#inputparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The input this method was called on. :rtype: class:`Input`
[ "Updates", "the", "server", "with", "any", "changes", "you", "ve", "made", "to", "the", "current", "input", "along", "with", "any", "additional", "arguments", "you", "specify", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2137-L2173
235,960
splunk/splunk-sdk-python
splunklib/client.py
Inputs.create
def create(self, name, kind, **kwargs): """Creates an input of a specific kind in this collection, with any arguments you specify. :param `name`: The input name. :type name: ``string`` :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splunktcp": TCP, processed - "tcp": TCP, unprocessed - "udp": UDP - "win-event-log-collections": Windows event log - "win-perfmon": Performance monitoring - "win-wmi-collections": WMI :type kind: ``string`` :param `kwargs`: Additional arguments (optional). For more about the available parameters, see `Input parameters <http://dev.splunk.com/view/SP-CAAAEE6#inputparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The new :class:`Input`. """ kindpath = self.kindpath(kind) self.post(kindpath, name=name, **kwargs) # If we created an input with restrictToHost set, then # its path will be <restrictToHost>:<name>, not just <name>, # and we have to adjust accordingly. # Url encodes the name of the entity. name = UrlEncoded(name, encode_slash=True) path = _path( self.path + kindpath, '%s:%s' % (kwargs['restrictToHost'], name) \ if 'restrictToHost' in kwargs else name ) return Input(self.service, path, kind)
python
def create(self, name, kind, **kwargs): kindpath = self.kindpath(kind) self.post(kindpath, name=name, **kwargs) # If we created an input with restrictToHost set, then # its path will be <restrictToHost>:<name>, not just <name>, # and we have to adjust accordingly. # Url encodes the name of the entity. name = UrlEncoded(name, encode_slash=True) path = _path( self.path + kindpath, '%s:%s' % (kwargs['restrictToHost'], name) \ if 'restrictToHost' in kwargs else name ) return Input(self.service, path, kind)
[ "def", "create", "(", "self", ",", "name", ",", "kind", ",", "*", "*", "kwargs", ")", ":", "kindpath", "=", "self", ".", "kindpath", "(", "kind", ")", "self", ".", "post", "(", "kindpath", ",", "name", "=", "name", ",", "*", "*", "kwargs", ")", ...
Creates an input of a specific kind in this collection, with any arguments you specify. :param `name`: The input name. :type name: ``string`` :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splunktcp": TCP, processed - "tcp": TCP, unprocessed - "udp": UDP - "win-event-log-collections": Windows event log - "win-perfmon": Performance monitoring - "win-wmi-collections": WMI :type kind: ``string`` :param `kwargs`: Additional arguments (optional). For more about the available parameters, see `Input parameters <http://dev.splunk.com/view/SP-CAAAEE6#inputparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The new :class:`Input`.
[ "Creates", "an", "input", "of", "a", "specific", "kind", "in", "this", "collection", "with", "any", "arguments", "you", "specify", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2264-L2314
235,961
splunk/splunk-sdk-python
splunklib/client.py
Inputs.delete
def delete(self, name, kind=None): """Removes an input from the collection. :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splunktcp": TCP, processed - "tcp": TCP, unprocessed - "udp": UDP - "win-event-log-collections": Windows event log - "win-perfmon": Performance monitoring - "win-wmi-collections": WMI :type kind: ``string`` :param name: The name of the input to remove. :type name: ``string`` :return: The :class:`Inputs` collection. """ if kind is None: self.service.delete(self[name].path) else: self.service.delete(self[name, kind].path) return self
python
def delete(self, name, kind=None): if kind is None: self.service.delete(self[name].path) else: self.service.delete(self[name, kind].path) return self
[ "def", "delete", "(", "self", ",", "name", ",", "kind", "=", "None", ")", ":", "if", "kind", "is", "None", ":", "self", ".", "service", ".", "delete", "(", "self", "[", "name", "]", ".", "path", ")", "else", ":", "self", ".", "service", ".", "d...
Removes an input from the collection. :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splunktcp": TCP, processed - "tcp": TCP, unprocessed - "udp": UDP - "win-event-log-collections": Windows event log - "win-perfmon": Performance monitoring - "win-wmi-collections": WMI :type kind: ``string`` :param name: The name of the input to remove. :type name: ``string`` :return: The :class:`Inputs` collection.
[ "Removes", "an", "input", "from", "the", "collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2316-L2351
235,962
splunk/splunk-sdk-python
splunklib/client.py
Job.cancel
def cancel(self): """Stops the current search and deletes the results cache. :return: The :class:`Job`. """ try: self.post("control", action="cancel") except HTTPError as he: if he.status == 404: # The job has already been cancelled, so # cancelling it twice is a nop. pass else: raise return self
python
def cancel(self): try: self.post("control", action="cancel") except HTTPError as he: if he.status == 404: # The job has already been cancelled, so # cancelling it twice is a nop. pass else: raise return self
[ "def", "cancel", "(", "self", ")", ":", "try", ":", "self", ".", "post", "(", "\"control\"", ",", "action", "=", "\"cancel\"", ")", "except", "HTTPError", "as", "he", ":", "if", "he", ".", "status", "==", "404", ":", "# The job has already been cancelled, ...
Stops the current search and deletes the results cache. :return: The :class:`Job`.
[ "Stops", "the", "current", "search", "and", "deletes", "the", "results", "cache", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2634-L2648
235,963
splunk/splunk-sdk-python
splunklib/client.py
Job.events
def events(self, **kwargs): """Returns a streaming handle to this job's events. :param kwargs: Additional parameters (optional). For a list of valid parameters, see `GET search/jobs/{search_id}/events <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fevents>`_ in the REST API documentation. :type kwargs: ``dict`` :return: The ``InputStream`` IO handle to this job's events. """ kwargs['segmentation'] = kwargs.get('segmentation', 'none') return self.get("events", **kwargs).body
python
def events(self, **kwargs): kwargs['segmentation'] = kwargs.get('segmentation', 'none') return self.get("events", **kwargs).body
[ "def", "events", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'segmentation'", "]", "=", "kwargs", ".", "get", "(", "'segmentation'", ",", "'none'", ")", "return", "self", ".", "get", "(", "\"events\"", ",", "*", "*", "kwargs", ")"...
Returns a streaming handle to this job's events. :param kwargs: Additional parameters (optional). For a list of valid parameters, see `GET search/jobs/{search_id}/events <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fevents>`_ in the REST API documentation. :type kwargs: ``dict`` :return: The ``InputStream`` IO handle to this job's events.
[ "Returns", "a", "streaming", "handle", "to", "this", "job", "s", "events", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2668-L2680
235,964
splunk/splunk-sdk-python
splunklib/client.py
Job.is_done
def is_done(self): """Indicates whether this job finished running. :return: ``True`` if the job is done, ``False`` if not. :rtype: ``boolean`` """ if not self.is_ready(): return False done = (self._state.content['isDone'] == '1') return done
python
def is_done(self): if not self.is_ready(): return False done = (self._state.content['isDone'] == '1') return done
[ "def", "is_done", "(", "self", ")", ":", "if", "not", "self", ".", "is_ready", "(", ")", ":", "return", "False", "done", "=", "(", "self", ".", "_state", ".", "content", "[", "'isDone'", "]", "==", "'1'", ")", "return", "done" ]
Indicates whether this job finished running. :return: ``True`` if the job is done, ``False`` if not. :rtype: ``boolean``
[ "Indicates", "whether", "this", "job", "finished", "running", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2690-L2699
235,965
splunk/splunk-sdk-python
splunklib/client.py
Job.is_ready
def is_ready(self): """Indicates whether this job is ready for querying. :return: ``True`` if the job is ready, ``False`` if not. :rtype: ``boolean`` """ response = self.get() if response.status == 204: return False self._state = self.read(response) ready = self._state.content['dispatchState'] not in ['QUEUED', 'PARSING'] return ready
python
def is_ready(self): response = self.get() if response.status == 204: return False self._state = self.read(response) ready = self._state.content['dispatchState'] not in ['QUEUED', 'PARSING'] return ready
[ "def", "is_ready", "(", "self", ")", ":", "response", "=", "self", ".", "get", "(", ")", "if", "response", ".", "status", "==", "204", ":", "return", "False", "self", ".", "_state", "=", "self", ".", "read", "(", "response", ")", "ready", "=", "sel...
Indicates whether this job is ready for querying. :return: ``True`` if the job is ready, ``False`` if not. :rtype: ``boolean``
[ "Indicates", "whether", "this", "job", "is", "ready", "for", "querying", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2701-L2713
235,966
splunk/splunk-sdk-python
splunklib/client.py
Job.preview
def preview(self, **query_params): """Returns a streaming handle to this job's preview search results. Unlike :class:`splunklib.results.ResultsReader`, which requires a job to be finished to return any results, the ``preview`` method returns any results that have been generated so far, whether the job is running or not. The returned search results are the raw data from the server. Pass the handle returned to :class:`splunklib.results.ResultsReader` to get a nice, Pythonic iterator over objects, as in:: import splunklib.client as client import splunklib.results as results service = client.connect(...) job = service.jobs.create("search * | head 5") rr = results.ResultsReader(job.preview()) for result in rr: if isinstance(result, results.Message): # Diagnostic messages may be returned in the results print '%s: %s' % (result.type, result.message) elif isinstance(result, dict): # Normal events are returned as dicts print result if rr.is_preview: print "Preview of a running search job." else: print "Job is finished. Results are final." This method makes one roundtrip to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :param query_params: Additional parameters (optional). For a list of valid parameters, see `GET search/jobs/{search_id}/results_preview <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fresults_preview>`_ in the REST API documentation. :type query_params: ``dict`` :return: The ``InputStream`` IO handle to this job's preview results. """ query_params['segmentation'] = query_params.get('segmentation', 'none') return self.get("results_preview", **query_params).body
python
def preview(self, **query_params): query_params['segmentation'] = query_params.get('segmentation', 'none') return self.get("results_preview", **query_params).body
[ "def", "preview", "(", "self", ",", "*", "*", "query_params", ")", ":", "query_params", "[", "'segmentation'", "]", "=", "query_params", ".", "get", "(", "'segmentation'", ",", "'none'", ")", "return", "self", ".", "get", "(", "\"results_preview\"", ",", "...
Returns a streaming handle to this job's preview search results. Unlike :class:`splunklib.results.ResultsReader`, which requires a job to be finished to return any results, the ``preview`` method returns any results that have been generated so far, whether the job is running or not. The returned search results are the raw data from the server. Pass the handle returned to :class:`splunklib.results.ResultsReader` to get a nice, Pythonic iterator over objects, as in:: import splunklib.client as client import splunklib.results as results service = client.connect(...) job = service.jobs.create("search * | head 5") rr = results.ResultsReader(job.preview()) for result in rr: if isinstance(result, results.Message): # Diagnostic messages may be returned in the results print '%s: %s' % (result.type, result.message) elif isinstance(result, dict): # Normal events are returned as dicts print result if rr.is_preview: print "Preview of a running search job." else: print "Job is finished. Results are final." This method makes one roundtrip to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :param query_params: Additional parameters (optional). For a list of valid parameters, see `GET search/jobs/{search_id}/results_preview <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#GET_search.2Fjobs.2F.7Bsearch_id.7D.2Fresults_preview>`_ in the REST API documentation. :type query_params: ``dict`` :return: The ``InputStream`` IO handle to this job's preview results.
[ "Returns", "a", "streaming", "handle", "to", "this", "job", "s", "preview", "search", "results", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2771-L2812
235,967
splunk/splunk-sdk-python
splunklib/client.py
Jobs.create
def create(self, query, **kwargs): """ Creates a search using a search query and any additional parameters you provide. :param query: The search query. :type query: ``string`` :param kwargs: Additiona parameters (optional). For a list of available parameters, see `Search job parameters <http://dev.splunk.com/view/SP-CAAAEE5#searchjobparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`Job`. """ if kwargs.get("exec_mode", None) == "oneshot": raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.") response = self.post(search=query, **kwargs) sid = _load_sid(response) return Job(self.service, sid)
python
def create(self, query, **kwargs): if kwargs.get("exec_mode", None) == "oneshot": raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.") response = self.post(search=query, **kwargs) sid = _load_sid(response) return Job(self.service, sid)
[ "def", "create", "(", "self", ",", "query", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "\"exec_mode\"", ",", "None", ")", "==", "\"oneshot\"", ":", "raise", "TypeError", "(", "\"Cannot specify exec_mode=oneshot; use the oneshot method in...
Creates a search using a search query and any additional parameters you provide. :param query: The search query. :type query: ``string`` :param kwargs: Additiona parameters (optional). For a list of available parameters, see `Search job parameters <http://dev.splunk.com/view/SP-CAAAEE5#searchjobparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`Job`.
[ "Creates", "a", "search", "using", "a", "search", "query", "and", "any", "additional", "parameters", "you", "provide", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2920-L2938
235,968
splunk/splunk-sdk-python
splunklib/client.py
Jobs.oneshot
def oneshot(self, query, **params): """Run a oneshot search and returns a streaming handle to the results. The ``InputStream`` object streams XML fragments from the server. To parse this stream into usable Python objects, pass the handle to :class:`splunklib.results.ResultsReader`:: import splunklib.client as client import splunklib.results as results service = client.connect(...) rr = results.ResultsReader(service.jobs.oneshot("search * | head 5")) for result in rr: if isinstance(result, results.Message): # Diagnostic messages may be returned in the results print '%s: %s' % (result.type, result.message) elif isinstance(result, dict): # Normal events are returned as dicts print result assert rr.is_preview == False The ``oneshot`` method makes a single roundtrip to the server (as opposed to two for :meth:`create` followed by :meth:`results`), plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :raises ValueError: Raised for invalid queries. :param query: The search query. :type query: ``string`` :param params: Additional arguments (optional): - "output_mode": Specifies the output format of the results (XML, JSON, or CSV). - "earliest_time": Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string. - "latest_time": Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string. - "rf": Specifies one or more fields to add to the search. :type params: ``dict`` :return: The ``InputStream`` IO handle to raw XML returned from the server. """ if "exec_mode" in params: raise TypeError("Cannot specify an exec_mode to oneshot.") params['segmentation'] = params.get('segmentation', 'none') return self.post(search=query, exec_mode="oneshot", **params).body
python
def oneshot(self, query, **params): if "exec_mode" in params: raise TypeError("Cannot specify an exec_mode to oneshot.") params['segmentation'] = params.get('segmentation', 'none') return self.post(search=query, exec_mode="oneshot", **params).body
[ "def", "oneshot", "(", "self", ",", "query", ",", "*", "*", "params", ")", ":", "if", "\"exec_mode\"", "in", "params", ":", "raise", "TypeError", "(", "\"Cannot specify an exec_mode to oneshot.\"", ")", "params", "[", "'segmentation'", "]", "=", "params", ".",...
Run a oneshot search and returns a streaming handle to the results. The ``InputStream`` object streams XML fragments from the server. To parse this stream into usable Python objects, pass the handle to :class:`splunklib.results.ResultsReader`:: import splunklib.client as client import splunklib.results as results service = client.connect(...) rr = results.ResultsReader(service.jobs.oneshot("search * | head 5")) for result in rr: if isinstance(result, results.Message): # Diagnostic messages may be returned in the results print '%s: %s' % (result.type, result.message) elif isinstance(result, dict): # Normal events are returned as dicts print result assert rr.is_preview == False The ``oneshot`` method makes a single roundtrip to the server (as opposed to two for :meth:`create` followed by :meth:`results`), plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :raises ValueError: Raised for invalid queries. :param query: The search query. :type query: ``string`` :param params: Additional arguments (optional): - "output_mode": Specifies the output format of the results (XML, JSON, or CSV). - "earliest_time": Specifies the earliest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string. - "latest_time": Specifies the latest time in the time range to search. The time string can be a UTC time (with fractional seconds), a relative time specifier (to now), or a formatted time string. - "rf": Specifies one or more fields to add to the search. :type params: ``dict`` :return: The ``InputStream`` IO handle to raw XML returned from the server.
[ "Run", "a", "oneshot", "search", "and", "returns", "a", "streaming", "handle", "to", "the", "results", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L2995-L3047
235,969
splunk/splunk-sdk-python
splunklib/client.py
SavedSearch.dispatch
def dispatch(self, **kwargs): """Runs the saved search and returns the resulting search job. :param `kwargs`: Additional dispatch arguments (optional). For details, see the `POST saved/searches/{name}/dispatch <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#POST_saved.2Fsearches.2F.7Bname.7D.2Fdispatch>`_ endpoint in the REST API documentation. :type kwargs: ``dict`` :return: The :class:`Job`. """ response = self.post("dispatch", **kwargs) sid = _load_sid(response) return Job(self.service, sid)
python
def dispatch(self, **kwargs): response = self.post("dispatch", **kwargs) sid = _load_sid(response) return Job(self.service, sid)
[ "def", "dispatch", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "post", "(", "\"dispatch\"", ",", "*", "*", "kwargs", ")", "sid", "=", "_load_sid", "(", "response", ")", "return", "Job", "(", "self", ".", "service", ...
Runs the saved search and returns the resulting search job. :param `kwargs`: Additional dispatch arguments (optional). For details, see the `POST saved/searches/{name}/dispatch <http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTsearch#POST_saved.2Fsearches.2F.7Bname.7D.2Fdispatch>`_ endpoint in the REST API documentation. :type kwargs: ``dict`` :return: The :class:`Job`.
[ "Runs", "the", "saved", "search", "and", "returns", "the", "resulting", "search", "job", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3142-L3154
235,970
splunk/splunk-sdk-python
splunklib/client.py
SavedSearch.history
def history(self): """Returns a list of search jobs corresponding to this saved search. :return: A list of :class:`Job` objects. """ response = self.get("history") entries = _load_atom_entries(response) if entries is None: return [] jobs = [] for entry in entries: job = Job(self.service, entry.title) jobs.append(job) return jobs
python
def history(self): response = self.get("history") entries = _load_atom_entries(response) if entries is None: return [] jobs = [] for entry in entries: job = Job(self.service, entry.title) jobs.append(job) return jobs
[ "def", "history", "(", "self", ")", ":", "response", "=", "self", ".", "get", "(", "\"history\"", ")", "entries", "=", "_load_atom_entries", "(", "response", ")", "if", "entries", "is", "None", ":", "return", "[", "]", "jobs", "=", "[", "]", "for", "...
Returns a list of search jobs corresponding to this saved search. :return: A list of :class:`Job` objects.
[ "Returns", "a", "list", "of", "search", "jobs", "corresponding", "to", "this", "saved", "search", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3177-L3189
235,971
splunk/splunk-sdk-python
splunklib/client.py
SavedSearch.update
def update(self, search=None, **kwargs): """Updates the server with any changes you've made to the current saved search along with any additional arguments you specify. :param `search`: The search query (optional). :type search: ``string`` :param `kwargs`: Additional arguments (optional). For a list of available parameters, see `Saved search parameters <http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`SavedSearch`. """ # Updates to a saved search *require* that the search string be # passed, so we pass the current search string if a value wasn't # provided by the caller. if search is None: search = self.content.search Entity.update(self, search=search, **kwargs) return self
python
def update(self, search=None, **kwargs): # Updates to a saved search *require* that the search string be # passed, so we pass the current search string if a value wasn't # provided by the caller. if search is None: search = self.content.search Entity.update(self, search=search, **kwargs) return self
[ "def", "update", "(", "self", ",", "search", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Updates to a saved search *require* that the search string be", "# passed, so we pass the current search string if a value wasn't", "# provided by the caller.", "if", "search", "is",...
Updates the server with any changes you've made to the current saved search along with any additional arguments you specify. :param `search`: The search query (optional). :type search: ``string`` :param `kwargs`: Additional arguments (optional). For a list of available parameters, see `Saved search parameters <http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`SavedSearch`.
[ "Updates", "the", "server", "with", "any", "changes", "you", "ve", "made", "to", "the", "current", "saved", "search", "along", "with", "any", "additional", "arguments", "you", "specify", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3191-L3210
235,972
splunk/splunk-sdk-python
splunklib/client.py
SavedSearch.scheduled_times
def scheduled_times(self, earliest_time='now', latest_time='+1h'): """Returns the times when this search is scheduled to run. By default this method returns the times in the next hour. For different time ranges, set *earliest_time* and *latest_time*. For example, for all times in the last day use "earliest_time=-1d" and "latest_time=now". :param earliest_time: The earliest time. :type earliest_time: ``string`` :param latest_time: The latest time. :type latest_time: ``string`` :return: The list of search times. """ response = self.get("scheduled_times", earliest_time=earliest_time, latest_time=latest_time) data = self._load_atom_entry(response) rec = _parse_atom_entry(data) times = [datetime.fromtimestamp(int(t)) for t in rec.content.scheduled_times] return times
python
def scheduled_times(self, earliest_time='now', latest_time='+1h'): response = self.get("scheduled_times", earliest_time=earliest_time, latest_time=latest_time) data = self._load_atom_entry(response) rec = _parse_atom_entry(data) times = [datetime.fromtimestamp(int(t)) for t in rec.content.scheduled_times] return times
[ "def", "scheduled_times", "(", "self", ",", "earliest_time", "=", "'now'", ",", "latest_time", "=", "'+1h'", ")", ":", "response", "=", "self", ".", "get", "(", "\"scheduled_times\"", ",", "earliest_time", "=", "earliest_time", ",", "latest_time", "=", "latest...
Returns the times when this search is scheduled to run. By default this method returns the times in the next hour. For different time ranges, set *earliest_time* and *latest_time*. For example, for all times in the last day use "earliest_time=-1d" and "latest_time=now". :param earliest_time: The earliest time. :type earliest_time: ``string`` :param latest_time: The latest time. :type latest_time: ``string`` :return: The list of search times.
[ "Returns", "the", "times", "when", "this", "search", "is", "scheduled", "to", "run", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3212-L3234
235,973
splunk/splunk-sdk-python
splunklib/client.py
SavedSearches.create
def create(self, name, search, **kwargs): """ Creates a saved search. :param name: The name for the saved search. :type name: ``string`` :param search: The search query. :type search: ``string`` :param kwargs: Additional arguments (optional). For a list of available parameters, see `Saved search parameters <http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`SavedSearches` collection. """ return Collection.create(self, name, search=search, **kwargs)
python
def create(self, name, search, **kwargs): return Collection.create(self, name, search=search, **kwargs)
[ "def", "create", "(", "self", ",", "name", ",", "search", ",", "*", "*", "kwargs", ")", ":", "return", "Collection", ".", "create", "(", "self", ",", "name", ",", "search", "=", "search", ",", "*", "*", "kwargs", ")" ]
Creates a saved search. :param name: The name for the saved search. :type name: ``string`` :param search: The search query. :type search: ``string`` :param kwargs: Additional arguments (optional). For a list of available parameters, see `Saved search parameters <http://dev.splunk.com/view/SP-CAAAEE5#savedsearchparams>`_ on Splunk Developer Portal. :type kwargs: ``dict`` :return: The :class:`SavedSearches` collection.
[ "Creates", "a", "saved", "search", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3278-L3292
235,974
splunk/splunk-sdk-python
splunklib/client.py
User.role_entities
def role_entities(self): """Returns a list of roles assigned to this user. :return: The list of roles. :rtype: ``list`` """ return [self.service.roles[name] for name in self.content.roles]
python
def role_entities(self): return [self.service.roles[name] for name in self.content.roles]
[ "def", "role_entities", "(", "self", ")", ":", "return", "[", "self", ".", "service", ".", "roles", "[", "name", "]", "for", "name", "in", "self", ".", "content", ".", "roles", "]" ]
Returns a list of roles assigned to this user. :return: The list of roles. :rtype: ``list``
[ "Returns", "a", "list", "of", "roles", "assigned", "to", "this", "user", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3320-L3326
235,975
splunk/splunk-sdk-python
splunklib/client.py
Role.grant
def grant(self, *capabilities_to_grant): """Grants additional capabilities to this role. :param capabilities_to_grant: Zero or more capabilities to grant this role. For a list of capabilities, see `Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_ on Splunk Developer Portal. :type capabilities_to_grant: ``string`` or ``list`` :return: The :class:`Role`. **Example**:: service = client.connect(...) role = service.roles['somerole'] role.grant('change_own_password', 'search') """ possible_capabilities = self.service.capabilities for capability in capabilities_to_grant: if capability not in possible_capabilities: raise NoSuchCapability(capability) new_capabilities = self['capabilities'] + list(capabilities_to_grant) self.post(capabilities=new_capabilities) return self
python
def grant(self, *capabilities_to_grant): possible_capabilities = self.service.capabilities for capability in capabilities_to_grant: if capability not in possible_capabilities: raise NoSuchCapability(capability) new_capabilities = self['capabilities'] + list(capabilities_to_grant) self.post(capabilities=new_capabilities) return self
[ "def", "grant", "(", "self", ",", "*", "capabilities_to_grant", ")", ":", "possible_capabilities", "=", "self", ".", "service", ".", "capabilities", "for", "capability", "in", "capabilities_to_grant", ":", "if", "capability", "not", "in", "possible_capabilities", ...
Grants additional capabilities to this role. :param capabilities_to_grant: Zero or more capabilities to grant this role. For a list of capabilities, see `Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_ on Splunk Developer Portal. :type capabilities_to_grant: ``string`` or ``list`` :return: The :class:`Role`. **Example**:: service = client.connect(...) role = service.roles['somerole'] role.grant('change_own_password', 'search')
[ "Grants", "additional", "capabilities", "to", "this", "role", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3404-L3426
235,976
splunk/splunk-sdk-python
splunklib/client.py
Role.revoke
def revoke(self, *capabilities_to_revoke): """Revokes zero or more capabilities from this role. :param capabilities_to_revoke: Zero or more capabilities to grant this role. For a list of capabilities, see `Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_ on Splunk Developer Portal. :type capabilities_to_revoke: ``string`` or ``list`` :return: The :class:`Role`. **Example**:: service = client.connect(...) role = service.roles['somerole'] role.revoke('change_own_password', 'search') """ possible_capabilities = self.service.capabilities for capability in capabilities_to_revoke: if capability not in possible_capabilities: raise NoSuchCapability(capability) old_capabilities = self['capabilities'] new_capabilities = [] for c in old_capabilities: if c not in capabilities_to_revoke: new_capabilities.append(c) if new_capabilities == []: new_capabilities = '' # Empty lists don't get passed in the body, so we have to force an empty argument. self.post(capabilities=new_capabilities) return self
python
def revoke(self, *capabilities_to_revoke): possible_capabilities = self.service.capabilities for capability in capabilities_to_revoke: if capability not in possible_capabilities: raise NoSuchCapability(capability) old_capabilities = self['capabilities'] new_capabilities = [] for c in old_capabilities: if c not in capabilities_to_revoke: new_capabilities.append(c) if new_capabilities == []: new_capabilities = '' # Empty lists don't get passed in the body, so we have to force an empty argument. self.post(capabilities=new_capabilities) return self
[ "def", "revoke", "(", "self", ",", "*", "capabilities_to_revoke", ")", ":", "possible_capabilities", "=", "self", ".", "service", ".", "capabilities", "for", "capability", "in", "capabilities_to_revoke", ":", "if", "capability", "not", "in", "possible_capabilities",...
Revokes zero or more capabilities from this role. :param capabilities_to_revoke: Zero or more capabilities to grant this role. For a list of capabilities, see `Capabilities <http://dev.splunk.com/view/SP-CAAAEJ6#capabilities>`_ on Splunk Developer Portal. :type capabilities_to_revoke: ``string`` or ``list`` :return: The :class:`Role`. **Example**:: service = client.connect(...) role = service.roles['somerole'] role.revoke('change_own_password', 'search')
[ "Revokes", "zero", "or", "more", "capabilities", "from", "this", "role", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3428-L3457
235,977
splunk/splunk-sdk-python
splunklib/client.py
Roles.create
def create(self, name, **params): """Creates a new role. This function makes two roundtrips to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :param name: Name for the role. :type name: ``string`` :param params: Additional arguments (optional). For a list of available parameters, see `Roles parameters <http://dev.splunk.com/view/SP-CAAAEJ6#rolesparams>`_ on Splunk Developer Portal. :type params: ``dict`` :return: The new role. :rtype: :class:`Role` **Example**:: import splunklib.client as client c = client.connect(...) roles = c.roles paltry = roles.create("paltry", imported_roles="user", defaultApp="search") """ if not isinstance(name, six.string_types): raise ValueError("Invalid role name: %s" % str(name)) name = name.lower() self.post(name=name, **params) # splunkd doesn't return the user in the POST response body, # so we have to make a second round trip to fetch it. response = self.get(name) entry = _load_atom(response, XNAME_ENTRY).entry state = _parse_atom_entry(entry) entity = self.item( self.service, urllib.parse.unquote(state.links.alternate), state=state) return entity
python
def create(self, name, **params): if not isinstance(name, six.string_types): raise ValueError("Invalid role name: %s" % str(name)) name = name.lower() self.post(name=name, **params) # splunkd doesn't return the user in the POST response body, # so we have to make a second round trip to fetch it. response = self.get(name) entry = _load_atom(response, XNAME_ENTRY).entry state = _parse_atom_entry(entry) entity = self.item( self.service, urllib.parse.unquote(state.links.alternate), state=state) return entity
[ "def", "create", "(", "self", ",", "name", ",", "*", "*", "params", ")", ":", "if", "not", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", ":", "raise", "ValueError", "(", "\"Invalid role name: %s\"", "%", "str", "(", "name", ")", ")",...
Creates a new role. This function makes two roundtrips to the server, plus at most two more if the ``autologin`` field of :func:`connect` is set to ``True``. :param name: Name for the role. :type name: ``string`` :param params: Additional arguments (optional). For a list of available parameters, see `Roles parameters <http://dev.splunk.com/view/SP-CAAAEJ6#rolesparams>`_ on Splunk Developer Portal. :type params: ``dict`` :return: The new role. :rtype: :class:`Role` **Example**:: import splunklib.client as client c = client.connect(...) roles = c.roles paltry = roles.create("paltry", imported_roles="user", defaultApp="search")
[ "Creates", "a", "new", "role", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3472-L3510
235,978
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollections.create
def create(self, name, indexes = {}, fields = {}, **kwargs): """Creates a KV Store Collection. :param name: name of collection to create :type name: ``string`` :param indexes: dictionary of index definitions :type indexes: ``dict`` :param fields: dictionary of field definitions :type fields: ``dict`` :param kwargs: a dictionary of additional parameters specifying indexes and field definitions :type kwargs: ``dict`` :return: Result of POST request """ for k, v in six.iteritems(indexes): if isinstance(v, dict): v = json.dumps(v) kwargs['index.' + k] = v for k, v in six.iteritems(fields): kwargs['field.' + k] = v return self.post(name=name, **kwargs)
python
def create(self, name, indexes = {}, fields = {}, **kwargs): for k, v in six.iteritems(indexes): if isinstance(v, dict): v = json.dumps(v) kwargs['index.' + k] = v for k, v in six.iteritems(fields): kwargs['field.' + k] = v return self.post(name=name, **kwargs)
[ "def", "create", "(", "self", ",", "name", ",", "indexes", "=", "{", "}", ",", "fields", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "indexes", ")", ":", "if", "isinstance", "(", ...
Creates a KV Store Collection. :param name: name of collection to create :type name: ``string`` :param indexes: dictionary of index definitions :type indexes: ``dict`` :param fields: dictionary of field definitions :type fields: ``dict`` :param kwargs: a dictionary of additional parameters specifying indexes and field definitions :type kwargs: ``dict`` :return: Result of POST request
[ "Creates", "a", "KV", "Store", "Collection", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3545-L3565
235,979
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollection.update_index
def update_index(self, name, value): """Changes the definition of a KV Store index. :param name: name of index to change :type name: ``string`` :param value: new index definition :type value: ``dict`` or ``string`` :return: Result of POST request """ kwargs = {} kwargs['index.' + name] = value if isinstance(value, basestring) else json.dumps(value) return self.post(**kwargs)
python
def update_index(self, name, value): kwargs = {} kwargs['index.' + name] = value if isinstance(value, basestring) else json.dumps(value) return self.post(**kwargs)
[ "def", "update_index", "(", "self", ",", "name", ",", "value", ")", ":", "kwargs", "=", "{", "}", "kwargs", "[", "'index.'", "+", "name", "]", "=", "value", "if", "isinstance", "(", "value", ",", "basestring", ")", "else", "json", ".", "dumps", "(", ...
Changes the definition of a KV Store index. :param name: name of index to change :type name: ``string`` :param value: new index definition :type value: ``dict`` or ``string`` :return: Result of POST request
[ "Changes", "the", "definition", "of", "a", "KV", "Store", "index", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3576-L3588
235,980
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollection.update_field
def update_field(self, name, value): """Changes the definition of a KV Store field. :param name: name of field to change :type name: ``string`` :param value: new field definition :type value: ``string`` :return: Result of POST request """ kwargs = {} kwargs['field.' + name] = value return self.post(**kwargs)
python
def update_field(self, name, value): kwargs = {} kwargs['field.' + name] = value return self.post(**kwargs)
[ "def", "update_field", "(", "self", ",", "name", ",", "value", ")", ":", "kwargs", "=", "{", "}", "kwargs", "[", "'field.'", "+", "name", "]", "=", "value", "return", "self", ".", "post", "(", "*", "*", "kwargs", ")" ]
Changes the definition of a KV Store field. :param name: name of field to change :type name: ``string`` :param value: new field definition :type value: ``string`` :return: Result of POST request
[ "Changes", "the", "definition", "of", "a", "KV", "Store", "field", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3590-L3602
235,981
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollectionData.query
def query(self, **query): """ Gets the results of query, with optional parameters sort, limit, skip, and fields. :param query: Optional parameters. Valid options are sort, limit, skip, and fields :type query: ``dict`` :return: Array of documents retrieved by query. :rtype: ``array`` """ return json.loads(self._get('', **query).body.read().decode('utf-8'))
python
def query(self, **query): return json.loads(self._get('', **query).body.read().decode('utf-8'))
[ "def", "query", "(", "self", ",", "*", "*", "query", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_get", "(", "''", ",", "*", "*", "query", ")", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", ")" ]
Gets the results of query, with optional parameters sort, limit, skip, and fields. :param query: Optional parameters. Valid options are sort, limit, skip, and fields :type query: ``dict`` :return: Array of documents retrieved by query. :rtype: ``array``
[ "Gets", "the", "results", "of", "query", "with", "optional", "parameters", "sort", "limit", "skip", "and", "fields", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3626-L3636
235,982
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollectionData.query_by_id
def query_by_id(self, id): """ Returns object with _id = id. :param id: Value for ID. If not a string will be coerced to string. :type id: ``string`` :return: Document with id :rtype: ``dict`` """ return json.loads(self._get(UrlEncoded(str(id))).body.read().decode('utf-8'))
python
def query_by_id(self, id): return json.loads(self._get(UrlEncoded(str(id))).body.read().decode('utf-8'))
[ "def", "query_by_id", "(", "self", ",", "id", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_get", "(", "UrlEncoded", "(", "str", "(", "id", ")", ")", ")", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "...
Returns object with _id = id. :param id: Value for ID. If not a string will be coerced to string. :type id: ``string`` :return: Document with id :rtype: ``dict``
[ "Returns", "object", "with", "_id", "=", "id", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3638-L3648
235,983
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollectionData.insert
def insert(self, data): """ Inserts item into this collection. An _id field will be generated if not assigned in the data. :param data: Document to insert :type data: ``string`` :return: _id of inserted object :rtype: ``dict`` """ return json.loads(self._post('', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
python
def insert(self, data): return json.loads(self._post('', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
[ "def", "insert", "(", "self", ",", "data", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_post", "(", "''", ",", "headers", "=", "KVStoreCollectionData", ".", "JSON_HEADER", ",", "body", "=", "data", ")", ".", "body", ".", "read", "(",...
Inserts item into this collection. An _id field will be generated if not assigned in the data. :param data: Document to insert :type data: ``string`` :return: _id of inserted object :rtype: ``dict``
[ "Inserts", "item", "into", "this", "collection", ".", "An", "_id", "field", "will", "be", "generated", "if", "not", "assigned", "in", "the", "data", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3650-L3660
235,984
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollectionData.update
def update(self, id, data): """ Replaces document with _id = id with data. :param id: _id of document to update :type id: ``string`` :param data: the new document to insert :type data: ``string`` :return: id of replaced document :rtype: ``dict`` """ return json.loads(self._post(UrlEncoded(str(id)), headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
python
def update(self, id, data): return json.loads(self._post(UrlEncoded(str(id)), headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
[ "def", "update", "(", "self", ",", "id", ",", "data", ")", ":", "return", "json", ".", "loads", "(", "self", ".", "_post", "(", "UrlEncoded", "(", "str", "(", "id", ")", ")", ",", "headers", "=", "KVStoreCollectionData", ".", "JSON_HEADER", ",", "bod...
Replaces document with _id = id with data. :param id: _id of document to update :type id: ``string`` :param data: the new document to insert :type data: ``string`` :return: id of replaced document :rtype: ``dict``
[ "Replaces", "document", "with", "_id", "=", "id", "with", "data", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3684-L3696
235,985
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollectionData.batch_find
def batch_find(self, *dbqueries): """ Returns array of results from queries dbqueries. :param dbqueries: Array of individual queries as dictionaries :type dbqueries: ``array`` of ``dict`` :return: Results of each query :rtype: ``array`` of ``array`` """ if len(dbqueries) < 1: raise Exception('Must have at least one query.') data = json.dumps(dbqueries) return json.loads(self._post('batch_find', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
python
def batch_find(self, *dbqueries): if len(dbqueries) < 1: raise Exception('Must have at least one query.') data = json.dumps(dbqueries) return json.loads(self._post('batch_find', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
[ "def", "batch_find", "(", "self", ",", "*", "dbqueries", ")", ":", "if", "len", "(", "dbqueries", ")", "<", "1", ":", "raise", "Exception", "(", "'Must have at least one query.'", ")", "data", "=", "json", ".", "dumps", "(", "dbqueries", ")", "return", "...
Returns array of results from queries dbqueries. :param dbqueries: Array of individual queries as dictionaries :type dbqueries: ``array`` of ``dict`` :return: Results of each query :rtype: ``array`` of ``array``
[ "Returns", "array", "of", "results", "from", "queries", "dbqueries", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3698-L3713
235,986
splunk/splunk-sdk-python
splunklib/client.py
KVStoreCollectionData.batch_save
def batch_save(self, *documents): """ Inserts or updates every document specified in documents. :param documents: Array of documents to save as dictionaries :type documents: ``array`` of ``dict`` :return: Results of update operation as overall stats :rtype: ``dict`` """ if len(documents) < 1: raise Exception('Must have at least one document.') data = json.dumps(documents) return json.loads(self._post('batch_save', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
python
def batch_save(self, *documents): if len(documents) < 1: raise Exception('Must have at least one document.') data = json.dumps(documents) return json.loads(self._post('batch_save', headers=KVStoreCollectionData.JSON_HEADER, body=data).body.read().decode('utf-8'))
[ "def", "batch_save", "(", "self", ",", "*", "documents", ")", ":", "if", "len", "(", "documents", ")", "<", "1", ":", "raise", "Exception", "(", "'Must have at least one document.'", ")", "data", "=", "json", ".", "dumps", "(", "documents", ")", "return", ...
Inserts or updates every document specified in documents. :param documents: Array of documents to save as dictionaries :type documents: ``array`` of ``dict`` :return: Results of update operation as overall stats :rtype: ``dict``
[ "Inserts", "or", "updates", "every", "document", "specified", "in", "documents", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/client.py#L3715-L3730
235,987
splunk/splunk-sdk-python
setup.py
DistCommand.get_python_files
def get_python_files(files): """Utility function to get .py files from a list""" python_files = [] for file_name in files: if file_name.endswith(".py"): python_files.append(file_name) return python_files
python
def get_python_files(files): python_files = [] for file_name in files: if file_name.endswith(".py"): python_files.append(file_name) return python_files
[ "def", "get_python_files", "(", "files", ")", ":", "python_files", "=", "[", "]", "for", "file_name", "in", "files", ":", "if", "file_name", ".", "endswith", "(", "\".py\"", ")", ":", "python_files", ".", "append", "(", "file_name", ")", "return", "python_...
Utility function to get .py files from a list
[ "Utility", "function", "to", "get", ".", "py", "files", "from", "a", "list" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/setup.py#L146-L153
235,988
splunk/splunk-sdk-python
splunklib/binding.py
_parse_cookies
def _parse_cookies(cookie_str, dictionary): """Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictionary['my'] == 'value' :param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header. :type cookie_str: ``str`` :param dictionary: A dictionary to update with any found key-value pairs. :type dictionary: ``dict`` """ parsed_cookie = six.moves.http_cookies.SimpleCookie(cookie_str) for cookie in parsed_cookie.values(): dictionary[cookie.key] = cookie.coded_value
python
def _parse_cookies(cookie_str, dictionary): parsed_cookie = six.moves.http_cookies.SimpleCookie(cookie_str) for cookie in parsed_cookie.values(): dictionary[cookie.key] = cookie.coded_value
[ "def", "_parse_cookies", "(", "cookie_str", ",", "dictionary", ")", ":", "parsed_cookie", "=", "six", ".", "moves", ".", "http_cookies", ".", "SimpleCookie", "(", "cookie_str", ")", "for", "cookie", "in", "parsed_cookie", ".", "values", "(", ")", ":", "dicti...
Tries to parse any key-value pairs of cookies in a string, then updates the the dictionary with any key-value pairs found. **Example**:: dictionary = {} _parse_cookies('my=value', dictionary) # Now the following is True dictionary['my'] == 'value' :param cookie_str: A string containing "key=value" pairs from an HTTP "Set-Cookie" header. :type cookie_str: ``str`` :param dictionary: A dictionary to update with any found key-value pairs. :type dictionary: ``dict``
[ "Tries", "to", "parse", "any", "key", "-", "value", "pairs", "of", "cookies", "in", "a", "string", "then", "updates", "the", "the", "dictionary", "with", "any", "key", "-", "value", "pairs", "found", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L78-L95
235,989
splunk/splunk-sdk-python
splunklib/binding.py
namespace
def namespace(sharing=None, owner=None, app=None, **kwargs): """This function constructs a Splunk namespace. Every Splunk resource belongs to a namespace. The namespace is specified by the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode. The possible values for ``sharing`` are: "user", "app", "global" and "system", which map to the following combinations of ``owner`` and ``app`` values: "user" => {owner}, {app} "app" => nobody, {app} "global" => nobody, {app} "system" => nobody, system "nobody" is a special user name that basically means no user, and "system" is the name reserved for system resources. "-" is a wildcard that can be used for both ``owner`` and ``app`` values and refers to all users and all apps, respectively. In general, when you specify a namespace you can specify any combination of these three values and the library will reconcile the triple, overriding the provided values as appropriate. Finally, if no namespacing is specified the library will make use of the ``/services`` branch of the REST API, which provides a namespaced view of Splunk resources equivelent to using ``owner={currentUser}`` and ``app={defaultApp}``. The ``namespace`` function returns a representation of the namespace from reconciling the values you provide. It ignores any keyword arguments other than ``owner``, ``app``, and ``sharing``, so you can provide ``dicts`` of configuration information without first having to extract individual keys. :param sharing: The sharing mode (the default is "user"). :type sharing: "system", "global", "app", or "user" :param owner: The owner context (the default is "None"). :type owner: ``string`` :param app: The app context (the default is "None"). :type app: ``string`` :returns: A :class:`splunklib.data.Record` containing the reconciled namespace. **Example**:: import splunklib.binding as binding n = binding.namespace(sharing="user", owner="boris", app="search") n = binding.namespace(sharing="global", app="search") """ if sharing in ["system"]: return record({'sharing': sharing, 'owner': "nobody", 'app': "system" }) if sharing in ["global", "app"]: return record({'sharing': sharing, 'owner': "nobody", 'app': app}) if sharing in ["user", None]: return record({'sharing': sharing, 'owner': owner, 'app': app}) raise ValueError("Invalid value for argument: 'sharing'")
python
def namespace(sharing=None, owner=None, app=None, **kwargs): if sharing in ["system"]: return record({'sharing': sharing, 'owner': "nobody", 'app': "system" }) if sharing in ["global", "app"]: return record({'sharing': sharing, 'owner': "nobody", 'app': app}) if sharing in ["user", None]: return record({'sharing': sharing, 'owner': owner, 'app': app}) raise ValueError("Invalid value for argument: 'sharing'")
[ "def", "namespace", "(", "sharing", "=", "None", ",", "owner", "=", "None", ",", "app", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "sharing", "in", "[", "\"system\"", "]", ":", "return", "record", "(", "{", "'sharing'", ":", "sharing", "...
This function constructs a Splunk namespace. Every Splunk resource belongs to a namespace. The namespace is specified by the pair of values ``owner`` and ``app`` and is governed by a ``sharing`` mode. The possible values for ``sharing`` are: "user", "app", "global" and "system", which map to the following combinations of ``owner`` and ``app`` values: "user" => {owner}, {app} "app" => nobody, {app} "global" => nobody, {app} "system" => nobody, system "nobody" is a special user name that basically means no user, and "system" is the name reserved for system resources. "-" is a wildcard that can be used for both ``owner`` and ``app`` values and refers to all users and all apps, respectively. In general, when you specify a namespace you can specify any combination of these three values and the library will reconcile the triple, overriding the provided values as appropriate. Finally, if no namespacing is specified the library will make use of the ``/services`` branch of the REST API, which provides a namespaced view of Splunk resources equivelent to using ``owner={currentUser}`` and ``app={defaultApp}``. The ``namespace`` function returns a representation of the namespace from reconciling the values you provide. It ignores any keyword arguments other than ``owner``, ``app``, and ``sharing``, so you can provide ``dicts`` of configuration information without first having to extract individual keys. :param sharing: The sharing mode (the default is "user"). :type sharing: "system", "global", "app", or "user" :param owner: The owner context (the default is "None"). :type owner: ``string`` :param app: The app context (the default is "None"). :type app: ``string`` :returns: A :class:`splunklib.data.Record` containing the reconciled namespace. **Example**:: import splunklib.binding as binding n = binding.namespace(sharing="user", owner="boris", app="search") n = binding.namespace(sharing="global", app="search")
[ "This", "function", "constructs", "a", "Splunk", "namespace", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L355-L412
235,990
splunk/splunk-sdk-python
splunklib/binding.py
Context.request
def request(self, path_segment, method="GET", headers=None, body="", owner=None, app=None, sharing=None): """Issues an arbitrary HTTP request to the REST path segment. This method is named to match ``httplib.request``. This function makes a single round trip to the server. If *owner*, *app*, and *sharing* are omitted, this method uses the default :class:`Context` namespace. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Context`` object is not logged in. :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*. :param path_segment: A REST path segment. :type path_segment: ``string`` :param method: The HTTP method to use (optional). :type method: ``string`` :param headers: List of extra HTTP headers to send (optional). :type headers: ``list`` of 2-tuples. :param body: Content of the HTTP request (optional). :type body: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode of the namespace (optional). :type sharing: ``string`` :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` **Example**:: c = binding.connect(...) c.request('saved/searches', method='GET') == \\ {'body': ...a response reader object..., 'headers': [('content-length', '46722'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 17:24:19 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} c.request('nonexistant/path', method='GET') # raises HTTPError c.logout() c.get('apps/local') # raises AuthenticationError """ if headers is None: headers = [] path = self.authority \ + self._abspath(path_segment, owner=owner, app=app, sharing=sharing) all_headers = headers + self.additional_headers + self._auth_headers logging.debug("%s request to %s (headers: %s, body: %s)", method, path, str(all_headers), repr(body)) response = self.http.request(path, {'method': method, 'headers': all_headers, 'body': body}) return response
python
def request(self, path_segment, method="GET", headers=None, body="", owner=None, app=None, sharing=None): if headers is None: headers = [] path = self.authority \ + self._abspath(path_segment, owner=owner, app=app, sharing=sharing) all_headers = headers + self.additional_headers + self._auth_headers logging.debug("%s request to %s (headers: %s, body: %s)", method, path, str(all_headers), repr(body)) response = self.http.request(path, {'method': method, 'headers': all_headers, 'body': body}) return response
[ "def", "request", "(", "self", ",", "path_segment", ",", "method", "=", "\"GET\"", ",", "headers", "=", "None", ",", "body", "=", "\"\"", ",", "owner", "=", "None", ",", "app", "=", "None", ",", "sharing", "=", "None", ")", ":", "if", "headers", "i...
Issues an arbitrary HTTP request to the REST path segment. This method is named to match ``httplib.request``. This function makes a single round trip to the server. If *owner*, *app*, and *sharing* are omitted, this method uses the default :class:`Context` namespace. All other keyword arguments are included in the URL as query parameters. :raises AuthenticationError: Raised when the ``Context`` object is not logged in. :raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*. :param path_segment: A REST path segment. :type path_segment: ``string`` :param method: The HTTP method to use (optional). :type method: ``string`` :param headers: List of extra HTTP headers to send (optional). :type headers: ``list`` of 2-tuples. :param body: Content of the HTTP request (optional). :type body: ``string`` :param owner: The owner context of the namespace (optional). :type owner: ``string`` :param app: The app context of the namespace (optional). :type app: ``string`` :param sharing: The sharing mode of the namespace (optional). :type sharing: ``string`` :param query: All other keyword arguments, which are used as query parameters. :type query: ``string`` :return: The response from the server. :rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status`` **Example**:: c = binding.connect(...) c.request('saved/searches', method='GET') == \\ {'body': ...a response reader object..., 'headers': [('content-length', '46722'), ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'), ('server', 'Splunkd'), ('connection', 'close'), ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'), ('date', 'Fri, 11 May 2012 17:24:19 GMT'), ('content-type', 'text/xml; charset=utf-8')], 'reason': 'OK', 'status': 200} c.request('nonexistant/path', method='GET') # raises HTTPError c.logout() c.get('apps/local') # raises AuthenticationError
[ "Issues", "an", "arbitrary", "HTTP", "request", "to", "the", "REST", "path", "segment", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L757-L824
235,991
splunk/splunk-sdk-python
splunklib/binding.py
HttpLib.delete
def delete(self, url, headers=None, **kwargs): """Sends a DELETE request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: Additional keyword arguments (optional). These arguments are interpreted as the query part of the URL. The order of keyword arguments is not preserved in the request, but the keywords and their arguments will be URL encoded. :type kwargs: ``dict`` :returns: A dictionary describing the response (see :class:`HttpLib` for its structure). :rtype: ``dict`` """ if headers is None: headers = [] if kwargs: # url is already a UrlEncoded. We have to manually declare # the query to be encoded or it will get automatically URL # encoded by being appended to url. url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True) message = { 'method': "DELETE", 'headers': headers, } return self.request(url, message)
python
def delete(self, url, headers=None, **kwargs): if headers is None: headers = [] if kwargs: # url is already a UrlEncoded. We have to manually declare # the query to be encoded or it will get automatically URL # encoded by being appended to url. url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True) message = { 'method': "DELETE", 'headers': headers, } return self.request(url, message)
[ "def", "delete", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "[", "]", "if", "kwargs", ":", "# url is already a UrlEncoded. We have to manually declare", "# the ...
Sends a DELETE request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: Additional keyword arguments (optional). These arguments are interpreted as the query part of the URL. The order of keyword arguments is not preserved in the request, but the keywords and their arguments will be URL encoded. :type kwargs: ``dict`` :returns: A dictionary describing the response (see :class:`HttpLib` for its structure). :rtype: ``dict``
[ "Sends", "a", "DELETE", "request", "to", "a", "URL", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1131-L1158
235,992
splunk/splunk-sdk-python
splunklib/binding.py
HttpLib.get
def get(self, url, headers=None, **kwargs): """Sends a GET request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: Additional keyword arguments (optional). These arguments are interpreted as the query part of the URL. The order of keyword arguments is not preserved in the request, but the keywords and their arguments will be URL encoded. :type kwargs: ``dict`` :returns: A dictionary describing the response (see :class:`HttpLib` for its structure). :rtype: ``dict`` """ if headers is None: headers = [] if kwargs: # url is already a UrlEncoded. We have to manually declare # the query to be encoded or it will get automatically URL # encoded by being appended to url. url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True) return self.request(url, { 'method': "GET", 'headers': headers })
python
def get(self, url, headers=None, **kwargs): if headers is None: headers = [] if kwargs: # url is already a UrlEncoded. We have to manually declare # the query to be encoded or it will get automatically URL # encoded by being appended to url. url = url + UrlEncoded('?' + _encode(**kwargs), skip_encode=True) return self.request(url, { 'method': "GET", 'headers': headers })
[ "def", "get", "(", "self", ",", "url", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "headers", "is", "None", ":", "headers", "=", "[", "]", "if", "kwargs", ":", "# url is already a UrlEncoded. We have to manually declare", "# the que...
Sends a GET request to a URL. :param url: The URL. :type url: ``string`` :param headers: A list of pairs specifying the headers for the HTTP response (for example, ``[('Content-Type': 'text/cthulhu'), ('Token': 'boris')]``). :type headers: ``list`` :param kwargs: Additional keyword arguments (optional). These arguments are interpreted as the query part of the URL. The order of keyword arguments is not preserved in the request, but the keywords and their arguments will be URL encoded. :type kwargs: ``dict`` :returns: A dictionary describing the response (see :class:`HttpLib` for its structure). :rtype: ``dict``
[ "Sends", "a", "GET", "request", "to", "a", "URL", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1160-L1183
235,993
splunk/splunk-sdk-python
splunklib/binding.py
ResponseReader.peek
def peek(self, size): """Nondestructively retrieves a given number of characters. The next :meth:`read` operation behaves as though this method was never called. :param size: The number of characters to retrieve. :type size: ``integer`` """ c = self.read(size) self._buffer = self._buffer + c return c
python
def peek(self, size): c = self.read(size) self._buffer = self._buffer + c return c
[ "def", "peek", "(", "self", ",", "size", ")", ":", "c", "=", "self", ".", "read", "(", "size", ")", "self", ".", "_buffer", "=", "self", ".", "_buffer", "+", "c", "return", "c" ]
Nondestructively retrieves a given number of characters. The next :meth:`read` operation behaves as though this method was never called. :param size: The number of characters to retrieve. :type size: ``integer``
[ "Nondestructively", "retrieves", "a", "given", "number", "of", "characters", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1284-L1295
235,994
splunk/splunk-sdk-python
splunklib/binding.py
ResponseReader.close
def close(self): """Closes this response.""" if self._connection: self._connection.close() self._response.close()
python
def close(self): if self._connection: self._connection.close() self._response.close()
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_connection", ":", "self", ".", "_connection", ".", "close", "(", ")", "self", ".", "_response", ".", "close", "(", ")" ]
Closes this response.
[ "Closes", "this", "response", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1297-L1301
235,995
splunk/splunk-sdk-python
splunklib/binding.py
ResponseReader.readinto
def readinto(self, byte_array): """ Read data into a byte array, upto the size of the byte array. :param byte_array: A byte array/memory view to pour bytes into. :type byte_array: ``bytearray`` or ``memoryview`` """ max_size = len(byte_array) data = self.read(max_size) bytes_read = len(data) byte_array[:bytes_read] = data return bytes_read
python
def readinto(self, byte_array): max_size = len(byte_array) data = self.read(max_size) bytes_read = len(data) byte_array[:bytes_read] = data return bytes_read
[ "def", "readinto", "(", "self", ",", "byte_array", ")", ":", "max_size", "=", "len", "(", "byte_array", ")", "data", "=", "self", ".", "read", "(", "max_size", ")", "bytes_read", "=", "len", "(", "data", ")", "byte_array", "[", ":", "bytes_read", "]", ...
Read data into a byte array, upto the size of the byte array. :param byte_array: A byte array/memory view to pour bytes into. :type byte_array: ``bytearray`` or ``memoryview``
[ "Read", "data", "into", "a", "byte", "array", "upto", "the", "size", "of", "the", "byte", "array", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/binding.py#L1322-L1333
235,996
splunk/splunk-sdk-python
splunklib/modularinput/validation_definition.py
ValidationDefinition.parse
def parse(stream): """Creates a ``ValidationDefinition`` from a provided stream containing XML. The XML typically will look like this: ``<items>`` `` <server_host>myHost</server_host>`` `` <server_uri>https://127.0.0.1:8089</server_uri>`` `` <session_key>123102983109283019283</session_key>`` `` <checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>`` `` <item name="myScheme">`` `` <param name="param1">value1</param>`` `` <param_list name="param2">`` `` <value>value2</value>`` `` <value>value3</value>`` `` <value>value4</value>`` `` </param_list>`` `` </item>`` ``</items>`` :param stream: ``Stream`` containing XML to parse. :return definition: A ``ValidationDefinition`` object. """ definition = ValidationDefinition() # parse XML from the stream, then get the root node root = ET.parse(stream).getroot() for node in root: # lone item node if node.tag == "item": # name from item node definition.metadata["name"] = node.get("name") definition.parameters = parse_xml_data(node, "") else: # Store anything else in metadata definition.metadata[node.tag] = node.text return definition
python
def parse(stream): definition = ValidationDefinition() # parse XML from the stream, then get the root node root = ET.parse(stream).getroot() for node in root: # lone item node if node.tag == "item": # name from item node definition.metadata["name"] = node.get("name") definition.parameters = parse_xml_data(node, "") else: # Store anything else in metadata definition.metadata[node.tag] = node.text return definition
[ "def", "parse", "(", "stream", ")", ":", "definition", "=", "ValidationDefinition", "(", ")", "# parse XML from the stream, then get the root node", "root", "=", "ET", ".", "parse", "(", "stream", ")", ".", "getroot", "(", ")", "for", "node", "in", "root", ":"...
Creates a ``ValidationDefinition`` from a provided stream containing XML. The XML typically will look like this: ``<items>`` `` <server_host>myHost</server_host>`` `` <server_uri>https://127.0.0.1:8089</server_uri>`` `` <session_key>123102983109283019283</session_key>`` `` <checkpoint_dir>/opt/splunk/var/lib/splunk/modinputs</checkpoint_dir>`` `` <item name="myScheme">`` `` <param name="param1">value1</param>`` `` <param_list name="param2">`` `` <value>value2</value>`` `` <value>value3</value>`` `` <value>value4</value>`` `` </param_list>`` `` </item>`` ``</items>`` :param stream: ``Stream`` containing XML to parse. :return definition: A ``ValidationDefinition`` object.
[ "Creates", "a", "ValidationDefinition", "from", "a", "provided", "stream", "containing", "XML", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/modularinput/validation_definition.py#L44-L84
235,997
splunk/splunk-sdk-python
examples/custom_search/bin/usercount.py
output_results
def output_results(results, mvdelim = '\n', output = sys.stdout): """Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline""" # We collect all the unique field names, as well as # convert all multivalue keys to the right form fields = set() for result in results: for key in result.keys(): if(isinstance(result[key], list)): result['__mv_' + key] = encode_mv(result[key]) result[key] = mvdelim.join(result[key]) fields.update(list(result.keys())) # convert the fields into a list and create a CSV writer # to output to stdout fields = sorted(list(fields)) writer = csv.DictWriter(output, fields) # Write out the fields, and then the actual results writer.writerow(dict(list(zip(fields, fields)))) writer.writerows(results)
python
def output_results(results, mvdelim = '\n', output = sys.stdout): # We collect all the unique field names, as well as # convert all multivalue keys to the right form fields = set() for result in results: for key in result.keys(): if(isinstance(result[key], list)): result['__mv_' + key] = encode_mv(result[key]) result[key] = mvdelim.join(result[key]) fields.update(list(result.keys())) # convert the fields into a list and create a CSV writer # to output to stdout fields = sorted(list(fields)) writer = csv.DictWriter(output, fields) # Write out the fields, and then the actual results writer.writerow(dict(list(zip(fields, fields)))) writer.writerows(results)
[ "def", "output_results", "(", "results", ",", "mvdelim", "=", "'\\n'", ",", "output", "=", "sys", ".", "stdout", ")", ":", "# We collect all the unique field names, as well as ", "# convert all multivalue keys to the right form", "fields", "=", "set", "(", ")", "for", ...
Given a list of dictionaries, each representing a single result, and an optional list of fields, output those results to stdout for consumption by the Splunk pipeline
[ "Given", "a", "list", "of", "dictionaries", "each", "representing", "a", "single", "result", "and", "an", "optional", "list", "of", "fields", "output", "those", "results", "to", "stdout", "for", "consumption", "by", "the", "Splunk", "pipeline" ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/custom_search/bin/usercount.py#L79-L103
235,998
splunk/splunk-sdk-python
examples/github_forks/github_forks.py
MyScript.validate_input
def validate_input(self, validation_definition): """In this example we are using external validation to verify that the Github repository exists. If validate_input does not raise an Exception, the input is assumed to be valid. Otherwise it prints the exception as an error message when telling splunkd that the configuration is invalid. When using external validation, after splunkd calls the modular input with --scheme to get a scheme, it calls it again with --validate-arguments for each instance of the modular input in its configuration files, feeding XML on stdin to the modular input to do validation. It is called the same way whenever a modular input's configuration is edited. :param validation_definition: a ValidationDefinition object """ # Get the values of the parameters, and construct a URL for the Github API owner = validation_definition.parameters["owner"] repo_name = validation_definition.parameters["repo_name"] repo_url = "https://api.github.com/repos/%s/%s" % (owner, repo_name) # Read the response from the Github API, then parse the JSON data into an object response = urllib2.urlopen(repo_url).read() jsondata = json.loads(response) # If there is only 1 field in the jsondata object,some kind or error occurred # with the Github API. # Typically, this will happen with an invalid repository. if len(jsondata) == 1: raise ValueError("The Github repository was not found.") # If the API response seems normal, validate the fork count # If there's something wrong with getting fork_count, raise a ValueError try: fork_count = int(jsondata["forks_count"]) except ValueError as ve: raise ValueError("Invalid fork count: %s", ve.message)
python
def validate_input(self, validation_definition): # Get the values of the parameters, and construct a URL for the Github API owner = validation_definition.parameters["owner"] repo_name = validation_definition.parameters["repo_name"] repo_url = "https://api.github.com/repos/%s/%s" % (owner, repo_name) # Read the response from the Github API, then parse the JSON data into an object response = urllib2.urlopen(repo_url).read() jsondata = json.loads(response) # If there is only 1 field in the jsondata object,some kind or error occurred # with the Github API. # Typically, this will happen with an invalid repository. if len(jsondata) == 1: raise ValueError("The Github repository was not found.") # If the API response seems normal, validate the fork count # If there's something wrong with getting fork_count, raise a ValueError try: fork_count = int(jsondata["forks_count"]) except ValueError as ve: raise ValueError("Invalid fork count: %s", ve.message)
[ "def", "validate_input", "(", "self", ",", "validation_definition", ")", ":", "# Get the values of the parameters, and construct a URL for the Github API", "owner", "=", "validation_definition", ".", "parameters", "[", "\"owner\"", "]", "repo_name", "=", "validation_definition"...
In this example we are using external validation to verify that the Github repository exists. If validate_input does not raise an Exception, the input is assumed to be valid. Otherwise it prints the exception as an error message when telling splunkd that the configuration is invalid. When using external validation, after splunkd calls the modular input with --scheme to get a scheme, it calls it again with --validate-arguments for each instance of the modular input in its configuration files, feeding XML on stdin to the modular input to do validation. It is called the same way whenever a modular input's configuration is edited. :param validation_definition: a ValidationDefinition object
[ "In", "this", "example", "we", "are", "using", "external", "validation", "to", "verify", "that", "the", "Github", "repository", "exists", ".", "If", "validate_input", "does", "not", "raise", "an", "Exception", "the", "input", "is", "assumed", "to", "be", "va...
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/examples/github_forks/github_forks.py#L73-L107
235,999
splunk/splunk-sdk-python
splunklib/searchcommands/internals.py
InputHeader.read
def read(self, ifile): """ Reads an input header from an input file. The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the input header is signalled by an empty line or an end-of-file. :param ifile: File-like object that supports iteration over lines. """ name, value = None, None for line in ifile: if line == '\n': break item = line.split(':', 1) if len(item) == 2: # start of a new item if name is not None: self[name] = value[:-1] # value sans trailing newline name, value = item[0], urllib.parse.unquote(item[1]) elif name is not None: # continuation of the current item value += urllib.parse.unquote(line) if name is not None: self[name] = value[:-1] if value[-1] == '\n' else value
python
def read(self, ifile): name, value = None, None for line in ifile: if line == '\n': break item = line.split(':', 1) if len(item) == 2: # start of a new item if name is not None: self[name] = value[:-1] # value sans trailing newline name, value = item[0], urllib.parse.unquote(item[1]) elif name is not None: # continuation of the current item value += urllib.parse.unquote(line) if name is not None: self[name] = value[:-1] if value[-1] == '\n' else value
[ "def", "read", "(", "self", ",", "ifile", ")", ":", "name", ",", "value", "=", "None", ",", "None", "for", "line", "in", "ifile", ":", "if", "line", "==", "'\\n'", ":", "break", "item", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "if"...
Reads an input header from an input file. The input header is read as a sequence of *<name>***:***<value>* pairs separated by a newline. The end of the input header is signalled by an empty line or an end-of-file. :param ifile: File-like object that supports iteration over lines.
[ "Reads", "an", "input", "header", "from", "an", "input", "file", "." ]
a245a4eeb93b3621730418008e31715912bcdcd8
https://github.com/splunk/splunk-sdk-python/blob/a245a4eeb93b3621730418008e31715912bcdcd8/splunklib/searchcommands/internals.py#L352-L376