-
Notifications
You must be signed in to change notification settings - Fork 0
/
akamai_api_wrapper.py
executable file
·151 lines (122 loc) · 7.22 KB
/
akamai_api_wrapper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#!/usr/bin/env python
from JsonObject import JsonObject
from CustomFormatter import CustomFormatter
import os
import sys
import argparse
import textwrap
from AkamaiResponse import AkamaiResponse
from Email import Email
with open('auth', 'r') as f:
auth = eval(f.read())
purge_request_post_uri = 'https://api.ccu.akamai.com/ccu/v2/queues/default'
purge_queues_get_uri = 'https://api.ccu.akamai.com/ccu/v2/queues/default'
purge_status_get_uri = 'https://api.ccu.akamai.com/ccu/v2/purges/'
def set_credentials():
return auth.get('username') if getattr(parsed_args, 'akamai_user') is None else getattr(parsed_args,
'akamai_user'), auth.get(
'username') if getattr(parsed_args, 'akamai_password') is None else getattr(parsed_args, 'akamai_password')
def send_email_notification(message, subject):
with open('email_settings', 'r') as f:
email_settings = eval(f.read())
sender = email_settings.get('default_sender')
recipient = email_settings.get('default_recipient')
if sender is not None:
recipients = recipient if getattr(parsed_args, 'email_recipients') is None else getattr(parsed_args, 'email_recipients')
if recipients is not None:
email = Email(subject, message, sender, recipients)
email.build_and_send()
def do_purge():
data2purge = getattr(parsed_args, 'data2purge')
if data2purge is None:
print 'you MUST specify what to purge'
sys.exit(1)
if os.path.isfile(data2purge):
f = open(data2purge)
data2purge = f.read()
f.close()
data = JsonObject(data2purge, getattr(parsed_args, 'object_type'), getattr(parsed_args, 'domain'),
getattr(parsed_args, 'akamai_action')).get_json()
do_request_and_handle_response(purge_request_post_uri, method='POST', data=data, original_success=201)
def do_check_status():
purgeid = getattr(parsed_args, 'purgeid')
if purgeid is None:
print 'you MUST specify a purgeid'
sys.exit(1)
purgeid = purgeid.replace('/ccu/v2/purges/', '')
do_request_and_handle_response(purge_status_get_uri + purgeid)
def do_check_queues():
do_request_and_handle_response(purge_queues_get_uri)
def do_request_and_handle_response(uri, method='GET', data=None, original_success=200):
success = original_success
ar = AkamaiResponse(username, password, uri, method=method, data=data, success=original_success)
subject = 'Your Akamai API-Request'
if method == 'POST':
subject, message, response = ar.get_response_but_wait_for_purge_completion()
success = 200
else:
message, response = ar.get_response()
if response.status_code == success:
print message
if getattr(parsed_args, 'send_mail_on_success'):
send_email_notification(message, subject)
else:
print 'something went wrong. please check the message'
try:
for x, y in response.json().iteritems():
message += str(x) + ': ' + str(y) + '\n'
except ValueError as e:
message = response.text
message = 'REQUEST: \nURL: ' + uri + '\nDATA: ' + (data if data is not None else 'None') + '\n\nRESULT:\n' + message
print message
if getattr(parsed_args, 'send_mail_on_error'):
send_email_notification(message, 'Akamai - Error while talking to API')
sys.exit(1)
def usage():
return 'see some examples (at the bottom)'
def epilog(name):
return textwrap.dedent('''\
- file auth must be present and contain a dict with username and password e.g. {'username': 'test', 'password': 'pass'}
- file cpcode must be present and contain a dict with cpode and human readable name for it e.g. {111: 'FOO', 222: 'BAR'}
- file email_settings must be present e.g. {'default_sender': 'foo@bar.com', 'default_recipient': 'foo@bar.com'}
some examples
--------------------------------
%s --do_purge -data testdata.txt (for purging the content of file testdata.txt - since no object_type is given, the content is assumend URLs)
%s --do_purge -data "www.foo.bar/test1, www.bar.foo/test2?me" (for purging www.foo.bar/test1 and www.bar.foo/test2?me)
%s --do_purge --object_type cpcode -data 12345 (for purging the content of the cpcode 12345)
%s --do_purge --object_type cpcode -data 12345 --send_mail_on_success True --email_recipients "sender@domain.org" (for purging the content of the cpcode 12345 and sending the response/result to the given email-address)
%s --do_purge --object_type cpcode -data FOO --domain staging (for purging the content of the cpcode FOO in staging, where FOO is a mapped cpcode for better reading and understanding)
%s --do_check_status
%s --do_check_queues
valid cpcodes are %s
for more examples and possibilities refer to https://api.ccu.akamai.com/ccu/v2/docs/index.html#section_Reference and read the optional arguments from this program
''' % (name, name, name, name, name, name, name, JsonObject.print_cpcode()))
parser = argparse.ArgumentParser(epilog=epilog(sys.argv[0].split(os.path.sep)[-1]), usage=usage(),
formatter_class=CustomFormatter)
parser.add_argument('--do_purge', dest='action', action='store_const', const=do_purge,
help='purge a list of urls/arls or cpcodes')
parser.add_argument('--do_check_status', dest='action', action='store_const', const=do_check_status,
help='check the status of a given purgeid')
parser.add_argument('--do_check_queues', dest='action', action='store_const', const=do_check_queues,
help='check the current queuelength')
parser.add_argument('--object_type', '-o', type=str, default='arl', metavar='arl or cpcode', choices=['arl', 'cpcode'],
help=' ')
parser.add_argument('--domain', '-d', type=str, default='production', metavar='production or staging',
choices=['production', 'staging'], help=' ')
parser.add_argument('--akamai_action', '-a', type=str, default='remove', metavar='remove or invalidate',
choices=['remove', 'invalidate'], help=' ')
parser.add_argument('--data2purge', '-data', default=None,
help='can be a file which contains the objects to purge or a list on the comand line')
parser.add_argument('--purgeid', '-id', type=str, default=None, metavar='to check', help=' ')
parser.add_argument('--send_mail_on_success', type=bool, default=False, metavar='send optional email on success',
help=' ')
parser.add_argument('--send_mail_on_error', type=bool, default=True, metavar='send optional email on error', help=' ')
parser.add_argument('--email_recipients', type=str, default=None, metavar='email addresses to send result to', help=' ')
parser.add_argument('--akamai_user', '-u', type=str, default=None, metavar='overwrite akamai user with this', help=' ')
parser.add_argument('--akamai_password', '-p', type=str, default=None, metavar='overwrite akamai password with this',
help=' ')
parsed_args = parser.parse_args()
if parsed_args.action is None:
parser.parse_args(['-h'])
(username, password) = set_credentials()
parsed_args.action()