This repository has been archived by the owner on May 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 48
/
logs_api.py
201 lines (161 loc) · 6.78 KB
/
logs_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import requests
import json
import utils
import clickhouse
import datetime
import logging
if utils.get_python_version().startswith('2'):
from urllib import urlencode
else:
from urllib.parse import urlencode
logger = logging.getLogger('logs_api')
HOST = 'https://api-metrika.yandex.ru'
def get_estimation(user_request):
'''Returns estimation of Logs API (whether it's possible to load data and max period in days)'''
url_params = urlencode(
[
('date1', user_request.start_date_str),
('date2', user_request.end_date_str),
('source', user_request.source),
('fields', ','.join(user_request.fields))
]
)
headers = {'Authorization': 'OAuth ' + user_request.token}
url = '{host}/management/v1/counter/{counter_id}/logrequests/evaluate?'\
.format(host=HOST, counter_id=user_request.counter_id) + url_params
r = requests.get(url, headers=headers)
if r.status_code == 200:
return json.loads(r.text)['log_request_evaluation']
else:
raise ValueError(r)
def get_api_requests(user_request):
'''Returns list of API requests for UserRequest'''
api_requests = []
estimation = get_estimation(user_request)
if estimation['possible']:
api_request = utils.Structure(
user_request=user_request,
date1_str=user_request.start_date_str,
date2_str=user_request.end_date_str,
status='new'
)
api_requests.append(api_request)
elif estimation['max_possible_day_quantity'] != 0:
start_date = datetime.datetime.strptime(
user_request.start_date_str,
utils.DATE_FORMAT
)
end_date = datetime.datetime.strptime(
user_request.end_date_str,
utils.DATE_FORMAT
)
days = (end_date - start_date).days
num_requests = int(days/estimation['max_possible_day_quantity']) + 1
days_in_period = int(days/num_requests) + 1
for i in range(num_requests):
date1 = start_date + datetime.timedelta(i*days_in_period)
date2 = min(
end_date,
start_date + datetime.timedelta((i+1)*days_in_period - 1)
)
api_request = utils.Structure(
user_request=user_request,
date1_str=date1.strftime(utils.DATE_FORMAT),
date2_str=date2.strftime(utils.DATE_FORMAT),
status='new'
)
api_requests.append(api_request)
else:
raise RuntimeError('Logs API can\'t load data: max_possible_day_quantity = 0')
return api_requests
def create_task(api_request):
'''Creates a Logs API task to generate data'''
url_params = urlencode(
[
('date1', api_request.date1_str),
('date2', api_request.date2_str),
('source', api_request.user_request.source),
('fields', ','.join(sorted(api_request.user_request.fields, key=lambda s: s.lower())))
]
)
url = '{host}/management/v1/counter/{counter_id}/logrequests?'\
.format(host=HOST,
counter_id=api_request.user_request.counter_id) \
+ url_params
headers = {'Authorization': 'OAuth ' + api_request.user_request.token}
r = requests.post(url, headers=headers)
logger.debug(r.text)
if r.status_code == 200:
logger.debug(json.dumps(json.loads(r.text)['log_request'], indent=2))
response = json.loads(r.text)['log_request']
api_request.status = response['status']
api_request.request_id = response['request_id']
# api_request.size = response['size']
return response
else:
raise ValueError(r.text)
def update_status(api_request):
'''Returns current tasks\'s status'''
url = '{host}/management/v1/counter/{counter_id}/logrequest/{request_id}' \
.format(request_id=api_request.request_id,
counter_id=api_request.user_request.counter_id,
host=HOST)
headers = {'Authorization': 'OAuth ' + api_request.user_request.token}
r = requests.get(url, headers=headers)
logger.debug(r.text)
if r.status_code == 200:
status = json.loads(r.text)['log_request']['status']
api_request.status = status
if status == 'processed':
size = len(json.loads(r.text)['log_request']['parts'])
api_request.size = size
return api_request
else:
raise ValueError(r.text)
def save_data(api_request, part):
'''Loads data chunk from Logs API and saves to ClickHouse'''
url = '{host}/management/v1/counter/{counter_id}/logrequest/{request_id}/part/{part}/download' \
.format(
host=HOST,
counter_id=api_request.user_request.counter_id,
request_id=api_request.request_id,
part=part
)
headers = {'Authorization': 'OAuth ' + api_request.user_request.token}
r = requests.get(url, headers=headers)
if r.status_code != 200:
logger.debug(r.text)
raise ValueError(r.text)
splitted_text = r.text.split('\n')
logger.info('### DATA SAMPLE')
logger.info('\n'.join(splitted_text[:5]))
headers_num = len(splitted_text[0].split('\t'))
splitted_text_filtered = list(filter(lambda x: len(x.split('\t')) == headers_num, r.text.split('\n')))
num_filtered = len(splitted_text) - len(splitted_text_filtered)
if num_filtered != 0:
logger.warning('%d rows were filtered out' % num_filtered)
if len(splitted_text_filtered) > 1:
output_data = '\n'.join(splitted_text_filtered[1:]) #.encode('utf-8')
output_data = '\t'.join(map(clickhouse.get_ch_field_name, splitted_text_filtered[0].split('\t'))) + '\n' + output_data # convert headers to CH column names
output_data = output_data.replace(r"\'", "'") # to correct escapes in params
clickhouse.save_data(api_request.user_request.source,
api_request.user_request.fields,
output_data)
else:
logger.warning('### No data to upload')
api_request.status = 'saved'
def clean_data(api_request):
'''Cleans generated data on server'''
url = '{host}/management/v1/counter/{counter_id}/logrequest/{request_id}/clean' \
.format(host=HOST,
counter_id=api_request.user_request.counter_id,
request_id=api_request.request_id)
headers = {'Authorization': 'OAuth ' + api_request.user_request.token}
r = requests.post(url, headers=headers)
logger.debug(r.text)
if r.status_code != 200:
raise ValueError(r.text)
api_request.status = json.loads(r.text)['log_request']['status']
return json.loads(r.text)['log_request']