Skip to content

Commit 58b7c00

Browse files
author
Frederick Ross
committed
some docstrings, and removed __call__ from Entity and Collection
1 parent c2ca157 commit 58b7c00

6 files changed

Lines changed: 100 additions & 71 deletions

File tree

‎examples/analytics/input.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,17 @@ def __init__(self, application_name, splunk_info, index = ANALYTICS_INDEX_NAME):
3737
self.splunk = client.connect(**splunk_info)
3838
self.index = index
3939

40-
if not self.splunk.indexes.contains(self.index):
40+
if not self.index in self.splunk.indexes:
4141
self.splunk.indexes.create(self.index)
42-
assert(self.splunk.indexes.contains(self.index))
42+
assert(self.index in self.splunk.indexes)
4343

44-
if not self.splunk.confs['props'].contains(ANALYTICS_SOURCETYPE):
44+
if ANALYTICS_SOURCETYPE not in self.splunk.confs['props']:
4545
self.splunk.confs["props"].create(ANALYTICS_SOURCETYPE)
4646
stanza = self.splunk.confs["props"][ANALYTICS_SOURCETYPE]
4747
stanza.submit("LINE_BREAKER = (%s)" % EVENT_TERMINATOR)
4848
stanza.submit("CHARSET = UTF-8")
4949
stanza.submit("SHOULD_LINEMERGE = false")
50-
assert(self.splunk.confs['props'].contains(ANALYTICS_SOURCETYPE))
50+
assert(ANALYTICS_SOURCETYPE in self.splunk.confs['props'])
5151

5252
@staticmethod
5353
def encode(props):

‎examples/analytics/output.py‎

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,18 @@ class TimeRange:
3737
WEEK="1w"
3838
MONTH="1mon"
3939

40+
def counts(job, result_key):
41+
applications = []
42+
reader = results.ResultsReader(job.results())
43+
for result in reader:
44+
if isinstance(result, dict):
45+
applications.append({
46+
"name": result[result_key],
47+
"count": int(result["count"] or 0)
48+
})
49+
return applications
50+
51+
4052
class AnalyticsRetriever:
4153
def __init__(self, application_name, splunk_info, index = ANALYTICS_INDEX_NAME):
4254
self.application_name = application_name
@@ -46,32 +58,12 @@ def __init__(self, application_name, splunk_info, index = ANALYTICS_INDEX_NAME):
4658
def applications(self):
4759
query = "search index=%s | stats count by application" % (self.index)
4860
job = self.splunk.jobs.create(query, exec_mode="blocking")
49-
50-
applications = []
51-
reader = results.ResultsReader(job.results())
52-
for kind,result in reader:
53-
if kind == results.RESULT:
54-
applications.append({
55-
"name": result["application"],
56-
"count": int(result["count"] or 0)
57-
})
58-
59-
return applications
61+
return counts(job, "application")
6062

6163
def events(self):
6264
query = "search index=%s application=%s | stats count by event" % (self.index, self.application_name)
6365
job = self.splunk.jobs.create(query, exec_mode="blocking")
64-
65-
events = []
66-
reader = results.ResultsReader(job.results())
67-
for kind,result in reader:
68-
if kind == results.RESULT:
69-
events.append({
70-
"name": result["event"],
71-
"count": int(result["count"] or 0)
72-
})
73-
74-
return events
66+
return counts(job, "event")
7567

