/
event_writer.py
281 lines (228 loc) · 9.59 KB
/
event_writer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# Copyright 2016 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the 'License'): you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
'''
This module provides two kinds of event writers (ClassicEventWriter,
HECEventWriter) to write Splunk modular input events.
'''
import sys
import time
import threading
import logging
import traceback
from abc import ABCMeta, abstractmethod
from splunklib import binding
import solnlib.splunk_rest_client as rest_client
from solnlib.splunkenv import get_splunkd_access_info
import solnlib.utils as utils
from solnlib.hec_config import HECConfig
from solnlib.utils import retry
from solnlib.modular_input.event import XMLEvent, HECEvent
__all__ = ['ClassicEventWriter',
'HECEventWriter']
class EventWriter(object):
'''Base class of event writer.
'''
__metaclass__ = ABCMeta
description = 'EventWriter'
@abstractmethod
def create_event(self, data, time=None,
index=None, host=None, source=None, sourcetype=None,
stanza=None, unbroken=False, done=False):
'''Create a new event.
:param data: Event data.
:type data: ``json object``
:param time: (optional) Event timestamp, default is None.
:type time: ``float``
:param index: (optional) The index event will be written to, default
is None
:type index: ``string``
:param host: (optional) Event host, default is None.
:type host: ``string``
:param source: (optional) Event source, default is None.
:type source: ``string``
:param sourcetype: (optional) Event sourcetype, default is None.
:type sourcetype: ``string``
:param stanza: (optional) Event stanza name, default is None.
:type stanza: ``string``
:param unbroken: (optional) Event unbroken flag, default is False.
It is only meaningful when for XMLEvent when using ClassicEventWriter.
:type unbroken: ``bool``
:param done: (optional) The last unbroken event, default is False.
It is only meaningful when for XMLEvent when using ClassicEventWriter.
:returns: ``bool``
:returns: A new event object.
:rtype: ``(XMLEvent, HECEvent)``
Usage::
>>> ew = event_writer.HECEventWriter(...)
>>> event = ew.create_event(
>>> data='This is a test data.',
>>> time='%.3f' % 1372274622.493,
>>> index='main',
>>> host='localhost',
>>> source='Splunk',
>>> sourcetype='misc',
>>> stanza='test_scheme://test',
>>> unbroken=True,
>>> done=True)
'''
pass
@abstractmethod
def write_events(self, events):
'''Write events.
:param events: List of events to write.
:type events: ``list``
Usage::
>>> from solnlib.modular_input import event_writer
>>> ew = event_writer.EventWriter(...)
>>> ew.write_events([event1, event2])
'''
pass
class ClassicEventWriter(EventWriter):
'''Classic event writer.
Use sys.stdout as the output.
:param lock: (optional) lock to exclusively access stdout.
by default, it is None and it will use threading safe lock.
if user would like to make the lock multiple-process safe, user should
pass in multiprocessing.Lock() instead
:type lock: ``theading.Lock or multiprocessing.Lock``
Usage::
>>> from solnlib.modular_input import event_writer
>>> ew = event_writer.ClassicEventWriter()
>>> ew.write_events([event1, event2])
'''
description = 'ClassicEventWriter'
def __init__(self, lock=None):
if lock is None:
self._lock = threading.Lock()
else:
self._lock = lock
def create_event(self, data, time=None,
index=None, host=None, source=None, sourcetype=None,
stanza=None, unbroken=False, done=False):
'''Create a new XMLEvent object.
'''
return XMLEvent(
data, time=time,
index=index, host=host, source=source, sourcetype=sourcetype,
stanza=stanza, unbroken=unbroken, done=done)
def write_events(self, events):
if not events:
return
stdout = sys.stdout
with self._lock:
for event in XMLEvent.format_events(events):
stdout.write(event)
stdout.flush()
class HECEventWriter(EventWriter):
'''Classic event writer.
Use Splunk HEC as the output.
:param hec_input_name: Splunk HEC input name.
:type hec_input_name: ``string``
:param session_key: Splunk access token.
:type session_key: ``string``
:param scheme: (optional) The access scheme, default is None.
:type scheme: ``string``
:param host: (optional) The host name, default is None.
:type host: ``string``
:param port: (optional) The port number, default is None.
:type port: ``integer``
:param hec_uri: (optional) If hec_uri and hec_token are provided, they will
higher precedence than hec_input_name
:type hec_token: ``integer``
:param context: Other configurations for Splunk rest client.
:type context: ``dict``
Usage::
>>> from solnlib.modular_input import event_writer
>>> ew = event_writer.HECEventWriter(hec_input_name, session_key)
>>> ew.write_events([event1, event2])
'''
WRITE_EVENT_RETRIES = 3
HTTP_INPUT_CONFIG_ENDPOINT = \
'/servicesNS/nobody/splunk_httpinput/data/inputs/http'
HTTP_EVENT_COLLECTOR_ENDPOINT = '/services/collector'
description = 'HECEventWriter'
def __init__(self, hec_input_name, session_key,
scheme=None, host=None, port=None, hec_uri=None,
hec_token=None, **context):
super(HECEventWriter, self).__init__()
self._session_key = session_key
if not all([scheme, host, port]):
scheme, host, port = get_splunkd_access_info()
if hec_uri and hec_token:
scheme, host, hec_port = utils.extract_http_scheme_host_port(
hec_uri)
else:
hec_port, hec_token = self._get_hec_config(
hec_input_name, session_key, scheme, host, port, **context)
if not context.get('pool_connections'):
context['pool_connections'] = 10
if not context.get('pool_maxsize'):
context['pool_maxsize'] = 10
self._rest_client = rest_client.SplunkRestClient(hec_token,
app='-',
scheme=scheme,
host=host,
port=hec_port,
**context)
@retry(exceptions=[binding.HTTPError])
def _get_hec_config(self, hec_input_name, session_key,
scheme, host, port, **context):
hc = HECConfig(
session_key, scheme=scheme, host=host, port=port, **context)
settings = hc.get_settings()
if utils.is_true(settings.get('disabled')):
# Enable HEC input
logging.info('Enabling HEC')
settings['disabled'] = '0'
settings['enableSSL'] = context.get('hec_enablessl', '1')
settings['port'] = context.get('hec_port', '8088')
hc.update_settings(settings)
hec_input = hc.get_input(hec_input_name)
if not hec_input:
# Create HEC input
logging.info('Create HEC datainput, name=%s', hec_input_name)
hinput = {
'index': context.get('index', 'main'),
}
if context.get('sourcetype'):
hinput['sourcetype'] = context['sourcetype']
if context.get('token'):
hinput['token'] = context['token']
hec_input = hc.create_input(hec_input_name, hinput)
limits = hc.get_limits()
HECEvent.max_hec_event_length = int(
limits.get('max_content_length', 1000000))
return settings['port'], hec_input['token']
def create_event(self, data, time=None,
index=None, host=None, source=None, sourcetype=None,
stanza=None, unbroken=False, done=False):
'''Create a new HECEvent object.
'''
return HECEvent(
data, time=time,
index=index, host=host, source=source, sourcetype=sourcetype)
def write_events(self, events):
if not events:
return
for event in HECEvent.format_events(events):
for i in xrange(self.WRITE_EVENT_RETRIES):
try:
self._rest_client.post(
self.HTTP_EVENT_COLLECTOR_ENDPOINT, body=event,
headers=[('Content-Type', 'application/json')])
break
except binding.HTTPError as e:
logging.error('Write events through HEC failed: %s.',
traceback.format_exc(e))
time.sleep(2 ** (i + 1))