├── .gitignore
├── .gitattributes
├── tests
├── logs
│ ├── common.log
│ ├── custom_regex_custom_date.log
│ ├── common_vhost.log
│ ├── icecast2.log
│ ├── ncsa_extended.log
│ ├── ovh.log
│ ├── common_complete.log
│ ├── shoutcast.log
│ ├── s3.log
│ ├── elb.log
│ ├── netscaler.log
│ ├── amazon_cloudfront_web.log
│ ├── iis.log
│ ├── amazon_cloudfront_rtmp.log
│ ├── iis_custom.log
│ ├── nginx_json.log
│ └── logs_to_tests.log
├── run_tests.sh
└── tests.py
├── .travis.yml
├── CONTRIBUTING.md
├── LEGALNOTICE
├── README.md
├── LICENSE.txt
└── import_logs.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text eol=lf
3 |
--------------------------------------------------------------------------------
/tests/logs/common.log:
--------------------------------------------------------------------------------
1 | 1.2.3.4 - theuser [10/Feb/2012:16:42:07 -0500] "GET / HTTP/1.0" 301 368
2 |
--------------------------------------------------------------------------------
/tests/logs/custom_regex_custom_date.log:
--------------------------------------------------------------------------------
1 | 1.2.3.4 - - [February - 10, 2012:16:42:07] "GET / HTTP/1.0" 301 368
2 |
--------------------------------------------------------------------------------
/tests/logs/common_vhost.log:
--------------------------------------------------------------------------------
1 | www.example.com 1.2.3.4 - theuser [10/Feb/2012:16:42:07 -0500] "GET / HTTP/1.0" 301 368
2 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | python:
4 | - "2.6"
5 | - "2.7"
6 | # 3.0 is not supported
7 |
8 | sudo: false
9 |
10 | script:
11 | - cd tests
12 | - ./run_tests.sh
13 |
14 |
--------------------------------------------------------------------------------
/tests/logs/icecast2.log:
--------------------------------------------------------------------------------
1 | 1.2.3.4 - theuser [10/Feb/2012:16:42:07 -0500] "GET / HTTP/1.0" 301 368 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11" 1807
--------------------------------------------------------------------------------
/tests/logs/ncsa_extended.log:
--------------------------------------------------------------------------------
1 | 1.2.3.4 - theuser [10/Feb/2012:16:42:07 -0500] "GET / HTTP/1.0" 301 368 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
2 |
--------------------------------------------------------------------------------
/tests/logs/ovh.log:
--------------------------------------------------------------------------------
1 | 1.2.3.4 www.example.com theuser [10/Feb/2012:16:42:07 -0500] "GET / HTTP/1.1" 301 368 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
2 |
--------------------------------------------------------------------------------
/tests/logs/common_complete.log:
--------------------------------------------------------------------------------
1 | www.example.com 1.2.3.4 - theuser [10/Feb/2012:16:42:07 -0500] "GET / HTTP/1.0" 301 368 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
2 |
--------------------------------------------------------------------------------
/tests/run_tests.sh:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | cd $(dirname $0)
4 |
5 | # Make sure nosetests is installed.
6 | nosetests -V >/dev/null 2>&1 || (echo "nose (http://readthedocs.org/docs/nose/en/latest/) must be installed"; exit 1)
7 |
8 | PYTHONPATH=.. nosetests tests.py $*
9 |
--------------------------------------------------------------------------------
/tests/logs/shoutcast.log:
--------------------------------------------------------------------------------
1 | #Software: SHOUTcast
2 | #Version: 2.4.7.256
3 | #Fields: c-ip c-dns date time cs-uri-stem c-status cs(User-Agent) sc-bytes x-duration avgbandwidth
4 | 1.2.3.4 5.6.7.8 2015-12-07 10:37:05 /stream?title=UKR%20Nights 200 NSPlayer%2F10.0.0.3702%20WMFSDK%2F10.0 65580 1 524640
--------------------------------------------------------------------------------
/tests/logs/s3.log:
--------------------------------------------------------------------------------
1 | b659b576cff1e15e4c0313ff8930fba9f53e6794567f5c60dab3abf2f8dfb6cc www.example.com [10/Feb/2012:16:42:07 -0500] 1.2.3.4 arn:aws:iam::179580289999:user/phillip.boss EB3502676500C6BE WEBSITE.GET.OBJECT index "GET /index HTTP/1.1" 200 - 368 368 10 9 "-" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11"
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # How to contribute
2 |
3 | Great to have you here!
4 |
5 | ## How to submit a bug report or suggest a feature?
6 |
7 | Please read the recommendations on writing a good [bug report](https://developer.piwik.org/guides/core-team-workflow#submitting-a-bug-report) or [feature request](https://developer.piwik.org/guides/core-team-workflow#submitting-a-feature-request).
8 |
9 |
--------------------------------------------------------------------------------
/tests/logs/elb.log:
--------------------------------------------------------------------------------
1 | 2015-05-13T23:39:43.945958Z my-loadbalancer 1.2.3.4:2817 10.0.0.1:80 0.000086 0.001048 0.001337 200 200 0 57 "GET https://www.example.com:443/path/index.html HTTP/1.1" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11" DHE-RSA-AES128-SHA TLSv1.2
2 | # line below should be ignored, as it is a TCP request, not containing any HTTP request data
3 | 2015-05-13T23:39:43.945958Z my-loadbalancer 192.168.131.39:2817 10.0.0.1:80 0.001069 0.000028 0.000041 - - 82 305 "- - - " "-" - -
--------------------------------------------------------------------------------
/tests/logs/netscaler.log:
--------------------------------------------------------------------------------
1 | #Version: 1.0
2 | #Software: Netscaler Web Logging(NSWL)
3 | #Date: 2014-02-18 11:55:13
4 | #Fields: date time c-ip cs-username sc-servicename s-ip s-port cs-method cs-uri-stem cs-uri-query sc-status cs-bytes sc-bytes time-taken cs-version cs(User-Agent) cs(Cookie) cs(Referer)
5 | 2012-08-16 11:55:13 172.20.1.0 - HTTP 192.168.6.254 8080 GET /Citrix/XenApp/Wan/auth/login.jsp - 302 247 355 1 HTTP/1.1 Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.04506.648;+.NET+CLR+3.5.21022) - -
6 |
--------------------------------------------------------------------------------
/tests/logs/amazon_cloudfront_web.log:
--------------------------------------------------------------------------------
1 | #Version: 1.0
2 | #Fields: date time x-edge-location sc-bytes c-ip cs-method cs(Host) cs-uri-stem sc-status cs(Referer) cs(User-Agent) cs-uri-query cs(Cookie) x-edge-result-type x-edge-request-id x-host-header cs-protocol cs-bytes time-taken
3 | 2014-05-23 01:13:11 FRA2 182 192.0.2.10 GET d111111abcdef8.cloudfront.net /view/my/file.html 200 www.displaymyfiles.com Mozilla/4.0%20(compatible;%20MSIE%205.0b1;%20Mac_PowerPC) - zip=98101 RefreshHit MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE== d111111abcdef8.cloudfront.net http - 0.001
4 |
--------------------------------------------------------------------------------
/tests/logs/iis.log:
--------------------------------------------------------------------------------
1 | #Software: Microsoft Internet Information Services 6.0
2 | #Version: 1.0
3 | #Date: 2012-04-01 00:00:13
4 | #Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs-version cs(User-Agent) cs(Cookie) cs(Referer) cs-host sc-status sc-substatus sc-win32-status sc-bytes cs-bytes time-taken
5 | 2012-04-01 00:00:13 W3SVC834221556 PXQD1 5.6.7.8 GET /foo/bar topCat1=divinity&submit=Search 80 theuser 1.2.3.4 HTTP/1.1 Mozilla/5.0+(X11;+U;+Linux+i686;+en-US;+rv:1.9.2.7)+Gecko/20100722+Firefox/3.6.7 "ASP.NET_SessionId=sldfkjs; __utma=21468.206199.142713.144683.183.1; utmccn=(direct)|utmcsr=(direct)|utmcmd=(none)" - example.com 200 654 456 27028 214 1687
6 |
--------------------------------------------------------------------------------
/LEGALNOTICE:
--------------------------------------------------------------------------------
1 | COPYRIGHT
2 |
3 | Matomo - free/libre analytics platform
4 |
5 | The software package is:
6 |
7 | Copyright (C) 2014 Matthieu Aubry
8 |
9 | Individual contributions, components, and libraries are copyright
10 | of their respective authors.
11 |
12 |
13 | SOFTWARE LICENSE
14 |
15 | The free software license of Matomo is GNU General Public License v3
16 | or later. A copy of GNU GPL v3 should have been included in this
17 | software package in LICENCE.txt.
18 |
19 |
20 | TRADEMARK
21 |
22 | Matomo (TM) is an internationally registered trademark.
23 |
24 | The software license does not grant any rights under trademark
25 | law for use of the trademark. Refer to https://matomo.org/trademark/
26 | for up-to-date trademark licensing information.
27 |
--------------------------------------------------------------------------------
/tests/logs/amazon_cloudfront_rtmp.log:
--------------------------------------------------------------------------------
1 | #Version: 1.0
2 | #Fields: date time x-edge-location c-ip x-event sc-bytes x-cf-status x-cf-client-id cs-uri-stem cs-uri-query c-referrer x-page-url c-user-agent x-sname x-sname-query x-file-ext x-sid
3 | 2010-03-12 23:51:20 SEA4 192.0.2.147 connect 2014 OK bfd8a98bee0840d9b871b7f6ade9908f rtmp://shqshne4jdp4b6.cloudfront.net/cfx/st key=value http://player.longtailvideo.com/player.swf http://www.longtailvideo.com/support/jw-player-setup-wizard?example=204 LNX%2010,0,32,18 - - - -
4 | 2010-03-12 23:51:21 SEA4 192.0.2.222 play 3914 OK bfd8a98bee0840d9b871b7f6ade9908f rtmp://shqshne4jdp4b6.cloudfront.net/cfx/st key=value http://player.longtailvideo.com/player.swf http://www.longtailvideo.com/support/jw-player-setup-wizard?example=204 LNX%2010,0,32,18 myvideo p=2&q=4 flv 1
5 |
--------------------------------------------------------------------------------
/tests/logs/iis_custom.log:
--------------------------------------------------------------------------------
1 | #Software: IIS Advanced Logging Module
2 |
3 | #Version: 1.0
4 |
5 | #Start-Date: 2014-11-18 00:00:00.128
6 |
7 | #Fields: date-local time-local s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) cs(Host) sc-status sc-substatus sc-win32-status TimeTakenMS
8 | 2012-08-15 17:00:00.363 1.2.3.4 GET /Products/theProduct - 80 - "70.95.0.0" "Mozilla/5.0 (Linux; Android 4.4.4; SM-G900V Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.59 Mobile Safari/537.36" "http://example.com/Search/SearchResults.pg?informationRecipient.languageCode.c=en" "xzy.example.com" 200 0 0 109
9 | 2012-08-15 17:00:00.660 10.10.28.140 GET /Topic/hw43061 - 80 - - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36" - "example.hello.com" 301 0 0 0
10 | 2012-08-15 17:00:00.675 10.10.28.140 GET /hello/world/6,681965 - 80 - "173.5.0.0" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36" - "hello.example.com" 404 " garbage w/ spaces " 0 359
11 |
--------------------------------------------------------------------------------
/tests/logs/nginx_json.log:
--------------------------------------------------------------------------------
1 | {"idsite":1,"ip": "1.2.3.4","host": "www.piwik.org","path": "/piwik.php?action_name=Clearcode%20-%20Web%20and%20Mobile%20Development%20%7C%20Technology%20With%20Passion&idsite=1&rec=1&r=983420&h=17&m=31&s=25&url=http%3A%2F%2Fclearcode.cc%2F&urlref=http%3A%2F%2Fclearcode.cc%2Fwelcome&_id=1da79fc743e8bcc4&_idts=1360047661&_idvc=1&_idn=0&_refts=1360047661&_viewts=1360047661&_ref=http%3A%2F%2Fpiwik.org%2Fthank-you-all%2F&pdf=1&qt=1&realp=0&wma=1&dir=1&fla=1&java=1&gears=0&ag=1&cookie=1&res=1680x1050","status": "200","referrer": "http://clearcode.cc/","user_agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17","length": 192,"generation_time_milli": 0.008,"date": "2013-10-10T16:52:00+02:00"}
2 | {"idsite":1,"ip": "1.2.3.4","host": "www.piwik.org","path": "/piwik.php?action_name=AdviserBrief%20-%20Track%20Your%20Investments%20and%20Plan%20Financial%20Future%20%7C%20Clearcode&idsite=1&rec=1&r=109464&h=17&m=31&s=40&url=http%3A%2F%2Fclearcode.cc%2Fcase%2Fadviserbrief-track-your-investments-and-plan-financial-future%2F&urlref=http%3A%2F%2Fclearcode.cc%2Fwelcome&_id=1da79fc743e8bcc4&_idts=1360047661&_idvc=1&_idn=0&_refts=1360047661&_viewts=1360047661&_ref=http%3A%2F%2Fpiwik.org%2Fthank-you-all%2F&pdf=1&qt=1&realp=0&wma=1&dir=1&fla=1&java=1&gears=0&ag=1&cookie=1&res=1680x1050","status": "200","referrer": "http://clearcode.cc/","user_agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17","length": 192,"generation_time_milli": 0.008,"date": "2013-10-10T16:52:00+02:00"}
3 |
--------------------------------------------------------------------------------
/tests/logs/logs_to_tests.log:
--------------------------------------------------------------------------------
1 | 203.38.78.246 - - [05/Feb/2013:07:01:26 +0000] "GET /piwik.php?action_name=Clearcode%20-%20Web%20and%20Mobile%20Development%20%7C%20Technology%20With%20Passion&idsite=1&rec=1&r=983420&h=17&m=31&s=25&url=http%3A%2F%2Fclearcode.cc%2F&urlref=http%3A%2F%2Fclearcode.cc%2Fwelcome&_id=1da79fc743e8bcc4&_idts=1360047661&_idvc=1&_idn=0&_refts=1360047661&_viewts=1360047661&_ref=http%3A%2F%2Fpiwik.org%2Fthank-you-all%2F&pdf=1&qt=1&realp=0&wma=1&dir=1&fla=1&java=1&gears=0&ag=1&cookie=1&res=1680x1050 HTTP/1.1" 200 192 "http://clearcode.cc/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17"
2 | 203.38.78.246 - - [05/Feb/2013:07:01:41 +0000] "GET /piwik.php?action_name=AdviserBrief%20-%20Track%20Your%20Investments%20and%20Plan%20Financial%20Future%20%7C%20Clearcode&idsite=1&rec=1&r=109464&h=17&m=31&s=40&url=http%3A%2F%2Fclearcode.cc%2Fcase%2Fadviserbrief-track-your-investments-and-plan-financial-future%2F&urlref=http%3A%2F%2Fclearcode.cc%2Fwelcome&_id=1da79fc743e8bcc4&_idts=1360047661&_idvc=1&_idn=0&_refts=1360047661&_viewts=1360047661&_ref=http%3A%2F%2Fpiwik.org%2Fthank-you-all%2F&pdf=1&qt=1&realp=0&wma=1&dir=1&fla=1&java=1&gears=0&ag=1&cookie=1&res=1680x1050 HTTP/1.1" 200 192 "http://clearcode.cc/case/adviserbrief-track-your-investments-and-plan-financial-future" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17"
3 | 203.38.78.246 - - [05/Feb/2013:07:01:46 +0000] "GET /piwik.php?action_name=ATL%20Apps%20-%20American%20Tailgating%20League%20Mobile%20Android%20IOS%20Games%20%7C%20Clearcode&idsite=1&rec=1&r=080064&h=17&m=31&s=46&url=http%3A%2F%2Fclearcode.cc%2Fcase%2Fatl-apps-mobile-android-ios-games%2F&urlref=http%3A%2F%2Fclearcode.cc%2Fwelcome&_id=1da79fc743e8bcc4&_idts=1360047661&_idvc=1&_idn=0&_refts=1360047661&_viewts=1360047661&_ref=http%3A%2F%2Fpiwik.org%2Fthank-you-all%2F&pdf=1&qt=1&realp=0&wma=1&dir=1&fla=1&java=1&gears=0&ag=1&cookie=1&res=1680x1050 HTTP/1.1" 200 192 "http://clearcode.cc/case/atl-apps-mobile-android-ios-games" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17"
4 |
5 | # Request with invalid length should not error out
6 | 95.81.66.139 - - [29/Oct/2013:00:48:46 +0100] "HEAD / HTTP/1.0" 403 - "-" "-"
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Matomo Server Log Analytics
2 |
3 | Import your server logs in Matomo with this powerful and easy to use tool.
4 |
5 | ## Requirements
6 |
7 | * Python 2.6 or 2.7. Python 3.x is not supported.
8 | * Matomo >= 2.14.0
9 |
10 | Build status (master branch) [](https://travis-ci.org/matomo/matomo-log-analytics)
11 |
12 | ## Supported log formats
13 |
14 |
15 | The script will import all standard web server log files, and some files with non-standard formats. The following log formats are supported:
16 | * all default log formats for: Nginx, Apache, IIS, Tomcat
17 | * all log formats commonly used such as: NCSA Common log format, Extended log format, W3C Extended log files, Nginx JSON, OVH
18 | * log files of some popular Cloud services: Amazon AWS CloudFront logs, AWS S3 logs, AWS ELB logs.
19 | * streaming media server log files such as: Icecast
20 | * log files with and without the virtual host will be imported
21 |
22 | In general, many fields are left optional to make the log importer very flexible.
23 |
24 | ## Get involved
25 |
26 | We're looking for contributors! Feel free to submit Pull requests on Github.
27 |
28 | ### Submit a new log format
29 |
30 | The Log Analytics importer is designed to detect and import into Matomo as many log files as possible. Help us add your log formats!
31 |
32 | * Implement your new log format in the import_logs.py file (look for `FORMATS = {` variable where the log formats are defined),
33 | * Add a new test in [tests/tests.py](https://github.com/matomo-org/matomo-log-analytics/blob/master/tests/tests.py),
34 | * Test that the logs are imported successfully as you expected (`tests/run_tests.sh`),
35 | * Open a Pull Request,
36 | * Check the test you have added works (the build should be green),
37 | * One Matomo team member will review and merge the Pull Request as soon as possible.
38 |
39 | We look forward to your contributions!
40 |
41 | ### Improve this guide
42 |
43 | This readme page could be improved and maybe you would like to help? feel free to create a "edit" this page and create a pull request.
44 |
45 | ### Implement new features or fixes
46 |
47 | if you're a Python developer and would like to contribute to open source log importer, check out the [list of issues for import_logs.py](https://github.com/matomo-org/matomo-log-analytics/issues) which lists all issues and suggestions.
48 |
49 | ## How to use this script?
50 |
51 | The most simple way to import your logs is to run:
52 |
53 | ./import_logs.py --url=matomo.example.com /path/to/access.log
54 |
55 | You must specify your Matomo URL with the `--url` argument.
56 | The script will automatically read your config.inc.php file to get the authentication
57 | token and communicate with your Matomo install to import the lines.
58 | The default mode will try to mimic the Javascript tracker as much as possible,
59 | and will not track bots, static files, or error requests.
60 |
61 | If you wish to track all requests the following command would be used:
62 |
63 | python /path/to/matomo/misc/log-analytics/import_logs.py --url=http://mysite/matomo/ --idsite=1234 --recorders=4 --enable-http-errors --enable-http-redirects --enable-static --enable-bots access.log
64 |
65 |
66 | ### Format Specific Details
67 |
68 | * If you are importing Netscaler log files, make sure to specify the `--iis-time-taken-secs` option. Netscaler stores
69 | the time-taken field in seconds while most other formats use milliseconds. Using this option will ensure that the
70 | log importer interprets the field correctly.
71 |
72 | * Some log formats can't be detected automatically as they would conflict with other formats. In order to import those logfiles make sure to specify the `--log-format-name` option.
73 | Those log formats are: OVH
74 |
75 | ## How to import your logs automatically every day?
76 |
77 | You must first make sure your logs are automatically rotated every day. The most
78 | popular ways to implement this are using either:
79 |
80 | * logrotate: http://www.linuxcommand.org/man_pages/logrotate8.html
81 | It will work with any HTTP daemon.
82 | * rotatelogs: http://httpd.apache.org/docs/2.0/programs/rotatelogs.html
83 | Only works with Apache.
84 | * let us know what else is useful and we will add it to the list
85 |
86 | Your logs should be automatically rotated and stored on your webserver, for instance in daily logs
87 | `/var/log/apache/access-%Y-%m-%d.log` (where %Y, %m and %d represent the year,
88 | month and day).
89 | You can then import your logs automatically each day (at 0:01). Setup a cron job with the command:
90 |
91 | 0 1 * * * /path/to/matomo/misc/log-analytics/import-logs.py -u matomo.example.com `date --date=yesterday +/var/log/apache/access-\%Y-\%m-\%d.log`
92 |
93 | ## Using Basic access authentication
94 |
95 | If you protect your site with Basic access authentication then you can pass the credentials via your
96 | cron job.
97 |
98 | Apache configuration:
99 | ```
100 |
101 | AuthType basic
102 | AuthName "Site requires authentication"
103 | # Where all the external login/passwords are
104 | AuthUserFile /etc/apache2/somefile
105 | Require valid-user
106 |
107 | ```
108 |
109 | cron job:
110 | ```
111 | 5 0 * * * /var/www/html/matomo/misc/log-analytics/import_logs.py --url https://www.mysite.com/matomo --auth-user=someuser --auth-password=somepassword --exclude-path=*/matomo/index.php --enable-http-errors --enable-reverse-dns --idsite=1 date --date=yesterday +/var/log/apache2/access-ssl-\%Y-\%m-\%d.log > /opt/scripts/import-logs.log
112 | ```
113 |
114 | Security tips:
115 | * Currently the credentials are not encrypted in the cron job. This should be a future enhancement.
116 | * Always use HTTPS with Basic access authentication to ensure you are not passing credentials clear text.
117 |
118 | ## Performance
119 |
120 | With an Intel Core i5-2400 @ 3.10GHz (2 cores, 4 virtual cores with Hyper-threading),
121 | running Matomo and its MySQL database, between 250 and 300 records were imported per second.
122 |
123 | The import_logs.py script needs CPU to read and parse the log files, but it is actually
124 | Matomo server itself (i.e. PHP/MySQL) which will use more CPU during data import.
125 |
126 | To improve performance,
127 |
128 | 1. by default, the script one thread to parse and import log lines.
129 | you can use the `--recorders` option to specify the number of parallel threads which will
130 | import hits into Matomo. We recommend to set `--recorders=N` to the number N of CPU cores
131 | that the server hosting Matomo has. The parsing will still be single-threaded,
132 | but several hits will be tracked in Matomo at the same time.
133 | 2. the script will issue hundreds of requests to matomo.php - to improve the Matomo webserver performance
134 | you can disable server access logging for these requests.
135 | Each Matomo webserver (Apache, Nginx, IIS) can also be tweaked a bit to handle more req/sec.
136 |
137 | ## Advanced uses
138 |
139 | ### Example Nginx Virtual Host Log Format
140 |
141 | nginx's default access log is parsed with the `--log-format-name=ncsa_extended` option.
142 |
143 | To log multiple virtual hosts in nginx's access log, use the following configuration:
144 |
145 | ```
146 | log_format vhosts '$host $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
147 | access_log /PATH/TO/access.log vhosts;
148 | ```
149 |
150 | When executing `import_logs.py`, use `--log-format-name=common_complete`.
151 |
152 | ### How do I import Page Speed Metric from logs?
153 |
154 | In Matomo> Actions> Page URLs and Page Title reports, Matomo reports the Avg. generation time, as an indicator of your website speed.
155 | This metric works by default when using the Javascript tracker, but you can use it with log file as well.
156 |
157 | Apache can log the generation time in microseconds using `%D` in the LogFormat.
158 | This metric can be imported using a custom log format in this script.
159 | In the command line, add the `--log-format-regex` parameter that contains the group `generation_time_micro`.
160 |
161 | Here's an example:
162 | ```
163 | Apache LogFormat "%h %l %u %t \"%r\" %>s %b %D"
164 | --log-format-regex="(?P\S+) \S+ \S+ \[(?P.*?) (?P.*?)\] \"\S+ (?P.*?) \S+\" (?P\S+) (?P\S+) (?P\S+)"
165 | ```
166 |
167 | Note: the group `` is also available if your server logs generation time in milliseconds rather than microseconds.
168 |
169 | ### How do I setup Nginx to directly import to Matomo via syslog?
170 |
171 | Since nginx 1.7.1 you can [log to syslog](http://nginx.org/en/docs/syslog.html) and import them live to Matomo.
172 |
173 | Path: nginx -> syslog -> (syslog central server) -> import_logs.py -> matomo
174 |
175 | As a syslog central server you could use rsyslog or syslog-ng, use relevant parts of documentation below. Rsyslog part is tested with Ubuntu 16.10 and is working out-of-the-box.
176 |
177 | You can use any log format that this script can handle, like Apache Combined, and Json format which needs less processing.
178 |
179 | ##### Setup Nginx logs
180 |
181 | ```
182 | http {
183 | ...
184 | log_format matomo '{"ip": "$remote_addr",'
185 | '"host": "$host",'
186 | '"path": "$request_uri",'
187 | '"status": "$status",'
188 | '"referrer": "$http_referer",'
189 | '"user_agent": "$http_user_agent",'
190 | '"length": $bytes_sent,'
191 | '"generation_time_milli": $request_time,'
192 | '"date": "$time_iso8601"}';
193 | ...
194 | server {
195 | ...
196 | # for syslog-ng
197 | access_log syslog:server=127.0.0.1,severity=info matomo;
198 | # for rsyslog
199 | access_log syslog:server=unix:/var/cache/nginx/access.socket,facility=local0 matomo;
200 | ...
201 | }
202 | }
203 | ```
204 |
205 | ##### Setup syslog-ng
206 |
207 | This is the config for the central server if any. If not, you can also use this config on the same server as Nginx.
208 |
209 | ```
210 | options {
211 | stats_freq(600); stats_level(1);
212 | log_fifo_size(1280000);
213 | log_msg_size(8192);
214 | };
215 | source s_nginx { udp(); };
216 | destination d_matomo {
217 | program("/usr/local/matomo/matomo.sh" template("$MSG\n"));
218 | };
219 | log { source(s_nginx); filter(f_info); destination(d_matomo); };
220 | ```
221 |
222 | ###### matomo.sh, syslog-ng version
223 |
224 | Just needed to configure the best params for import_logs.py, file `/usr/local/matomo/matomo.sh`:
225 | ```
226 | #!/bin/sh
227 |
228 | /path/to/misc/log-analytics/import_logs.py \
229 | --url=http://localhost/matomo/ \
230 | --idsite=1 --recorders=4 --enable-http-errors --enable-http-redirects --enable-static --enable-bots \
231 | --log-format-name=nginx_json -
232 | ```
233 |
234 | ##### Example of regex for syslog format (centralized logs)
235 |
236 | ###### log format exemple
237 |
238 | ```
239 | Aug 31 23:59:59 tt-srv-name www.tt.com: 1.1.1.1 - - [31/Aug/2014:23:59:59 +0200] "GET /index.php HTTP/1.0" 200 3838 "http://www.tt.com/index.php" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0" 365020 www.tt.com
240 | ```
241 |
242 | ###### Corresponding regex
243 |
244 | ```
245 | --log-format-regex='.* ((?P\S+) \S+ \S+ \[(?P.*?) (?P.*?)\] "\S+ (?P.*?) \S+" (?P\S+) (?P\S+) "(?P.*?)" "(?P.*?)").*'
246 | ```
247 |
248 | ##### Setup rsyslog
249 |
250 | Create new file `/etc/rsyslog.d/10-matomo.conf` with following content and restart rsyslog service afterwards:
251 | ```
252 | # socket to which you should send nginx data
253 | $AddUnixListenSocket /var/cache/nginx/access.socket
254 |
255 | # message starts with tag, "nginx: <...>", which we remove
256 | $template matomo,"%msg:9:$%\n"
257 |
258 | # uncomment following line to debug what is sent to matomo and in which format
259 | # to check script part you could issue following command
260 | # and expected result is "1 requests imported successfully":
261 | # 'tail -1 /var/tmp/nginx.tmp | /usr/local/matomo/matomo.sh'
262 |
263 | #local0.* /var/tmp/nginx.tmp;matomo
264 | if $syslogfacility-text == 'local0' then ^/usr/local/matomo/matomo.sh;matomo
265 | ```
266 |
267 | ###### matomo.sh, rsyslog version
268 |
269 | `/usr/local/matomo/matomo.sh`, won't work without `--token-auth` parameter:
270 | ```
271 | #!/bin/sh
272 |
273 | echo "${@}" | /path/to/misc/log-analytics/import_logs.py \
274 | --url=https://localhost/matomo/ --token-auth= \
275 | --enable-http-errors --enable-http-redirects --enable-static --enable-bots \
276 | --idsite=1 --recorders=4 --log-format-name=nginx_json -
277 | ```
278 |
279 |
280 | ### Setup Apache CustomLog that directly imports in Matomo
281 |
282 | Since apache CustomLog directives can send log data to a script, it is possible to import hits into matomo server-side in real-time rather than processing a logfile each day.
283 |
284 | This approach has many advantages, including real-time data being available on your matomo site, using real logs files instead of relying on client-side Javacsript, and not having a surge of CPU/RAM usage during log processing.
285 | The disadvantage is that if Matomo is unavailable, logging data will be lost. Therefore we recommend to also log into a standard log file. Bear in mind also that apache processes will wait until a request is logged before processing a new request, so if matomo runs slow so does your site: it's therefore important to tune `--recorders` to the right level.
286 |
287 | ##### Basic setup example
288 |
289 | You might have in your main config section:
290 |
291 | ```
292 | # Set up your log format as a normal extended format, with hostname at the start
293 | LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" myLogFormat
294 | # Log to a file as usual
295 | CustomLog /path/to/logfile myLogFormat
296 | # Log to matomo as well
297 | CustomLog "|/path/to/import_logs.py --option1 --option2 ... -" myLogFormat
298 | ```
299 |
300 | Note: on Debian/Ubuntu, the default configuration defines the `vhost_combined` format. You can use it instead of defining `myLogFormat`.
301 |
302 | Here is another example on Apache defining the custom log:
303 | ```
304 | LogFormat "%v %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\"" matomoLogFormat
305 |
306 | CustomLog "||/var/www/virtual/test.tld/matomo/htdocs/misc/log-analytics/import_logs.py \
307 | --debug --enable-http-errors --enable-http-redirects --enable-bots \
308 | --url=http://matomo.test.tld --output=/var/log/matomo.log --recorders=1 \
309 | --recorder-max-payload-size=1 --log-format-name=common_complete \
310 | -" matomoLogFormat
311 | ```
312 |
313 | Useful options here are:
314 |
315 | * `--add-sites-new-hosts` (creates new websites in matomo based on %v in the LogFormat)
316 | * `--output=/path/to/matomo.log` (puts any output into a log file for reference/debugging later)
317 | * `--recorders=4` (use whatever value seems sensible for you - higher traffic sites will need more recorders to keep up)
318 | * `-` so it reads straight from /dev/stdin
319 |
320 | You can have as many CustomLog statements as you like. However, if you define any CustomLog directives within a block, all CustomLogs in the main config will be overridden. Therefore if you require custom logging for particular VirtualHosts, it is recommended to use mod_macro to make configuration more maintainable.
321 |
322 |
323 | ##### Advanced setup: Apache vhost, custom logs, automatic website creation
324 |
325 | As a rather extreme example of what you can do, here is an apache config with:
326 |
327 | * standard logging in the main config area for the majority of VirtualHosts
328 | * customised logging in a particular virtualhost to change the hostname (for instance, if a particular virtualhost should be logged as if it were a different site)
329 | * customised logging in another virtualhost which creates new websites in matomo for subsites (e.g. to have domain.com/subsite1 as a whole website in its own right). This requires setting up a custom `--log-format-regex` to allow "/" in the hostname section (NB the escaping necessary for apache to pass through the regex to matomo properly), and also to have multiple CustomLog directives so the subsite gets logged to both domain.com and domain.com/subsite1 websites in matomo
330 | * we also use mod_rewrite to set environment variables so that if you have multiple subsites with the same format , e.g. /subsite1, /subsite2, etc, you can automatically create a new matomo website for each one without having to configure them manually
331 |
332 | NB use of mod_macro to ensure consistency and maintainability
333 |
334 | Apache configuration source code:
335 |
336 | ```
337 | # Set up macro with the options
338 | # * $vhost (this will be used as the matomo website name),
339 | # * $logname (the name of the LogFormat we're using),
340 | # * $output (which logfile to save import_logs.py output to),
341 | # * $env (CustomLog can be set only to fire if an environment variable is set - this contains that environment variable, so subsites only log when it's set)
342 | # NB the --log-format-regex line is exactly the same regex as import_logs.py's own 'common_vhost' format, but with "\/" added in the "host" section's allowed characters
343 |
344 | LogFormat "$vhost %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" $logname
345 | CustomLog "|/path/to/matomo/misc/log-analytics/import_logs.py \
346 | --add-sites-new-hosts \
347 | --config=/path/to/matomo/config/config.ini.php \
348 | --url='http://your.matomo.install/' \
349 | --recorders=4 \
350 | --log-format-regex='(?P[\\\\w\\\\-\\\\.\\\\/]*)(?::\\\\d+)? (?P\\\\S+) \\\\S+ \\\\S+ \\\\[(?P.*?) (?P.*?)\\\\] \\\"\\\\S+ (?P.*?) \\\\S+\\\" (?P\\\\S+) (?P\\\\S+) \\\"(?P.*?)\\\" \\\"(?P.*?)\\\"' \
351 | --output=/var/log/matomo/$output.log \
352 | -" \
353 | $logname \
354 | $env
355 |
356 | # Set up main apache logging, with:
357 |
358 | # * normal %v as hostname,
359 | # * vhost_common as logformat name,
360 | # * /var/log/matomo/main.log as the logfile,
361 | # * no env variable needed since we always want to trigger
362 | Use matomolog %v vhost_common main " "
363 |
364 | ServerName example.com
365 | # Set this host to log to matomo with a different hostname (and using a different output file, /var/log/matomo/example_com.log)
366 | Use matomolog "another-host.com" vhost_common example_com " "
367 |
368 |
369 |
370 | ServerName domain.com
371 | # We want to log this normally, so repeat the CustomLog from the main section
372 | # (if this is omitted, our other CustomLogs below will override the one in the main section, so the main site won't be logged)
373 | Use matomolog %v vhost_common main " "
374 |
375 | # Now set up mod_rewrite to detect our subsites and set up new matomo websites to track just hits to these (this is a bit like profiles in Google Analytics).
376 | # We want to match domain.com/anothersubsite and domain.com/subsite[0-9]+
377 |
378 | # First to be on the safe side, unset the env we'll use to test if we're in a subsite:
379 | UnsetEnv vhostLogName
380 |
381 | # Subsite definitions. NB check for both URI and REFERER (some files used in a page, or downloads linked from a page, may not reside within our subsite directory):
382 | # Do the one-off subsite first:
383 | RewriteCond %{REQUEST_URI} ^/anothersubsite(/|$) [OR]
384 | RewriteCond %{HTTP_REFERER} domain\.com/anothersubsite(/|$)
385 | RewriteRule ^/.* - [E=vhostLogName:anothersubsite]
386 | # Subsite of the form /subsite[0-9]+. NB the capture brackets in the RewriteCond rules which get mapped to %1 in the RewriteRule
387 | RewriteCond %{REQUEST_URI} ^/(subsite[0-9]+)(/|$)) [OR]
388 | RewriteCond %{HTTP_REFERER} domain\.com/(subsite[0-9]+)(/|$)
389 | RewriteRule ^/.* - [E=vhostLogName:subsite%1]
390 |
391 | # Now set the logging to matomo setting:
392 | # * the hostname to domain.com/
393 | # * the logformat to vhost_domain_com_subsites (can be anything so long as it's unique)
394 | # * the output to go to /var/log/matomo/domain_com_subsites.log (again, can be anything)
395 | # * triggering only when the env variable is set, so requests to other URIs on this domain don't call this logging rule
396 | Use matomolog domain.com/%{vhostLogName}e vhost_domain_com_subsites domain_com_subsites env=vhostLogName
397 |
398 | ```
399 |
400 | ### License
401 |
402 | As [matomo](`https://github.com/matomo-org/matomo`) (which includes this code as a git reference), matomo-log-analytics is released under the GPLv3 or later. Please refer to [LEGALNOTICE](LEGALNOTICE) for copyright and trademark statements and [LICENSE.txt](LICENSE.txt) for the full text of the GPLv3.
403 |
404 | ### And that's all !
405 |
406 |
407 | ***This documentation is a community effort, we welcome your pull requests to [improve this documentation](https://github.com/matomo-org/matomo-log-analytics/edit/master/README.md).***
408 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/tests/tests.py:
--------------------------------------------------------------------------------
1 | # vim: et sw=4 ts=4:
2 | import functools
3 | import os
4 | import datetime
5 | import re
6 |
7 | import import_logs
8 |
9 | # utility functions
10 | def add_junk_to_file(path):
11 | file = open(path)
12 | contents = file.read()
13 | file.close()
14 |
15 | file = open('tmp.log', 'w')
16 | file.write(contents + ' junk')
17 | file.close()
18 |
19 | return 'tmp.log'
20 |
21 | def add_multiple_spaces_to_file(path):
22 | file = open(path)
23 | contents = file.read()
24 | file.close()
25 |
26 | # replace spaces that aren't between " quotes
27 | contents = contents.split('"')
28 | for i in xrange(0, len(contents), 2):
29 | contents[i] = re.sub(' ', " ", contents[i])
30 | contents = '"'.join(contents)
31 | import_logs.logging.debug(contents)
32 |
33 | assert " " in contents # sanity check
34 |
35 | file = open('tmp.log', 'w')
36 | file.write(contents)
37 | file.close()
38 |
39 | return 'tmp.log'
40 |
41 | def use_ipv6_in_file(path):
42 | file = open(path)
43 | contents = file.read()
44 | file.close()
45 |
46 | if '1.2.3.4' not in contents:
47 | raise RuntimeError('could not find ipv4 IP in ' + path +
48 | ', make sure the IP 1.2.3.4 is used for tests')
49 |
50 | contents = contents.replace('1.2.3.4', '0:0:0:0:0:ffff:7b2d:4359')
51 |
52 | file = open('tmp.log', 'w')
53 | file.write(contents)
54 | file.close()
55 |
56 | return 'tmp.log'
57 |
58 | def tearDownModule():
59 | if os.path.exists('tmp.log'):
60 | os.remove('tmp.log')
61 |
62 | def test_format_detection():
63 | def _test(format_name, log_file = None):
64 | if log_file is None:
65 | log_file = 'logs/%s.log' % format_name
66 |
67 | file = open(log_file)
68 | import_logs.config = Config()
69 | format = import_logs.Parser.detect_format(file)
70 | assert(format is not None)
71 | assert(format.name == format_name)
72 |
73 | def _test_junk(format_name, log_file = None):
74 | if log_file is None:
75 | log_file = 'logs/%s.log' % format_name
76 |
77 | tmp_path = add_junk_to_file(log_file)
78 |
79 | file = open(tmp_path)
80 | import_logs.config = Config()
81 | format = import_logs.Parser.detect_format(file)
82 | assert(format is not None)
83 | assert(format.name == format_name)
84 |
85 | def _test_multiple_spaces(format_name, log_file = None):
86 | if log_file is None:
87 | log_file = 'logs/%s.log' % format_name
88 |
89 | tmp_path = add_multiple_spaces_to_file(log_file)
90 |
91 | file = open(tmp_path)
92 | import_logs.config = Config()
93 | format = import_logs.Parser.detect_format(file)
94 | assert(format is not None)
95 | assert(format.name == format_name)
96 |
97 | def _test_ipv6(format_name, log_file = None):
98 | if log_file is None:
99 | log_file = 'logs/%s.log' % format_name
100 |
101 | tmp_path = use_ipv6_in_file(log_file)
102 |
103 | # test correct format is detected first
104 | file = open(tmp_path)
105 | import_logs.config = Config()
106 | format = import_logs.Parser.detect_format(file)
107 | assert(format is not None)
108 | assert(format.name == format_name)
109 |
110 | # then parse the file and test the IP is parsed correctly
111 | groups = parse_log_file_line(format_name, tmp_path)
112 | assert groups['ip'] == '0:0:0:0:0:ffff:7b2d:4359'
113 |
114 | for format_name in import_logs.FORMATS.iterkeys():
115 | # w3c extended tested by iis and netscaler log files; amazon cloudfront tested later
116 | if format_name == 'w3c_extended' or format_name == 'amazon_cloudfront' or format_name == 'ovh':
117 | continue
118 |
119 | f = functools.partial(_test, format_name)
120 | f.description = 'Testing autodetection of format ' + format_name
121 | yield f
122 |
123 | f = functools.partial(_test_junk, format_name)
124 | f.description = 'Testing autodetection of format ' + format_name + ' w/ garbage at end of line'
125 | yield f
126 |
127 | f = functools.partial(_test_multiple_spaces, format_name)
128 | f.description = 'Testing autodetection of format ' + format_name + ' when multiple spaces separate fields'
129 | yield f
130 |
131 | f = functools.partial(_test_ipv6, format_name)
132 | f.description = 'Testing parsing of IPv6 address with format ' + format_name
133 | yield f
134 |
135 | # add tests for amazon cloudfront (normal web + rtmp)
136 | f = functools.partial(_test, 'amazon_cloudfront', 'logs/amazon_cloudfront_web.log')
137 | f.description = 'Testing autodetection of amazon cloudfront (web) logs.'
138 | yield f
139 |
140 | f = functools.partial(_test_junk, 'amazon_cloudfront', 'logs/amazon_cloudfront_web.log')
141 | f.description = 'Testing autodetection of amazon cloudfront (web) logs w/ garbage at end of line'
142 | yield f
143 |
144 | f = functools.partial(_test_multiple_spaces, 'amazon_cloudfront', 'logs/amazon_cloudfront_web.log')
145 | f.description = 'Testing autodetection of format amazon cloudfront (web) logs when multiple spaces separate fields'
146 | yield f
147 |
148 | f = functools.partial(_test, 'amazon_cloudfront', 'logs/amazon_cloudfront_rtmp.log')
149 | f.description = 'Testing autodetection of amazon cloudfront (rtmp) logs.'
150 | yield f
151 |
152 | f = functools.partial(_test_junk, 'amazon_cloudfront', 'logs/amazon_cloudfront_rtmp.log')
153 | f.description = 'Testing autodetection of amazon cloudfront (rtmp) logs w/ garbage at end of line.'
154 | yield f
155 |
156 | f = functools.partial(_test_multiple_spaces, 'amazon_cloudfront', 'logs/amazon_cloudfront_rtmp.log')
157 | f.description = 'Testing autodetection of format amazon cloudfront (rtmp) logs when multiple spaces separate fields'
158 | yield f
159 |
160 | class Options(object):
161 | """Mock config options necessary to run checkers from Parser class."""
162 | debug = False
163 | encoding = 'utf-8'
164 | log_hostname = 'foo'
165 | query_string_delimiter = '?'
166 | piwik_token_auth = False
167 | piwik_url = 'http://example.com'
168 | recorder_max_payload_size = 200
169 | replay_tracking = True
170 | show_progress = False
171 | skip = False
172 | hostnames = []
173 | excluded_paths = []
174 | excluded_useragents = []
175 | enable_bots = []
176 | force_lowercase_path = False
177 | included_paths = []
178 | enable_http_errors = False
179 | download_extensions = 'doc,pdf'
180 | custom_w3c_fields = {}
181 | dump_log_regex = False
182 | w3c_time_taken_in_millisecs = False
183 | w3c_fields = None
184 | w3c_field_regexes = {}
185 | regex_group_to_visit_cvars_map = {}
186 | regex_group_to_page_cvars_map = {}
187 | regex_groups_to_ignore = None
188 | replay_tracking_expected_tracker_file = 'piwik.php'
189 | debug_request_limit = None
190 | exclude_host = []
191 | include_host = []
192 | exclude_older_than = None
193 | exclude_newer_than = None
194 | track_http_method = True
195 | seconds_to_add_to_date = 0
196 | request_suffix = None
197 |
198 | class Config(object):
199 | """Mock configuration."""
200 | options = Options()
201 | format = import_logs.FORMATS['ncsa_extended']
202 |
203 | class Resolver(object):
204 | """Mock resolver which doesn't check connection to real piwik."""
205 | def check_format(self, format_):
206 | pass
207 |
208 | class Recorder(object):
209 | """Mock recorder which collects hits but doesn't put their in database."""
210 | recorders = []
211 |
212 | @classmethod
213 | def add_hits(cls, hits):
214 | cls.recorders.extend(hits)
215 |
216 | def test_replay_tracking_arguments():
217 | """Test data parsing from sample log file."""
218 | file_ = 'logs/logs_to_tests.log'
219 |
220 | import_logs.stats = import_logs.Statistics()
221 | import_logs.config = Config()
222 | import_logs.resolver = Resolver()
223 | import_logs.Recorder = Recorder()
224 | import_logs.parser = import_logs.Parser()
225 | import_logs.parser.parse(file_)
226 |
227 | hits = [hit.args for hit in import_logs.Recorder.recorders]
228 |
229 | assert hits[0]['_idn'] == '0'
230 | assert hits[0]['ag'] == '1'
231 | assert hits[0]['_viewts'] == '1360047661'
232 | assert hits[0]['urlref'] == 'http://clearcode.cc/welcome'
233 | assert hits[0]['_ref'] == 'http://piwik.org/thank-you-all/'
234 | assert hits[0]['_idts'] == '1360047661'
235 | assert hits[0]['java'] == '1'
236 | assert hits[0]['res'] == '1680x1050'
237 | assert hits[0]['idsite'] == '1'
238 | assert hits[0]['realp'] == '0'
239 | assert hits[0]['wma'] == '1'
240 | assert hits[0]['_idvc'] == '1'
241 | assert hits[0]['action_name'] == 'Clearcode - Web and Mobile Development | Technology With Passion'
242 | assert hits[0]['cookie'] == '1'
243 | assert hits[0]['rec'] == '1'
244 | assert hits[0]['qt'] == '1'
245 | assert hits[0]['url'] == 'http://clearcode.cc/'
246 | assert hits[0]['h'] == '17'
247 | assert hits[0]['m'] == '31'
248 | assert hits[0]['s'] == '25'
249 | assert hits[0]['r'] == '983420'
250 | assert hits[0]['gears'] == '0'
251 | assert hits[0]['fla'] == '1'
252 | assert hits[0]['pdf'] == '1'
253 | assert hits[0]['_id'] == '1da79fc743e8bcc4'
254 | assert hits[0]['dir'] == '1'
255 | assert hits[0]['_refts'] == '1360047661'
256 |
257 | assert hits[1]['_idn'] == '0'
258 | assert hits[1]['ag'] == '1'
259 | assert hits[1]['_viewts'] == '1360047661'
260 | assert hits[1]['urlref'] == 'http://clearcode.cc/welcome'
261 | assert hits[1]['_ref'] == 'http://piwik.org/thank-you-all/'
262 | assert hits[1]['_idts'] == '1360047661'
263 | assert hits[1]['java'] == '1'
264 | assert hits[1]['res'] == '1680x1050'
265 | assert hits[1]['idsite'] == '1'
266 | assert hits[1]['realp'] == '0'
267 | assert hits[1]['wma'] == '1'
268 | assert hits[1]['_idvc'] == '1'
269 | assert hits[1]['action_name'] == 'AdviserBrief - Track Your Investments and Plan Financial Future | Clearcode'
270 | assert hits[1]['cookie'] == '1'
271 | assert hits[1]['rec'] == '1'
272 | assert hits[1]['qt'] == '1'
273 | assert hits[1]['url'] == 'http://clearcode.cc/case/adviserbrief-track-your-investments-and-plan-financial-future/'
274 | assert hits[1]['h'] == '17'
275 | assert hits[1]['m'] == '31'
276 | assert hits[1]['s'] == '40'
277 | assert hits[1]['r'] == '109464'
278 | assert hits[1]['gears'] == '0'
279 | assert hits[1]['fla'] == '1'
280 | assert hits[1]['pdf'] == '1'
281 | assert hits[1]['_id'] == '1da79fc743e8bcc4'
282 | assert hits[1]['dir'] == '1'
283 | assert hits[1]['_refts'] == '1360047661'
284 |
285 | assert hits[2]['_idn'] == '0'
286 | assert hits[2]['ag'] == '1'
287 | assert hits[2]['_viewts'] == '1360047661'
288 | assert hits[2]['urlref'] == 'http://clearcode.cc/welcome'
289 | assert hits[2]['_ref'] == 'http://piwik.org/thank-you-all/'
290 | assert hits[2]['_idts'] == '1360047661'
291 | assert hits[2]['java'] == '1'
292 | assert hits[2]['res'] == '1680x1050'
293 | assert hits[2]['idsite'] == '1'
294 | assert hits[2]['realp'] == '0'
295 | assert hits[2]['wma'] == '1'
296 | assert hits[2]['_idvc'] == '1'
297 | assert hits[2]['action_name'] == 'ATL Apps - American Tailgating League Mobile Android IOS Games | Clearcode'
298 | assert hits[2]['cookie'] == '1'
299 | assert hits[2]['rec'] == '1'
300 | assert hits[2]['qt'] == '1'
301 | assert hits[2]['url'] == 'http://clearcode.cc/case/atl-apps-mobile-android-ios-games/'
302 | assert hits[2]['h'] == '17'
303 | assert hits[2]['m'] == '31'
304 | assert hits[2]['s'] == '46'
305 | assert hits[2]['r'] == '080064'
306 | assert hits[2]['gears'] == '0'
307 | assert hits[2]['fla'] == '1'
308 | assert hits[2]['pdf'] == '1'
309 | assert hits[2]['_id'] == '1da79fc743e8bcc4'
310 | assert hits[2]['dir'] == '1'
311 | assert hits[2]['_refts'] == '1360047661'
312 |
313 | def parse_log_file_line(format_name, file_):
314 | format = import_logs.FORMATS[format_name]
315 |
316 | import_logs.config.options.custom_w3c_fields = {}
317 |
318 | file = open(file_)
319 | match = format.check_format(file)
320 | file.close()
321 |
322 | return format.get_all()
323 |
324 | # check parsing groups
325 | def check_common_groups(groups):
326 | assert groups['ip'] == '1.2.3.4'
327 | assert groups['date'] == '10/Feb/2012:16:42:07'
328 | assert groups['timezone'] == '-0500'
329 | assert groups['path'] == '/'
330 | assert groups['status'] == '301'
331 | assert groups['length'] == '368'
332 | assert groups['userid'] == 'theuser'
333 |
334 | def check_ncsa_extended_groups(groups):
335 | check_common_groups(groups)
336 |
337 | assert groups['referrer'] == '-'
338 | assert groups['user_agent'] == 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
339 |
340 | def check_common_vhost_groups(groups):
341 | check_common_groups(groups)
342 |
343 | assert groups['host'] == 'www.example.com'
344 |
345 | def check_common_complete_groups(groups):
346 | check_ncsa_extended_groups(groups)
347 |
348 | assert groups['host'] == 'www.example.com'
349 |
350 | def check_iis_groups(groups):
351 | assert groups['date'] == '2012-04-01 00:00:13'
352 | assert groups['path'] == '/foo/bar'
353 | assert groups['query_string'] == 'topCat1=divinity&submit=Search'
354 | assert groups['ip'] == '1.2.3.4'
355 | assert groups['referrer'] == '-'
356 | assert groups['user_agent'] == 'Mozilla/5.0+(X11;+U;+Linux+i686;+en-US;+rv:1.9.2.7)+Gecko/20100722+Firefox/3.6.7'
357 | assert groups['status'] == '200'
358 | assert groups['length'] == '27028'
359 | assert groups['host'] == 'example.com'
360 |
361 | expected_hit_properties = ['date', 'path', 'query_string', 'ip', 'referrer', 'user_agent',
362 | 'status', 'length', 'host', 'userid', 'generation_time_milli',
363 | '__win32_status', 'cookie', 'method']
364 |
365 | for property_name in groups.keys():
366 | assert property_name in expected_hit_properties
367 |
368 | def check_s3_groups(groups):
369 | assert groups['host'] == 'www.example.com'
370 | assert groups['date'] == '10/Feb/2012:16:42:07'
371 | assert groups['timezone'] == '-0500'
372 | assert groups['ip'] == '1.2.3.4'
373 | assert groups['userid'] == 'arn:aws:iam::179580289999:user/phillip.boss'
374 | assert groups['path'] == '/index'
375 | assert groups['status'] == '200'
376 | assert groups['length'] == '368'
377 | assert groups['referrer'] == '-'
378 | assert groups['user_agent'] == 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
379 |
380 | def check_nginx_json_groups(groups):
381 | assert groups['host'] == 'www.piwik.org'
382 | assert groups['status'] == '200'
383 | assert groups['ip'] == '1.2.3.4'
384 | assert groups['length'] == 192
385 | assert groups['user_agent'] == 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'
386 | assert groups['date'] == '2013-10-10T16:52:00+02:00'
387 |
388 | def check_icecast2_groups(groups):
389 | check_ncsa_extended_groups(groups)
390 |
391 | assert groups['session_time'] == '1807'
392 |
393 | def check_match_groups(format_name, groups):
394 | symbols = globals()
395 | check_function = symbols['check_' + format_name + '_groups']
396 | return check_function(groups)
397 |
398 | def check_ovh_groups(groups):
399 | check_common_complete_groups(groups)
400 |
401 | # parsing tests
402 | def test_format_parsing():
403 | # test format regex parses correctly
404 | def _test(format_name, path):
405 | groups = parse_log_file_line(format_name, path)
406 | check_match_groups(format_name, groups)
407 |
408 | # test format regex parses correctly when there's added junk at the end of the line
409 | def _test_with_junk(format_name, path):
410 | tmp_path = add_junk_to_file(path)
411 | _test(format_name, tmp_path)
412 |
413 | for format_name in import_logs.FORMATS.iterkeys():
414 | # w3c extended tested by IIS and netscaler logs; amazon cloudfront tested individually
415 | if format_name == 'w3c_extended' or format_name == 'amazon_cloudfront' or format_name == 'shoutcast' or format_name == 'elb':
416 | continue
417 |
418 | f = functools.partial(_test, format_name, 'logs/' + format_name + '.log')
419 | f.description = 'Testing parsing of format "%s"' % format_name
420 | yield f
421 |
422 | f = functools.partial(_test_with_junk, format_name, 'logs/' + format_name + '.log')
423 | f.description = 'Testing parsing of format "%s" with junk appended to path' % format_name
424 | yield f
425 |
426 | f = functools.partial(_test, 'common', 'logs/ncsa_extended.log')
427 | f.description = 'Testing parsing of format "common" with ncsa_extended log'
428 | yield f
429 |
430 | def test_iis_custom_format():
431 | """test IIS custom format name parsing."""
432 |
433 | file_ = 'logs/iis_custom.log'
434 |
435 | # have to override previous globals override for this test
436 | import_logs.config.options.custom_w3c_fields = {
437 | 'date-local': 'date',
438 | 'time-local': 'time',
439 | 'cs(Host)': 'cs-host',
440 | 'TimeTakenMS': 'time-taken'
441 | }
442 | Recorder.recorders = []
443 | import_logs.parser = import_logs.Parser()
444 | import_logs.config.format = None
445 | import_logs.config.options.enable_http_redirects = True
446 | import_logs.config.options.enable_http_errors = True
447 | import_logs.config.options.replay_tracking = False
448 | # import_logs.config.options.w3c_time_taken_in_millisecs = True test that even w/o this, we get the right values
449 | import_logs.parser.parse(file_)
450 |
451 | hits = [hit.__dict__ for hit in Recorder.recorders]
452 |
453 | assert hits[0]['status'] == '200'
454 | assert hits[0]['is_error'] == False
455 | assert hits[0]['extension'] == u'/products/theproduct'
456 | assert hits[0]['is_download'] == False
457 | assert hits[0]['referrer'] == u'http://example.com/Search/SearchResults.pg?informationRecipient.languageCode.c=en'
458 | assert hits[0]['args'] == {'cvar': {1: ['HTTP-method', 'GET']}}
459 | assert hits[0]['generation_time_milli'] == 109
460 | assert hits[0]['host'] == 'foo'
461 | assert hits[0]['filename'] == 'logs/iis_custom.log'
462 | assert hits[0]['is_redirect'] == False
463 | assert hits[0]['date'] == datetime.datetime(2012, 8, 15, 17, 0)
464 | assert hits[0]['lineno'] == 7
465 | assert hits[0]['ip'] == u'70.95.0.0'
466 | assert hits[0]['query_string'] == ''
467 | assert hits[0]['path'] == u'/Products/theProduct'
468 | assert hits[0]['is_robot'] == False
469 | assert hits[0]['full_path'] == u'/Products/theProduct'
470 | assert hits[0]['user_agent'] == u'Mozilla/5.0 (Linux; Android 4.4.4; SM-G900V Build/KTU84P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.59 Mobile Safari/537.36'
471 |
472 | assert hits[1]['status'] == u'301'
473 | assert hits[1]['is_error'] == False
474 | assert hits[1]['extension'] == u'/topic/hw43061'
475 | assert hits[1]['is_download'] == False
476 | assert hits[1]['referrer'] == ''
477 | assert hits[1]['args'] == {'cvar': {1: ['HTTP-method', 'GET']}}
478 | assert hits[1]['generation_time_milli'] == 0
479 | assert hits[1]['host'] == 'foo'
480 | assert hits[1]['filename'] == 'logs/iis_custom.log'
481 | assert hits[1]['is_redirect'] == True
482 | assert hits[1]['date'] == datetime.datetime(2012, 8, 15, 17, 0)
483 | assert hits[1]['lineno'] == 8
484 | assert hits[1]['ip'] == '-'
485 | assert hits[1]['query_string'] == ''
486 | assert hits[1]['path'] == u'/Topic/hw43061'
487 | assert hits[1]['is_robot'] == False
488 | assert hits[1]['full_path'] == u'/Topic/hw43061'
489 | assert hits[1]['user_agent'] == u'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36'
490 |
491 | assert hits[2]['status'] == u'404'
492 | assert hits[2]['is_error'] == True
493 | assert hits[2]['extension'] == u'/hello/world/6,681965'
494 | assert hits[2]['is_download'] == False
495 | assert hits[2]['referrer'] == ''
496 | assert hits[2]['args'] == {'cvar': {1: ['HTTP-method', 'GET']}}
497 | assert hits[2]['generation_time_milli'] == 359
498 | assert hits[2]['host'] == 'foo'
499 | assert hits[2]['filename'] == 'logs/iis_custom.log'
500 | assert hits[2]['is_redirect'] == False
501 | assert hits[2]['date'] == datetime.datetime(2012, 8, 15, 17, 0)
502 | assert hits[2]['lineno'] == 9
503 | assert hits[2]['ip'] == u'173.5.0.0'
504 | assert hits[2]['query_string'] == ''
505 | assert hits[2]['path'] == u'/hello/world/6,681965'
506 | assert hits[2]['is_robot'] == False
507 | assert hits[2]['full_path'] == u'/hello/world/6,681965'
508 | assert hits[2]['user_agent'] == u'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36'
509 |
510 | def test_netscaler_parsing():
511 | """test parsing of netscaler logs (which use extended W3C log format)"""
512 |
513 | file_ = 'logs/netscaler.log'
514 |
515 | # have to override previous globals override for this test
516 | import_logs.config.options.custom_w3c_fields = {}
517 | Recorder.recorders = []
518 | import_logs.parser = import_logs.Parser()
519 | import_logs.config.format = None
520 | import_logs.config.options.enable_http_redirects = True
521 | import_logs.config.options.enable_http_errors = True
522 | import_logs.config.options.replay_tracking = False
523 | import_logs.config.options.w3c_time_taken_in_millisecs = False
524 | import_logs.parser.parse(file_)
525 |
526 | hits = [hit.__dict__ for hit in Recorder.recorders]
527 |
528 | assert hits[0]['status'] == u'302'
529 | assert hits[0]['userid'] == None
530 | assert hits[0]['is_error'] == False
531 | assert hits[0]['extension'] == u'jsp'
532 | assert hits[0]['is_download'] == False
533 | assert hits[0]['referrer'] == ''
534 | assert hits[0]['args'] == {'cvar': {1: ['HTTP-method', 'GET']}}
535 | assert hits[0]['generation_time_milli'] == 1000
536 | assert hits[0]['host'] == 'foo'
537 | assert hits[0]['filename'] == 'logs/netscaler.log'
538 | assert hits[0]['is_redirect'] == True
539 | assert hits[0]['date'] == datetime.datetime(2012, 8, 16, 11, 55, 13)
540 | assert hits[0]['lineno'] == 4
541 | assert hits[0]['ip'] == u'172.20.1.0'
542 | assert hits[0]['query_string'] == ''
543 | assert hits[0]['path'] == u'/Citrix/XenApp/Wan/auth/login.jsp'
544 | assert hits[0]['is_robot'] == False
545 | assert hits[0]['full_path'] == u'/Citrix/XenApp/Wan/auth/login.jsp'
546 | assert hits[0]['user_agent'] == u'Mozilla/4.0+(compatible;+MSIE+7.0;+Windows+NT+5.1;+Trident/4.0;+.NET+CLR+1.1.4322;+.NET+CLR+2.0.50727;+.NET+CLR+3.0.04506.648;+.NET+CLR+3.5.21022)'
547 |
548 | def test_shoutcast_parsing():
549 | """test parsing of shoutcast logs (which use extended W3C log format)"""
550 |
551 | file_ = 'logs/shoutcast.log'
552 |
553 | # have to override previous globals override for this test
554 | import_logs.config.options.custom_w3c_fields = {}
555 | Recorder.recorders = []
556 | import_logs.parser = import_logs.Parser()
557 | import_logs.config.format = None
558 | import_logs.config.options.enable_http_redirects = True
559 | import_logs.config.options.enable_http_errors = True
560 | import_logs.config.options.replay_tracking = False
561 | import_logs.config.options.w3c_time_taken_in_millisecs = False
562 | import_logs.parser.parse(file_)
563 |
564 | hits = [hit.__dict__ for hit in Recorder.recorders]
565 |
566 | assert hits[0]['status'] == u'200'
567 | assert hits[0]['userid'] == None
568 | assert hits[0]['is_error'] == False
569 | assert hits[0]['extension'] == u'/stream'
570 | assert hits[0]['is_download'] == False
571 | assert hits[0]['referrer'] == ''
572 | assert hits[0]['args'] == {}
573 | assert hits[0]['generation_time_milli'] == 1000.0
574 | assert hits[0]['host'] == 'foo'
575 | assert hits[0]['filename'] == 'logs/shoutcast.log'
576 | assert hits[0]['is_redirect'] == False
577 | assert hits[0]['date'] == datetime.datetime(2015, 12, 7, 10, 37, 5)
578 | assert hits[0]['lineno'] == 3
579 | assert hits[0]['ip'] == u'1.2.3.4'
580 | assert hits[0]['query_string'] == u'title=UKR%20Nights'
581 | assert hits[0]['path'] == u'/stream'
582 | assert hits[0]['is_robot'] == False
583 | assert hits[0]['full_path'] == u'/stream?title=UKR%20Nights'
584 | assert hits[0]['user_agent'] == u'NSPlayer/10.0.0.3702 WMFSDK/10.0'
585 | assert hits[0]['length'] == 65580
586 |
587 | def test_elb_parsing():
588 | """test parsing of elb logs"""
589 |
590 | file_ = 'logs/elb.log'
591 |
592 | # have to override previous globals override for this test
593 | import_logs.config.options.custom_w3c_fields = {}
594 | Recorder.recorders = []
595 | import_logs.parser = import_logs.Parser()
596 | import_logs.config.format = None
597 | import_logs.config.options.enable_http_redirects = True
598 | import_logs.config.options.enable_http_errors = True
599 | import_logs.config.options.replay_tracking = False
600 | import_logs.config.options.w3c_time_taken_in_millisecs = False
601 | import_logs.parser.parse(file_)
602 |
603 | hits = [hit.__dict__ for hit in Recorder.recorders]
604 |
605 | assert len(hits) == 1
606 |
607 | assert hits[0]['status'] == u'200'
608 | assert hits[0]['userid'] == None
609 | assert hits[0]['is_error'] == False
610 | assert hits[0]['extension'] == u'html'
611 | assert hits[0]['is_download'] == False
612 | assert hits[0]['referrer'] == ''
613 | assert hits[0]['args'] == {}
614 | assert hits[0]['generation_time_milli'] == 1.048
615 | assert hits[0]['host'] == 'foo'
616 | assert hits[0]['filename'] == 'logs/elb.log'
617 | assert hits[0]['is_redirect'] == False
618 | assert hits[0]['date'] == datetime.datetime(2015, 05, 13, 23, 39, 43)
619 | assert hits[0]['lineno'] == 0
620 | assert hits[0]['ip'] == u'1.2.3.4'
621 | assert hits[0]['query_string'] == u''
622 | assert hits[0]['path'] == u'/path/index.html'
623 | assert hits[0]['is_robot'] == False
624 | assert hits[0]['full_path'] == u'/path/index.html'
625 | assert hits[0]['user_agent'] == u'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
626 | assert hits[0]['length'] == 57
627 |
628 | def test_amazon_cloudfront_web_parsing():
629 | """test parsing of amazon cloudfront logs (which use extended W3C log format)"""
630 |
631 | file_ = 'logs/amazon_cloudfront_web.log'
632 |
633 | # have to override previous globals override for this test
634 | import_logs.config.options.custom_w3c_fields = {}
635 | Recorder.recorders = []
636 | import_logs.parser = import_logs.Parser()
637 | import_logs.config.format = None
638 | import_logs.config.options.enable_http_redirects = True
639 | import_logs.config.options.enable_http_errors = True
640 | import_logs.config.options.replay_tracking = False
641 | import_logs.config.options.w3c_time_taken_in_millisecs = False
642 | import_logs.parser.parse(file_)
643 |
644 | hits = [hit.__dict__ for hit in Recorder.recorders]
645 |
646 | assert hits[0]['status'] == u'200'
647 | assert hits[0]['userid'] == None
648 | assert hits[0]['is_error'] == False
649 | assert hits[0]['extension'] == u'html'
650 | assert hits[0]['is_download'] == False
651 | assert hits[0]['referrer'] == u'www.displaymyfiles.com'
652 | assert hits[0]['args'] == {'cvar': {1: ['HTTP-method', 'GET']}}
653 | assert hits[0]['generation_time_milli'] == 1.0
654 | assert hits[0]['host'] == 'foo'
655 | assert hits[0]['filename'] == 'logs/amazon_cloudfront_web.log'
656 | assert hits[0]['is_redirect'] == False
657 | assert hits[0]['date'] == datetime.datetime(2014, 5, 23, 1, 13, 11)
658 | assert hits[0]['lineno'] == 2
659 | assert hits[0]['ip'] == u'192.0.2.10'
660 | assert hits[0]['query_string'] == ''
661 | assert hits[0]['path'] == u'/view/my/file.html'
662 | assert hits[0]['is_robot'] == False
663 | assert hits[0]['full_path'] == u'/view/my/file.html'
664 | assert hits[0]['user_agent'] == u'Mozilla/4.0 (compatible; MSIE 5.0b1; Mac_PowerPC)'
665 |
666 | assert len(hits) == 1
667 |
668 | def test_ovh_parsing():
669 | """test parsing of ovh logs (which needs to be forced, as it's not autodetected)"""
670 |
671 | file_ = 'logs/ovh.log'
672 |
673 | # have to override previous globals override for this test
674 | import_logs.config.options.custom_w3c_fields = {}
675 | Recorder.recorders = []
676 | import_logs.parser = import_logs.Parser()
677 | import_logs.config.format = import_logs.FORMATS['ovh']
678 | import_logs.config.options.log_hostname = None
679 | import_logs.config.options.enable_http_redirects = True
680 | import_logs.config.options.enable_http_errors = True
681 | import_logs.config.options.replay_tracking = False
682 | import_logs.config.options.w3c_time_taken_in_millisecs = False
683 | import_logs.parser.parse(file_)
684 |
685 | hits = [hit.__dict__ for hit in Recorder.recorders]
686 |
687 | assert hits[0]['status'] == u'301'
688 | assert hits[0]['userid'] == u'theuser'
689 | assert hits[0]['is_error'] == False
690 | assert hits[0]['extension'] == u'/'
691 | assert hits[0]['is_download'] == False
692 | assert hits[0]['referrer'] == u''
693 | assert hits[0]['args'] == {'uid': u'theuser'}
694 | assert hits[0]['generation_time_milli'] == 0
695 | assert hits[0]['host'] == 'www.example.com'
696 | assert hits[0]['filename'] == 'logs/ovh.log'
697 | assert hits[0]['is_redirect'] == True
698 | assert hits[0]['date'] == datetime.datetime(2012, 2, 10, 21, 42, 07)
699 | assert hits[0]['lineno'] == 0
700 | assert hits[0]['ip'] == u'1.2.3.4'
701 | assert hits[0]['query_string'] == ''
702 | assert hits[0]['path'] == u'/'
703 | assert hits[0]['is_robot'] == False
704 | assert hits[0]['full_path'] == u'/'
705 | assert hits[0]['user_agent'] == u'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11'
706 |
707 | assert len(hits) == 1
708 |
709 | import_logs.config.options.log_hostname = 'foo'
710 |
711 | def test_amazon_cloudfront_rtmp_parsing():
712 | """test parsing of amazon cloudfront rtmp logs (which use extended W3C log format w/ custom fields for event info)"""
713 |
714 | file_ = 'logs/amazon_cloudfront_rtmp.log'
715 |
716 | # have to override previous globals override for this test
717 | import_logs.config.options.custom_w3c_fields = {}
718 | Recorder.recorders = []
719 | import_logs.parser = import_logs.Parser()
720 | import_logs.config.format = None
721 | import_logs.config.options.enable_http_redirects = True
722 | import_logs.config.options.enable_http_errors = True
723 | import_logs.config.options.replay_tracking = False
724 | import_logs.config.options.w3c_time_taken_in_millisecs = False
725 | import_logs.parser.parse(file_)
726 |
727 | hits = [hit.__dict__ for hit in Recorder.recorders]
728 |
729 | assert hits[0]['is_download'] == False
730 | assert hits[0]['ip'] == u'192.0.2.147'
731 | assert hits[0]['is_redirect'] == False
732 | assert hits[0]['filename'] == 'logs/amazon_cloudfront_rtmp.log'
733 | assert hits[0]['event_category'] == 'cloudfront_rtmp'
734 | assert hits[0]['event_action'] == u'connect'
735 | assert hits[0]['lineno'] == 2
736 | assert hits[0]['status'] == '200'
737 | assert hits[0]['is_error'] == False
738 | assert hits[0]['event_name'] == None
739 | assert hits[0]['args'] == {}
740 | assert hits[0]['host'] == 'foo'
741 | assert hits[0]['date'] == datetime.datetime(2010, 3, 12, 23, 51, 20)
742 | assert hits[0]['path'] == u'/shqshne4jdp4b6.cloudfront.net/cfx/st\u200b'
743 | assert hits[0]['extension'] == u'net/cfx/st\u200b'
744 | assert hits[0]['referrer'] == ''
745 | assert hits[0]['userid'] == None
746 | assert hits[0]['user_agent'] == u'LNX 10,0,32,18'
747 | assert hits[0]['generation_time_milli'] == 0
748 | assert hits[0]['query_string'] == u'key=value'
749 | assert hits[0]['is_robot'] == False
750 | assert hits[0]['full_path'] == u'/shqshne4jdp4b6.cloudfront.net/cfx/st\u200b'
751 |
752 | assert hits[1]['is_download'] == False
753 | assert hits[1]['ip'] == u'192.0.2.222'
754 | assert hits[1]['is_redirect'] == False
755 | assert hits[1]['filename'] == 'logs/amazon_cloudfront_rtmp.log'
756 | assert hits[1]['event_category'] == 'cloudfront_rtmp'
757 | assert hits[1]['event_action'] == u'play'
758 | assert hits[1]['lineno'] == 3
759 | assert hits[1]['status'] == '200'
760 | assert hits[1]['is_error'] == False
761 | assert hits[1]['event_name'] == u'myvideo'
762 | assert hits[1]['args'] == {}
763 | assert hits[1]['host'] == 'foo'
764 | assert hits[1]['date'] == datetime.datetime(2010, 3, 12, 23, 51, 21)
765 | assert hits[1]['path'] == u'/shqshne4jdp4b6.cloudfront.net/cfx/st\u200b'
766 | assert hits[1]['extension'] == u'net/cfx/st\u200b'
767 | assert hits[1]['referrer'] == ''
768 | assert hits[1]['userid'] == None
769 | assert hits[1]['length'] == 3914
770 | assert hits[1]['user_agent'] == u'LNX 10,0,32,18'
771 | assert hits[1]['generation_time_milli'] == 0
772 | assert hits[1]['query_string'] == u'key=value'
773 | assert hits[1]['is_robot'] == False
774 | assert hits[1]['full_path'] == u'/shqshne4jdp4b6.cloudfront.net/cfx/st\u200b'
775 |
776 | assert len(hits) == 2
777 |
778 | def test_ignore_groups_option_removes_groups():
779 | """Test that the --ignore-groups option removes groups so they do not appear in hits."""
780 |
781 | file_ = 'logs/iis.log'
782 |
783 | # have to override previous globals override for this test
784 | import_logs.config.options.custom_w3c_fields = {}
785 | Recorder.recorders = []
786 | import_logs.parser = import_logs.Parser()
787 | import_logs.config.format = None
788 | import_logs.config.options.enable_http_redirects = True
789 | import_logs.config.options.enable_http_errors = True
790 | import_logs.config.options.replay_tracking = False
791 | import_logs.config.options.w3c_time_taken_in_millisecs = True
792 | import_logs.config.options.regex_groups_to_ignore = set(['userid','generation_time_milli'])
793 | import_logs.parser.parse(file_)
794 |
795 | hits = [hit.__dict__ for hit in Recorder.recorders]
796 |
797 | assert hits[0]['userid'] == None
798 | assert hits[0]['generation_time_milli'] == 0
799 |
800 | def test_regex_group_to_custom_var_options():
801 | """Test that the --regex-group-to-visit-cvar and --regex-group-to-page-cvar track regex groups to custom vars."""
802 |
803 | file_ = 'logs/iis.log'
804 |
805 | # have to override previous globals override for this test
806 | import_logs.config.options.custom_w3c_fields = {}
807 | Recorder.recorders = []
808 | import_logs.parser = import_logs.Parser()
809 | import_logs.config.format = None
810 | import_logs.config.options.enable_http_redirects = True
811 | import_logs.config.options.enable_http_errors = True
812 | import_logs.config.options.replay_tracking = False
813 | import_logs.config.options.w3c_time_taken_in_millisecs = True
814 | import_logs.config.options.regex_groups_to_ignore = set()
815 | import_logs.config.options.regex_group_to_visit_cvars_map = {
816 | 'userid': "User Name",
817 | 'date': "The Date"
818 | }
819 | import_logs.config.options.regex_group_to_page_cvars_map = {
820 | 'generation_time_milli': 'Geneartion Time',
821 | 'referrer': 'The Referrer'
822 | }
823 | import_logs.parser.parse(file_)
824 |
825 | hits = [hit.__dict__ for hit in Recorder.recorders]
826 |
827 | assert hits[0]['args']['_cvar'] == {1: ['The Date', '2012-04-01 00:00:13'], 2: ['User Name', 'theuser']} # check visit custom vars
828 | assert hits[0]['args']['cvar'] == {1: ['Geneartion Time', '1687'], 2: ['HTTP-method', 'GET']} # check page custom vars
829 |
830 | assert hits[0]['userid'] == 'theuser'
831 | assert hits[0]['date'] == datetime.datetime(2012, 4, 1, 0, 0, 13)
832 | assert hits[0]['generation_time_milli'] == 1687
833 | assert hits[0]['referrer'] == ''
834 |
835 | def test_w3c_custom_field_regex_option():
836 | """Test that --w3c-field-regex can be used to match custom W3C log fields."""
837 |
838 | file_ = 'logs/iis.log'
839 |
840 | # have to override previous globals override for this test
841 | import_logs.config.options.custom_w3c_fields = {}
842 | Recorder.recorders = []
843 | import_logs.parser = import_logs.Parser()
844 | import_logs.config.format = None
845 | import_logs.config.options.enable_http_redirects = True
846 | import_logs.config.options.enable_http_errors = True
847 | import_logs.config.options.replay_tracking = False
848 | import_logs.config.options.w3c_time_taken_in_millisecs = True
849 | import_logs.config.options.w3c_field_regexes = {
850 | 'sc-substatus': '(?P\S+)',
851 | 'sc-win32-status': '(?P\S+)'
852 | }
853 |
854 | format = import_logs.W3cExtendedFormat()
855 |
856 | file_handle = open(file_)
857 | format.check_format(file_handle)
858 | match = None
859 | while not match:
860 | line = file_handle.readline()
861 | if not line:
862 | break
863 | match = format.match(line)
864 | file_handle.close()
865 |
866 | assert match is not None
867 | assert format.get('substatus') == '654'
868 | assert format.get('win32_status') == '456'
869 |
870 | def test_custom_log_date_format_option():
871 | """Test that --log-date-format will change how dates are parsed in a custom log format."""
872 |
873 | file_ = 'logs/custom_regex_custom_date.log'
874 |
875 | # have to override previous globals override for this test
876 | Recorder.recorders = []
877 | import_logs.parser = import_logs.Parser()
878 | import_logs.config.options.w3c_field_regexes = None
879 | import_logs.config.options.regex_group_to_visit_cvars_map = None
880 | import_logs.config.options.regex_group_to_page_cvars_map = None
881 | import_logs.config.options.log_format_regex = (
882 | '(?P\S+)\s+\S+\s+\S+\s+\[(?P.*?)\]\s+'
883 | '"\S+\s+(?P.*?)\s+\S+"\s+(?P\S+)\s+(?P\S+)'
884 | )
885 | import_logs.config.options.log_date_format = '%B - %d, %Y:%H:%M:%S'
886 | import_logs.config.format = import_logs.RegexFormat('custom', import_logs.config.options.log_format_regex,
887 | import_logs.config.options.log_date_format)
888 |
889 | import_logs.parser.parse(file_)
890 |
891 | hits = [hit.__dict__ for hit in Recorder.recorders]
892 |
893 | assert hits[0]['date'] == datetime.datetime(2012, 2, 10, 16, 42, 7)
894 |
--------------------------------------------------------------------------------
/import_logs.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python
2 | # vim: et sw=4 ts=4:
3 | # -*- coding: utf-8 -*-
4 | #
5 | # Matomo - free/libre analytics platform
6 | #
7 | # @link https://matomo.org
8 | # @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
9 | # @version $Id$
10 | #
11 | # For more info see: https://matomo.org/log-analytics/ and https://matomo.org/docs/log-analytics-tool-how-to/
12 | #
13 | # Requires Python 2.6 or 2.7
14 | #
15 |
16 | import sys
17 |
18 | if sys.version_info[0] != 2:
19 | print('The log importer currently does not work with Python 3 (or higher)')
20 | print('Please use Python 2.6 or 2.7')
21 | sys.exit(1)
22 |
23 | import base64
24 | import bz2
25 | import ConfigParser
26 | import datetime
27 | import fnmatch
28 | import gzip
29 | import hashlib
30 | import httplib
31 | import inspect
32 | import itertools
33 | import logging
34 | import optparse
35 | import os
36 | import os.path
37 | import Queue
38 | import re
39 | import ssl
40 | import sys
41 | import threading
42 | import time
43 | import urllib
44 | import urllib2
45 | import urlparse
46 | import subprocess
47 | import functools
48 | import traceback
49 | import socket
50 | import textwrap
51 |
52 | try:
53 | import json
54 | except ImportError:
55 | try:
56 | import simplejson as json
57 | except ImportError:
58 | if sys.version_info < (2, 6):
59 | print >> sys.stderr, 'simplejson (http://pypi.python.org/pypi/simplejson/) is required.'
60 | sys.exit(1)
61 |
62 |
63 |
64 | ##
65 | ## Constants.
66 | ##
67 |
68 | STATIC_EXTENSIONS = set((
69 | 'gif jpg jpeg png bmp ico svg svgz ttf otf eot woff woff2 class swf css js xml robots.txt webp'
70 | ).split())
71 |
72 | DOWNLOAD_EXTENSIONS = set((
73 | '7z aac arc arj asf asx avi bin csv deb dmg doc docx exe flac flv gz gzip hqx '
74 | 'ibooks jar json mpg mp2 mp3 mp4 mpeg mov movie msi msp odb odf odg odp '
75 | 'ods odt ogg ogv pdf phps ppt pptx qt qtm ra ram rar rpm rtf sea sit tar tbz '
76 | 'bz2 tbz tgz torrent txt wav webm wma wmv wpd xls xlsx xml xsd z zip '
77 | 'azw3 epub mobi apk'
78 | ).split())
79 |
80 | # A good source is: http://phpbb-bots.blogspot.com/
81 | # user agents must be lowercase
82 | EXCLUDED_USER_AGENTS = (
83 | 'adsbot-google',
84 | 'ask jeeves',
85 | 'baidubot',
86 | 'bot-',
87 | 'bot/',
88 | 'ccooter/',
89 | 'crawl',
90 | 'curl',
91 | 'echoping',
92 | 'exabot',
93 | 'feed',
94 | 'googlebot',
95 | 'ia_archiver',
96 | 'java/',
97 | 'libwww',
98 | 'mediapartners-google',
99 | 'msnbot',
100 | 'netcraftsurvey',
101 | 'panopta',
102 | 'pingdom.com_bot_',
103 | 'robot',
104 | 'spider',
105 | 'surveybot',
106 | 'twiceler',
107 | 'voilabot',
108 | 'yahoo',
109 | 'yandex',
110 | )
111 |
112 | MATOMO_DEFAULT_MAX_ATTEMPTS = 3
113 | MATOMO_DEFAULT_DELAY_AFTER_FAILURE = 10
114 | DEFAULT_SOCKET_TIMEOUT = 300
115 |
116 | MATOMO_EXPECTED_IMAGE = base64.b64decode(
117 | 'R0lGODlhAQABAIAAAAAAAAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw=='
118 | )
119 |
120 | ##
121 | ## Formats.
122 | ##
123 |
124 | class BaseFormatException(Exception): pass
125 |
126 | class BaseFormat(object):
127 | def __init__(self, name):
128 | self.name = name
129 | self.regex = None
130 | self.date_format = '%d/%b/%Y:%H:%M:%S'
131 |
132 | def check_format(self, file):
133 | line = file.readline()
134 | try:
135 | file.seek(0)
136 | except IOError:
137 | pass
138 |
139 | return self.check_format_line(line)
140 |
141 | def check_format_line(self, line):
142 | return False
143 |
144 | class JsonFormat(BaseFormat):
145 | def __init__(self, name):
146 | super(JsonFormat, self).__init__(name)
147 | self.json = None
148 | self.date_format = '%Y-%m-%dT%H:%M:%S'
149 |
150 | def check_format_line(self, line):
151 | try:
152 | self.json = json.loads(line)
153 | return True
154 | except:
155 | return False
156 |
157 | def match(self, line):
158 | try:
159 | # nginx outputs malformed JSON w/ hex escapes when confronted w/ non-UTF input. we have to
160 | # workaround this by converting hex escapes in strings to unicode escapes. the conversion is naive,
161 | # so it does not take into account the string's actual encoding (which we don't have access to).
162 | line = line.replace('\\x', '\\u00')
163 |
164 | self.json = json.loads(line)
165 | return self
166 | except:
167 | self.json = None
168 | return None
169 |
170 | def get(self, key):
171 | # Some ugly patchs ...
172 | if key == 'generation_time_milli':
173 | self.json[key] = int(float(self.json[key]) * 1000)
174 | # Patch date format ISO 8601
175 | elif key == 'date':
176 | tz = self.json[key][19:]
177 | self.json['timezone'] = tz.replace(':', '')
178 | self.json[key] = self.json[key][:19]
179 |
180 | try:
181 | return self.json[key]
182 | except KeyError:
183 | raise BaseFormatException()
184 |
185 | def get_all(self,):
186 | return self.json
187 |
188 | def remove_ignored_groups(self, groups):
189 | for group in groups:
190 | del self.json[group]
191 |
192 | class RegexFormat(BaseFormat):
193 |
194 | def __init__(self, name, regex, date_format=None):
195 | super(RegexFormat, self).__init__(name)
196 | if regex is not None:
197 | self.regex = re.compile(regex)
198 | if date_format is not None:
199 | self.date_format = date_format
200 | self.matched = None
201 |
202 | def check_format_line(self, line):
203 | return self.match(line)
204 |
205 | def match(self,line):
206 | if not self.regex:
207 | return None
208 | match_result = self.regex.match(line)
209 | if match_result:
210 | self.matched = match_result.groupdict()
211 | else:
212 | self.matched = None
213 | return match_result
214 |
215 | def get(self, key):
216 | try:
217 | return self.matched[key]
218 | except KeyError:
219 | raise BaseFormatException("Cannot find group '%s'." % key)
220 |
221 | def get_all(self,):
222 | return self.matched
223 |
224 | def remove_ignored_groups(self, groups):
225 | for group in groups:
226 | del self.matched[group]
227 |
228 | class W3cExtendedFormat(RegexFormat):
229 |
230 | FIELDS_LINE_PREFIX = '#Fields: '
231 |
232 | fields = {
233 | 'date': '(?P\d+[-\d+]+',
234 | 'time': '[\d+:]+)[.\d]*?', # TODO should not assume date & time will be together not sure how to fix ATM.
235 | 'cs-uri-stem': '(?P/\S*)',
236 | 'cs-uri-query': '(?P\S*)',
237 | 'c-ip': '"?(?P[\w*.:-]*)"?',
238 | 'cs(User-Agent)': '(?P".*?"|\S*)',
239 | 'cs(Referer)': '(?P\S+)',
240 | 'sc-status': '(?P\d+)',
241 | 'sc-bytes': '(?P\S+)',
242 | 'cs-host': '(?P\S+)',
243 | 'cs-method': '(?P\S+)',
244 | 'cs-username': '(?P\S+)',
245 | 'time-taken': '(?P[.\d]+)'
246 | }
247 |
248 | def __init__(self):
249 | super(W3cExtendedFormat, self).__init__('w3c_extended', None, '%Y-%m-%d %H:%M:%S')
250 |
251 | def check_format(self, file):
252 | self.create_regex(file)
253 |
254 | # if we couldn't create a regex, this file does not follow the W3C extended log file format
255 | if not self.regex:
256 | try:
257 | file.seek(0)
258 | except IOError:
259 | pass
260 |
261 | return
262 |
263 | first_line = file.readline()
264 |
265 | try:
266 | file.seek(0)
267 | except IOError:
268 | pass
269 |
270 | return self.check_format_line(first_line)
271 |
272 | def create_regex(self, file):
273 | fields_line = None
274 | if config.options.w3c_fields:
275 | fields_line = config.options.w3c_fields
276 |
277 | # collect all header lines up until the Fields: line
278 | # if we're reading from stdin, we can't seek, so don't read any more than the Fields line
279 | header_lines = []
280 | while fields_line is None:
281 | line = file.readline().strip()
282 |
283 | if not line:
284 | continue
285 |
286 | if not line.startswith('#'):
287 | break
288 |
289 | if line.startswith(W3cExtendedFormat.FIELDS_LINE_PREFIX):
290 | fields_line = line
291 | else:
292 | header_lines.append(line)
293 |
294 | if not fields_line:
295 | return
296 |
297 | # store the header lines for a later check for IIS
298 | self.header_lines = header_lines
299 |
300 | # Parse the 'Fields: ' line to create the regex to use
301 | full_regex = []
302 |
303 | expected_fields = type(self).fields.copy() # turn custom field mapping into field => regex mapping
304 |
305 | # if the --w3c-time-taken-millisecs option is used, make sure the time-taken field is interpreted as milliseconds
306 | if config.options.w3c_time_taken_in_millisecs:
307 | expected_fields['time-taken'] = '(?P[\d.]+)'
308 |
309 | for mapped_field_name, field_name in config.options.custom_w3c_fields.iteritems():
310 | expected_fields[mapped_field_name] = expected_fields[field_name]
311 | del expected_fields[field_name]
312 |
313 | # add custom field regexes supplied through --w3c-field-regex option
314 | for field_name, field_regex in config.options.w3c_field_regexes.iteritems():
315 | expected_fields[field_name] = field_regex
316 |
317 | # Skip the 'Fields: ' prefix.
318 | fields_line = fields_line[9:].strip()
319 | for field in re.split('\s+', fields_line):
320 | try:
321 | regex = expected_fields[field]
322 | except KeyError:
323 | regex = '(?:".*?"|\S+)'
324 | full_regex.append(regex)
325 | full_regex = '\s+'.join(full_regex)
326 |
327 | logging.debug("Based on 'Fields:' line, computed regex to be %s", full_regex)
328 |
329 | self.regex = re.compile(full_regex)
330 |
331 | def check_for_iis_option(self):
332 | if not config.options.w3c_time_taken_in_millisecs and self._is_time_taken_milli() and self._is_iis():
333 | logging.info("WARNING: IIS log file being parsed without --w3c-time-taken-milli option. IIS"
334 | " stores millisecond values in the time-taken field. If your logfile does this, the aforementioned"
335 | " option must be used in order to get accurate generation times.")
336 |
337 | def _is_iis(self):
338 | return len([line for line in self.header_lines if 'internet information services' in line.lower() or 'iis' in line.lower()]) > 0
339 |
340 | def _is_time_taken_milli(self):
341 | return 'generation_time_milli' not in self.regex.pattern
342 |
343 | class IisFormat(W3cExtendedFormat):
344 |
345 | fields = W3cExtendedFormat.fields.copy()
346 | fields.update({
347 | 'time-taken': '(?P[.\d]+)',
348 | 'sc-win32-status': '(?P<__win32_status>\S+)' # this group is useless for log importing, but capturing it
349 | # will ensure we always select IIS for the format instead of
350 | # W3C logs when detecting the format. This way there will be
351 | # less accidental importing of IIS logs w/o --w3c-time-taken-milli.
352 | })
353 |
354 | def __init__(self):
355 | super(IisFormat, self).__init__()
356 |
357 | self.name = 'iis'
358 |
359 | class ShoutcastFormat(W3cExtendedFormat):
360 |
361 | fields = W3cExtendedFormat.fields.copy()
362 | fields.update({
363 | 'c-status': '(?P\d+)',
364 | 'x-duration': '(?P[.\d]+)'
365 | })
366 |
367 | def __init__(self):
368 | super(ShoutcastFormat, self).__init__()
369 |
370 | self.name = 'shoutcast'
371 |
372 | def get(self, key):
373 | if key == 'user_agent':
374 | user_agent = super(ShoutcastFormat, self).get(key)
375 | return urllib2.unquote(user_agent)
376 | else:
377 | return super(ShoutcastFormat, self).get(key)
378 |
379 | class AmazonCloudFrontFormat(W3cExtendedFormat):
380 |
381 | fields = W3cExtendedFormat.fields.copy()
382 | fields.update({
383 | 'x-event': '(?P\S+)',
384 | 'x-sname': '(?P\S+)',
385 | 'cs-uri-stem': '(?:rtmp:/)?(?P/\S*)',
386 | 'c-user-agent': '(?P".*?"|\S+)',
387 |
388 | # following are present to match cloudfront instead of W3C when we know it's cloudfront
389 | 'x-edge-location': '(?P".*?"|\S+)',
390 | 'x-edge-result-type': '(?P".*?"|\S+)',
391 | 'x-edge-request-id': '(?P".*?"|\S+)',
392 | 'x-host-header': '(?P".*?"|\S+)'
393 | })
394 |
395 | def __init__(self):
396 | super(AmazonCloudFrontFormat, self).__init__()
397 |
398 | self.name = 'amazon_cloudfront'
399 |
400 | def get(self, key):
401 | if key == 'event_category' and 'event_category' not in self.matched:
402 | return 'cloudfront_rtmp'
403 | elif key == 'status' and 'status' not in self.matched:
404 | return '200'
405 | elif key == 'user_agent':
406 | user_agent = super(AmazonCloudFrontFormat, self).get(key)
407 | return urllib2.unquote(user_agent)
408 | else:
409 | return super(AmazonCloudFrontFormat, self).get(key)
410 |
411 | _HOST_PREFIX = '(?P[\w\-\.]*)(?::\d+)?\s+'
412 |
413 | _COMMON_LOG_FORMAT = (
414 | '(?P[\w*.:-]+)\s+\S+\s+(?P\S+)\s+\[(?P.*?)\s+(?P.*?)\]\s+'
415 | '"(?P\S+)\s+(?P.*?)\s+\S+"\s+(?P\d+)\s+(?P\S+)'
416 | )
417 | _NCSA_EXTENDED_LOG_FORMAT = (_COMMON_LOG_FORMAT +
418 | '\s+"(?P.*?)"\s+"(?P.*?)"'
419 | )
420 | _S3_LOG_FORMAT = (
421 | '\S+\s+(?P\S+)\s+\[(?P.*?)\s+(?P.*?)\]\s+(?P[\w*.:-]+)\s+'
422 | '(?P\S+)\s+\S+\s+\S+\s+\S+\s+"(?P\S+)\s+(?P.*?)\s+\S+"\s+(?P\d+)\s+\S+\s+(?P\S+)\s+'
423 | '\S+\s+\S+\s+\S+\s+"(?P.*?)"\s+"(?P.*?)"'
424 | )
425 | _ICECAST2_LOG_FORMAT = ( _NCSA_EXTENDED_LOG_FORMAT +
426 | '\s+(?P[0-9-]+)'
427 | )
428 | _ELB_LOG_FORMAT = (
429 | '(?P[0-9-]+T[0-9:]+)\.\S+\s+\S+\s+(?P[\w*.:-]+):\d+\s+\S+:\d+\s+\S+\s+(?P\S+)\s+\S+\s+'
430 | '(?P\d+)\s+\S+\s+\S+\s+(?P\S+)\s+'
431 | '"\S+\s+\w+:\/\/(?P[\w\-\.]*):\d+(?P\/\S*)\s+[^"]+"\s+"(?P[^"]+)"\s+\S+\s+\S+'
432 | )
433 |
434 | _OVH_FORMAT = (
435 | '(?P\S+)\s+' + _HOST_PREFIX + '(?P\S+)\s+\[(?P.*?)\s+(?P.*?)\]\s+'
436 | '"\S+\s+(?P.*?)\s+\S+"\s+(?P\S+)\s+(?P\S+)'
437 | '\s+"(?P.*?)"\s+"(?P.*?)"'
438 | )
439 |
440 | FORMATS = {
441 | 'common': RegexFormat('common', _COMMON_LOG_FORMAT),
442 | 'common_vhost': RegexFormat('common_vhost', _HOST_PREFIX + _COMMON_LOG_FORMAT),
443 | 'ncsa_extended': RegexFormat('ncsa_extended', _NCSA_EXTENDED_LOG_FORMAT),
444 | 'common_complete': RegexFormat('common_complete', _HOST_PREFIX + _NCSA_EXTENDED_LOG_FORMAT),
445 | 'w3c_extended': W3cExtendedFormat(),
446 | 'amazon_cloudfront': AmazonCloudFrontFormat(),
447 | 'iis': IisFormat(),
448 | 'shoutcast': ShoutcastFormat(),
449 | 's3': RegexFormat('s3', _S3_LOG_FORMAT),
450 | 'icecast2': RegexFormat('icecast2', _ICECAST2_LOG_FORMAT),
451 | 'elb': RegexFormat('elb', _ELB_LOG_FORMAT, '%Y-%m-%dT%H:%M:%S'),
452 | 'nginx_json': JsonFormat('nginx_json'),
453 | 'ovh': RegexFormat('ovh', _OVH_FORMAT)
454 | }
455 |
456 | ##
457 | ## Code.
458 | ##
459 |
460 | class Configuration(object):
461 | """
462 | Stores all the configuration options by reading sys.argv and parsing,
463 | if needed, the config.inc.php.
464 |
465 | It has 2 attributes: options and filenames.
466 | """
467 |
468 | class Error(Exception):
469 | pass
470 |
471 | def _create_parser(self):
472 | """
473 | Initialize and return the OptionParser instance.
474 | """
475 | option_parser = optparse.OptionParser(
476 | usage='Usage: %prog [options] log_file [ log_file [...] ]',
477 | description="Import HTTP access logs to Matomo. "
478 | "log_file is the path to a server access log file (uncompressed, .gz, .bz2, or specify - to read from stdin). "
479 | " You may also import many log files at once (for example set log_file to *.log or *.log.gz)."
480 | " 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.",
481 | epilog="About Matomo Server Log Analytics: https://matomo.org/log-analytics/ "
482 | " Found a bug? Please create a ticket in https://dev.matomo.org/ "
483 | " Please send your suggestions or successful user story to hello@matomo.org "
484 | )
485 |
486 | # Basic auth user
487 | option_parser.add_option(
488 | '--auth-user', dest='auth_user',
489 | help="Basic auth user",
490 | )
491 | # Basic auth password
492 | option_parser.add_option(
493 | '--auth-password', dest='auth_password',
494 | help="Basic auth password",
495 | )
496 | option_parser.add_option(
497 | '--debug', '-d', dest='debug', action='count', default=0,
498 | help="Enable debug output (specify multiple times for more verbose)",
499 | )
500 | option_parser.add_option(
501 | '--debug-tracker', dest='debug_tracker', action='store_true', default=False,
502 | help="Appends &debug=1 to tracker requests and prints out the result so the tracker can be debugged. If "
503 | "using the log importer results in errors with the tracker or improperly recorded visits, this option can "
504 | "be used to find out what the tracker is doing wrong. To see debug tracker output, you must also set the "
505 | "[Tracker] debug_on_demand INI config to 1 in your Matomo's config.ini.php file."
506 | )
507 | option_parser.add_option(
508 | '--debug-request-limit', dest='debug_request_limit', type='int', default=None,
509 | help="Debug option that will exit after N requests are parsed. Can be used w/ --debug-tracker to limit the "
510 | "output of a large log file."
511 | )
512 | option_parser.add_option(
513 | '--url', dest='matomo_url',
514 | help="REQUIRED Your Matomo server URL, eg. http://example.com/matomo/ or http://analytics.example.net",
515 | )
516 | option_parser.add_option(
517 | '--api-url', dest='matomo_api_url',
518 | help="This URL will be used to send API requests (use it if your tracker URL differs from UI/API url), "
519 | "eg. http://other-example.com/matomo/ or http://analytics-api.example.net",
520 | )
521 | option_parser.add_option(
522 | '--dry-run', dest='dry_run',
523 | action='store_true', default=False,
524 | help="Perform a trial run with no tracking data being inserted into Matomo",
525 | )
526 | option_parser.add_option(
527 | '--show-progress', dest='show_progress',
528 | action='store_true', default=os.isatty(sys.stdout.fileno()),
529 | help="Print a progress report X seconds (default: 1, use --show-progress-delay to override)"
530 | )
531 | option_parser.add_option(
532 | '--show-progress-delay', dest='show_progress_delay',
533 | type='int', default=1,
534 | help="Change the default progress delay"
535 | )
536 | option_parser.add_option(
537 | '--add-sites-new-hosts', dest='add_sites_new_hosts',
538 | action='store_true', default=False,
539 | help="When a hostname is found in the log file, but not matched to any website "
540 | "in Matomo, automatically create a new website in Matomo with this hostname to "
541 | "import the logs"
542 | )
543 | option_parser.add_option(
544 | '--idsite', dest='site_id',
545 | help= ("When specified, "
546 | "data in the specified log files will be tracked for this Matomo site ID."
547 | " The script will not auto-detect the website based on the log line hostname (new websites will not be automatically created).")
548 | )
549 | option_parser.add_option(
550 | '--idsite-fallback', dest='site_id_fallback',
551 | help="Default Matomo site ID to use if the hostname doesn't match any "
552 | "known Website's URL. New websites will not be automatically created. "
553 | " Used only if --add-sites-new-hosts or --idsite are not set",
554 | )
555 | default_config = os.path.abspath(
556 | os.path.join(os.path.dirname(__file__),
557 | '../../config/config.ini.php'),
558 | )
559 | option_parser.add_option(
560 | '--config', dest='config_file', default=default_config,
561 | help=(
562 | "This is only used when --login and --password is not used. "
563 | "Matomo will read the configuration file (default: %default) to "
564 | "fetch the Super User token_auth from the config file. "
565 | )
566 | )
567 | option_parser.add_option(
568 | '--login', dest='login',
569 | help="You can manually specify the Matomo Super User login"
570 | )
571 | option_parser.add_option(
572 | '--password', dest='password',
573 | help="You can manually specify the Matomo Super User password"
574 | )
575 | option_parser.add_option(
576 | '--token-auth', dest='matomo_token_auth',
577 | help="Matomo user token_auth, the token_auth is found in Matomo > Settings > API. "
578 | "You must use a token_auth that has at least 'admin' or 'super user' permission. "
579 | "If you use a token_auth for a non admin user, your users' IP addresses will not be tracked properly. "
580 | )
581 |
582 | option_parser.add_option(
583 | '--hostname', dest='hostnames', action='append', default=[],
584 | help="Accepted hostname (requests with other hostnames will be excluded). "
585 | " You may use the star character * "
586 | " Example: --hostname=*domain.com"
587 | " Can be specified multiple times"
588 | )
589 | option_parser.add_option(
590 | '--exclude-path', dest='excluded_paths', action='append', default=[],
591 | help="Any URL path matching this exclude-path will not be imported in Matomo. "
592 | " You must use the star character *. "
593 | " Example: --exclude-path=*/admin/*"
594 | " Can be specified multiple times. "
595 | )
596 | option_parser.add_option(
597 | '--exclude-path-from', dest='exclude_path_from',
598 | help="Each line from this file is a path to exclude. Each path must contain the character * to match a string. (see: --exclude-path)"
599 | )
600 | option_parser.add_option(
601 | '--include-path', dest='included_paths', action='append', default=[],
602 | help="Paths to include. Can be specified multiple times. If not specified, all paths are included."
603 | )
604 | option_parser.add_option(
605 | '--include-path-from', dest='include_path_from',
606 | help="Each line from this file is a path to include"
607 | )
608 | option_parser.add_option(
609 | '--useragent-exclude', dest='excluded_useragents',
610 | action='append', default=[],
611 | help="User agents to exclude (in addition to the standard excluded "
612 | "user agents). Can be specified multiple times",
613 | )
614 | option_parser.add_option(
615 | '--enable-static', dest='enable_static',
616 | action='store_true', default=False,
617 | help="Track static files (images, css, js, ico, ttf, etc.)"
618 | )
619 | option_parser.add_option(
620 | '--enable-bots', dest='enable_bots',
621 | action='store_true', default=False,
622 | help="Track bots. All bot visits will have a Custom Variable set with name='Bot' and value='$Bot_user_agent_here$'"
623 | )
624 | option_parser.add_option(
625 | '--enable-http-errors', dest='enable_http_errors',
626 | action='store_true', default=False,
627 | help="Track HTTP errors (status code 4xx or 5xx)"
628 | )
629 | option_parser.add_option(
630 | '--enable-http-redirects', dest='enable_http_redirects',
631 | action='store_true', default=False,
632 | help="Track HTTP redirects (status code 3xx except 304)"
633 | )
634 | option_parser.add_option(
635 | '--enable-reverse-dns', dest='reverse_dns',
636 | action='store_true', default=False,
637 | help="Enable reverse DNS, used to generate the 'Providers' report in Matomo. "
638 | "Disabled by default, as it impacts performance"
639 | )
640 | option_parser.add_option(
641 | '--strip-query-string', dest='strip_query_string',
642 | action='store_true', default=False,
643 | help="Strip the query string from the URL"
644 | )
645 | option_parser.add_option(
646 | '--query-string-delimiter', dest='query_string_delimiter', default='?',
647 | help="The query string delimiter (default: %default)"
648 | )
649 | option_parser.add_option(
650 | '--log-format-name', dest='log_format_name', default=None,
651 | help=("Access log format to detect (supported are: %s). "
652 | "When not specified, the log format will be autodetected by trying all supported log formats."
653 | % ', '.join(sorted(FORMATS.iterkeys())))
654 | )
655 | available_regex_groups = ['date', 'path', 'query_string', 'ip', 'user_agent', 'referrer', 'status',
656 | 'length', 'host', 'userid', 'generation_time_milli', 'event_action',
657 | 'event_name', 'timezone', 'session_time']
658 | option_parser.add_option(
659 | '--log-format-regex', dest='log_format_regex', default=None,
660 | help="Regular expression used to parse log entries. Regexes must contain named groups for different log fields. "
661 | "Recognized fields include: %s. For an example of a supported Regex, see the source code of this file. "
662 | "Overrides --log-format-name." % (', '.join(available_regex_groups))
663 | )
664 | option_parser.add_option(
665 | '--log-date-format', dest='log_date_format', default=None,
666 | help="Format string used to parse dates. You can specify any format that can also be specified to "
667 | "the strptime python function."
668 | )
669 | option_parser.add_option(
670 | '--log-hostname', dest='log_hostname', default=None,
671 | help="Force this hostname for a log format that doesn't include it. All hits "
672 | "will seem to come to this host"
673 | )
674 | option_parser.add_option(
675 | '--skip', dest='skip', default=0, type='int',
676 | help="Skip the n first lines to start parsing/importing data at a given line for the specified log file",
677 | )
678 | option_parser.add_option(
679 | '--recorders', dest='recorders', default=1, type='int',
680 | help="Number of simultaneous recorders (default: %default). "
681 | "It should be set to the number of CPU cores in your server. "
682 | "You can also experiment with higher values which may increase performance until a certain point",
683 | )
684 | option_parser.add_option(
685 | '--recorder-max-payload-size', dest='recorder_max_payload_size', default=200, type='int',
686 | help="Maximum number of log entries to record in one tracking request (default: %default). "
687 | )
688 | option_parser.add_option(
689 | '--replay-tracking', dest='replay_tracking',
690 | action='store_true', default=False,
691 | help="Replay piwik.php requests found in custom logs (only piwik.php requests expected). \nSee https://matomo.org/faq/how-to/faq_17033/"
692 | )
693 | option_parser.add_option(
694 | '--replay-tracking-expected-tracker-file', dest='replay_tracking_expected_tracker_file', default='piwik.php',
695 | help="The expected suffix for tracking request paths. Only logs whose paths end with this will be imported. Defaults "
696 | "to 'piwik.php' so only requests to the piwik.php file will be imported."
697 | )
698 | option_parser.add_option(
699 | '--output', dest='output',
700 | help="Redirect output (stdout and stderr) to the specified file"
701 | )
702 | option_parser.add_option(
703 | '--encoding', dest='encoding', default='utf8',
704 | help="Log files encoding (default: %default)"
705 | )
706 | option_parser.add_option(
707 | '--disable-bulk-tracking', dest='use_bulk_tracking',
708 | default=True, action='store_false',
709 | help="Disables use of bulk tracking so recorders record one hit at a time."
710 | )
711 | option_parser.add_option(
712 | '--debug-force-one-hit-every-Ns', dest='force_one_action_interval', default=False, type='float',
713 | help="Debug option that will force each recorder to record one hit every N secs."
714 | )
715 | option_parser.add_option(
716 | '--force-lowercase-path', dest='force_lowercase_path', default=False, action='store_true',
717 | help="Make URL path lowercase so paths with the same letters but different cases are "
718 | "treated the same."
719 | )
720 | option_parser.add_option(
721 | '--enable-testmode', dest='enable_testmode', default=False, action='store_true',
722 | help="If set, it will try to get the token_auth from the matomo_tests directory"
723 | )
724 | option_parser.add_option(
725 | '--download-extensions', dest='download_extensions', default=None,
726 | 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."
727 | )
728 | option_parser.add_option(
729 | '--add-download-extensions', dest='extra_download_extensions', default=None,
730 | help="Add extensions that should be treated as downloads. See --download-extensions for more info."
731 | )
732 | option_parser.add_option(
733 | '--w3c-map-field', action='callback', callback=functools.partial(self._set_option_map, 'custom_w3c_fields'), type='string',
734 | help="Map a custom log entry field in your W3C log to a default one. Use this option to load custom log "
735 | "files that use the W3C extended log format such as those from the Advanced Logging W3C module. Used "
736 | "as, eg, --w3c-map-field my-date=date. Recognized default fields include: %s\n\n"
737 | "Formats that extend the W3C extended log format (like the cloudfront RTMP log format) may define more "
738 | "fields that can be mapped."
739 | % (', '.join(W3cExtendedFormat.fields.keys()))
740 | )
741 | option_parser.add_option(
742 | '--w3c-time-taken-millisecs', action='store_true', default=False, dest='w3c_time_taken_in_millisecs',
743 | help="If set, interprets the time-taken W3C log field as a number of milliseconds. This must be set for importing"
744 | " IIS logs."
745 | )
746 | option_parser.add_option(
747 | '--w3c-fields', dest='w3c_fields', default=None,
748 | help="Specify the '#Fields:' line for a log file in the W3C Extended log file format. Use this option if "
749 | "your log file doesn't contain the '#Fields:' line which is required for parsing. This option must be used "
750 | "in conjuction with --log-format-name=w3c_extended.\n"
751 | "Example: --w3c-fields='#Fields: date time c-ip ...'"
752 | )
753 | option_parser.add_option(
754 | '--w3c-field-regex', action='callback', callback=functools.partial(self._set_option_map, 'w3c_field_regexes'), type='string',
755 | help="Specify a regex for a field in your W3C extended log file. You can use this option to parse fields the "
756 | "importer does not natively recognize and then use one of the --regex-group-to-XXX-cvar options to track "
757 | "the field in a custom variable. For example, specifying --w3c-field-regex=sc-win32-status=(?P\\S+) "
758 | "--regex-group-to-page-cvar=\"win32_status=Windows Status Code\" will track the sc-win32-status IIS field "
759 | "in the 'Windows Status Code' custom variable. Regexes must contain a named group."
760 | )
761 | option_parser.add_option(
762 | '--title-category-delimiter', dest='title_category_delimiter', default='/',
763 | help="If --enable-http-errors is used, errors are shown in the page titles report. If you have "
764 | "changed General.action_title_category_delimiter in your Matomo configuration, you need to set this "
765 | "option to the same value in order to get a pretty page titles report."
766 | )
767 | option_parser.add_option(
768 | '--dump-log-regex', dest='dump_log_regex', action='store_true', default=False,
769 | help="Prints out the regex string used to parse log lines and exists. Can be useful for using formats "
770 | "in newer versions of the script in older versions of the script. The output regex can be used with "
771 | "the --log-format-regex option."
772 | )
773 |
774 | option_parser.add_option(
775 | '--ignore-groups', dest='regex_groups_to_ignore', default=None,
776 | help="Comma separated list of regex groups to ignore when parsing log lines. Can be used to, for example, "
777 | "disable normal user id tracking. See documentation for --log-format-regex for list of available "
778 | "regex groups."
779 | )
780 |
781 | option_parser.add_option(
782 | '--regex-group-to-visit-cvar', action='callback', callback=functools.partial(self._set_option_map, 'regex_group_to_visit_cvars_map'), type='string',
783 | help="Track an attribute through a custom variable with visit scope instead of through Matomo's normal "
784 | "approach. For example, to track usernames as a custom variable instead of through the uid tracking "
785 | "parameter, supply --regex-group-to-visit-cvar=\"userid=User Name\". This will track usernames in a "
786 | "custom variable named 'User Name'. The list of available regex groups can be found in the documentation "
787 | "for --log-format-regex (additional regex groups you may have defined "
788 | "in --log-format-regex can also be used)."
789 | )
790 | option_parser.add_option(
791 | '--regex-group-to-page-cvar', action='callback', callback=functools.partial(self._set_option_map, 'regex_group_to_page_cvars_map'), type='string',
792 | help="Track an attribute through a custom variable with page scope instead of through Matomo's normal "
793 | "approach. For example, to track usernames as a custom variable instead of through the uid tracking "
794 | "parameter, supply --regex-group-to-page-cvar=\"userid=User Name\". This will track usernames in a "
795 | "custom variable named 'User Name'. The list of available regex groups can be found in the documentation "
796 | "for --log-format-regex (additional regex groups you may have defined "
797 | "in --log-format-regex can also be used)."
798 | )
799 | option_parser.add_option(
800 | '--track-http-method', dest='track_http_method', default=False,
801 | help="Enables tracking of http method as custom page variable if method group is available in log format."
802 | )
803 | option_parser.add_option(
804 | '--retry-max-attempts', dest='max_attempts', default=MATOMO_DEFAULT_MAX_ATTEMPTS, type='int',
805 | help="The maximum number of times to retry a failed tracking request."
806 | )
807 | option_parser.add_option(
808 | '--retry-delay', dest='delay_after_failure', default=MATOMO_DEFAULT_DELAY_AFTER_FAILURE, type='int',
809 | help="The number of seconds to wait before retrying a failed tracking request."
810 | )
811 | option_parser.add_option(
812 | '--request-timeout', dest='request_timeout', default=DEFAULT_SOCKET_TIMEOUT, type='int',
813 | help="The maximum number of seconds to wait before terminating an HTTP request to Matomo."
814 | )
815 | option_parser.add_option(
816 | '--include-host', action='callback', type='string', callback=functools.partial(self._add_to_array, 'include_host'),
817 | help="Only import logs from the specified host(s)."
818 | )
819 | option_parser.add_option(
820 | '--exclude-host', action='callback', type='string', callback=functools.partial(self._add_to_array, 'exclude_host'),
821 | help="Only import logs that are not from the specified host(s)."
822 | )
823 | option_parser.add_option(
824 | '--exclude-older-than', action='callback', type='string', default=None, callback=functools.partial(self._set_date, 'exclude_older_than'),
825 | help="Ignore logs older than the specified date. Exclusive. Date format must be YYYY-MM-DD hh:mm:ss +/-0000. The timezone offset is required."
826 | )
827 | option_parser.add_option(
828 | '--exclude-newer-than', action='callback', type='string', default=None, callback=functools.partial(self._set_date, 'exclude_newer_than'),
829 | help="Ignore logs newer than the specified date. Exclusive. Date format must be YYYY-MM-DD hh:mm:ss +/-0000. The timezone offset is required."
830 | )
831 | option_parser.add_option(
832 | '--add-to-date', dest='seconds_to_add_to_date', default=0, type='int',
833 | help="A number of seconds to add to each date value in the log file."
834 | )
835 | option_parser.add_option(
836 | '--request-suffix', dest='request_suffix', default=None, type='string', help="Extra parameters to append to tracker and API requests."
837 | )
838 | option_parser.add_option(
839 | '--accept-invalid-ssl-certificate',
840 | dest='accept_invalid_ssl_certificate', action='store_true',
841 | default=False,
842 | help="Do not verify the SSL / TLS certificate when contacting the Matomo server. This is the default when running on Python 2.7.8 or older."
843 | )
844 | return option_parser
845 |
846 | def _set_date(self, option_attr_name, option, opt_str, value, parser):
847 | try:
848 | (date_str, timezone) = value.rsplit(' ', 1)
849 | except:
850 | fatal_error("Invalid date value '%s'." % value)
851 |
852 | if not re.match('[-+][0-9]{4}', timezone):
853 | fatal_error("Invalid date value '%s': expected valid timzeone like +0100 or -1200, got '%s'" % (value, timezone))
854 |
855 | timezone = float(timezone)
856 |
857 | date = datetime.datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
858 | date -= datetime.timedelta(hours=timezone/100)
859 |
860 | setattr(parser.values, option_attr_name, date)
861 |
862 | def _add_to_array(self, option_attr_name, option, opt_str, value, parser):
863 | if not hasattr(parser.values, option_attr_name) or not getattr(parser.values, option_attr_name):
864 | setattr(parser.values, option_attr_name, [])
865 | getattr(parser.values, option_attr_name).append(value)
866 |
867 | def _set_option_map(self, option_attr_name, option, opt_str, value, parser):
868 | """
869 | Sets a key-value mapping in a dict that is built from command line options. Options that map
870 | string keys to string values (like --w3c-map-field) can set the callback to a bound partial
871 | of this method to handle the option.
872 | """
873 |
874 | parts = value.split('=')
875 |
876 | if len(parts) != 2:
877 | fatal_error("Invalid %s option: '%s'" % (opt_str, value))
878 |
879 | key, value = parts
880 |
881 | if not hasattr(parser.values, option_attr_name):
882 | setattr(parser.values, option_attr_name, {})
883 |
884 | getattr(parser.values, option_attr_name)[key] = value
885 |
886 | def _parse_args(self, option_parser):
887 | """
888 | Parse the command line args and create self.options and self.filenames.
889 | """
890 | self.options, self.filenames = option_parser.parse_args(sys.argv[1:])
891 |
892 | if self.options.output:
893 | sys.stdout = sys.stderr = open(self.options.output, 'a+', 0)
894 |
895 | if not self.filenames:
896 | print(option_parser.format_help())
897 | sys.exit(1)
898 |
899 | # Configure logging before calling logging.{debug,info}.
900 | logging.basicConfig(
901 | format='%(asctime)s: [%(levelname)s] %(message)s',
902 | level=logging.DEBUG if self.options.debug >= 1 else logging.INFO,
903 | )
904 |
905 | self.options.excluded_useragents = set([s.lower() for s in self.options.excluded_useragents])
906 |
907 | if self.options.exclude_path_from:
908 | paths = [path.strip() for path in open(self.options.exclude_path_from).readlines()]
909 | self.options.excluded_paths.extend(path for path in paths if len(path) > 0)
910 | if self.options.excluded_paths:
911 | self.options.excluded_paths = set(self.options.excluded_paths)
912 | logging.debug('Excluded paths: %s', ' '.join(self.options.excluded_paths))
913 |
914 | if self.options.include_path_from:
915 | paths = [path.strip() for path in open(self.options.include_path_from).readlines()]
916 | self.options.included_paths.extend(path for path in paths if len(path) > 0)
917 | if self.options.included_paths:
918 | self.options.included_paths = set(self.options.included_paths)
919 | logging.debug('Included paths: %s', ' '.join(self.options.included_paths))
920 |
921 | if self.options.hostnames:
922 | logging.debug('Accepted hostnames: %s', ', '.join(self.options.hostnames))
923 | else:
924 | logging.debug('Accepted hostnames: all')
925 |
926 | if self.options.log_format_regex:
927 | self.format = RegexFormat('custom', self.options.log_format_regex, self.options.log_date_format)
928 | elif self.options.log_format_name:
929 | try:
930 | self.format = FORMATS[self.options.log_format_name]
931 | except KeyError:
932 | fatal_error('invalid log format: %s' % self.options.log_format_name)
933 | else:
934 | self.format = None
935 |
936 | if not hasattr(self.options, 'custom_w3c_fields'):
937 | self.options.custom_w3c_fields = {}
938 | elif self.format is not None:
939 | # validate custom field mappings
940 | for custom_name, default_name in self.options.custom_w3c_fields.iteritems():
941 | if default_name not in type(format).fields:
942 | fatal_error("custom W3C field mapping error: don't know how to parse and use the '%' field" % default_name)
943 | return
944 |
945 | if not hasattr(self.options, 'regex_group_to_visit_cvars_map'):
946 | self.options.regex_group_to_visit_cvars_map = {}
947 |
948 | if not hasattr(self.options, 'regex_group_to_page_cvars_map'):
949 | self.options.regex_group_to_page_cvars_map = {}
950 |
951 | if not hasattr(self.options, 'w3c_field_regexes'):
952 | self.options.w3c_field_regexes = {}
953 | else:
954 | # make sure each custom w3c field regex has a named group
955 | for field_name, field_regex in self.options.w3c_field_regexes.iteritems():
956 | if '(?P<' not in field_regex:
957 | fatal_error("cannot find named group in custom w3c field regex '%s' for field '%s'" % (field_regex, field_name))
958 | return
959 |
960 | if not self.options.matomo_url:
961 | fatal_error('no URL given for Matomo')
962 |
963 | if not (self.options.matomo_url.startswith('http://') or self.options.matomo_url.startswith('https://')):
964 | self.options.matomo_url = 'http://' + self.options.matomo_url
965 | logging.debug('Matomo Tracker API URL is: %s', self.options.matomo_url)
966 |
967 | if not self.options.matomo_api_url:
968 | self.options.matomo_api_url = self.options.matomo_url
969 |
970 | if not (self.options.matomo_api_url.startswith('http://') or self.options.matomo_api_url.startswith('https://')):
971 | self.options.matomo_api_url = 'http://' + self.options.matomo_api_url
972 | logging.debug('Matomo Analytics API URL is: %s', self.options.matomo_api_url)
973 |
974 | if self.options.recorders < 1:
975 | self.options.recorders = 1
976 |
977 | download_extensions = DOWNLOAD_EXTENSIONS
978 | if self.options.download_extensions:
979 | download_extensions = set(self.options.download_extensions.split(','))
980 |
981 | if self.options.extra_download_extensions:
982 | download_extensions.update(self.options.extra_download_extensions.split(','))
983 | self.options.download_extensions = download_extensions
984 |
985 | if self.options.regex_groups_to_ignore:
986 | self.options.regex_groups_to_ignore = set(self.options.regex_groups_to_ignore.split(','))
987 |
988 | def __init__(self):
989 | self._parse_args(self._create_parser())
990 |
991 | def _get_token_auth(self):
992 | """
993 | If the token auth is not specified in the options, get it from Matomo.
994 | """
995 | # Get superuser login/password from the options.
996 | logging.debug('No token-auth specified')
997 |
998 | if self.options.login and self.options.password:
999 | matomo_login = self.options.login
1000 | matomo_password = hashlib.md5(self.options.password).hexdigest()
1001 |
1002 | logging.debug('Using credentials: (login = %s, password = %s)', matomo_login, matomo_password)
1003 | try:
1004 | api_result = matomo.call_api('UsersManager.getTokenAuth',
1005 | userLogin=matomo_login,
1006 | md5Password=matomo_password,
1007 | _token_auth='',
1008 | _url=self.options.matomo_api_url,
1009 | )
1010 | except urllib2.URLError as e:
1011 | fatal_error('error when fetching token_auth from the API: %s' % e)
1012 |
1013 | try:
1014 | return api_result['value']
1015 | except KeyError:
1016 | # Happens when the credentials are invalid.
1017 | message = api_result.get('message')
1018 | fatal_error(
1019 | 'error fetching authentication token token_auth%s' % (
1020 | ': %s' % message if message else '')
1021 | )
1022 | else:
1023 | # Fallback to the given (or default) configuration file, then
1024 | # get the token from the API.
1025 | logging.debug(
1026 | 'No credentials specified, reading them from "%s"',
1027 | self.options.config_file,
1028 | )
1029 | config_file = ConfigParser.RawConfigParser()
1030 | success = len(config_file.read(self.options.config_file)) > 0
1031 | if not success:
1032 | fatal_error(
1033 | "the configuration file" + self.options.config_file + " could not be read. Please check permission. This file must be readable by the user running this script to get the authentication token"
1034 | )
1035 |
1036 | updatetokenfile = os.path.abspath(
1037 | os.path.join(os.path.dirname(__file__),
1038 | '../../misc/cron/updatetoken.php'),
1039 | )
1040 |
1041 | phpBinary = 'php'
1042 |
1043 | is_windows = sys.platform.startswith('win')
1044 | if is_windows:
1045 | try:
1046 | processWin = subprocess.Popen('where php.exe', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1047 | [stdout, stderr] = processWin.communicate()
1048 | if processWin.returncode == 0:
1049 | phpBinary = stdout.strip()
1050 | else:
1051 | fatal_error("We couldn't detect PHP. It might help to add your php.exe to the path or alternatively run the importer using the --login and --password option")
1052 | except:
1053 | fatal_error("We couldn't detect PHP. You can run the importer using the --login and --password option to fix this issue")
1054 |
1055 | command = [phpBinary, updatetokenfile]
1056 | if self.options.enable_testmode:
1057 | command.append('--testmode')
1058 |
1059 | hostname = urlparse.urlparse( self.options.matomo_url ).hostname
1060 | command.append('--piwik-domain=' + hostname )
1061 |
1062 | command = subprocess.list2cmdline(command)
1063 |
1064 | # logging.debug(command);
1065 |
1066 | process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
1067 | [stdout, stderr] = process.communicate()
1068 | if process.returncode != 0:
1069 | fatal_error("`" + command + "` failed with error: " + stderr + ".\nReponse code was: " + str(process.returncode) + ". You can alternatively run the importer using the --login and --password option")
1070 |
1071 | filename = stdout
1072 | credentials = open(filename, 'r').readline()
1073 | credentials = credentials.split('\t')
1074 | return credentials[1]
1075 |
1076 | def get_resolver(self):
1077 | if self.options.site_id:
1078 | logging.debug('Resolver: static')
1079 | return StaticResolver(self.options.site_id)
1080 | else:
1081 | logging.debug('Resolver: dynamic')
1082 | return DynamicResolver()
1083 |
1084 | def init_token_auth(self):
1085 | if not self.options.matomo_token_auth:
1086 | try:
1087 | self.options.matomo_token_auth = self._get_token_auth()
1088 | except Matomo.Error as e:
1089 | fatal_error(e)
1090 | logging.debug('Authentication token token_auth is: %s', self.options.matomo_token_auth)
1091 |
1092 |
1093 | class Statistics(object):
1094 | """
1095 | Store statistics about parsed logs and recorded entries.
1096 | Can optionally print statistics on standard output every second.
1097 | """
1098 |
1099 | class Counter(object):
1100 | """
1101 | Simple integers cannot be used by multithreaded programs. See:
1102 | http://stackoverflow.com/questions/6320107/are-python-ints-thread-safe
1103 | """
1104 | def __init__(self):
1105 | # itertools.count's implementation in C does not release the GIL and
1106 | # therefore is thread-safe.
1107 | self.counter = itertools.count(1)
1108 | self.value = 0
1109 |
1110 | def increment(self):
1111 | self.value = self.counter.next()
1112 |
1113 | def advance(self, n):
1114 | for i in range(n):
1115 | self.increment()
1116 |
1117 | def __str__(self):
1118 | return str(int(self.value))
1119 |
1120 | def __init__(self):
1121 | self.time_start = None
1122 | self.time_stop = None
1123 |
1124 | self.matomo_sites = set() # sites ID
1125 | self.matomo_sites_created = [] # (hostname, site ID)
1126 | self.matomo_sites_ignored = set() # hostname
1127 |
1128 | self.count_lines_parsed = self.Counter()
1129 | self.count_lines_recorded = self.Counter()
1130 |
1131 | # requests that the Matomo tracker considered invalid (or failed to track)
1132 | self.invalid_lines = []
1133 |
1134 | # Do not match the regexp.
1135 | self.count_lines_invalid = self.Counter()
1136 | # Were filtered out.
1137 | self.count_lines_filtered = self.Counter()
1138 | # No site ID found by the resolver.
1139 | self.count_lines_no_site = self.Counter()
1140 | # Hostname filtered by config.options.hostnames
1141 | self.count_lines_hostname_skipped = self.Counter()
1142 | # Static files.
1143 | self.count_lines_static = self.Counter()
1144 | # Ignored user-agents.
1145 | self.count_lines_skipped_user_agent = self.Counter()
1146 | # Ignored HTTP erors.
1147 | self.count_lines_skipped_http_errors = self.Counter()
1148 | # Ignored HTTP redirects.
1149 | self.count_lines_skipped_http_redirects = self.Counter()
1150 | # Downloads
1151 | self.count_lines_downloads = self.Counter()
1152 | # Ignored downloads when --download-extensions is used
1153 | self.count_lines_skipped_downloads = self.Counter()
1154 |
1155 | # Misc
1156 | self.dates_recorded = set()
1157 | self.monitor_stop = False
1158 |
1159 | def set_time_start(self):
1160 | self.time_start = time.time()
1161 |
1162 | def set_time_stop(self):
1163 | self.time_stop = time.time()
1164 |
1165 | def _compute_speed(self, value, start, end):
1166 | delta_time = end - start
1167 | if value == 0:
1168 | return 0
1169 | if delta_time == 0:
1170 | return 'very high!'
1171 | else:
1172 | return value / delta_time
1173 |
1174 | def _round_value(self, value, base=100):
1175 | return round(value * base) / base
1176 |
1177 | def _indent_text(self, lines, level=1):
1178 | """
1179 | Return an indented text. 'lines' can be a list of lines or a single
1180 | line (as a string). One level of indentation is 4 spaces.
1181 | """
1182 | prefix = ' ' * (4 * level)
1183 | if isinstance(lines, basestring):
1184 | return prefix + lines
1185 | else:
1186 | return '\n'.join(
1187 | prefix + line
1188 | for line in lines
1189 | )
1190 |
1191 | def print_summary(self):
1192 | invalid_lines_summary = ''
1193 | if self.invalid_lines:
1194 | invalid_lines_summary = '''Invalid log lines
1195 | -----------------
1196 |
1197 | The following lines were not tracked by Matomo, either due to a malformed tracker request or error in the tracker:
1198 |
1199 | %s
1200 |
1201 | ''' % textwrap.fill(", ".join(self.invalid_lines), 80)
1202 |
1203 | print('''
1204 | %(invalid_lines)sLogs import summary
1205 | -------------------
1206 |
1207 | %(count_lines_recorded)d requests imported successfully
1208 | %(count_lines_downloads)d requests were downloads
1209 | %(total_lines_ignored)d requests ignored:
1210 | %(count_lines_skipped_http_errors)d HTTP errors
1211 | %(count_lines_skipped_http_redirects)d HTTP redirects
1212 | %(count_lines_invalid)d invalid log lines
1213 | %(count_lines_filtered)d filtered log lines
1214 | %(count_lines_no_site)d requests did not match any known site
1215 | %(count_lines_hostname_skipped)d requests did not match any --hostname
1216 | %(count_lines_skipped_user_agent)d requests done by bots, search engines...
1217 | %(count_lines_static)d requests to static resources (css, js, images, ico, ttf...)
1218 | %(count_lines_skipped_downloads)d requests to file downloads did not match any --download-extensions
1219 |
1220 | Website import summary
1221 | ----------------------
1222 |
1223 | %(count_lines_recorded)d requests imported to %(total_sites)d sites
1224 | %(total_sites_existing)d sites already existed
1225 | %(total_sites_created)d sites were created:
1226 | %(sites_created)s
1227 | %(total_sites_ignored)d distinct hostnames did not match any existing site:
1228 | %(sites_ignored)s
1229 | %(sites_ignored_tips)s
1230 |
1231 | Performance summary
1232 | -------------------
1233 |
1234 | Total time: %(total_time)d seconds
1235 | Requests imported per second: %(speed_recording)s requests per second
1236 |
1237 | Processing your log data
1238 | ------------------------
1239 |
1240 | In order for your logs to be processed by Matomo, you may need to run the following command:
1241 | ./console core:archive --force-all-websites --force-all-periods=315576000 --force-date-last-n=1000 --url='%(url)s'
1242 | ''' % {
1243 |
1244 | 'count_lines_recorded': self.count_lines_recorded.value,
1245 | 'count_lines_downloads': self.count_lines_downloads.value,
1246 | 'total_lines_ignored': sum([
1247 | self.count_lines_invalid.value,
1248 | self.count_lines_filtered.value,
1249 | self.count_lines_skipped_user_agent.value,
1250 | self.count_lines_skipped_http_errors.value,
1251 | self.count_lines_skipped_http_redirects.value,
1252 | self.count_lines_static.value,
1253 | self.count_lines_skipped_downloads.value,
1254 | self.count_lines_no_site.value,
1255 | self.count_lines_hostname_skipped.value,
1256 | ]),
1257 | 'count_lines_invalid': self.count_lines_invalid.value,
1258 | 'count_lines_filtered': self.count_lines_filtered.value,
1259 | 'count_lines_skipped_user_agent': self.count_lines_skipped_user_agent.value,
1260 | 'count_lines_skipped_http_errors': self.count_lines_skipped_http_errors.value,
1261 | 'count_lines_skipped_http_redirects': self.count_lines_skipped_http_redirects.value,
1262 | 'count_lines_static': self.count_lines_static.value,
1263 | 'count_lines_skipped_downloads': self.count_lines_skipped_downloads.value,
1264 | 'count_lines_no_site': self.count_lines_no_site.value,
1265 | 'count_lines_hostname_skipped': self.count_lines_hostname_skipped.value,
1266 | 'total_sites': len(self.matomo_sites),
1267 | 'total_sites_existing': len(self.matomo_sites - set(site_id for hostname, site_id in self.matomo_sites_created)),
1268 | 'total_sites_created': len(self.matomo_sites_created),
1269 | 'sites_created': self._indent_text(
1270 | ['%s (ID: %d)' % (hostname, site_id) for hostname, site_id in self.matomo_sites_created],
1271 | level=3,
1272 | ),
1273 | 'total_sites_ignored': len(self.matomo_sites_ignored),
1274 | 'sites_ignored': self._indent_text(
1275 | self.matomo_sites_ignored, level=3,
1276 | ),
1277 | 'sites_ignored_tips': '''
1278 | TIPs:
1279 | - if one of these hosts is an alias host for one of the websites
1280 | in Matomo, you can add this host as an "Alias URL" in Settings > Websites.
1281 | - use --add-sites-new-hosts if you wish to automatically create
1282 | one website for each of these hosts in Matomo rather than discarding
1283 | these requests.
1284 | - use --idsite-fallback to force all these log lines with a new hostname
1285 | to be recorded in a specific idsite (for example for troubleshooting/visualizing the data)
1286 | - use --idsite to force all lines in the specified log files
1287 | to be all recorded in the specified idsite
1288 | - or you can also manually create a new Website in Matomo with the URL set to this hostname
1289 | ''' if self.matomo_sites_ignored else '',
1290 | 'total_time': self.time_stop - self.time_start,
1291 | 'speed_recording': self._round_value(self._compute_speed(
1292 | self.count_lines_recorded.value,
1293 | self.time_start, self.time_stop,
1294 | )),
1295 | 'url': config.options.matomo_api_url,
1296 | 'invalid_lines': invalid_lines_summary
1297 | })
1298 |
1299 | ##
1300 | ## The monitor is a thread that prints a short summary each second.
1301 | ##
1302 |
1303 | def _monitor(self):
1304 | latest_total_recorded = 0
1305 | while not self.monitor_stop:
1306 | current_total = stats.count_lines_recorded.value
1307 | time_elapsed = time.time() - self.time_start
1308 | print('%d lines parsed, %d lines recorded, %d records/sec (avg), %d records/sec (current)' % (
1309 | stats.count_lines_parsed.value,
1310 | current_total,
1311 | current_total / time_elapsed if time_elapsed != 0 else 0,
1312 | (current_total - latest_total_recorded) / config.options.show_progress_delay,
1313 | ))
1314 | latest_total_recorded = current_total
1315 | time.sleep(config.options.show_progress_delay)
1316 |
1317 | def start_monitor(self):
1318 | t = threading.Thread(target=self._monitor)
1319 | t.daemon = True
1320 | t.start()
1321 |
1322 | def stop_monitor(self):
1323 | self.monitor_stop = True
1324 |
1325 | class Matomo(object):
1326 | """
1327 | Make requests to Matomo.
1328 | """
1329 |
1330 | class Error(Exception):
1331 |
1332 | def __init__(self, message, code = None):
1333 | super(Exception, self).__init__(message)
1334 |
1335 | self.code = code
1336 |
1337 | class RedirectHandlerWithLogging(urllib2.HTTPRedirectHandler):
1338 | """
1339 | Special implementation of HTTPRedirectHandler that logs redirects in debug mode
1340 | to help users debug system issues.
1341 | """
1342 |
1343 | def redirect_request(self, req, fp, code, msg, hdrs, newurl):
1344 | logging.debug("Request redirected (code: %s) to '%s'" % (code, newurl))
1345 |
1346 | return urllib2.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, hdrs, newurl)
1347 |
1348 | @staticmethod
1349 | def _call(path, args, headers=None, url=None, data=None):
1350 | """
1351 | Make a request to the Matomo site. It is up to the caller to format
1352 | arguments, to embed authentication, etc.
1353 | """
1354 | if url is None:
1355 | url = config.options.matomo_url
1356 | headers = headers or {}
1357 |
1358 | if data is None:
1359 | # If Content-Type isn't defined, PHP do not parse the request's body.
1360 | headers['Content-type'] = 'application/x-www-form-urlencoded'
1361 | data = urllib.urlencode(args)
1362 | elif not isinstance(data, basestring) and headers['Content-type'] == 'application/json':
1363 | data = json.dumps(data)
1364 |
1365 | if args:
1366 | path = path + '?' + urllib.urlencode(args)
1367 |
1368 | if config.options.request_suffix:
1369 | path = path + ('&' if '?' in path else '?') + config.options.request_suffix
1370 |
1371 | headers['User-Agent'] = 'Matomo/LogImport'
1372 |
1373 | try:
1374 | timeout = config.options.request_timeout
1375 | except:
1376 | timeout = None # the config global object may not be created at this point
1377 |
1378 | request = urllib2.Request(url + path, data, headers)
1379 |
1380 | # Handle basic auth if auth_user set
1381 | try:
1382 | auth_user = config.options.auth_user
1383 | auth_password = config.options.auth_password
1384 | except:
1385 | auth_user = None
1386 | auth_password = None
1387 |
1388 | if auth_user is not None:
1389 | base64string = base64.encodestring('%s:%s' % (auth_user, auth_password)).replace('\n', '')
1390 | request.add_header("Authorization", "Basic %s" % base64string)
1391 |
1392 | # Use non-default SSL context if invalid certificates shall be
1393 | # accepted.
1394 | if config.options.accept_invalid_ssl_certificate and \
1395 | sys.version_info >= (2, 7, 9):
1396 | ssl_context = ssl.create_default_context()
1397 | ssl_context.check_hostname = False
1398 | ssl_context.verify_mode = ssl.CERT_NONE
1399 | https_handler_args = {'context': ssl_context}
1400 | else:
1401 | https_handler_args = {}
1402 | opener = urllib2.build_opener(
1403 | Matomo.RedirectHandlerWithLogging(),
1404 | urllib2.HTTPSHandler(**https_handler_args))
1405 | response = opener.open(request, timeout = timeout)
1406 | result = response.read()
1407 | response.close()
1408 | return result
1409 |
1410 | @staticmethod
1411 | def _call_api(method, **kwargs):
1412 | """
1413 | Make a request to the Matomo API taking care of authentication, body
1414 | formatting, etc.
1415 | """
1416 | args = {
1417 | 'module' : 'API',
1418 | 'format' : 'json2',
1419 | 'method' : method,
1420 | 'filter_limit' : '-1',
1421 | }
1422 | # token_auth, by default, is taken from config.
1423 | token_auth = kwargs.pop('_token_auth', None)
1424 | if token_auth is None:
1425 | token_auth = config.options.matomo_token_auth
1426 | if token_auth:
1427 | args['token_auth'] = token_auth
1428 |
1429 | url = kwargs.pop('_url', None)
1430 | if url is None:
1431 | url = config.options.matomo_api_url
1432 |
1433 |
1434 | if kwargs:
1435 | args.update(kwargs)
1436 |
1437 | # Convert lists into appropriate format.
1438 | # See: http://developer.matomo.org/api-reference/reporting-api#passing-an-array-of-data-as-a-parameter
1439 | # Warning: we have to pass the parameters in order: foo[0], foo[1], foo[2]
1440 | # and not foo[1], foo[0], foo[2] (it will break Matomo otherwise.)
1441 | final_args = []
1442 | for key, value in args.iteritems():
1443 | if isinstance(value, (list, tuple)):
1444 | for index, obj in enumerate(value):
1445 | final_args.append(('%s[%d]' % (key, index), obj))
1446 | else:
1447 | final_args.append((key, value))
1448 |
1449 |
1450 | # logging.debug('%s' % final_args)
1451 | # logging.debug('%s' % url)
1452 |
1453 | res = Matomo._call('/', final_args, url=url)
1454 |
1455 |
1456 | try:
1457 | return json.loads(res)
1458 | except ValueError:
1459 | raise urllib2.URLError('Matomo returned an invalid response: ' + res)
1460 |
1461 | @staticmethod
1462 | def _call_wrapper(func, expected_response, on_failure, *args, **kwargs):
1463 | """
1464 | Try to make requests to Matomo at most MATOMO_FAILURE_MAX_RETRY times.
1465 | """
1466 | errors = 0
1467 | while True:
1468 | try:
1469 | response = func(*args, **kwargs)
1470 | if expected_response is not None and response != expected_response:
1471 | if on_failure is not None:
1472 | error_message = on_failure(response, kwargs.get('data'))
1473 | else:
1474 | error_message = "didn't receive the expected response. Response was %s " % response
1475 |
1476 | raise urllib2.URLError(error_message)
1477 | return response
1478 | except (urllib2.URLError, httplib.HTTPException, ValueError, socket.timeout) as e:
1479 | logging.info('Error when connecting to Matomo: %s', e)
1480 |
1481 | code = None
1482 | if isinstance(e, urllib2.HTTPError):
1483 | # See Python issue 13211.
1484 | message = 'HTTP Error %s %s' % (e.code, e.msg)
1485 | code = e.code
1486 | elif isinstance(e, urllib2.URLError):
1487 | message = e.reason
1488 | else:
1489 | message = str(e)
1490 |
1491 | # decorate message w/ HTTP response, if it can be retrieved
1492 | if hasattr(e, 'read'):
1493 | message = message + ", response: " + e.read()
1494 |
1495 | try:
1496 | delay_after_failure = config.options.delay_after_failure
1497 | max_attempts = config.options.max_attempts
1498 | except NameError:
1499 | delay_after_failure = MATOMO_DEFAULT_DELAY_AFTER_FAILURE
1500 | max_attempts = MATOMO_DEFAULT_MAX_ATTEMPTS
1501 |
1502 | errors += 1
1503 | if errors == max_attempts:
1504 | logging.info("Max number of attempts reached, server is unreachable!")
1505 |
1506 | raise Matomo.Error(message, code)
1507 | else:
1508 | logging.info("Retrying request, attempt number %d" % (errors + 1))
1509 |
1510 | time.sleep(delay_after_failure)
1511 |
1512 | @classmethod
1513 | def call(cls, path, args, expected_content=None, headers=None, data=None, on_failure=None):
1514 | return cls._call_wrapper(cls._call, expected_content, on_failure, path, args, headers,
1515 | data=data)
1516 |
1517 | @classmethod
1518 | def call_api(cls, method, **kwargs):
1519 | return cls._call_wrapper(cls._call_api, None, None, method, **kwargs)
1520 |
1521 | ##
1522 | ## Resolvers.
1523 | ##
1524 | ## A resolver is a class that turns a hostname into a Matomo site ID.
1525 | ##
1526 |
1527 | class StaticResolver(object):
1528 | """
1529 | Always return the same site ID, specified in the configuration.
1530 | """
1531 |
1532 | def __init__(self, site_id):
1533 | self.site_id = site_id
1534 | # Go get the main URL
1535 | site = matomo.call_api(
1536 | 'SitesManager.getSiteFromId', idSite=self.site_id
1537 | )
1538 | if site.get('result') == 'error':
1539 | fatal_error(
1540 | "cannot get the main URL of this site: %s" % site.get('message')
1541 | )
1542 | self._main_url = site['main_url']
1543 | stats.matomo_sites.add(self.site_id)
1544 |
1545 | def resolve(self, hit):
1546 | return (self.site_id, self._main_url)
1547 |
1548 | def check_format(self, format):
1549 | pass
1550 |
1551 | class DynamicResolver(object):
1552 | """
1553 | Use Matomo API to determine the site ID.
1554 | """
1555 |
1556 | _add_site_lock = threading.Lock()
1557 |
1558 | def __init__(self):
1559 | self._cache = {}
1560 | if config.options.replay_tracking:
1561 | # get existing sites
1562 | self._cache['sites'] = matomo.call_api('SitesManager.getAllSites')
1563 |
1564 | def _get_site_id_from_hit_host(self, hit):
1565 | return matomo.call_api(
1566 | 'SitesManager.getSitesIdFromSiteUrl',
1567 | url=hit.host,
1568 | )
1569 |
1570 | def _add_site(self, hit):
1571 | main_url = 'http://' + hit.host
1572 | DynamicResolver._add_site_lock.acquire()
1573 |
1574 | try:
1575 | # After we obtain the lock, make sure the site hasn't already been created.
1576 | res = self._get_site_id_from_hit_host(hit)
1577 | if res:
1578 | return res[0]['idsite']
1579 |
1580 | # The site doesn't exist.
1581 | logging.debug('No Matomo site found for the hostname: %s', hit.host)
1582 | if config.options.site_id_fallback is not None:
1583 | logging.debug('Using default site for hostname: %s', hit.host)
1584 | return config.options.site_id_fallback
1585 | elif config.options.add_sites_new_hosts:
1586 | if config.options.dry_run:
1587 | # Let's just return a fake ID.
1588 | return 0
1589 | logging.debug('Creating a Matomo site for hostname %s', hit.host)
1590 | result = matomo.call_api(
1591 | 'SitesManager.addSite',
1592 | siteName=hit.host,
1593 | urls=[main_url],
1594 | )
1595 | if result.get('result') == 'error':
1596 | logging.error("Couldn't create a Matomo site for host %s: %s",
1597 | hit.host, result.get('message'),
1598 | )
1599 | return None
1600 | else:
1601 | site_id = result['value']
1602 | stats.matomo_sites_created.append((hit.host, site_id))
1603 | return site_id
1604 | else:
1605 | # The site doesn't exist, we don't want to create new sites and
1606 | # there's no default site ID. We thus have to ignore this hit.
1607 | return None
1608 | finally:
1609 | DynamicResolver._add_site_lock.release()
1610 |
1611 | def _resolve(self, hit):
1612 | res = self._get_site_id_from_hit_host(hit)
1613 | if res:
1614 | # The site already exists.
1615 | site_id = res[0]['idsite']
1616 | else:
1617 | site_id = self._add_site(hit)
1618 | if site_id is not None:
1619 | stats.matomo_sites.add(site_id)
1620 | return site_id
1621 |
1622 | def _resolve_when_replay_tracking(self, hit):
1623 | """
1624 | If parsed site ID found in the _cache['sites'] return site ID and main_url,
1625 | otherwise return (None, None) tuple.
1626 | """
1627 | site_id = hit.args['idsite']
1628 | if site_id in self._cache['sites']:
1629 | stats.matomo_sites.add(site_id)
1630 | return (site_id, self._cache['sites'][site_id]['main_url'])
1631 | else:
1632 | return (None, None)
1633 |
1634 | def _resolve_by_host(self, hit):
1635 | """
1636 | Returns the site ID and site URL for a hit based on the hostname.
1637 | """
1638 | try:
1639 | site_id = self._cache[hit.host]
1640 | except KeyError:
1641 | logging.debug(
1642 | 'Site ID for hostname %s not in cache', hit.host
1643 | )
1644 | site_id = self._resolve(hit)
1645 | logging.debug('Site ID for hostname %s: %s', hit.host, site_id)
1646 | self._cache[hit.host] = site_id
1647 | return (site_id, 'http://' + hit.host)
1648 |
1649 | def resolve(self, hit):
1650 | """
1651 | Return the site ID from the cache if found, otherwise call _resolve.
1652 | If replay_tracking option is enabled, call _resolve_when_replay_tracking.
1653 | """
1654 | if config.options.replay_tracking:
1655 | # We only consider requests with piwik.php which don't need host to be imported
1656 | return self._resolve_when_replay_tracking(hit)
1657 | else:
1658 | # Workaround for empty Host bug issue #126
1659 | if hit.host.strip() == '':
1660 | hit.host = 'no-hostname-found-in-log'
1661 | return self._resolve_by_host(hit)
1662 |
1663 | def check_format(self, format):
1664 | if config.options.replay_tracking:
1665 | pass
1666 | elif format.regex is not None and 'host' not in format.regex.groupindex and not config.options.log_hostname:
1667 | fatal_error(
1668 | "the selected log format doesn't include the hostname: you must "
1669 | "specify the Matomo site ID with the --idsite argument"
1670 | )
1671 |
1672 | class Recorder(object):
1673 | """
1674 | A Recorder fetches hits from the Queue and inserts them into Matomo using
1675 | the API.
1676 | """
1677 |
1678 | recorders = []
1679 |
1680 | def __init__(self):
1681 | self.queue = Queue.Queue(maxsize=2)
1682 |
1683 | # if bulk tracking disabled, make sure we can store hits outside of the Queue
1684 | if not config.options.use_bulk_tracking:
1685 | self.unrecorded_hits = []
1686 |
1687 | @classmethod
1688 | def launch(cls, recorder_count):
1689 | """
1690 | Launch a bunch of Recorder objects in a separate thread.
1691 | """
1692 | for i in xrange(recorder_count):
1693 | recorder = Recorder()
1694 | cls.recorders.append(recorder)
1695 |
1696 | run = recorder._run_bulk if config.options.use_bulk_tracking else recorder._run_single
1697 | t = threading.Thread(target=run)
1698 |
1699 | t.daemon = True
1700 | t.start()
1701 | logging.debug('Launched recorder')
1702 |
1703 | @classmethod
1704 | def add_hits(cls, all_hits):
1705 | """
1706 | Add a set of hits to the recorders queue.
1707 | """
1708 | # Organize hits so that one client IP will always use the same queue.
1709 | # We have to do this so visits from the same IP will be added in the right order.
1710 | hits_by_client = [[] for r in cls.recorders]
1711 | for hit in all_hits:
1712 | hits_by_client[hit.get_visitor_id_hash() % len(cls.recorders)].append(hit)
1713 |
1714 | for i, recorder in enumerate(cls.recorders):
1715 | recorder.queue.put(hits_by_client[i])
1716 |
1717 | @classmethod
1718 | def wait_empty(cls):
1719 | """
1720 | Wait until all recorders have an empty queue.
1721 | """
1722 | for recorder in cls.recorders:
1723 | recorder._wait_empty()
1724 |
1725 | def _run_bulk(self):
1726 | while True:
1727 | try:
1728 | hits = self.queue.get()
1729 | except:
1730 | # TODO: we should log something here, however when this happens, logging.etc will throw
1731 | return
1732 |
1733 | if len(hits) > 0:
1734 | try:
1735 | self._record_hits(hits)
1736 | except Matomo.Error as e:
1737 | fatal_error(e, hits[0].filename, hits[0].lineno) # approximate location of error
1738 | self.queue.task_done()
1739 |
1740 | def _run_single(self):
1741 | while True:
1742 | if config.options.force_one_action_interval != False:
1743 | time.sleep(config.options.force_one_action_interval)
1744 |
1745 | if len(self.unrecorded_hits) > 0:
1746 | hit = self.unrecorded_hits.pop(0)
1747 |
1748 | try:
1749 | self._record_hits([hit])
1750 | except Matomo.Error as e:
1751 | fatal_error(e, hit.filename, hit.lineno)
1752 | else:
1753 | self.unrecorded_hits = self.queue.get()
1754 | self.queue.task_done()
1755 |
1756 | def _wait_empty(self):
1757 | """
1758 | Wait until the queue is empty.
1759 | """
1760 | while True:
1761 | if self.queue.empty():
1762 | # We still have to wait for the last queue item being processed
1763 | # (queue.empty() returns True before queue.task_done() is
1764 | # called).
1765 | self.queue.join()
1766 | return
1767 | time.sleep(1)
1768 |
1769 | def date_to_matomo(self, date):
1770 | date, time = date.isoformat(sep=' ').split()
1771 | return '%s %s' % (date, time.replace('-', ':'))
1772 |
1773 | def _get_hit_args(self, hit):
1774 | """
1775 | Returns the args used in tracking a hit, without the token_auth.
1776 | """
1777 | site_id, main_url = resolver.resolve(hit)
1778 | if site_id is None:
1779 | # This hit doesn't match any known Matomo site.
1780 | if config.options.replay_tracking:
1781 | stats.matomo_sites_ignored.add('unrecognized site ID %s' % hit.args.get('idsite'))
1782 | else:
1783 | stats.matomo_sites_ignored.add(hit.host)
1784 | stats.count_lines_no_site.increment()
1785 | return
1786 |
1787 | stats.dates_recorded.add(hit.date.date())
1788 |
1789 | path = hit.path
1790 | if hit.query_string and not config.options.strip_query_string:
1791 | path += config.options.query_string_delimiter + hit.query_string
1792 |
1793 | # only prepend main url / host if it's a path
1794 | url_prefix = self._get_host_with_protocol(hit.host, main_url) if hasattr(hit, 'host') else main_url
1795 | url = (url_prefix if path.startswith('/') else '') + path[:1024]
1796 |
1797 | # handle custom variables before generating args dict
1798 | if config.options.enable_bots:
1799 | if hit.is_robot:
1800 | hit.add_visit_custom_var("Bot", hit.user_agent)
1801 | else:
1802 | hit.add_visit_custom_var("Not-Bot", hit.user_agent)
1803 |
1804 | hit.add_page_custom_var("HTTP-code", hit.status)
1805 |
1806 | args = {
1807 | 'rec': '1',
1808 | 'apiv': '1',
1809 | 'url': url.encode('utf8'),
1810 | 'urlref': hit.referrer[:1024].encode('utf8'),
1811 | 'cip': hit.ip,
1812 | 'cdt': self.date_to_matomo(hit.date),
1813 | 'idsite': site_id,
1814 | 'dp': '0' if config.options.reverse_dns else '1',
1815 | 'ua': hit.user_agent.encode('utf8')
1816 | }
1817 |
1818 | if config.options.replay_tracking:
1819 | # prevent request to be force recorded when option replay-tracking
1820 | args['rec'] = '0'
1821 |
1822 | # idsite is already determined by resolver
1823 | if 'idsite' in hit.args:
1824 | del hit.args['idsite']
1825 |
1826 | args.update(hit.args)
1827 |
1828 | if hit.is_download:
1829 | args['download'] = args['url']
1830 |
1831 | if config.options.enable_bots:
1832 | args['bots'] = '1'
1833 |
1834 | if hit.is_error or hit.is_redirect:
1835 | args['action_name'] = '%s%sURL = %s%s' % (
1836 | hit.status,
1837 | config.options.title_category_delimiter,
1838 | urllib.quote(args['url'], ''),
1839 | ("%sFrom = %s" % (
1840 | config.options.title_category_delimiter,
1841 | urllib.quote(args['urlref'], '')
1842 | ) if args['urlref'] != '' else '')
1843 | )
1844 |
1845 | if hit.generation_time_milli > 0:
1846 | args['gt_ms'] = int(hit.generation_time_milli)
1847 |
1848 | if hit.event_category and hit.event_action:
1849 | args['e_c'] = hit.event_category
1850 | args['e_a'] = hit.event_action
1851 |
1852 | if hit.event_name:
1853 | args['e_n'] = hit.event_name
1854 |
1855 | if hit.length:
1856 | args['bw_bytes'] = hit.length
1857 |
1858 | # convert custom variable args to JSON
1859 | if 'cvar' in args and not isinstance(args['cvar'], basestring):
1860 | args['cvar'] = json.dumps(args['cvar'])
1861 |
1862 | if '_cvar' in args and not isinstance(args['_cvar'], basestring):
1863 | args['_cvar'] = json.dumps(args['_cvar'])
1864 |
1865 | return args
1866 |
1867 | def _get_host_with_protocol(self, host, main_url):
1868 | if '://' not in host:
1869 | parts = urlparse.urlparse(main_url)
1870 | host = parts.scheme + '://' + host
1871 | return host
1872 |
1873 | def _record_hits(self, hits):
1874 | """
1875 | Inserts several hits into Matomo.
1876 | """
1877 | if not config.options.dry_run:
1878 | data = {
1879 | 'token_auth': config.options.matomo_token_auth,
1880 | 'requests': [self._get_hit_args(hit) for hit in hits]
1881 | }
1882 | try:
1883 | args = {}
1884 |
1885 | if config.options.debug_tracker:
1886 | args['debug'] = '1'
1887 |
1888 | response = matomo.call(
1889 | '/piwik.php', args=args,
1890 | expected_content=None,
1891 | headers={'Content-type': 'application/json'},
1892 | data=data,
1893 | on_failure=self._on_tracking_failure
1894 | )
1895 |
1896 | if config.options.debug_tracker:
1897 | logging.debug('tracker response:\n%s' % response)
1898 |
1899 | # check for invalid requests
1900 | try:
1901 | response = json.loads(response)
1902 | except:
1903 | logging.info("bulk tracking returned invalid JSON")
1904 |
1905 | # don't display the tracker response if we're debugging the tracker.
1906 | # debug tracker output will always break the normal JSON output.
1907 | if not config.options.debug_tracker:
1908 | logging.info("tracker response:\n%s" % response)
1909 |
1910 | response = {}
1911 |
1912 | if ('invalid_indices' in response and isinstance(response['invalid_indices'], list) and
1913 | response['invalid_indices']):
1914 | invalid_count = len(response['invalid_indices'])
1915 |
1916 | invalid_lines = [str(hits[index].lineno) for index in response['invalid_indices']]
1917 | invalid_lines_str = ", ".join(invalid_lines)
1918 |
1919 | stats.invalid_lines.extend(invalid_lines)
1920 |
1921 | logging.info("The Matomo tracker identified %s invalid requests on lines: %s" % (invalid_count, invalid_lines_str))
1922 | elif 'invalid' in response and response['invalid'] > 0:
1923 | logging.info("The Matomo tracker identified %s invalid requests." % response['invalid'])
1924 | except Matomo.Error as e:
1925 | # if the server returned 400 code, BulkTracking may not be enabled
1926 | if e.code == 400:
1927 | fatal_error("Server returned status 400 (Bad Request).\nIs the BulkTracking plugin disabled?", hits[0].filename, hits[0].lineno)
1928 |
1929 | raise
1930 |
1931 | stats.count_lines_recorded.advance(len(hits))
1932 |
1933 | def _is_json(self, result):
1934 | try:
1935 | json.loads(result)
1936 | return True
1937 | except ValueError as e:
1938 | return False
1939 |
1940 | def _on_tracking_failure(self, response, data):
1941 | """
1942 | Removes the successfully tracked hits from the request payload so
1943 | they are not logged twice.
1944 | """
1945 | try:
1946 | response = json.loads(response)
1947 | except:
1948 | # the response should be in JSON, but in case it can't be parsed just try another attempt
1949 | logging.debug("cannot parse tracker response, should be valid JSON")
1950 | return response
1951 |
1952 | # remove the successfully tracked hits from payload
1953 | tracked = response['tracked']
1954 | data['requests'] = data['requests'][tracked:]
1955 |
1956 | return response['message']
1957 |
1958 | class Hit(object):
1959 | """
1960 | It's a simple container.
1961 | """
1962 | def __init__(self, **kwargs):
1963 | for key, value in kwargs.iteritems():
1964 | setattr(self, key, value)
1965 | super(Hit, self).__init__()
1966 |
1967 | if config.options.force_lowercase_path:
1968 | self.full_path = self.full_path.lower()
1969 |
1970 | def get_visitor_id_hash(self):
1971 | visitor_id = self.ip
1972 |
1973 | if config.options.replay_tracking:
1974 | for param_name_to_use in ['uid', 'cid', '_id', 'cip']:
1975 | if param_name_to_use in self.args:
1976 | visitor_id = self.args[param_name_to_use]
1977 | break
1978 |
1979 | return abs(hash(visitor_id))
1980 |
1981 | def add_page_custom_var(self, key, value):
1982 | """
1983 | Adds a page custom variable to this Hit.
1984 | """
1985 | self._add_custom_var(key, value, 'cvar')
1986 |
1987 | def add_visit_custom_var(self, key, value):
1988 | """
1989 | Adds a visit custom variable to this Hit.
1990 | """
1991 | self._add_custom_var(key, value, '_cvar')
1992 |
1993 | def _add_custom_var(self, key, value, api_arg_name):
1994 | if api_arg_name not in self.args:
1995 | self.args[api_arg_name] = {}
1996 |
1997 | if isinstance(self.args[api_arg_name], basestring):
1998 | logging.debug("Ignoring custom %s variable addition [ %s = %s ], custom var already set to string." % (api_arg_name, key, value))
1999 | return
2000 |
2001 | index = len(self.args[api_arg_name]) + 1
2002 | self.args[api_arg_name][index] = [key, value]
2003 |
2004 | class Parser(object):
2005 | """
2006 | The Parser parses the lines in a specified file and inserts them into
2007 | a Queue.
2008 | """
2009 |
2010 | def __init__(self):
2011 | self.check_methods = [method for name, method
2012 | in inspect.getmembers(self, predicate=inspect.ismethod)
2013 | if name.startswith('check_')]
2014 |
2015 | ## All check_* methods are called for each hit and must return True if the
2016 | ## hit can be imported, False otherwise.
2017 |
2018 | def check_hostname(self, hit):
2019 | # Check against config.hostnames.
2020 | if not hasattr(hit, 'host') or not config.options.hostnames:
2021 | return True
2022 |
2023 | # Accept the hostname only if it matches one pattern in the list.
2024 | result = any(
2025 | fnmatch.fnmatch(hit.host, pattern)
2026 | for pattern in config.options.hostnames
2027 | )
2028 | if not result:
2029 | stats.count_lines_hostname_skipped.increment()
2030 | return result
2031 |
2032 | def check_static(self, hit):
2033 | if hit.extension in STATIC_EXTENSIONS:
2034 | if config.options.enable_static:
2035 | hit.is_download = True
2036 | return True
2037 | else:
2038 | stats.count_lines_static.increment()
2039 | return False
2040 | return True
2041 |
2042 | def check_download(self, hit):
2043 | if hit.extension in config.options.download_extensions:
2044 | stats.count_lines_downloads.increment()
2045 | hit.is_download = True
2046 | return True
2047 | # the file is not in the white-listed downloads
2048 | # if it's a know download file, we shall skip it
2049 | elif hit.extension in DOWNLOAD_EXTENSIONS:
2050 | stats.count_lines_skipped_downloads.increment()
2051 | return False
2052 | return True
2053 |
2054 | def check_user_agent(self, hit):
2055 | user_agent = hit.user_agent.lower()
2056 | for s in itertools.chain(EXCLUDED_USER_AGENTS, config.options.excluded_useragents):
2057 | if s in user_agent:
2058 | if config.options.enable_bots:
2059 | hit.is_robot = True
2060 | return True
2061 | else:
2062 | stats.count_lines_skipped_user_agent.increment()
2063 | return False
2064 | return True
2065 |
2066 | def check_http_error(self, hit):
2067 | if hit.status[0] in ('4', '5'):
2068 | if config.options.replay_tracking:
2069 | # process error logs for replay tracking, since we don't care if matomo error-ed the first time
2070 | return True
2071 | elif config.options.enable_http_errors:
2072 | hit.is_error = True
2073 | return True
2074 | else:
2075 | stats.count_lines_skipped_http_errors.increment()
2076 | return False
2077 | return True
2078 |
2079 | def check_http_redirect(self, hit):
2080 | if hit.status[0] == '3' and hit.status != '304':
2081 | if config.options.enable_http_redirects:
2082 | hit.is_redirect = True
2083 | return True
2084 | else:
2085 | stats.count_lines_skipped_http_redirects.increment()
2086 | return False
2087 | return True
2088 |
2089 | def check_path(self, hit):
2090 | for excluded_path in config.options.excluded_paths:
2091 | if fnmatch.fnmatch(hit.path, excluded_path):
2092 | return False
2093 | # By default, all paths are included.
2094 | if config.options.included_paths:
2095 | for included_path in config.options.included_paths:
2096 | if fnmatch.fnmatch(hit.path, included_path):
2097 | return True
2098 | return False
2099 | return True
2100 |
2101 | @staticmethod
2102 | def check_format(lineOrFile):
2103 | format = False
2104 | format_groups = 0
2105 | for name, candidate_format in FORMATS.iteritems():
2106 | logging.debug("Check format %s", name)
2107 |
2108 | # skip auto detection for formats that can't be detected automatically
2109 | if name == 'ovh':
2110 | continue
2111 |
2112 | match = None
2113 | try:
2114 | if isinstance(lineOrFile, basestring):
2115 | match = candidate_format.check_format_line(lineOrFile)
2116 | else:
2117 | match = candidate_format.check_format(lineOrFile)
2118 | except Exception as e:
2119 | logging.debug('Error in format checking: %s', traceback.format_exc())
2120 | pass
2121 |
2122 | if match:
2123 | logging.debug('Format %s matches', name)
2124 |
2125 | # compare format groups if this *BaseFormat has groups() method
2126 | try:
2127 | # if there's more info in this match, use this format
2128 | match_groups = len(match.groups())
2129 |
2130 | logging.debug('Format match contains %d groups' % match_groups)
2131 |
2132 | if format_groups < match_groups:
2133 | format = candidate_format
2134 | format_groups = match_groups
2135 | except AttributeError:
2136 | format = candidate_format
2137 |
2138 | else:
2139 | logging.debug('Format %s does not match', name)
2140 |
2141 | # if the format is W3cExtendedFormat, check if the logs are from IIS and if so, issue a warning if the
2142 | # --w3c-time-taken-milli option isn't set
2143 | if isinstance(format, W3cExtendedFormat):
2144 | format.check_for_iis_option()
2145 |
2146 | return format
2147 |
2148 | @staticmethod
2149 | def detect_format(file):
2150 | """
2151 | Return the best matching format for this file, or None if none was found.
2152 | """
2153 | logging.debug('Detecting the log format')
2154 |
2155 | format = False
2156 |
2157 | # check the format using the file (for formats like the W3cExtendedFormat one)
2158 | format = Parser.check_format(file)
2159 |
2160 | # check the format using the first N lines (to avoid irregular ones)
2161 | lineno = 0
2162 | limit = 100000
2163 | while not format and lineno < limit:
2164 | line = file.readline()
2165 | if not line: # if at eof, don't keep looping
2166 | break
2167 |
2168 | lineno = lineno + 1
2169 |
2170 | logging.debug("Detecting format against line %i" % lineno)
2171 | format = Parser.check_format(line)
2172 |
2173 | try:
2174 | file.seek(0)
2175 | except IOError:
2176 | pass
2177 |
2178 | if not format:
2179 | fatal_error("cannot automatically determine the log format using the first %d lines of the log file. " % limit +
2180 | "\nMaybe try specifying the format with the --log-format-name command line argument." )
2181 | return
2182 |
2183 | logging.debug('Format %s is the best match', format.name)
2184 | return format
2185 |
2186 | def is_filtered(self, hit):
2187 | host = None
2188 | if hasattr(hit, 'host'):
2189 | host = hit.host
2190 | else:
2191 | try:
2192 | host = urlparse.urlparse(hit.path).hostname
2193 | except:
2194 | pass
2195 |
2196 | if host:
2197 | if config.options.exclude_host and len(config.options.exclude_host) > 0 and host in config.options.exclude_host:
2198 | return (True, 'host matched --exclude-host')
2199 |
2200 | if config.options.include_host and len(config.options.include_host) > 0 and host not in config.options.include_host:
2201 | return (True, 'host did not match --include-host')
2202 |
2203 | if config.options.exclude_older_than and hit.date < config.options.exclude_older_than:
2204 | return (True, 'date is older than --exclude-older-than')
2205 |
2206 | if config.options.exclude_newer_than and hit.date > config.options.exclude_newer_than:
2207 | return (True, 'date is newer than --exclude-newer-than')
2208 |
2209 | return (False, None)
2210 |
2211 | def parse(self, filename):
2212 | """
2213 | Parse the specified filename and insert hits in the queue.
2214 | """
2215 | def invalid_line(line, reason):
2216 | stats.count_lines_invalid.increment()
2217 | if config.options.debug >= 2:
2218 | logging.debug('Invalid line detected (%s): %s' % (reason, line))
2219 |
2220 | def filtered_line(line, reason):
2221 | stats.count_lines_filtered.increment()
2222 | if config.options.debug >= 2:
2223 | logging.debug('Filtered line out (%s): %s' % (reason, line))
2224 |
2225 | if filename == '-':
2226 | filename = '(stdin)'
2227 | file = sys.stdin
2228 | else:
2229 | if not os.path.exists(filename):
2230 | print >> sys.stderr, "\n=====> Warning: File %s does not exist <=====" % filename
2231 | return
2232 | else:
2233 | if filename.endswith('.bz2'):
2234 | open_func = bz2.BZ2File
2235 | elif filename.endswith('.gz'):
2236 | open_func = gzip.open
2237 | else:
2238 | open_func = open
2239 | file = open_func(filename, 'r')
2240 |
2241 | if config.options.show_progress:
2242 | print('Parsing log %s...' % filename)
2243 |
2244 | if config.format:
2245 | # The format was explicitely specified.
2246 | format = config.format
2247 |
2248 | if isinstance(format, W3cExtendedFormat):
2249 | format.create_regex(file)
2250 |
2251 | if format.regex is None:
2252 | return fatal_error(
2253 | "File is not in the correct format, is there a '#Fields:' line? "
2254 | "If not, use the --w3c-fields option."
2255 | )
2256 | else:
2257 | # If the file is empty, don't bother.
2258 | data = file.read(100)
2259 | if len(data.strip()) == 0:
2260 | return
2261 | try:
2262 | file.seek(0)
2263 | except IOError:
2264 | pass
2265 |
2266 | format = self.detect_format(file)
2267 | if format is None:
2268 | return fatal_error(
2269 | 'Cannot guess the logs format. Please give one using '
2270 | 'either the --log-format-name or --log-format-regex option'
2271 | )
2272 | # Make sure the format is compatible with the resolver.
2273 | resolver.check_format(format)
2274 |
2275 | if config.options.dump_log_regex:
2276 | logging.info("Using format '%s'." % format.name)
2277 | if format.regex:
2278 | logging.info("Regex being used: %s" % format.regex.pattern)
2279 | else:
2280 | logging.info("Format %s does not use a regex to parse log lines." % format.name)
2281 | logging.info("--dump-log-regex option used, aborting log import.")
2282 | os._exit(0)
2283 |
2284 | valid_lines_count = 0
2285 |
2286 | hits = []
2287 | lineno = -1
2288 | while True:
2289 | line = file.readline()
2290 | if not line: break
2291 | lineno = lineno + 1
2292 |
2293 | try:
2294 | line = line.decode(config.options.encoding)
2295 | except UnicodeDecodeError:
2296 | invalid_line(line, 'invalid encoding')
2297 | continue
2298 |
2299 | stats.count_lines_parsed.increment()
2300 | if stats.count_lines_parsed.value <= config.options.skip:
2301 | continue
2302 |
2303 | match = format.match(line)
2304 | if not match:
2305 | invalid_line(line, 'line did not match')
2306 | continue
2307 |
2308 | valid_lines_count = valid_lines_count + 1
2309 | if config.options.debug_request_limit and valid_lines_count >= config.options.debug_request_limit:
2310 | if len(hits) > 0:
2311 | Recorder.add_hits(hits)
2312 | logging.info("Exceeded limit specified in --debug-request-limit, exiting.")
2313 | return
2314 |
2315 | hit = Hit(
2316 | filename=filename,
2317 | lineno=lineno,
2318 | status=format.get('status'),
2319 | full_path=format.get('path'),
2320 | is_download=False,
2321 | is_robot=False,
2322 | is_error=False,
2323 | is_redirect=False,
2324 | args={},
2325 | )
2326 |
2327 | if config.options.regex_group_to_page_cvars_map:
2328 | self._add_custom_vars_from_regex_groups(hit, format, config.options.regex_group_to_page_cvars_map, True)
2329 |
2330 | if config.options.regex_group_to_visit_cvars_map:
2331 | self._add_custom_vars_from_regex_groups(hit, format, config.options.regex_group_to_visit_cvars_map, False)
2332 |
2333 | if config.options.regex_groups_to_ignore:
2334 | format.remove_ignored_groups(config.options.regex_groups_to_ignore)
2335 |
2336 | # Add http method page cvar
2337 | try:
2338 | httpmethod = format.get('method')
2339 | if config.options.track_http_method and httpmethod != '-':
2340 | hit.add_page_custom_var('HTTP-method', httpmethod)
2341 | except:
2342 | pass
2343 |
2344 | try:
2345 | hit.query_string = format.get('query_string')
2346 | hit.path = hit.full_path
2347 | except BaseFormatException:
2348 | hit.path, _, hit.query_string = hit.full_path.partition(config.options.query_string_delimiter)
2349 |
2350 | # W3cExtendedFormat detaults to - when there is no query string, but we want empty string
2351 | if hit.query_string == '-':
2352 | hit.query_string = ''
2353 |
2354 | hit.extension = hit.path.rsplit('.')[-1].lower()
2355 |
2356 | try:
2357 | hit.referrer = format.get('referrer')
2358 |
2359 | if hit.referrer.startswith('"'):
2360 | hit.referrer = hit.referrer[1:-1]
2361 | except BaseFormatException:
2362 | hit.referrer = ''
2363 | if hit.referrer == '-':
2364 | hit.referrer = ''
2365 |
2366 | try:
2367 | hit.user_agent = format.get('user_agent')
2368 |
2369 | # in case a format parser included enclosing quotes, remove them so they are not
2370 | # sent to Matomo
2371 | if hit.user_agent.startswith('"'):
2372 | hit.user_agent = hit.user_agent[1:-1]
2373 | except BaseFormatException:
2374 | hit.user_agent = ''
2375 |
2376 | hit.ip = format.get('ip')
2377 | try:
2378 | hit.length = int(format.get('length'))
2379 | except (ValueError, BaseFormatException):
2380 | # Some lines or formats don't have a length (e.g. 304 redirects, W3C logs)
2381 | hit.length = 0
2382 |
2383 | try:
2384 | hit.generation_time_milli = float(format.get('generation_time_milli'))
2385 | except (ValueError, BaseFormatException):
2386 | try:
2387 | hit.generation_time_milli = float(format.get('generation_time_micro')) / 1000
2388 | except (ValueError, BaseFormatException):
2389 | try:
2390 | hit.generation_time_milli = float(format.get('generation_time_secs')) * 1000
2391 | except (ValueError, BaseFormatException):
2392 | hit.generation_time_milli = 0
2393 |
2394 | if config.options.log_hostname:
2395 | hit.host = config.options.log_hostname
2396 | else:
2397 | try:
2398 | hit.host = format.get('host').lower().strip('.')
2399 |
2400 | if hit.host.startswith('"'):
2401 | hit.host = hit.host[1:-1]
2402 | except BaseFormatException:
2403 | # Some formats have no host.
2404 | pass
2405 |
2406 | # Add userid
2407 | try:
2408 | hit.userid = None
2409 |
2410 | userid = format.get('userid')
2411 | if userid != '-':
2412 | hit.args['uid'] = hit.userid = userid
2413 | except:
2414 | pass
2415 |
2416 | # add event info
2417 | try:
2418 | hit.event_category = hit.event_action = hit.event_name = None
2419 |
2420 | hit.event_category = format.get('event_category')
2421 | hit.event_action = format.get('event_action')
2422 |
2423 | hit.event_name = format.get('event_name')
2424 | if hit.event_name == '-':
2425 | hit.event_name = None
2426 | except:
2427 | pass
2428 |
2429 | # Check if the hit must be excluded.
2430 | if not all((method(hit) for method in self.check_methods)):
2431 | continue
2432 |
2433 | # Parse date.
2434 | # We parse it after calling check_methods as it's quite CPU hungry, and
2435 | # we want to avoid that cost for excluded hits.
2436 | date_string = format.get('date')
2437 | try:
2438 | hit.date = datetime.datetime.strptime(date_string, format.date_format)
2439 | hit.date += datetime.timedelta(seconds = config.options.seconds_to_add_to_date)
2440 | except ValueError as e:
2441 | invalid_line(line, 'invalid date or invalid format: %s' % str(e))
2442 | continue
2443 |
2444 | # Parse timezone and substract its value from the date
2445 | try:
2446 | timezone = float(format.get('timezone'))
2447 | except BaseFormatException:
2448 | timezone = 0
2449 | except ValueError:
2450 | invalid_line(line, 'invalid timezone')
2451 | continue
2452 |
2453 | if timezone:
2454 | hit.date -= datetime.timedelta(hours=timezone/100)
2455 |
2456 | if config.options.replay_tracking:
2457 | # we need a query string and we only consider requests with piwik.php
2458 | if not hit.query_string or not hit.path.lower().endswith(config.options.replay_tracking_expected_tracker_file):
2459 | invalid_line(line, 'no query string, or ' + hit.path.lower() + ' does not end with piwik.php')
2460 | continue
2461 |
2462 | query_arguments = urlparse.parse_qs(hit.query_string)
2463 | if not "idsite" in query_arguments:
2464 | invalid_line(line, 'missing idsite')
2465 | continue
2466 |
2467 | try:
2468 | hit.args.update((k, v.pop().encode('raw_unicode_escape').decode(config.options.encoding)) for k, v in query_arguments.iteritems())
2469 | except UnicodeDecodeError:
2470 | invalid_line(line, 'invalid encoding')
2471 | continue
2472 |
2473 | (is_filtered, reason) = self.is_filtered(hit)
2474 | if is_filtered:
2475 | filtered_line(line, reason)
2476 | continue
2477 |
2478 | hits.append(hit)
2479 |
2480 | if len(hits) >= config.options.recorder_max_payload_size * len(Recorder.recorders):
2481 | Recorder.add_hits(hits)
2482 | hits = []
2483 |
2484 | # add last chunk of hits
2485 | if len(hits) > 0:
2486 | Recorder.add_hits(hits)
2487 |
2488 | def _add_custom_vars_from_regex_groups(self, hit, format, groups, is_page_var):
2489 | for group_name, custom_var_name in groups.iteritems():
2490 | if group_name in format.get_all():
2491 | value = format.get(group_name)
2492 |
2493 | # don't track the '-' empty placeholder value
2494 | if value == '-':
2495 | continue
2496 |
2497 | if is_page_var:
2498 | hit.add_page_custom_var(custom_var_name, value)
2499 | else:
2500 | hit.add_visit_custom_var(custom_var_name, value)
2501 |
2502 | def main():
2503 | """
2504 | Start the importing process.
2505 | """
2506 | stats.set_time_start()
2507 |
2508 | if config.options.show_progress:
2509 | stats.start_monitor()
2510 |
2511 | recorders = Recorder.launch(config.options.recorders)
2512 |
2513 | try:
2514 | for filename in config.filenames:
2515 | parser.parse(filename)
2516 |
2517 | Recorder.wait_empty()
2518 | except KeyboardInterrupt:
2519 | pass
2520 |
2521 | stats.set_time_stop()
2522 |
2523 | if config.options.show_progress:
2524 | stats.stop_monitor()
2525 |
2526 | stats.print_summary()
2527 |
2528 | def fatal_error(error, filename=None, lineno=None):
2529 | print >> sys.stderr, 'Fatal error: %s' % error
2530 | if filename and lineno is not None:
2531 | print >> sys.stderr, (
2532 | 'You can restart the import of "%s" from the point it failed by '
2533 | 'specifying --skip=%d on the command line.\n' % (filename, lineno)
2534 | )
2535 | os._exit(1)
2536 |
2537 | if __name__ == '__main__':
2538 | try:
2539 | config = Configuration()
2540 | # The matomo object depends on the config object, so we have to create
2541 | # it after creating the configuration.
2542 | matomo = Matomo()
2543 | # The init_token_auth method may need the matomo option, so we must call
2544 | # it after creating the matomo object.
2545 | config.init_token_auth()
2546 | stats = Statistics()
2547 | resolver = config.get_resolver()
2548 | parser = Parser()
2549 | main()
2550 | sys.exit(0)
2551 | except KeyboardInterrupt:
2552 | pass
2553 |
--------------------------------------------------------------------------------