@@ -222,40 +222,67 @@ def connect(**kwargs):
222222 return Service (** kwargs ).login ()
223223
224224class Service (Context ):
225- """This class represents a Splunk service instance at a given address
226- (host:port), accessed using the *http* or *https* protocol scheme.
227-
228- A :class:`Service` instance also captures an optional namespace context
229- consisting of an optional owner name (or "-" wildcard) and optional app name
230- (or "-" wildcard). To access :class:`Service` members, the instance must
231- be authenticated by presenting credentials using the :meth:`login` method,
232- or by constructing the instance using the :func:`connect` function, which
233- both creates and authenticates the instance.
234-
235- :param `host`: The host name (the default is *localhost*).
236- :param `port`: The port number (the default is *8089*).
237- :param `scheme`: The scheme for accessing the service (the default is
238- *https*).
239- :param `owner`: The owner namespace (optional).
240- :param `app`: The app context (optional).
225+ """A Pythonic binding to Splunk instances.
226+
227+ A :class:`Service` represents a binding to a Splunk instane on an
228+ HTTP or HTTPS port. It handles the details of authentication, wire
229+ formats, and wraps the REST API endpoints into something more
230+ Pythonic. All the low level operations on the instance from
231+ :class:`splunklib.Context` are available as well in case you need
232+ to do something outside of what :class:`Service` provides.
233+
234+ After creating a :class:`Service`, you must call its :meth:`login`
235+ method before you can issue useful requests to Splunk.
236+ Alternately, use the :func:`connect` function to create an already
237+ authenticated :class:`Service` object, or provide a session token
238+ when creating the :class:`Service` object explicitly (the same
239+ token may be shared by multiple :class:`Service` objects).
240+
241+ :param `host`: The host name (default: ``"localhost"``).
242+ :type host: string
243+ :param `port`: The port number (default: 8089).
244+ :type port: int
245+ :param `scheme`: The scheme for accessing the service (default: ``"https"``)
246+ :type scheme: ``"https"`` or ``"http"``
247+ :param `owner`: The owner namespace (optional; use ``"-"`` for wildcard).
248+ :type owner: string
249+ :param `app`: The app context (optional; use ``"-"`` for wildcard).
250+ :type app: string
241251 :param `token`: The current session token (optional). Session tokens can be
242252 shared across multiple service instances.
253+ :type token: string
243254 :param `username`: The Splunk account username, which is used to
244255 authenticate the Splunk instance.
256+ :type username: string
245257 :param `password`: The password, which is used to authenticate the Splunk
246258 instance.
259+ :type password: string
260+ :returns: A :class:`Service` instance.
261+
262+ **Example**::
263+
264+ import splunklib.client as client
265+ s = client.Service(username="boris", password="natasha", ...)
266+ s.login()
267+ # Or equivalently
268+ s = client.connect(username="boris", password="natasha")
269+ # Or if you already have a session token
270+ s = client.Service(token="atg232342aa34324a")
247271 """
248272 def __init__ (self , ** kwargs ):
249273 Context .__init__ (self , ** kwargs )
250274
251275 @property
252276 def apps (self ):
253- """Returns a collection of Splunk applications."""
277+ """The applications installed in this instance of Splunk.
278+
279+ :rtype: :class:`Collection`
280+ """
254281 return Collection (self , PATH_APPS , item = Application )
255282
256283 @property
257284 def confs (self ):
258- """Returns a collection of Splunk configurations ."""
285+ """The configuration files of this Splunk instance ."""
259286 return Configurations (self )
260287
261288 @property
@@ -286,18 +313,17 @@ def deployment_tenants(self):
286313
287314 @property
288315 def event_types (self ):
289- """Returns a collection of saved event types."""
316+ """The saved event types known by this Splunk instance ."""
290317 return Collection (self , PATH_EVENT_TYPES )
291318
292319 @property
293320 def fired_alerts (self ):
294- """Returns a collection of alerts that have been fired by the service.
295- """
321+ """Alerts that have been fired on the Splunk instance."""
296322 return Collection (self , PATH_FIRED_ALERTS , item = AlertGroup )
297323
298324 @property
299325 def indexes (self ):
300- """Returns a collection of indexes ."""
326+ """The indexes of this Splunk instance ."""
301327 return Collection (self , PATH_INDEXES , item = Index )
302328
303329 @property
@@ -308,7 +334,7 @@ def info(self):
308334
309335 @property
310336 def inputs (self ):
311- """Returns a collection of configured inputs ."""
337+ """The inputs configured on this Splunk instance ."""
312338 return Inputs (self )
313339
314340 @property
@@ -339,8 +365,10 @@ def parse(self, query, **kwargs):
339365 return self .get ("search/parser" , q = query , ** kwargs )
340366
341367 def restart (self ):
342- """Restarts the service. The service will be unavailable until it has
343- successfully restarted.
368+ """Restarts this Splunk instance.
369+
370+ The service will be unavailable until it has successfully
371+ restarted.
344372 """
345373 return self .get ("server/control/restart" )
346374
@@ -509,6 +537,12 @@ class Entity(Endpoint):
509537 subdictionary, so ``email.body.salutation`` would be accessed at
510538 ``ent['email']['body']['salutation']`` or
511539 ``ent['email.body.salutation']``.
540+
541+ The state of an :class:`Entity` is cached, so accessing a field
542+ does not contact the server. If you expect the values on the
543+ server have changed, you have to call the :meth:`refresh` method
544+ on the :class:`Entity` before the updated values will be
545+ available.
512546 """
513547 # Not every endpoint in the API is an Entity or a Collection. For
514548 # example, a saved search at saved/searches/{name} has an additional
@@ -647,8 +681,18 @@ def _run_method(self, path_segment, **kwargs):
647681 return rec .content
648682
649683 def refresh (self , state = None ):
650- """Refreshes the cached state of this entity, using either the given
651- state record, or by calling :meth:`read` if no state record is provided.
684+ """Refresh the state of this entity.
685+
686+ If *state* is provided, load it as the new state for this
687+ entity. Otherwise, make a roundtrip to the server (by calling
688+ the :meth:`read`f method of self) to fetch an updated state.
689+
690+ **Example**::
691+
692+ import splunklib.client as client
693+ s = client.connect(...)
694+ search = s.apps['search']
695+ search.refresh()
652696 """
653697 if state is not None :
654698 self ._state = state
@@ -746,12 +790,57 @@ def update(self, **kwargs):
746790 return self
747791
748792class Collection (Endpoint ):
749- """This class contains a collection of entities."""
793+ """A collection of entities in the Splunk instance.
794+
795+ Splunk provides a number of different collections of distinct
796+ entity types: applications, saved searches, fired alerts, and a
797+ number of others. Each particular type is available separately
798+ from the Splunk instance, and the entities of that type are
799+ returned in a :class:`Collection`.
800+
801+ :class:`Collection`'s interface does not quite match either
802+ ``list`` or ``dict`` in Python, since there are enough semantic
803+ mismatches with either to make its behavior surprising. A unique
804+ element in a :class:`Collection` is defined by a string giving its
805+ name plus a namespace object (though the namespace is optional if
806+ the name is unique).::
807+
808+ import splunklib.client as client
809+ s = client.connect(...)
810+ c = s.saved_searches # c is a Collection
811+ m = c['my_search', client.namespace(owner='boris', app='natasha', sharing='user')]
812+ # Or if there is only one search visible named 'my_search'
813+ m = c['my_search']
814+
815+ Similarly, ``"name" in c`` works as you expect (though you cannot
816+ currently pass a namespace to the ``in`` operator), as does
817+ ``len(c)``.
818+
819+ However, as an aggregate, :class:`Collection` behaves more like a
820+ list. If you iterate over a :class:`Collection`, you get an
821+ iterator over the entities, not the names and namespaces::
822+
823+ for entity in c:
824+ assert isinstance(entity, client.Entity)
825+
826+ The :meth:`create` and :meth:`delete` methods create and delete
827+ entities in this collection. The access control list and other
828+ metadata of the collection is returned by the :meth:`itemmeta`
829+ method.
830+
831+ :class:`Collection` does no caching. Each call makes at least one
832+ round trip to the server to fetch data.
833+ """
750834 def __init__ (self , service , path , item = Entity ):
751835 Endpoint .__init__ (self , service , path )
752836 self .item = item # Item accessor
753837
754838 def __contains__ (self , name ):
839+ """Is there at least one entry called *name* in this collection?
840+
841+ Makes a single roundtrip to the server, plus at most two more
842+ if autologin is enabled.
843+ """
755844 for item in self .list ():
756845 if item .name == name : return True
757846 return False
@@ -874,7 +963,29 @@ def _entity_path(self, state):
874963 return urllib .unquote (state .links .alternate )
875964
876965 def _load_list (self , response ):
877- """Loads an entity list from a response."""
966+ """Converts *response* to a list of entities.
967+
968+ *response* is assumed to be a :class:`Record` containing an
969+ HTTP response, of the form::
970+
971+ {'status': 200,
972+ 'headers': [('content-length', '232642'),
973+ ('expires', 'Fri, 30 Oct 1998 00:00:00 GMT'),
974+ ('server', 'Splunkd'),
975+ ('connection', 'close'),
976+ ('cache-control', 'no-store, max-age=0, must-revalidate, no-cache'),
977+ ('date', 'Tue, 29 May 2012 15:27:08 GMT'),
978+ ('content-type', 'text/xml; charset=utf-8')],
979+ 'reason': 'OK',
980+ 'body': ...a stream implementing .read()...}
981+
982+ The ``'body'`` key refers to a stream containing an Atom feed,
983+ that is, an XML document with a toplevel element ``<feed>``,
984+ and within that element one or more ``<entry>`` elements.
985+ """
986+ # Some subclasses of Collection have to override this because
987+ # splunkd returns something that doesn't match
988+ # <feed><entry></entry><feed>.
878989 entries = _load_atom_entries (response )
879990 if entries is None : return []
880991 entities = []
@@ -891,6 +1002,9 @@ def contains(self, name):
8911002 """**Deprecated**: Use the ``in`` operator instead.
8921003
8931004 Indicates whether an entity name exists in the collection.
1005+
1006+ Makes a single roundtrip to the server, plus at most two more
1007+ if autologin is enabled.
8941008
8951009 :param `name`: The entity name.
8961010 :rtype: Boolean
@@ -900,11 +1014,27 @@ def contains(self, name):
9001014 def create (self , name , ** params ):
9011015 """Create a new entity in this collection.
9021016
1017+ This function makes either one or two roundtrips to the
1018+ server, depending on the type of the entities in this
1019+ collection, plus at most two more if autologin is enabled.
1020+
9031021 :param name: The name of the entity to create.
9041022 :type name: string
1023+ :param namespace: A namespace, as created by the :func:`namespace`
1024+ function (optional). If you wish, you can set
1025+ ``owner``, ``app``, and ``sharing`` directly.
1026+ :type namespace: :class:`Record` with keys ``'owner'``, ``'app'``, and
1027+ ``'sharing'``
9051028 :param params: Additional entity-specific arguments (optional).
9061029 :return: The new entity.
9071030 :rtype: subclass of ``Entity``, chosen by ``self.item`` in ``Collection``
1031+
1032+ **Example**::
1033+
1034+ import splunklib.client as client
1035+ s = client.connect(...)
1036+ applications = s.apps
1037+ new_app = applications.create("my_fake_app")
9081038 """
9091039 if not isinstance (name , basestring ):
9101040 raise ValueError ("Invalid argument: 'name'" )
@@ -973,14 +1103,51 @@ def delete(self, name, **params):
9731103 return self
9741104
9751105 def itemmeta (self ):
976- """Returns metadata for members of the collection."""
1106+ """Returns metadata for members of the collection.
1107+
1108+ Makes a single roundtrip to the server, plus at most two more
1109+ if autologin is enabled.
1110+
1111+ **Example**::
1112+
1113+ import splunklib.client as client
1114+ import pprint
1115+ s = client.connect(...)
1116+ pprint.pprint(s.apps.itemmeta())
1117+ {'access': {'app': 'search',
1118+ 'can_change_perms': '1',
1119+ 'can_list': '1',
1120+ 'can_share_app': '1',
1121+ 'can_share_global': '1',
1122+ 'can_share_user': '1',
1123+ 'can_write': '1',
1124+ 'modifiable': '1',
1125+ 'owner': 'admin',
1126+ 'perms': {'read': ['*'], 'write': ['admin']},
1127+ 'removable': '0',
1128+ 'sharing': 'user'},
1129+ 'fields': {'optional': ['author',
1130+ 'configured',
1131+ 'description',
1132+ 'label',
1133+ 'manageable',
1134+ 'template',
1135+ 'visible'],
1136+ 'required': ['name'],
1137+ 'wildcard': []}}
1138+ """
9771139 response = self .get ("_new" )
9781140 content = _load_atom (response , MATCH_ENTRY_CONTENT )
9791141 return _parse_atom_metadata (content )
9801142
9811143 # kwargs: count, offset, search, sort_dir, sort_key, sort_mode
9821144 def list (self , count = - 1 , ** kwargs ):
983- """Returns the contents of the collection.
1145+ """Fetch a list of the entities in this collection.
1146+
1147+ There is no laziness in this function. The entire collection
1148+ is loaded at once and returned as a list. This function makes
1149+ a single roundtrip to the server, plus at most two more if
1150+ autologin is enabled.
9841151
9851152 :param `count`: The maximum number of items to return (optional).
9861153 :param `offset`: The offset of the first item to return (optional).
@@ -990,6 +1157,7 @@ def list(self, count=-1, **kwargs):
9901157 :param `sort_key`: The field to use for sorting (optional).
9911158 :param `sort_mode`: The collating sequence for sorting returned items:
9921159 *auto*, *alpha*, *alpha_case*, *num* (optional).
1160+ :rtype: list
9931161
9941162 This function always makes a roundtrip to the server, and
9951163 makes no attempt at caching.
0 commit comments