-
Notifications
You must be signed in to change notification settings - Fork 72
mirrors stats script #169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
mirrors stats script #169
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
ad4bae2
add mirrors stats script and cronjob
abizer 2f31f1c
templatize mirrors stats script
abizer 9063da6
secrets in cron env instead of templates
abizer 2846a04
rename mirrors stats script, add argparse
abizer 0fc9eb5
messed up the rebase
abizer 1a00549
messed up more than the rebase
abizer File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| #!/usr/bin/python3 | ||
| import argparse | ||
| import os | ||
| from datetime import date | ||
| from datetime import timedelta | ||
| from datetime import datetime | ||
|
|
||
| import pymysql | ||
|
|
||
| OCFSTATS_PWD = os.environ['OCFSTATS_PWD'] | ||
| MIRRORS_PATH = '/opt/mirrors/ftp' | ||
| LOG_PATH = '/var/log/apache2' | ||
| LOG_NAME = 'mirrors.ocf.berkeley.edu_access.log' | ||
|
|
||
| def process_log(dists, fn, log_date): | ||
| with open(fn, 'r') as f: | ||
| n = 0 | ||
| for line in f: | ||
| n += 1 | ||
| stats = line.split() | ||
|
|
||
| # apache log date format looks like [11/Jul/2017:00:05:16 -0700] | ||
| # line.split()[3][1:12] = 11/Jul/2017 | ||
| # we need to dump dates that don't match because | ||
| # logrotate rotates the logs at 6am | ||
| line_date = datetime.strptime(stats[3][1:12], '%d/%b/%Y') | ||
| if line_date.date() != log_date: | ||
| continue | ||
|
|
||
| # extract dist name from request url | ||
| # '/debian/pool/main/h/hwdata/...' -> 'debian' | ||
| dist = stats[6] | ||
| dist = dist.split('/')[1] if '/' in dist else dist | ||
|
|
||
| # record if we returned http 2xx/3xx | ||
| if stats[8][0] in ('2', '3') and dist in dists: | ||
| dists[dist]['up'] += int(stats[-2]) | ||
| dists[dist]['down'] += int(stats[-1]) | ||
| else: | ||
| dists['other']['up'] += int(stats[-2]) | ||
| dists['other']['down'] += int(stats[-1]) | ||
|
|
||
| return dists | ||
|
|
||
|
|
||
| def to_mysql(dists, dt=None, quiet=False): | ||
| dt = dt or date.today() | ||
| conn = pymysql.connect( | ||
| host='mysql.ocf.berkeley.edu', | ||
| user='ocfstats', | ||
| password=OCFSTATS_PWD, | ||
| db='ocfstats', | ||
| autocommit=True, | ||
| cursorclass=pymysql.cursors.DictCursor, | ||
| ) | ||
|
|
||
| with conn as cursor: | ||
| for dist in dists: | ||
| cursor.execute( | ||
| 'INSERT INTO `mirrors` (`date`, `dist`, `up`, `down`) VALUES (%s, %s, %s, %s)', | ||
| (dt, dist, dists[dist]['up'], dists[dist]['down']) | ||
| ) | ||
|
|
||
| if not quiet: | ||
| print('{:20} {:8} {:8}'.format(dist, | ||
| _humanize(dists[dist]['up']), | ||
| _humanize(dists[dist]['down']))) | ||
|
|
||
| def _humanize(n): | ||
| for unit in ['', 'KB', 'MB', 'GB', 'TB', 'PB']: | ||
| if n < 1024.0: | ||
| return '{:3.2f} {}'.format(n, unit) | ||
| n /= 1024.0 | ||
|
|
||
| if __name__ == '__main__': | ||
| parser = argparse.ArgumentParser(description='Process mirrors logs to calculate network usage ' | ||
| 'and store in ocfstats') | ||
| parser.add_argument('-q', '--quiet', action='store_true', | ||
| help='do not print stats after collecting them') | ||
| parser.add_argument('log_files', nargs='*', | ||
| help='log file(s) to process') | ||
| parser.add_argument('date', nargs='?', default=date.today() - timedelta(1), | ||
| help='date for use in filtering log entries') | ||
|
|
||
| args = parser.parse_args() | ||
|
|
||
| if not args.log_files: | ||
| log = os.path.join(LOG_PATH, LOG_NAME) | ||
| # logrotate rotates the log at 6am, but this script | ||
| # runs at midnight. So to capture 24h of data, we need | ||
| # to parse the rotated log as well. | ||
| log_files = [log, log + '.1'] | ||
| else: | ||
| log_files = args.log_files | ||
|
|
||
| sources = [mirrored for mirrored in os.listdir(MIRRORS_PATH) | ||
| if os.path.isdir(os.path.join(MIRRORS_PATH, mirrored)) and not mirrored.startswith('.')] | ||
|
|
||
| sources.append('other') # catchall | ||
|
|
||
| dists = {mirrored: {'up': 0, 'down': 0} for mirrored in sources} | ||
|
|
||
| for fn in log_files: | ||
| dists = process_log(dists, fn, args.date) | ||
|
|
||
| to_mysql( | ||
| dists = dists, | ||
| dt = args.date, | ||
| quiet = args.quiet | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think I forgot to mention this before, but the reason why I was using
mirrors.ocf.berkeley.edu_access.log.1instead of this was because the logs get rotated at around 6 AM, so if you check them once a day, unless you check very close to when they are rotated, you lose some data. For example, this is currently checked at midnight, so all the data from midnight to around 6 AM is currently lost since it is rotated before the next midnight.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Another option I just thought of is to scan both log files and check if the date is within the current day, that might be the best if you truly want the numbers to be representative of the actual day boundaries instead of 6 AM - 6 AM the next day. (honestly I don't think it matters, but it wouldn't be too bad to scan both log files either)