53 lines
2.1 KiB
Python
Executable File
53 lines
2.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
r"""
|
|
Documentation
|
|
|
|
License: This program is released under the MIT License
|
|
"""
|
|
|
|
# Imports
|
|
import boto3
|
|
from datetime import datetime, timedelta
|
|
from dateutil.relativedelta import relativedelta
|
|
import humanize
|
|
|
|
# Main function
|
|
def main() -> None:
|
|
# get distributions
|
|
cw = boto3.client('cloudwatch', region_name='us-east-1')
|
|
cf = boto3.client('cloudfront', region_name='us-east-1')
|
|
distros = cf.list_distributions()['DistributionList']['Items']
|
|
dist_ids = [d['Id'] for d in distros if d['Status'] == 'Deployed']
|
|
|
|
for dist_id in dist_ids:
|
|
for month_offset in range(-3, 0): # Past 3 months
|
|
now = datetime.now()
|
|
first_of_current_month = now.replace(day=1)
|
|
start = (first_of_current_month + relativedelta(months=month_offset)).replace(day=1)
|
|
end = (start + relativedelta(months=1)) - relativedelta(seconds=1) # Last day
|
|
|
|
# BytesDownloaded
|
|
bytes_resp = cw.get_metric_statistics(
|
|
Namespace='AWS/CloudFront', MetricName='BytesDownloaded',
|
|
Dimensions=[{'Name': 'DistributionId', 'Value': dist_id}, {'Name': 'Region', 'Value': 'Global'}],
|
|
StartTime=start, EndTime=end, Period=2678400, Statistics=['Sum']
|
|
)
|
|
bytes_total = bytes_resp['Datapoints'][0]['Sum'] if bytes_resp['Datapoints'] else 0
|
|
|
|
# Requests
|
|
reqs_resp = cw.get_metric_statistics(
|
|
Namespace='AWS/CloudFront', MetricName='Requests',
|
|
Dimensions=[{'Name': 'DistributionId', 'Value': dist_id}, {'Name': 'Region', 'Value': 'Global'}],
|
|
StartTime=start, EndTime=end, Period=2678400, Statistics=['Sum']
|
|
)
|
|
reqs_total = reqs_resp['Datapoints'][0]['Sum'] if reqs_resp['Datapoints'] else 0
|
|
|
|
# only interested in distro with high traffic (>10G)
|
|
if bytes_total > 10 * 1024 ** 3:
|
|
print(f"{dist_id}: {start:%Y-%b} Requests: {reqs_total:,.0f} BytesDownloaded: {humanize.naturalsize(bytes_total)}")
|
|
|
|
|
|
# Call main function
|
|
if __name__ == '__main__':
|
|
main()
|