-
Notifications
You must be signed in to change notification settings - Fork 374
/
Copy pathsearch_command.py
1113 lines (826 loc) · 37.8 KB
/
search_command.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
#
# Copyright © 2011-2015 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.
from __future__ import absolute_import, division, print_function, unicode_literals
# Absolute imports
from collections import namedtuple
import io
try:
from collections import OrderedDict # must be python 2.7
except ImportError:
from ..ordereddict import OrderedDict
from copy import deepcopy
from splunklib.six.moves import StringIO
from itertools import chain, islice
from splunklib.six.moves import filter as ifilter, map as imap, zip as izip
from splunklib import six
if six.PY2:
from logging import _levelNames, getLevelName, getLogger
else:
from logging import _nameToLevel as _levelNames, getLevelName, getLogger
try:
from shutil import make_archive
except ImportError:
# Used for recording, skip on python 2.6
pass
from time import time
from splunklib.six.moves.urllib.parse import unquote
from splunklib.six.moves.urllib.parse import urlsplit
from warnings import warn
from xml.etree import ElementTree
import os
import sys
import re
import csv
import tempfile
import traceback
# Relative imports
from .internals import (
CommandLineParser,
CsvDialect,
InputHeader,
Message,
MetadataDecoder,
MetadataEncoder,
ObjectView,
Recorder,
RecordWriterV1,
RecordWriterV2,
json_encode_string)
from . import Boolean, Option, environment
from ..client import Service
# ----------------------------------------------------------------------------------------------------------------------
# P1 [ ] TODO: Log these issues against ChunkedExternProcessor
#
# 1. Implement requires_preop configuration setting.
# This configuration setting is currently rejected by ChunkedExternProcessor.
#
# 2. Rename type=events as type=eventing for symmetry with type=reporting and type=streaming
# Eventing commands process records on the events pipeline. This change effects ChunkedExternProcessor.cpp,
# eventing_command.py, and generating_command.py.
#
# 3. For consistency with SCPV1, commands.conf should not require filename setting when chunked = true
# The SCPV1 processor uses <stanza-name>.py as the default filename. The ChunkedExternProcessor should do the same.
# P1 [ ] TODO: Verify that ChunkedExternProcessor complains if a streaming_preop has a type other than 'streaming'
# It once looked like sending type='reporting' for the streaming_preop was accepted.
# ----------------------------------------------------------------------------------------------------------------------
# P2 [ ] TODO: Consider bumping None formatting up to Option.Item.__str__
class SearchCommand(object):
""" Represents a custom search command.
"""
def __init__(self):
# Variables that may be used, but not altered by derived classes
class_name = self.__class__.__name__
self._logger, self._logging_configuration = getLogger(class_name), environment.logging_configuration
# Variables backing option/property values
self._configuration = self.ConfigurationSettings(self)
self._input_header = InputHeader()
self._fieldnames = None
self._finished = None
self._metadata = None
self._options = None
self._protocol_version = None
self._search_results_info = None
self._service = None
# Internal variables
self._default_logging_level = self._logger.level
self._record_writer = None
self._records = None
def __str__(self):
text = ' '.join(chain((type(self).name, str(self.options)), [] if self.fieldnames is None else self.fieldnames))
return text
# region Options
@Option
def logging_configuration(self):
""" **Syntax:** logging_configuration=<path>
**Description:** Loads an alternative logging configuration file for
a command invocation. The logging configuration file must be in Python
ConfigParser-format. Path names are relative to the app root directory.
"""
return self._logging_configuration
@logging_configuration.setter
def logging_configuration(self, value):
self._logger, self._logging_configuration = environment.configure_logging(self.__class__.__name__, value)
@Option
def logging_level(self):
""" **Syntax:** logging_level=[CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]
**Description:** Sets the threshold for the logger of this command invocation. Logging messages less severe than
`logging_level` will be ignored.
"""
return getLevelName(self._logger.getEffectiveLevel())
@logging_level.setter
def logging_level(self, value):
if value is None:
value = self._default_logging_level
if isinstance(value, (bytes, six.text_type)):
try:
level = _levelNames[value.upper()]
except KeyError:
raise ValueError('Unrecognized logging level: {}'.format(value))
else:
try:
level = int(value)
except ValueError:
raise ValueError('Unrecognized logging level: {}'.format(value))
self._logger.setLevel(level)
record = Option(doc='''
**Syntax: record=<bool>
**Description:** When `true`, records the interaction between the command and splunkd. Defaults to `false`.
''', default=False, validate=Boolean())
show_configuration = Option(doc='''
**Syntax:** show_configuration=<bool>
**Description:** When `true`, reports command configuration as an informational message. Defaults to `false`.
''', default=False, validate=Boolean())
# endregion
# region Properties
@property
def configuration(self):
""" Returns the configuration settings for this command.
"""
return self._configuration
@property
def fieldnames(self):
""" Returns the fieldnames specified as argument to this command.
"""
return self._fieldnames
@fieldnames.setter
def fieldnames(self, value):
self._fieldnames = value
@property
def input_header(self):
""" Returns the input header for this command.
:return: The input header for this command.
:rtype: InputHeader
"""
warn(
'SearchCommand.input_header is deprecated and will be removed in a future release. '
'Please use SearchCommand.metadata instead.', DeprecationWarning, 2)
return self._input_header
@property
def logger(self):
""" Returns the logger for this command.
:return: The logger for this command.
:rtype:
"""
return self._logger
@property
def metadata(self):
return self._metadata
@property
def options(self):
""" Returns the options specified as argument to this command.
"""
if self._options is None:
self._options = Option.View(self)
return self._options
@property
def protocol_version(self):
return self._protocol_version
@property
def search_results_info(self):
""" Returns the search results info for this command invocation.
The search results info object is created from the search results info file associated with the command
invocation.
:return: Search results info:const:`None`, if the search results info file associated with the command
invocation is inaccessible.
:rtype: SearchResultsInfo or NoneType
"""
if self._search_results_info is not None:
return self._search_results_info
if self._protocol_version == 1:
try:
path = self._input_header['infoPath']
except KeyError:
return None
else:
assert self._protocol_version == 2
try:
dispatch_dir = self._metadata.searchinfo.dispatch_dir
except AttributeError:
return None
path = os.path.join(dispatch_dir, 'info.csv')
try:
with io.open(path, 'r') as f:
reader = csv.reader(f, dialect=CsvDialect)
fields = next(reader)
values = next(reader)
except IOError as error:
if error.errno == 2:
self.logger.error('Search results info file {} does not exist.'.format(json_encode_string(path)))
return
raise
def convert_field(field):
return (field[1:] if field[0] == '_' else field).replace('.', '_')
decode = MetadataDecoder().decode
def convert_value(value):
try:
return decode(value) if len(value) > 0 else value
except ValueError:
return value
info = ObjectView(dict(imap(lambda f_v: (convert_field(f_v[0]), convert_value(f_v[1])), izip(fields, values))))
try:
count_map = info.countMap
except AttributeError:
pass
else:
count_map = count_map.split(';')
n = len(count_map)
info.countMap = dict(izip(islice(count_map, 0, n, 2), islice(count_map, 1, n, 2)))
try:
msg_type = info.msgType
msg_text = info.msg
except AttributeError:
pass
else:
messages = ifilter(lambda t_m: t_m[0] or t_m[1], izip(msg_type.split('\n'), msg_text.split('\n')))
info.msg = [Message(message) for message in messages]
del info.msgType
try:
info.vix_families = ElementTree.fromstring(info.vix_families)
except AttributeError:
pass
self._search_results_info = info
return info
@property
def service(self):
""" Returns a Splunk service object for this command invocation or None.
The service object is created from the Splunkd URI and authentication token passed to the command invocation in
the search results info file. This data is not passed to a command invocation by default. You must request it by
specifying this pair of configuration settings in commands.conf:
.. code-block:: python
enableheader = true
requires_srinfo = true
The :code:`enableheader` setting is :code:`true` by default. Hence, you need not set it. The
:code:`requires_srinfo` setting is false by default. Hence, you must set it.
:return: :class:`splunklib.client.Service`, if :code:`enableheader` and :code:`requires_srinfo` are both
:code:`true`. Otherwise, if either :code:`enableheader` or :code:`requires_srinfo` are :code:`false`, a value
of :code:`None` is returned.
"""
if self._service is not None:
return self._service
metadata = self._metadata
if metadata is None:
return None
try:
searchinfo = self._metadata.searchinfo
except AttributeError:
return None
splunkd_uri = searchinfo.splunkd_uri
if splunkd_uri is None:
return None
uri = urlsplit(splunkd_uri, allow_fragments=False)
self._service = Service(
scheme=uri.scheme, host=uri.hostname, port=uri.port, app=searchinfo.app, token=searchinfo.session_key)
return self._service
# endregion
# region Methods
def error_exit(self, error, message=None):
self.write_error(error.message if message is None else message)
self.logger.error('Abnormal exit: %s', error)
exit(1)
def finish(self):
""" Flushes the output buffer and signals that this command has finished processing data.
:return: :const:`None`
"""
self._record_writer.flush(finished=True)
def flush(self):
""" Flushes the output buffer.
:return: :const:`None`
"""
self._record_writer.flush(finished=False)
def prepare(self):
""" Prepare for execution.
This method should be overridden in search command classes that wish to examine and update their configuration
or option settings prior to execution. It is called during the getinfo exchange before command metadata is sent
to splunkd.
:return: :const:`None`
:rtype: NoneType
"""
pass
def process(self, argv=sys.argv, ifile=sys.stdin, ofile=sys.stdout):
""" Process data.
:param argv: Command line arguments.
:type argv: list or tuple
:param ifile: Input data file.
:type ifile: file
:param ofile: Output data file.
:type ofile: file
:return: :const:`None`
:rtype: NoneType
"""
if len(argv) > 1:
self._process_protocol_v1(argv, ifile, ofile)
else:
self._process_protocol_v2(argv, ifile, ofile)
def _map_input_header(self):
metadata = self._metadata
searchinfo = metadata.searchinfo
self._input_header.update(
allowStream=None,
infoPath=os.path.join(searchinfo.dispatch_dir, 'info.csv'),
keywords=None,
preview=metadata.preview,
realtime=searchinfo.earliest_time != 0 and searchinfo.latest_time != 0,
search=searchinfo.search,
sid=searchinfo.sid,
splunkVersion=searchinfo.splunk_version,
truncated=None)
def _map_metadata(self, argv):
source = SearchCommand._MetadataSource(argv, self._input_header, self.search_results_info)
def _map(metadata_map):
metadata = {}
for name, value in six.iteritems(metadata_map):
if isinstance(value, dict):
value = _map(value)
else:
transform, extract = value
if extract is None:
value = None
else:
value = extract(source)
if not (value is None or transform is None):
value = transform(value)
metadata[name] = value
return ObjectView(metadata)
self._metadata = _map(SearchCommand._metadata_map)
_metadata_map = {
'action':
(lambda v: 'getinfo' if v == '__GETINFO__' else 'execute' if v == '__EXECUTE__' else None, lambda s: s.argv[1]),
'preview':
(bool, lambda s: s.input_header.get('preview')),
'searchinfo': {
'app':
(lambda v: v.ppc_app, lambda s: s.search_results_info),
'args':
(None, lambda s: s.argv),
'dispatch_dir':
(os.path.dirname, lambda s: s.input_header.get('infoPath')),
'earliest_time':
(lambda v: float(v.rt_earliest) if len(v.rt_earliest) > 0 else 0.0, lambda s: s.search_results_info),
'latest_time':
(lambda v: float(v.rt_latest) if len(v.rt_latest) > 0 else 0.0, lambda s: s.search_results_info),
'owner':
(None, None),
'raw_args':
(None, lambda s: s.argv),
'search':
(unquote, lambda s: s.input_header.get('search')),
'session_key':
(lambda v: v.auth_token, lambda s: s.search_results_info),
'sid':
(None, lambda s: s.input_header.get('sid')),
'splunk_version':
(None, lambda s: s.input_header.get('splunkVersion')),
'splunkd_uri':
(lambda v: v.splunkd_uri, lambda s: s.search_results_info),
'username':
(lambda v: v.ppc_user, lambda s: s.search_results_info)}}
_MetadataSource = namedtuple('Source', ('argv', 'input_header', 'search_results_info'))
def _prepare_protocol_v1(self, argv, ifile, ofile):
debug = environment.splunklib_logger.debug
# Provide as much context as possible in advance of parsing the command line and preparing for execution
self._input_header.read(ifile)
self._protocol_version = 1
self._map_metadata(argv)
debug(' metadata=%r, input_header=%r', self._metadata, self._input_header)
try:
tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
except AttributeError:
raise RuntimeError('{}.metadata.searchinfo.dispatch_dir is undefined'.format(self.__class__.__name__))
debug(' tempfile.tempdir=%r', tempfile.tempdir)
CommandLineParser.parse(self, argv[2:])
self.prepare()
if self.record:
self.record = False
record_argv = [argv[0], argv[1], str(self._options), ' '.join(self.fieldnames)]
ifile, ofile = self._prepare_recording(record_argv, ifile, ofile)
self._record_writer.ofile = ofile
ifile.record(str(self._input_header), '\n\n')
if self.show_configuration:
self.write_info(self.name + ' command configuration: ' + str(self._configuration))
return ifile # wrapped, if self.record is True
def _prepare_recording(self, argv, ifile, ofile):
# Create the recordings directory, if it doesn't already exist
recordings = os.path.join(environment.splunk_home, 'var', 'run', 'splunklib.searchcommands', 'recordings')
if not os.path.isdir(recordings):
os.makedirs(recordings)
# Create input/output recorders from ifile and ofile
recording = os.path.join(recordings, self.__class__.__name__ + '-' + repr(time()) + '.' + self._metadata.action)
ifile = Recorder(recording + '.input', ifile)
ofile = Recorder(recording + '.output', ofile)
# Archive the dispatch directory--if it exists--so that it can be used as a baseline in mocks)
dispatch_dir = self._metadata.searchinfo.dispatch_dir
if dispatch_dir is not None: # __GETINFO__ action does not include a dispatch_dir
root_dir, base_dir = os.path.split(dispatch_dir)
make_archive(recording + '.dispatch_dir', 'gztar', root_dir, base_dir, logger=self.logger)
# Save a splunk command line because it is useful for developing tests
with open(recording + '.splunk_cmd', 'wb') as f:
f.write('splunk cmd python '.encode())
f.write(os.path.basename(argv[0]).encode())
for arg in islice(argv, 1, len(argv)):
f.write(' '.encode())
f.write(arg.encode())
return ifile, ofile
def _process_protocol_v1(self, argv, ifile, ofile):
debug = environment.splunklib_logger.debug
class_name = self.__class__.__name__
debug('%s.process started under protocol_version=1', class_name)
self._record_writer = RecordWriterV1(ofile)
# noinspection PyBroadException
try:
if argv[1] == '__GETINFO__':
debug('Writing configuration settings')
ifile = self._prepare_protocol_v1(argv, ifile, ofile)
self._record_writer.write_record(dict(
(n, ','.join(v) if isinstance(v, (list, tuple)) else v) for n, v in six.iteritems(self._configuration)))
self.finish()
elif argv[1] == '__EXECUTE__':
debug('Executing')
ifile = self._prepare_protocol_v1(argv, ifile, ofile)
self._records = self._records_protocol_v1
self._metadata.action = 'execute'
self._execute(ifile, None)
else:
message = (
'Command {0} appears to be statically configured for search command protocol version 1 and static '
'configuration is unsupported by splunklib.searchcommands. Please ensure that '
'default/commands.conf contains this stanza:\n'
'[{0}]\n'
'filename = {1}\n'
'enableheader = true\n'
'outputheader = true\n'
'requires_srinfo = true\n'
'supports_getinfo = true\n'
'supports_multivalues = true\n'
'supports_rawargs = true'.format(self.name, os.path.basename(argv[0])))
raise RuntimeError(message)
except (SyntaxError, ValueError) as error:
self.write_error(six.text_type(error))
self.flush()
exit(0)
except SystemExit:
self.flush()
raise
except:
self._report_unexpected_error()
self.flush()
raise
debug('%s.process finished under protocol_version=1', class_name)
def _process_protocol_v2(self, argv, ifile, ofile):
""" Processes records on the `input stream optionally writing records to the output stream.
:param ifile: Input file object.
:type ifile: file or InputType
:param ofile: Output file object.
:type ofile: file or OutputType
:return: :const:`None`
"""
debug = environment.splunklib_logger.debug
class_name = self.__class__.__name__
debug('%s.process started under protocol_version=2', class_name)
self._protocol_version = 2
# Read search command metadata from splunkd
# noinspection PyBroadException
try:
debug('Reading metadata')
metadata, body = self._read_chunk(ifile)
action = getattr(metadata, 'action', None)
if action != 'getinfo':
raise RuntimeError('Expected getinfo action, not {}'.format(action))
if len(body) > 0:
raise RuntimeError('Did not expect data for getinfo action')
self._metadata = deepcopy(metadata)
searchinfo = self._metadata.searchinfo
searchinfo.earliest_time = float(searchinfo.earliest_time)
searchinfo.latest_time = float(searchinfo.latest_time)
searchinfo.search = unquote(searchinfo.search)
self._map_input_header()
debug(' metadata=%r, input_header=%r', self._metadata, self._input_header)
try:
tempfile.tempdir = self._metadata.searchinfo.dispatch_dir
except AttributeError:
raise RuntimeError('%s.metadata.searchinfo.dispatch_dir is undefined'.format(class_name))
debug(' tempfile.tempdir=%r', tempfile.tempdir)
except:
self._record_writer = RecordWriterV2(ofile)
self._report_unexpected_error()
self.finish()
raise
# Write search command configuration for consumption by splunkd
# noinspection PyBroadException
try:
self._record_writer = RecordWriterV2(ofile, getattr(self._metadata.searchinfo, 'maxresultrows', None))
self.fieldnames = []
self.options.reset()
args = self.metadata.searchinfo.args
error_count = 0
debug('Parsing arguments')
if args and type(args) == list:
for arg in args:
result = arg.split('=', 1)
if len(result) == 1:
self.fieldnames.append(str(result[0]))
else:
name, value = result
name = str(name)
try:
option = self.options[name]
except KeyError:
self.write_error('Unrecognized option: {}={}'.format(name, value))
error_count += 1
continue
try:
option.value = value
except ValueError:
self.write_error('Illegal value: {}={}'.format(name, value))
error_count += 1
continue
missing = self.options.get_missing()
if missing is not None:
if len(missing) == 1:
self.write_error('A value for "{}" is required'.format(missing[0]))
else:
self.write_error('Values for these required options are missing: {}'.format(', '.join(missing)))
error_count += 1
if error_count > 0:
exit(1)
debug(' command: %s', six.text_type(self))
debug('Preparing for execution')
self.prepare()
if self.record:
ifile, ofile = self._prepare_recording(argv, ifile, ofile)
self._record_writer.ofile = ofile
# Record the metadata that initiated this command after removing the record option from args/raw_args
info = self._metadata.searchinfo
for attr in 'args', 'raw_args':
setattr(info, attr, [arg for arg in getattr(info, attr) if not arg.startswith('record=')])
metadata = MetadataEncoder().encode(self._metadata)
ifile.record('chunked 1.0,', six.text_type(len(metadata)), ',0\n', metadata)
if self.show_configuration:
self.write_info(self.name + ' command configuration: ' + str(self._configuration))
debug(' command configuration: %s', self._configuration)
except SystemExit:
self._record_writer.write_metadata(self._configuration)
self.finish()
raise
except:
self._record_writer.write_metadata(self._configuration)
self._report_unexpected_error()
self.finish()
raise
self._record_writer.write_metadata(self._configuration)
# Execute search command on data passing through the pipeline
# noinspection PyBroadException
try:
debug('Executing under protocol_version=2')
self._metadata.action = 'execute'
self._execute(ifile, None)
except SystemExit:
self.finish()
raise
except:
self._report_unexpected_error()
self.finish()
raise
debug('%s.process completed', class_name)
def write_debug(self, message, *args):
self._record_writer.write_message('DEBUG', message, *args)
def write_error(self, message, *args):
self._record_writer.write_message('ERROR', message, *args)
def write_fatal(self, message, *args):
self._record_writer.write_message('FATAL', message, *args)
def write_info(self, message, *args):
self._record_writer.write_message('INFO', message, *args)
def write_warning(self, message, *args):
self._record_writer.write_message('WARN', message, *args)
def write_metric(self, name, value):
""" Writes a metric that will be added to the search inspector.
:param name: Name of the metric.
:type name: basestring
:param value: A 4-tuple containing the value of metric ``name`` where
value[0] = Elapsed seconds or :const:`None`.
value[1] = Number of invocations or :const:`None`.
value[2] = Input count or :const:`None`.
value[3] = Output count or :const:`None`.
The :data:`SearchMetric` type provides a convenient encapsulation of ``value``.
The :data:`SearchMetric` type provides a convenient encapsulation of ``value``.
:return: :const:`None`.
"""
self._record_writer.write_metric(name, value)
# P2 [ ] TODO: Support custom inspector values
@staticmethod
def _decode_list(mv):
return [match.replace('$$', '$') for match in SearchCommand._encoded_value.findall(mv)]
_encoded_value = re.compile(r'\$(?P<item>(?:\$\$|[^$])*)\$(?:;|$)') # matches a single value in an encoded list
# Note: Subclasses must override this method so that it can be called
# called as self._execute(ifile, None)
def _execute(self, ifile, process):
""" Default processing loop
:param ifile: Input file object.
:type ifile: file
:param process: Bound method to call in processing loop.
:type process: instancemethod
:return: :const:`None`.
:rtype: NoneType
"""
if self.protocol_version == 1:
self._record_writer.write_records(process(self._records(ifile)))
self.finish()
else:
assert self._protocol_version == 2
self._execute_v2(ifile, process)
@staticmethod
def _read_chunk(ifile):
# noinspection PyBroadException
try:
header = ifile.readline()
except Exception as error:
raise RuntimeError('Failed to read transport header: {}'.format(error))
if not header:
return None
match = SearchCommand._header.match(header)
if match is None:
raise RuntimeError('Failed to parse transport header: {}'.format(header))
metadata_length, body_length = match.groups()
metadata_length = int(metadata_length)
body_length = int(body_length)
try:
metadata = ifile.read(metadata_length)
except Exception as error:
raise RuntimeError('Failed to read metadata of length {}: {}'.format(metadata_length, error))
decoder = MetadataDecoder()
try:
metadata = decoder.decode(metadata)
except Exception as error:
raise RuntimeError('Failed to parse metadata of length {}: {}'.format(metadata_length, error))
# if body_length <= 0:
# return metadata, ''
body = ""
try:
if body_length > 0:
body = ifile.read(body_length)
except Exception as error:
raise RuntimeError('Failed to read body of length {}: {}'.format(body_length, error))
return metadata, body
_header = re.compile(r'chunked\s+1.0\s*,\s*(\d+)\s*,\s*(\d+)\s*\n')
def _records_protocol_v1(self, ifile):
return self._read_csv_records(ifile)
def _read_csv_records(self, ifile):
reader = csv.reader(ifile, dialect=CsvDialect)
try:
fieldnames = next(reader)
except StopIteration:
return
mv_fieldnames = dict([(name, name[len('__mv_'):]) for name in fieldnames if name.startswith('__mv_')])
if len(mv_fieldnames) == 0:
for values in reader:
yield OrderedDict(izip(fieldnames, values))
return
for values in reader:
record = OrderedDict()
for fieldname, value in izip(fieldnames, values):
if fieldname.startswith('__mv_'):
if len(value) > 0:
record[mv_fieldnames[fieldname]] = self._decode_list(value)
elif fieldname not in record:
record[fieldname] = value
yield record
def _execute_v2(self, ifile, process):
while True:
result = self._read_chunk(ifile)
if not result:
return
metadata, body = result
action = getattr(metadata, 'action', None)
if action != 'execute':
raise RuntimeError('Expected execute action, not {}'.format(action))
self._finished = getattr(metadata, 'finished', False)
self._record_writer.is_flushed = False
self._execute_chunk_v2(process, result)
self._record_writer.write_chunk(finished=self._finished)
def _execute_chunk_v2(self, process, chunk):
metadata, body = chunk
if len(body) <= 0:
return
records = self._read_csv_records(StringIO(body))
self._record_writer.write_records(process(records))
def _report_unexpected_error(self):
error_type, error, tb = sys.exc_info()
origin = tb
while origin.tb_next is not None:
origin = origin.tb_next
filename = origin.tb_frame.f_code.co_filename
lineno = origin.tb_lineno
message = '{0} at "{1}", line {2:d} : {3}'.format(error_type.__name__, filename, lineno, error)
environment.splunklib_logger.error(message + '\nTraceback:\n' + ''.join(traceback.format_tb(tb)))
self.write_error(message)
# endregion
# region Types
class ConfigurationSettings(object):
""" Represents the configuration settings common to all :class:`SearchCommand` classes.
"""
def __init__(self, command):
self.command = command
def __repr__(self):
""" Converts the value of this instance to its string representation.
The value of this ConfigurationSettings instance is represented as a string of comma-separated
:code:`(name, value)` pairs.
:return: String representation of this instance
"""
definitions = type(self).configuration_setting_definitions
settings = imap(
lambda setting: repr((setting.name, setting.__get__(self), setting.supporting_protocols)), definitions)
return '[' + ', '.join(settings) + ']'