Skip to content

Commit 9448df9

Browse files
author
Fred Ross
committed
Add contextmanager attached_socket to Index.
1 parent 2597485 commit 9448df9

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

‎splunklib/client.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@
6767
import logging
6868
from time import sleep
6969
from datetime import datetime, timedelta
70+
import socket
71+
import contextlib
7072

7173
from binding import Context, HTTPError, AuthenticationError, namespace, UrlEncoded
7274
from data import record
@@ -1476,6 +1478,32 @@ def attach(self, host=None, source=None, sourcetype=None):
14761478
sock.write(h)
14771479
return sock
14781480

1481+
@contextlib.contextmanager
1482+
def attached_socket(self, *args, **kwargs):
1483+
"""Open a raw socket in a with block to write data to Splunk.
1484+
1485+
The arguments are identical to those for ``attach``. The socket is automatically
1486+
closed at the end of the with block, even if an exception is raised in the block.
1487+
1488+
:param `host`: The host value for events written to the stream.
1489+
:param `source`: The source value for events written to the stream.
1490+
:param `sourcetype`: The sourcetype value for events written to the
1491+
1492+
**Example**::
1493+
1494+
import splunklib.client as client
1495+
s = client.connect(...)
1496+
index = s.indexes['some_index']
1497+
with index.attached_socket(sourcetype='test') as sock:
1498+
sock.send('Test event\r\n')
1499+
"""
1500+
try:
1501+
sock = self.attach(*args, **kwargs)
1502+
yield sock
1503+
finally:
1504+
sock.shutdown(socket.SHUT_RDWR)
1505+
sock.close()
1506+
14791507
def clean(self, timeout=60):
14801508
"""Deletes the contents of the index.
14811509

‎tests/test_index.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def test_disable_enable(self):
5656
class IndexWithRestartTest(IndexTest):
5757
def setUp(self):
5858
super(IndexWithRestartTest, self).setUp()
59-
self.service.restart(timeout=120)
59+
self.service.restart(timeout=300)
6060
self.index = self.service.indexes[self.index_name]
6161

6262
def test_cannot_clean_enabled(self):
@@ -97,6 +97,14 @@ def test_submit_via_attach(self):
9797
self.index.refresh()
9898
self.assertEqual(self.index['totalEventCount'], str(eventCount+1))
9999

100+
def test_submit_via_attached_socket(self):
101+
eventCount = int(self.index['totalEventCount'])
102+
f = self.index.attached_socket
103+
with f() as sock:
104+
sock.send('Hello world!\r\n')
105+
testlib.retry(self.index, 'totalEventCount', str(eventCount+1), step=1)
106+
self.assertEqual(self.index['totalEventCount'], str(eventCount+1))
107+
100108
def test_upload(self):
101109
# The following test must run on machine where splunkd runs,
102110
# otherwise a failure is expected

0 commit comments

Comments
 (0)