7668
def properties(self, event_name):
7769
query = 'search index=%s application=%s event="%s" | stats dc(%s*) as *' % (
@@ -81,17 +73,18 @@ def properties(self, event_name):
8173

8274
properties = []
8375
reader = results.ResultsReader(job.results())
84-
for kind,result in reader:
85-
if kind == results.RESULT:
86-
for field, count in result.iteritems():
87-
# Ignore internal ResultsReader properties
88-
if field.startswith("$"):
89-
continue
90-
91-
properties.append({
76+
for result in reader:
77+
if not isinstance(result, dict):
78+
continue
79+
for field, count in result.iteritems():
80+
# Ignore internal ResultsReader properties
81+
if field.startswith("$"):
82+
continue
83+
84+
properties.append({
9285
"name": field,
9386
"count": int(count or 0)
94-
})
87+
})
9588

9689
return properties
9790

@@ -105,8 +98,8 @@ def property_values(self, event_name, property):
10598

10699
values = []
107100
reader = results.ResultsReader(job.results())
108-
for kind,result in reader:
109-
if kind == results.RESULT:
101+
for result in reader:
102+
if isinstance(result, dict):
110103
if result[property]:
111104
values.append({
112105
"name": result[property],
@@ -125,8 +118,8 @@ def events_over_time(self, event_name = "", time_range = TimeRange.MONTH, proper
125118

126119
over_time = {}
127120
reader = results.ResultsReader(job.results())
128-
for kind,result in reader:
129-
if kind == results.RESULT:
121+
for result in reader:
122+
if isinstance(result, dict):
130123
# Get the time for this entry
131124
time = result["_time"]
132125
del result["_time"]

‎examples/job.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ def sid(self, spec):
183183
"""Convert the given search specifier into a search-id (sid)."""
184184
if spec.startswith('@'):
185185
index = int(spec[1:])
186-
jobs = self.service.jobs()
186+
jobs = self.service.jobs.list()
187187
if index < len(jobs):
188188
return jobs[index].sid
189189
return spec # Assume it was already a valid sid

‎splunklib/client.py‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,35 @@
2626
# Entity state, are written so that they may be used in a fluent style.
2727
#
2828

29-
"""This module provides a client interface for the `Splunk REST API
30-
<http://docs.splunk.com/Documentation/Splunk/latest/RESTAPI/RESTcontents>`_."""
29+
"""A Pythonic interface to the Splunk REST API.
30+
31+
``splunklib.client`` wraps a Pythonic layer around the wire level
32+
binding of ``splunklib.binding``. The core of the library is the
33+
``Service`` class that encapsulates a connection to the server, and
34+
provides access to the various aspects of the REST API. Typically you
35+
would create a server with the :func:`connect` function, as in::
36+
37+
import splunklib.client as client
38+
s = client.connect(host='localhost', port=8089,
39+
username='admin', password='...')
40+
assert isinstance(s, client.Service)
41+
42+
``Service``s have fields for the various API functionality (``apps``,
43+
``saved_searches``, etc.). All these fields are ``Collection``s. For
44+
example,::
45+
46+
a = s.apps
47+
my_app = a.create('my_app')
48+
my_app = a['my_app']
49+
a.delete('my_app')
50+
51+
The individual applications, or elements of the other ``Collection``s,
52+
are subclasses of ``Entity``. An ``Entity`` has fields giving its
53+
attributes, and methods specific to each kind of entity.::
54+
55+
print my_app['author'] # or print my_app.author
56+
my_app.package() # Create a compressed package of this application
57+
"""
3158

3259
# UNDONE: Add Collection.refresh and list caching
3360
# UNDONE: Resolve conflict between Collection.delete and name of REST method
@@ -48,6 +75,7 @@
4875
"connect",
4976
"NotSupportedError",
5077
"OperationError",
78+
"IncomparableException",
5179
"Service"
5280
]
5381

@@ -150,22 +178,38 @@ def _parse_atom_metadata(content):
150178

151179
# kwargs: scheme, host, port, app, owner, username, password
152180
def connect(**kwargs):
153-
"""Establishes an authenticated connection to a Splunk :class:`Service`
154-
instance.
181+
"""Connect and log in to a Splunk instance.
155182
156-
:param `host`: The host name (the default is *localhost*).
157-
:param `port`: The port number (the default is *8089*).
158-
:param `scheme`: The scheme for accessing the service (the default is
159-
*https*).
183+
This is a shorthand for ``Service(...).login()``. :func:`connect` makes one round trip to the server (for logging in).
184+
185+
:param `host`: The host name (default: ``"localhost"``).
186+
:type host: string
187+
:param `port`: The port number (default: 8089).
188+
:type port: integer
189+
:param `scheme`: The scheme for accessing the service (default: ``"https"``)
190+
:type scheme: ``"https"``
160191
:param `owner`: The owner namespace (optional).
192+
:type owner: string
161193
:param `app`: The app context (optional).
194+
:type app: string
162195
:param `token`: The current session token (optional). Session tokens can be
163196
shared across multiple service instances.
197+
:type token: string
164198
:param `username`: The Splunk account username, which is used to
165199
authenticate the Splunk instance.
200+
:type username: string
166201
:param `password`: The password, which is used to authenticate the Splunk
167202
instance.
168-
:return: An initialized :class:`Service` instance.
203+
:type password: string
204+
:return: An initialized connection
205+
:rtype: :class:`Service`
206+
207+
**Example**:
208+
209+
import splunklib.client as client
210+
s = client.connect(...)
211+
a = s.apps["my_app"]
212+
...
169213
"""
170214
return Service(**kwargs).login()
171215

@@ -699,9 +743,6 @@ def __init__(self, service, path, item=Entity):
699743
Endpoint.__init__(self, service, path)
700744
self.item = item # Item accessor
701745

702-
def __call__(self, **kwargs):
703-
return self.list(**kwargs)
704-
705746
def __contains__(self, name):
706747
for item in self.list():
707748
if item.name == name: return True
@@ -978,8 +1019,7 @@ def __getitem__(self, key):
9781019
try:
9791020
path = self.service._abspath(PATH_CONF % key)
9801021
response = self.get(path)
981-
entries = self._load_list(response)
982-
return entries
1022+
return ConfigurationFile(self.service, path, state={'title': key})
9831023
except HTTPError as he:
9841024
if he.status == 404: # No entity matching key
9851025
raise KeyError(key)
@@ -1169,10 +1209,6 @@ def __init__(self, service, kindmap=None):
11691209
Collection.__init__(self, service, PATH_INPUTS)
11701210
self._kindmap = kindmap if kindmap is not None else INPUT_KINDMAP
11711211

1172-
# args: kind*
1173-
def __call__(self, *args):
1174-
return self.list(*args)
1175-
11761212
def __getitem__(self, key):
11771213
if isinstance(key, tuple) and len(key) == 2:
11781214
kind, key = key
@@ -1586,7 +1622,6 @@ def oneshot(self, query, **params):
15861622
else:
15871623
raise
15881624

1589-
15901625
def list(self, count=0, **kwargs):
15911626
return Collection.list(self, count, **kwargs)
15921627

‎tests/test_job.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def test_read(self):
6464
service = client.connect(**self.opts.kwargs)
6565

6666
for job in service.jobs:
67+
service.jobs[job.sid]
6768
self.check_job(job)
6869
job.refresh()
6970
self.check_job(job)

‎tests/test_service.py‎

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,28 +58,28 @@ def test_namespaces(self):
5858

5959
# Verify connect with no namespace
6060
service = client.connect(**kwargs)
61-
service.apps()
61+
service.apps.list()
6262

6363
# Verify namespace permutations using standard app & owner args
6464
kwargs.update({ 'app': "search", 'owner': None })
6565
service_ns = client.connect(**kwargs)
66-
service_ns.apps()
66+
service_ns.apps.list()
6767

6868
kwargs.update({ 'app': "search", 'owner': "-" })
6969
service_ns = client.connect(**kwargs)
70-
service_ns.apps()
70+
service_ns.apps.list()
7171

7272
kwargs.update({ 'app': None, 'owner': "admin" })
7373
service_ns = client.connect(**kwargs)
74-
service_ns.apps()
74+
service_ns.apps.list()
7575

7676
kwargs.update({ 'app': "-", 'owner': "admin" })
7777
service_ns = client.connect(**kwargs)
78-
service_ns.apps()
78+
service_ns.apps.list()
7979

8080
kwargs.update({ 'app': "search", 'owner': "admin" })
8181
service_ns = client.connect(**kwargs)
82-
service_ns.apps()
82+
service_ns.apps.list()
8383

8484
appname = "sdk-test-app"
8585
username = "sdk-test-user"
@@ -92,31 +92,31 @@ def test_namespaces(self):
9292
kwargs.update({ 'app': appname, 'owner': username })
9393
with self.assertRaises(HTTPError):
9494
service_ns = client.connect(**kwargs)
95-
service_ns.apps()
95+
service_ns.apps.list()
9696

9797
# Validate namespace permutations with new app & user
9898
service.apps.create(appname)
9999
service.users.create(username, password="changeme", roles="power")
100100

101101
kwargs.update({ 'app': appname, 'owner': None })
102102
service_ns = client.connect(**kwargs)
103-
service_ns.apps()
103+
service_ns.apps.list()
104104

105105
kwargs.update({ 'app': appname, 'owner': "-" })
106106
service_ns = client.connect(**kwargs)
107-
service_ns.apps()
107+
service_ns.apps.list()
108108

109109
kwargs.update({ 'app': None, 'owner': username })
110110
service_ns = client.connect(**kwargs)
111-
service_ns.apps()
111+
service_ns.apps.list()
112112

113113
kwargs.update({ 'app': "-", 'owner': username })
114114
service_ns = client.connect(**kwargs)
115-
service_ns.apps()
115+
service_ns.apps.list()
116116

117117
kwargs.update({ 'app': appname, 'owner': username })
118118
service_ns = client.connect(**kwargs)
119-
service_ns.apps()
119+
service_ns.apps.list()
120120

121121
# Cleanup
122122
testlib.delete_app(service, appname)

0 commit comments

Comments
 (0)