-
Notifications
You must be signed in to change notification settings - Fork 117
/
import_logs.py
executable file
·2828 lines (2392 loc) · 109 KB
/
import_logs.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
#!/usr/bin/python
# vim: et sw=4 ts=4:
# -*- coding: utf-8 -*-
#
# Matomo - free/libre analytics platform
#
# @link https://matomo.org
# @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
# @version $Id$
#
# For more info see: https://matomo.org/log-analytics/ and https://matomo.org/docs/log-analytics-tool-how-to/
#
# Requires Python 3.5, 3.6 or 3.7
#
from __future__ import print_function # this is needed that python2 can run the script until the warning below
import sys
if sys.version_info[0] != 3:
print('The log importer currently does not support Python 2 any more.')
print('Please use Python 3.5, 3.6, 3.7 or 3.8')
sys.exit(1)
import base64
import bz2
import configparser
import codecs
import datetime
import fnmatch
import gzip
import hashlib
import http.client
import inspect
import itertools
import json
import logging
import argparse
import os
import os.path
import queue
import re
import ssl
import sys
import threading
import time
import urllib.request, urllib.parse, urllib.error
import urllib.request, urllib.error, urllib.parse
import urllib.parse
import subprocess
import traceback
import socket
import textwrap
import collections
import glob
import io
# Avoid "got more than 100 headers" error
http.client._MAXHEADERS = 1000
##
## Constants.
##
STATIC_EXTENSIONS = set((
'gif jpg jpeg png bmp ico svg svgz ttf otf eot woff woff2 class swf css js xml webp avif'
).split())
STATIC_FILES = set((
'robots.txt'
).split())
DOWNLOAD_EXTENSIONS = set((
'7z aac arc arj asf asx avi bin csv deb dmg doc docx exe flac flv gz gzip hqx '
'ibooks jar json mpg mp2 mp3 mp4 mpeg mov movie msi msp odb odf odg odp '
'ods odt ogg ogv pdf phps ppt pptx qt qtm ra ram rar rpm rtf sea sit tar tbz '
'bz2 tbz tgz torrent txt wav webm wma wmv wpd xls xlsx xml xsd z zip '
'azw3 epub mobi apk '
'md5 sig'
).split())
# If you want to add more bots, take a look at the Matomo Device Detector botlist:
# https://github.com/matomo-org/device-detector/blob/master/regexes/bots.yml
# user agents must be lowercase
EXCLUDED_USER_AGENTS = (
'adsbot-google',
'ask jeeves',
'baidubot',
'bot-',
'bot/',
'ccooter/',
'crawl',
'curl',
'echoping',
'exabot',
'feed',
'googlebot',
'ia_archiver',
'java/',
'libwww',
'mediapartners-google',
'msnbot',
'netcraftsurvey',
'panopta',
'pingdom.com_bot_',
'robot',
'spider',
'surveybot',
'twiceler',
'voilabot',
'yahoo',
'yandex',
'zabbix',
'googlestackdrivermonitoring',
)
MATOMO_DEFAULT_MAX_ATTEMPTS = 3
MATOMO_DEFAULT_DELAY_AFTER_FAILURE = 10
DEFAULT_SOCKET_TIMEOUT = 300
MATOMO_EXPECTED_IMAGE = base64.b64decode(
'R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='
)
##
## Formats.
##
class BaseFormatException(Exception): pass
class BaseFormat:
def __init__(self, name):
self.name = name
self.regex = None
self.date_format = '%d/%b/%Y:%H:%M:%S'
def check_format(self, file):
line = file.readline()
try:
file.seek(0)
except IOError:
pass
return self.check_format_line(line)
def check_format_line(self, line):
return False
class NginxJsonFormat(BaseFormat):
def __init__(self, name):
super(NginxJsonFormat, self).__init__(name)
self.json = None
self.date_format = '%Y-%m-%dT%H:%M:%S'
def check_format_line(self, line):
try:
self.json = json.loads(line)
# Check if it contains these: "referrer" and date".
# Those are currently not used in other detected json formats, so it should be enough
if "referrer" in self.json and "date" in self.json:
return True
return False
except:
return False
def match(self, line):
try:
# nginx outputs malformed JSON w/ hex escapes when confronted w/ non-UTF input. we have to
# workaround this by converting hex escapes in strings to unicode escapes. the conversion is naive,
# so it does not take into account the string's actual encoding (which we don't have access to).
line = line.replace('\\x', '\\u00')
self.json = json.loads(line)
return self
except:
self.json = None
return None
def get(self, key):
# Some ugly patchs ...
if key == 'generation_time_milli':
self.json[key] = int(float(self.json[key]) * 1000)
# Patch date format ISO 8601
elif key == 'date':
tz = self.json[key][19:]
self.json['timezone'] = tz.replace(':', '')
self.json[key] = self.json[key][:19]
try:
return self.json[key]
except KeyError:
raise BaseFormatException()
def get_all(self,):
return self.json
def remove_ignored_groups(self, groups):
for group in groups:
del self.json[group]
class TraefikJsonFormat(BaseFormat):
TRAEFIK_KEYS_MAPPING = {
'date': 'time',
'generation_time_milli': 'Duration',
'host': 'RequestHost',
'ip': 'ClientHost',
'length': 'DownstreamContentSize',
'method': 'RequestMethod',
'path': 'RequestPath',
'referrer': 'request_Referer',
'status': 'DownstreamStatus',
'userid': 'ClientUsername',
'user_agent': 'request_User-Agent',
}
def __init__(self, name):
super(TraefikJsonFormat, self).__init__(name)
self.json = None
self.date_format = '%Y-%m-%dT%H:%M:%S'
def check_format_line(self, line):
try:
self.json = json.loads(line)
# Check if it contains all of these: "level", "msg", and "time".
# This is unique to Traefik, we can use this to tell it apart from other json log formats.
if "msg" in self.json and "level" in self.json and "time" in self.json:
return True
return False
except:
return False
def match(self, line):
try:
self.json = json.loads(line)
return self
except:
self.json = None
return None
def get(self, key):
value = ''
try:
value = self.json[self.TRAEFIK_KEYS_MAPPING[key]]
if key == 'generation_time_milli':
value = value / 1000000
# Patch date format ISO 8601, example: 2023-08-14T12:25:56+02:00
if key == 'date':
tz = value[19:] # get the last part
self.json['timezone'] = tz.replace(':', '')
value = value[:19]
except:
logging.debug("Could not find %s in Traefik log", key)
return ''
return str(value)
def get_all(self,):
modified_json = self.json.copy()
REVERSED_KEYS_MAPPING = {v: k for k, v in self.TRAEFIK_KEYS_MAPPING.items()}
for key in self.json:
new_key = REVERSED_KEYS_MAPPING.get(key, key)
if new_key != key:
modified_json[new_key] = modified_json.pop(key)
return modified_json
def remove_ignored_groups(self, groups):
for group in groups:
del self.json[group]
class CaddyJsonFormat(BaseFormat):
def __init__(self, name):
super(CaddyJsonFormat, self).__init__(name)
self.json = None
self.date_format = '%Y-%m-%dT%H:%M:%S.%f'
def check_format_line(self, line):
try:
self.json = json.loads(line)
return "request" in self.json and "user_id" in self.json and "resp_headers" in self.json
except:
return False
def match(self, line):
try:
self.json = json.loads(line)
return self
except:
self.json = None
return None
def get(self, key):
try:
return self.get_all().get(key)
except KeyError:
raise BaseFormatException()
def get_all(self,):
tz = datetime.timezone.utc
date = datetime.datetime.fromtimestamp(self.json['ts'], tz=tz)
self.json['date'] = date.strftime(self.date_format)
self.json['timezone'] = date.strftime('%z')
self.json['length'] = str(self.json['size'])
self.json['status'] = str(self.json['status'])
self.json['generation_time_milli'] = str(self.json['duration'] * 1000.)
self.json['userid'] = self.json['user_id']
self.json['ip'] = self.json['request']['client_ip']
self.json['host'] = self.json['request']['host']
self.json['method'] = self.json['request']['method']
self.json['path'] = self.json['request']['uri']
self.json['referrer'] = next(iter(self.json['request']['headers'].get('Referer', [])), None)
self.json['user_agent'] = next(iter(self.json['request']['headers'].get('User-Agent', [])), None)
return self.json
def remove_ignored_groups(self, groups):
for group in groups:
del self.json[group]
class RegexFormat(BaseFormat):
def __init__(self, name, regex, date_format=None):
super(RegexFormat, self).__init__(name)
if regex is not None:
self.regex = re.compile(regex)
if date_format is not None:
self.date_format = date_format
self.matched = None
def check_format_line(self, line):
return self.match(line)
def match(self,line):
if not self.regex:
return None
match_result = self.regex.match(line)
if match_result:
self.matched = match_result.groupdict()
if 'time' in self.matched:
self.matched['date'] = self.matched['date'] + ' ' + self.matched['time']
del self.matched['time']
else:
self.matched = None
return match_result
def get(self, key):
try:
return self.matched[key]
except KeyError:
raise BaseFormatException("Cannot find group '%s'." % key)
def get_all(self,):
return self.matched
def remove_ignored_groups(self, groups):
for group in groups:
del self.matched[group]
class W3cExtendedFormat(RegexFormat):
FIELDS_LINE_PREFIX = '#Fields: '
REGEX_UNKNOWN_FIELD = r'(?:".*?"|\S+)'
fields = {
'date': r'"?(?P<date>\d+[-\d+]+)"?',
'time': r'"?(?P<time>[\d+:]+)[.\d]*?"?',
'cs-uri-stem': r'(?P<path>/\S*)',
'cs-uri-query': r'(?P<query_string>\S*)',
'c-ip': r'"?(?P<ip>[\w*.:-]*)"?',
'cs(User-Agent)': r'(?P<user_agent>".*?"|\S*)',
'cs(Referer)': r'(?P<referrer>\S+)',
'sc-status': r'(?P<status>\d+)',
'sc-bytes': r'(?P<length>\S+)',
'cs-host': r'(?P<host>\S+)',
'cs-method': r'(?P<method>\S+)',
'cs-username': r'(?P<userid>\S+)',
'time-taken': r'(?P<generation_time_secs>[.\d]+)'
}
def __init__(self):
super(W3cExtendedFormat, self).__init__('w3c_extended', None, '%Y-%m-%d %H:%M:%S')
def check_format(self, file):
try:
file.seek(0)
except IOError:
pass
self.create_regex(file)
# if we couldn't create a regex, this file does not follow the W3C extended log file format
if not self.regex:
try:
file.seek(0)
except IOError:
pass
return
first_line = file.readline()
try:
file.seek(0)
except IOError:
pass
return self.check_format_line(first_line)
def create_regex(self, file):
fields_line = None
if config.options.w3c_fields:
fields_line = config.options.w3c_fields
# collect all header lines up until the Fields: line
# if we're reading from stdin, we can't seek, so don't read any more than the Fields line
header_lines = []
while fields_line is None:
line = file.readline().strip()
if not line:
continue
if not line.startswith('#'):
break
if line.startswith(self.FIELDS_LINE_PREFIX):
fields_line = line
else:
header_lines.append(line)
if not fields_line:
return
# store the header lines for a later check for IIS
self.header_lines = header_lines
# Parse the 'Fields: ' line to create the regex to use
full_regex = []
expected_fields = type(self).fields.copy() # turn custom field mapping into field => regex mapping
# if the --w3c-time-taken-millisecs option is used, make sure the time-taken field is interpreted as milliseconds
if config.options.w3c_time_taken_in_millisecs:
expected_fields['time-taken'] = r'(?P<generation_time_milli>[\d.]+)'
for mapped_field_name, field_name in config.options.custom_w3c_fields.items():
expected_fields[mapped_field_name] = expected_fields[field_name]
del expected_fields[field_name]
# add custom field regexes supplied through --w3c-field-regex option
for field_name, field_regex in config.options.w3c_field_regexes.items():
expected_fields[field_name] = field_regex
# Skip the 'Fields: ' prefix.
fields_line = fields_line[9:].strip()
for field in re.split(r'\s+', fields_line):
try:
regex = expected_fields[field]
except KeyError:
regex = self.REGEX_UNKNOWN_FIELD
full_regex.append(regex)
full_regex = r'\s+'.join(full_regex)
logging.debug("Based on 'Fields:' line, computed regex to be %s", full_regex)
self.regex = re.compile(full_regex)
def check_for_iis_option(self):
if not config.options.w3c_time_taken_in_millisecs and self._is_time_taken_milli() and self._is_iis():
logging.info("WARNING: IIS log file being parsed without --w3c-time-taken-milli option. IIS"
" stores millisecond values in the time-taken field. If your logfile does this, the aforementioned"
" option must be used in order to get accurate generation times.")
def _is_iis(self):
return len([line for line in self.header_lines if 'internet information services' in line.lower() or 'iis' in line.lower()]) > 0
def _is_time_taken_milli(self):
return 'generation_time_milli' not in self.regex.pattern
class IisFormat(W3cExtendedFormat):
fields = W3cExtendedFormat.fields.copy()
fields.update({
'time-taken': r'(?P<generation_time_milli>[.\d]+)',
'sc-win32-status': r'(?P<__win32_status>\S+)' # this group is useless for log importing, but capturing it
# will ensure we always select IIS for the format instead of
# W3C logs when detecting the format. This way there will be
# less accidental importing of IIS logs w/o --w3c-time-taken-milli.
})
def __init__(self):
super(IisFormat, self).__init__()
self.name = 'iis'
class IncapsulaW3CFormat(W3cExtendedFormat):
# use custom unknown field regex to make resulting regex much simpler
REGEX_UNKNOWN_FIELD = r'".*?"'
fields = W3cExtendedFormat.fields.copy()
# redefines all fields as they are always encapsulated with "
fields.update({
'cs-uri': r'"(?P<host>[^\/\s]+)(?P<path>\S+)"',
'cs-uri-query': r'"(?P<query_string>\S*)"',
'c-ip': r'"(?P<ip>[\w*.:-]*)"',
'cs(User-Agent)': r'"(?P<user_agent>.*?)"',
'cs(Referer)': r'"(?P<referrer>\S+)"',
'sc-status': r'(?P<status>"\d*")',
'cs-bytes': r'(?P<length>"\d*")',
})
def __init__(self):
super(IncapsulaW3CFormat, self).__init__()
self.name = 'incapsula_w3c'
def get(self, key):
value = super(IncapsulaW3CFormat, self).get(key)
if key == 'status' or key == 'length':
value = value.strip('"')
if key == 'status' and value == '':
value = '200'
return value
class ShoutcastFormat(W3cExtendedFormat):
fields = W3cExtendedFormat.fields.copy()
fields.update({
'c-status': r'(?P<status>\d+)',
'x-duration': r'(?P<generation_time_secs>[.\d]+)'
})
def __init__(self):
super(ShoutcastFormat, self).__init__()
self.name = 'shoutcast'
def get(self, key):
if key == 'user_agent':
user_agent = super(ShoutcastFormat, self).get(key)
return urllib.parse.unquote(user_agent)
else:
return super(ShoutcastFormat, self).get(key)
class AmazonCloudFrontFormat(W3cExtendedFormat):
fields = W3cExtendedFormat.fields.copy()
fields.update({
'x-event': r'(?P<event_action>\S+)',
'x-sname': r'(?P<event_name>\S+)',
'cs-uri-stem': r'(?:rtmp:/)?(?P<path>/\S*)',
'c-user-agent': r'(?P<user_agent>".*?"|\S+)',
# following are present to match cloudfront instead of W3C when we know it's cloudfront
'x-edge-location': r'(?P<x_edge_location>".*?"|\S+)',
'x-edge-result-type': r'(?P<x_edge_result_type>".*?"|\S+)',
'x-edge-request-id': r'(?P<x_edge_request_id>".*?"|\S+)',
'x-host-header': r'(?P<host>".*?"|\S+)'
})
def __init__(self):
super(AmazonCloudFrontFormat, self).__init__()
self.name = 'amazon_cloudfront'
def get(self, key):
if key == 'event_category' and 'event_category' not in self.matched:
return 'cloudfront_rtmp'
elif key == 'status' and 'status' not in self.matched:
return '200'
elif key == 'user_agent':
user_agent = super(AmazonCloudFrontFormat, self).get(key)
return urllib.parse.unquote(urllib.parse.unquote(user_agent)) # Value is double quoted!
else:
return super(AmazonCloudFrontFormat, self).get(key)
_HOST_PREFIX = r'(?P<host>[\w\-\.]*)(?::\d+)?\s+'
_COMMON_LOG_FORMAT = (
r'(?P<ip>[\w*.:-]+)\s+\S+\s+(?P<userid>\S+)\s+\[(?P<date>.*?)\s+(?P<timezone>.*?)\]\s+'
r'"(?P<method>\S+)\s+(?P<path>.*?)\s+\S+"\s+(?P<status>\d+)\s+(?P<length>\S+)'
)
_NCSA_EXTENDED_LOG_FORMAT = (_COMMON_LOG_FORMAT +
r'\s+"(?P<referrer>.*?)"\s+"(?P<user_agent>.*?)"'
)
_S3_LOG_FORMAT = (
r'\S+\s+(?P<host>\S+)\s+\[(?P<date>.*?)\s+(?P<timezone>.*?)\]\s+(?P<ip>[\w*.:-]+)\s+'
r'(?P<userid>\S+)\s+\S+\s+\S+\s+\S+\s+"(?P<method>\S+)\s+(?P<path>.*?)\s+\S+"\s+(?P<status>\d+)\s+\S+\s+(?P<length>\S+)\s+'
r'\S+\s+\S+\s+\S+\s+"(?P<referrer>.*?)"\s+"(?P<user_agent>.*?)"'
)
_ICECAST2_LOG_FORMAT = ( _NCSA_EXTENDED_LOG_FORMAT +
r'\s+(?P<session_time>[0-9-]+)'
)
_ELB_LOG_FORMAT = (
r'(?:\S+\s+)?(?P<date>[0-9-]+T[0-9:]+)\.\S+\s+\S+\s+(?P<ip>[\w*.:-]+):\d+\s+\S+:\d+\s+\S+\s+(?P<generation_time_secs>\S+)\s+\S+\s+'
r'(?P<status>\d+)\s+\S+\s+\S+\s+(?P<length>\S+)\s+'
r'"\S+\s+\w+:\/\/(?P<host>[\w\-\.]*):\d+(?P<path>\/\S*)\s+[^"]+"\s+"(?P<user_agent>[^"]+)"\s+\S+\s+\S+'
)
_OVH_FORMAT = (
r'(?P<ip>\S+)\s+' + _HOST_PREFIX + r'(?P<userid>\S+)\s+\[(?P<date>.*?)\s+(?P<timezone>.*?)\]\s+'
r'"\S+\s+(?P<path>.*?)\s+\S+"\s+(?P<status>\S+)\s+(?P<length>\S+)'
r'\s+"(?P<referrer>.*?)"\s+"(?P<user_agent>.*?)"'
)
_HAPROXY_FORMAT = (
r'.*:\ (?P<ip>[\w*.]+).*\[(?P<date>.*)\].*\ (?P<status>\b\d{3}\b)\ (?P<length>\d+)\ -.*\"(?P<method>\S+)\ (?P<path>\S+).*'
)
_GANDI_SIMPLE_HOSTING_FORMAT = (
r'(?P<host>[0-9a-zA-Z-_.]+)\s+(?P<ip>[a-zA-Z0-9.]+)\s+\S+\s+(?P<userid>\S+)\s+\[(?P<date>.+?)\s+(?P<timezone>.+?)\]\s+\((?P<generation_time_secs>[0-9a-zA-Z\s]*)\)\s+"(?P<method>[A-Z]+)\s+(?P<path>\S+)\s+(\S+)"\s+(?P<status>[0-9]+)\s+(?P<length>\S+)\s+"(?P<referrer>\S+)"\s+"(?P<user_agent>[^"]+)"'
)
FORMATS = {
'common': RegexFormat('common', _COMMON_LOG_FORMAT),
'common_vhost': RegexFormat('common_vhost', _HOST_PREFIX + _COMMON_LOG_FORMAT),
'ncsa_extended': RegexFormat('ncsa_extended', _NCSA_EXTENDED_LOG_FORMAT),
'common_complete': RegexFormat('common_complete', _HOST_PREFIX + _NCSA_EXTENDED_LOG_FORMAT),
'w3c_extended': W3cExtendedFormat(),
'amazon_cloudfront': AmazonCloudFrontFormat(),
'incapsula_w3c': IncapsulaW3CFormat(),
'iis': IisFormat(),
'shoutcast': ShoutcastFormat(),
's3': RegexFormat('s3', _S3_LOG_FORMAT),
'icecast2': RegexFormat('icecast2', _ICECAST2_LOG_FORMAT),
'elb': RegexFormat('elb', _ELB_LOG_FORMAT, '%Y-%m-%dT%H:%M:%S'),
'traefik_json': TraefikJsonFormat('traefik_json'),
'nginx_json': NginxJsonFormat('nginx_json'),
'caddy_json': CaddyJsonFormat('caddy_json'),
'ovh': RegexFormat('ovh', _OVH_FORMAT),
'haproxy': RegexFormat('haproxy', _HAPROXY_FORMAT, '%d/%b/%Y:%H:%M:%S.%f'),
'gandi': RegexFormat('gandi', _GANDI_SIMPLE_HOSTING_FORMAT, '%d/%b/%Y:%H:%M:%S')
}
##
## Code.
##
class StoreDictKeyPair(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
my_dict = getattr(namespace, self.dest, None)
if not my_dict:
my_dict = {}
for kv in values.split(","):
k,v = kv.split("=")
my_dict[k] = v
setattr(namespace, self.dest, my_dict)
class Configuration:
"""
Stores all the configuration options by reading sys.argv and parsing,
if needed, the config.inc.php.
It has 2 attributes: options and filenames.
"""
class Error(Exception):
pass
def _create_parser(self):
"""
Initialize and return the OptionParser instance.
"""
parser = argparse.ArgumentParser(
# usage='Usage: %prog [options] log_file [ log_file [...] ]',
description="Import HTTP access logs to Matomo. "
"log_file is the path to a server access log file (uncompressed, .gz, .bz2, or specify - to read from stdin). "
" You may also import many log files at once (for example set log_file to *.log or *.log.gz)."
" By default, the script will try to produce clean reports and will exclude bots, static files, discard http error and redirects, etc. This is customizable, see below.",
epilog="About Matomo Server Log Analytics: https://matomo.org/log-analytics/ "
" Found a bug? Please create a ticket in https://github.com/matomo-org/matomo-log-analytics/ "
" Please send your suggestions or successful user story to [email protected] "
)
parser.add_argument('file', type=str, nargs='+')
# Basic auth user
parser.add_argument(
'--auth-user', dest='auth_user',
help="Basic auth user",
)
# Basic auth password
parser.add_argument(
'--auth-password', dest='auth_password',
help="Basic auth password",
)
parser.add_argument(
'--debug', '-d', dest='debug', action='count', default=0,
help="Enable debug output (specify multiple times for more verbose)",
)
parser.add_argument(
'--debug-tracker', dest='debug_tracker', action='store_true', default=False,
help="Appends &debug=1 to tracker requests and prints out the result so the tracker can be debugged. If "
"using the log importer results in errors with the tracker or improperly recorded visits, this option can "
"be used to find out what the tracker is doing wrong. To see debug tracker output, you must also set the "
"[Tracker] debug_on_demand INI config to 1 in your Matomo's config.ini.php file."
)
parser.add_argument(
'--debug-request-limit', dest='debug_request_limit', type=int, default=None,
help="Debug option that will exit after N requests are parsed. Can be used w/ --debug-tracker to limit the "
"output of a large log file."
)
parser.add_argument(
'--url', dest='matomo_url', required=True,
help="REQUIRED Your Matomo server URL, eg. https://example.com/matomo/ or https://analytics.example.net",
)
parser.add_argument(
'--api-url', dest='matomo_api_url',
help="This URL will be used to send API requests (use it if your tracker URL differs from UI/API url), "
"eg. https://other-example.com/matomo/ or https://analytics-api.example.net",
)
parser.add_argument(
'--tracker-endpoint-path', dest='matomo_tracker_endpoint_path', default='/piwik.php',
help="The tracker endpoint path to use when tracking. Defaults to /piwik.php."
)
parser.add_argument(
'--dry-run', dest='dry_run',
action='store_true', default=False,
help="Perform a trial run with no tracking data being inserted into Matomo",
)
parser.add_argument(
'--show-progress', dest='show_progress',
action='store_true', default=hasattr(sys.stdout, 'fileno') and os.isatty(sys.stdout.fileno()),
help="Print a progress report X seconds (default: 1, use --show-progress-delay to override)"
)
parser.add_argument(
'--show-progress-delay', dest='show_progress_delay',
type=int, default=1,
help="Change the default progress delay"
)
parser.add_argument(
'--add-sites-new-hosts', dest='add_sites_new_hosts',
action='store_true', default=False,
help="When a hostname is found in the log file, but not matched to any website "
"in Matomo, automatically create a new website in Matomo with this hostname to "
"import the logs"
)
parser.add_argument(
'--idsite', dest='site_id',
help= ("When specified, "
"data in the specified log files will be tracked for this Matomo site ID."
" The script will not auto-detect the website based on the log line hostname (new websites will not be automatically created).")
)
parser.add_argument(
'--idsite-fallback', dest='site_id_fallback',
help="Default Matomo site ID to use if the hostname doesn't match any "
"known Website's URL. New websites will not be automatically created. "
" Used only if --add-sites-new-hosts or --idsite are not set",
)
default_config = os.path.abspath(
os.path.join(os.path.dirname(__file__),
'../../config/config.ini.php'),
)
parser.add_argument(
'--config', dest='config_file', default=default_config,
help=(
"This is only used when --login and --password is not used. "
"Matomo will read the configuration file (default: %(default)s) to "
"fetch the Super User token_auth from the config file. "
)
)
parser.add_argument(
'--login', dest='login',
help="You can manually specify the Matomo Super User login"
)
parser.add_argument(
'--password', dest='password',
help="You can manually specify the Matomo Super User password"
)
parser.add_argument(
'--token-auth', dest='matomo_token_auth',
help="Matomo user token_auth, the token_auth is found in Matomo > Settings > API. "
"You must use a token_auth that has at least 'admin' or 'super user' permission. "
"If you use a token_auth for a non admin user, your users' IP addresses will not be tracked properly. "
)
parser.add_argument(
'--hostname', dest='hostnames', action='append', default=[],
help="Accepted hostname (requests with other hostnames will be excluded). "
" You may use the star character * "
" Example: --hostname=*domain.com"
" Can be specified multiple times"
)
parser.add_argument(
'--exclude-path', dest='excluded_paths', action='append', default=[],
help="Any URL path matching this exclude-path will not be imported in Matomo. "
" You must use the star character *. "
" Example: --exclude-path=*/admin/*"
" Can be specified multiple times. "
)
parser.add_argument(
'--exclude-path-from', dest='exclude_path_from',
help="Each line from this file is a path to exclude. Each path must contain the character * to match a string. (see: --exclude-path)"
)
parser.add_argument(
'--include-path', dest='included_paths', action='append', default=[],
help="Paths to include. Can be specified multiple times. If not specified, all paths are included."
)
parser.add_argument(
'--include-path-from', dest='include_path_from',
help="Each line from this file is a path to include"
)
parser.add_argument(
'--useragent-exclude', dest='excluded_useragents',
action='append', default=[],
help="User agents to exclude (in addition to the standard excluded "
"user agents). Can be specified multiple times",
)
parser.add_argument(
'--enable-static', dest='enable_static',
action='store_true', default=False,
help="Track static files (images, css, js, ico, ttf, etc.)"
)
parser.add_argument(
'--enable-bots', dest='enable_bots',
action='store_true', default=False,
help="Track bots. All bot visits will have a Custom Variable set with name='Bot' and value='$Bot_user_agent_here$'"
)
parser.add_argument(
'--enable-http-errors', dest='enable_http_errors',
action='store_true', default=False,
help="Track HTTP errors (status code 4xx or 5xx)"
)
parser.add_argument(
'--enable-http-redirects', dest='enable_http_redirects',
action='store_true', default=False,
help="Track HTTP redirects (status code 3xx except 304)"
)
parser.add_argument(
'--enable-reverse-dns', dest='reverse_dns',
action='store_true', default=False,
help="Enable reverse DNS, used to generate the 'Providers' report in Matomo. "
"Disabled by default, as it impacts performance"
)
parser.add_argument(
'--strip-query-string', dest='strip_query_string',
action='store_true', default=False,
help="Strip the query string from the URL"
)
parser.add_argument(
'--query-string-delimiter', dest='query_string_delimiter', default='?',
help="The query string delimiter (default: %(default)s)"
)
parser.add_argument(
'--log-format-name', dest='log_format_name', default=None,
help=("Access log format to detect (supported are: %s). "
"When not specified, the log format will be autodetected by trying all supported log formats."
% ', '.join(sorted(FORMATS.keys())))
)
available_regex_groups = ['date', 'path', 'query_string', 'ip', 'user_agent', 'referrer', 'status',
'length', 'host', 'userid', 'generation_time_milli', 'event_action',
'event_name', 'timezone', 'session_time']
parser.add_argument(
'--log-format-regex', dest='log_format_regex', default=None,
help="Regular expression used to parse log entries. Regexes must contain named groups for different log fields. "
"Recognized fields include: %s. For an example of a supported Regex, see the source code of this file. "
"Overrides --log-format-name." % (', '.join(available_regex_groups))
)
parser.add_argument(
'--log-date-format', dest='log_date_format', default=None,
help="Format string used to parse dates. You can specify any format that can also be specified to "
"the strptime python function."
)
parser.add_argument(
'--log-hostname', dest='log_hostname', default=None,
help="Force this hostname for a log format that doesn't include it. All hits "
"will seem to come to this host"
)
parser.add_argument(
'--skip', dest='skip', default=0, type=int,
help="Skip the n first lines to start parsing/importing data at a given line for the specified log file",
)
parser.add_argument(
'--recorders', dest='recorders', default=1, type=int,
help="Number of simultaneous recorders (default: %(default)s). "
"It should be set to the number of CPU cores in your server. "
"You can also experiment with higher values which may increase performance until a certain point",
)
parser.add_argument(
'--recorder-max-payload-size', dest='recorder_max_payload_size', default=200, type=int,
help="Maximum number of log entries to record in one tracking request (default: %(default)s). "
)
parser.add_argument(
'--replay-tracking', dest='replay_tracking',
action='store_true', default=False,
help="Replay piwik.php requests found in custom logs (only piwik.php requests expected). \nSee https://matomo.org/faq/how-to/faq_17033/"
)
parser.add_argument(
'--replay-tracking-expected-tracker-file', dest='replay_tracking_expected_tracker_file', default=None,
help="The expected suffix for tracking request paths. Only logs whose paths end with this will be imported. By default "
"requests to the piwik.php file or the matomo.php file will be imported."
)
parser.add_argument(
'--output', dest='output',
help="Redirect output (stdout and stderr) to the specified file"
)
parser.add_argument(
'--encoding', dest='encoding', default='utf8',
help="Log files encoding (default: %(default)s)"
)
parser.add_argument(
'--disable-bulk-tracking', dest='use_bulk_tracking',
default=True, action='store_false',
help="Disables use of bulk tracking so recorders record one hit at a time."
)
parser.add_argument(
'--debug-force-one-hit-every-Ns', dest='force_one_action_interval', default=False, type=float,
help="Debug option that will force each recorder to record one hit every N secs."
)
parser.add_argument(
'--force-lowercase-path', dest='force_lowercase_path', default=False, action='store_true',
help="Make URL path lowercase so paths with the same letters but different cases are "
"treated the same."
)
parser.add_argument(
'--enable-testmode', dest='enable_testmode', default=False, action='store_true',
help="If set, it will try to get the token_auth from the matomo_tests directory"
)
parser.add_argument(
'--download-extensions', dest='download_extensions', default=None,
help="By default Matomo tracks as Downloads the most popular file extensions. If you set this parameter (format: pdf,doc,...) then files with an extension found in the list will be imported as Downloads, other file extensions downloads will be skipped."
)
parser.add_argument(
'--add-download-extensions', dest='extra_download_extensions', default=None,
help="Add extensions that should be treated as downloads. See --download-extensions for more info."
)
parser.add_argument(
'--w3c-map-field', action=StoreDictKeyPair, metavar='KEY=VAL', default={}, dest="custom_w3c_fields",
help="Map a custom log entry field in your W3C log to a default one. Use this option to load custom log "
"files that use the W3C extended log format such as those from the Advanced Logging W3C module. Used "
"as, eg, --w3c-map-field my-date=date. Recognized default fields include: %s\n\n"
"Formats that extend the W3C extended log format (like the cloudfront RTMP log format) may define more "
"fields that can be mapped."
% (', '.join(list(W3cExtendedFormat.fields.keys())))
)
parser.add_argument(
'--w3c-time-taken-millisecs', action='store_true', default=False, dest='w3c_time_taken_in_millisecs',
help="If set, interprets the time-taken W3C log field as a number of milliseconds. This must be set for importing"
" IIS logs."
)
parser.add_argument(
'--w3c-fields', dest='w3c_fields', default=None,
help="Specify the '#Fields:' line for a log file in the W3C Extended log file format. Use this option if "
"your log file doesn't contain the '#Fields:' line which is required for parsing. This option must be used "
"in conjunction with --log-format-name=w3c_extended.\n"
"Example: --w3c-fields='#Fields: date time c-ip ...'"
)
parser.add_argument(
'--w3c-field-regex', action=StoreDictKeyPair, metavar='KEY=VAL', default={}, dest="w3c_field_regexes", type=str,
help="Specify a regex for a field in your W3C extended log file. You can use this option to parse fields the "
"importer does not natively recognize and then use one of the --regex-group-to-XXX-cvar options to track "
"the field in a custom variable. For example, specifying --w3c-field-regex=sc-win32-status=(?P<win32_status>\\S+) "
"--regex-group-to-page-cvar=\"win32_status=Windows Status Code\" will track the sc-win32-status IIS field "
"in the 'Windows Status Code' custom variable. Regexes must contain a named group."
)
parser.add_argument(
'--title-category-delimiter', dest='title_category_delimiter', default='/',
help="If --enable-http-errors is used, errors are shown in the page titles report. If you have "
"changed General.action_title_category_delimiter in your Matomo configuration, you need to set this "
"option to the same value in order to get a pretty page titles report."
)
parser.add_argument(
'--dump-log-regex', dest='dump_log_regex', action='store_true', default=False,
help="Prints out the regex string used to parse log lines and exists. Can be useful for using formats "
"in newer versions of the script in older versions of the script. The output regex can be used with "
"the --log-format-regex option."
)
parser.add_argument(
'--ignore-groups', dest='regex_groups_to_ignore', default=None,
help="Comma separated list of regex groups to ignore when parsing log lines. Can be used to, for example, "
"disable normal user id tracking. See documentation for --log-format-regex for list of available "
"regex groups."
)
parser.add_argument(
'--regex-group-to-visit-cvar', action=StoreDictKeyPair, metavar='KEY=VAL',dest='regex_group_to_visit_cvars_map', default={},
help="Track an attribute through a custom variable with visit scope instead of through Matomo's normal "
"approach. For example, to track usernames as a custom variable instead of through the uid tracking "
"parameter, supply --regex-group-to-visit-cvar=\"userid=User Name\". This will track usernames in a "
"custom variable named 'User Name'. The list of available regex groups can be found in the documentation "
"for --log-format-regex (additional regex groups you may have defined "
"in --log-format-regex can also be used)."
)
parser.add_argument(
'--regex-group-to-page-cvar', action=StoreDictKeyPair, metavar='KEY=VAL', dest='regex_group_to_page_cvars_map', default={},
help="Track an attribute through a custom variable with page scope instead of through Matomo's normal "
"approach. For example, to track usernames as a custom variable instead of through the uid tracking "