1a1a11a's picture
Add files using upload-large-folder tool
8dc315b verified
import os, sys
import csv
import time
import datetime
import time, datetime
import pickle, json
from threading import Thread, Lock
from multiprocessing import Process, Queue, Lock
from concurrent.futures import ProcessPoolExecutor, as_completed
from inspect import currentframe, getframeinfo
from collections import defaultdict
import hashlib
import re
import IP2Location
import geoip2.database
ip_database = geoip2.database.Reader("GeoLite2-Country.mmdb")
# ip_database_v4 = IP2Location.IP2Location("IP-COUNTRY.BIN", "SHARE_MEMORY")
# ip_database_v6 = IP2Location.IP2Location("IPV6-COUNTRY.BIN", "SHARE_MEMORY")
s = '2021-08-19T23:00:39.753 28m480 2021/08/19 23:00:39 [error] 1094334#1094334: *4470570 [lua] log_main.lua:420: extra_logging(): {"resp_size":"1889","length":"39","zone":"103893895","body_size":"39","cstatus":"MISS","plan":"ENT","src":"cache","cc":"no-store, no-cache, must-revalidate, max-age=0","jira":"CACHE-8300","method":"GET","key":"0ec9788cd6532247d8369d483f8b95a6","type":"text\/plain; charset=UTF-8","obody_size":"39","osize":"296","ts":1629414039.753} while logging request, client: 97.113.133.242, id: 6816ffd443380939, server: 28c480, request: "GET /SIE/?Q_BID=tracfone&Q_CLIENTTYPE=MobileAndroid&Q_CLIENTVERSION=1.13&Q_DEVICEOS=9_28&Q_DEVICETYPE=motorola_moto%20g%286%29&Q_LOC=com.tracfone.tracfone.myaccount&Q_PageView=1&Q_SIID=SI_3EkJhpdZLwLyWA5&r=1629414039 HTTP/1.1", upstream: "https://162.247.217.100:443/SIE/?Q_BID=tracfone&Q_CLIENTTYPE=MobileAndroid&Q_CLIENTVERSION=1.13&Q_DEVICEOS=9_28&Q_DEVICETYPE=motorola_moto%20g%286%29&Q_LOC=com.tracfone.tracfone.myaccount&Q_PageView=1&Q_SIID=SI_3EkJhpdZLwLyWA5&r=1629414039", host: "zncvomiueeqmfxynn-tracfone.siteintercept.qualtrics.com", referrer: "com.tracfone.tracfone.myaccount"'
s = '2021-08-19T23:53:08.148 137m8 2021/08/19 23:53:08 [error] 3542366#3542366: *735895 [lua] log_main.lua:420: extra_logging(): {"resp_size":"21739","expire":"Fri, 20 Aug 2021 23:53:08 GMT","zone":"103899181","body_size":"18223","cstatus":"MISS","last_modified":["Fri, 25 Jun 2021 23:13:29 GMT","Fri, 25 Jun 2021 23:13:29 GMT"],"plan":"ENT","src":"cache","cc":"public, max-age=86400","jira":"CACHE-8300","method":"GET","key":"5edda60a313d23db437a9e50792855cd","type":"image\/jpeg","obody_size":"18223","osize":"20307","ts":1629417188.148} while logging request, client: 73.214.193.14, id: 68174cb0eec5f176, server: 137c8, request: "GET /media/hms/THUM/4/DSnoJ?_a=ChgyMDIxMDgxOTIzNDUwNjIwNDo1NjU5MTkSBTg0NTg3GgpPTkVfU0VBUkNIIg4xOTIuMjAzLjIzMy4zNSoHMjAzMjMyMDIKMjU0NDkzOTkwODoLSW5saW5lSW1hZ2VCATBSBk9ubGluZVoDSUxJYgRUSFVNagoyMDIxLzAxLzAxcgoyMDIxLzEyLzMxegCCASlQLTEwMDc4NTYtMjgzNjUtQ1VTVE9NRVItMTAwMDAyNTUtNTc2OTM3M5IBBk9ubGluZcoBeU1vemlsbGEvNS4wIChNYWNpbnRvc2g7IEludGVsIE1hYyBPUyBYIDEwXzE1XzcpIEFwcGxlV2ViS2l0LzUzNy4zNiAoS0hUTUwsIGxpa2UgR2Vja28pIENocm9tZS85Mi4wLjQ1MTUuMTA3IFNhZmFyaS81MzcuMzbSARJTY2hvbGFybHkgSm91cm5hbHOaAgdQcmVQYWlkqgIsT1M6RU1TLVRleHRQbHVzR3JhcGhpY3NDb250YWluZXItcHJlcGFyZUJvZHnKAg9BcnRpY2xlfEZlYXR1cmXiAgDyAgD6AgFZggMDV2ViigMcQ0lEOjIwMjEwODE5MjM0NTA2MjYzOjg5NDM4Ng%3D%3D&_s=oosxWzL5AWX7t4Ii7OiQIFf4jVY%3D HTTP/1.1", upstream: "http://unix:/cf/socks/nginx-be.sock/@@argo/?ray=68174cb0eec5f176", host: "media.proquest.com", referrer: "https://www-proquest-com.reddog.rmu.edu/"'
s = '2021-08-20T00:48:24.913 35m780 2021/08/20 00:48:24 [error] 61992#61992: *4137811 [lua] log_main.lua:420: extra_logging(): {"resp_size":"6814","length":"4372","expire":"Fri, 24 Jun 2022 16:43:55 GMT","zone":"26539756","body_size":"4372","cstatus":"MISS","last_modified":"Thu, 24 Jun 2021 16:43:55 GMT","src":"cache","cc":"public, max-age=31536000, s-maxage=31536000, stale-while-revalidate=63072000, stale-if-error=63072000","jira":"CACHE-8300","method":"GET","key":"9b5c61632e311f75ec698a8950bd0eb0","type":"image\/jpeg","ts":1629420504.913} while logging request, client: 113.184.81.90, id: 68179daba80701e1, server: 35c780, request: "GET /bloganchoi.com/wp-content/uploads/2017/09/lee-jong-suk-anh-bia-218x150.jpg?fit=218%2C20000&quality=95&ssl=1 HTTP/1.1", host: "i.bloganchoi.com", referrer: "https://bloganchoi.com/"'
s = '2021-08-21T00:17:14.098 27m376 2021/08/21 00:17:14 [error] 803136#803136: *164921146 [lua] log_main.lua:420: extra_logging(): {"resp_size":"196878","length":"194247","zone":"203788237","body_size":"194247","cstatus":"HIT","plan":"FREE","src":"cache","cc":"public, max-age=31536000","jira":"CACHE-8300","method":"GET","key":"702d065cf85479789d3ffec28759280d","type":"\xecmage\/jpeg","ts":1629505034.098} while logging request, client: 34.73.126.234, id: 681fad5ef847f309, server: 27c376, request: "GET /assets/image/314fc099-6532-470f-8cd5-bb096d0ab5f3.jpeg HTTP/1.1", host: "www.merfolkslullaby.com"'
regex = re.compile(r'(?P<ts>.+?) (?P<node>.+?) .+? (?P<jmsg>{.+?}) while logging request, client: (?P<ip>[0-9a-z.:]+?), .+? request: "(?P<request>.+?)"(?P<upstream>, upstream: ".*?")?(?P<host>, host: ".*?")?(?P<referrer>, referrer: ".*?")?')
# when request is too long and log line ends with partial request
regex2 = re.compile(r'(?P<ts>.+?) (?P<node>.+?) .+? (?P<jmsg>{.+?}) while logging request, client: (?P<ip>[0-9a-z.:]+?), .+? request: "(?P<request>.+?)(?P<host>.*?)')
n = 0
n_dynamic = 0
n_expire_err = 0
n_last_modified_err = 0
def parse_test():
# regex = re.compile(r'(?P<ts>.+?) (?P<node>.+?) .+? (?P<jmsg>{.+?}) while logging request, client: (?P<ip>[0-9.]+?), .+? request: "(?P<request>.+?)", ')
m = regex.match(s)
# print(m)
# print(m.group("ts"))
# print(m.group("node"))
# print(jmsg)
# print(m.group("request"))
# print(m.group("ip"))
# req_ts = datetime.datetime.strptime(m.group("ts").split(".")[0], "%Y-%m-%dT%H:%M:%S")
# exp_ts = datetime.datetime.strptime(jmsg["expire"], "%Y-%m-%dT%H:%M:%S")
print(m)
def parse_logline(log_line):
global n_expire_err, n_last_modified_err, n_dynamic
m = regex.match(log_line)
if not m:
m = regex2.match(log_line)
jmsg = json.loads(m.group("jmsg"))
cstatus = jmsg.pop("cstatus", "noStatus")
if cstatus == "DYNAMIC":
n_dynamic += 1
return None
if "key" not in jmsg:
assert "/cdn-cgi/build/nginx-cache" in log_line or "multipart\/mirage-bag-base64" in log_line, "key error "
return None
ts = str(int(jmsg.pop("ts")))
obj_id = jmsg.pop("key")
body_sz = jmsg.pop("body_size")
resp_sz = jmsg.pop("resp_size")
obody_sz = jmsg.pop("obody_size", 0)
oresp_sz = jmsg.pop("osize", 0)
method = jmsg.pop("method")
content_type = jmsg.pop("type", "no_type").replace(" ", "")
if ";" in content_type:
# assert len(content_type.split(";")) == 2, "content type error 1 " + content_type
# assert content_type.split(";")[1].lower() == "charset=utf-8", "content type error 2 " + content_type
content_type = content_type.split(";")[0]
if "/" in content_type:
content_type = content_type.split("/")[1]
content_length = jmsg.pop("length", "")
zone = jmsg.pop("zone", "-1")
plan = jmsg.pop("plan", "noPlan")
src = jmsg.pop("src")
range = jmsg.pop("range", "")
if range:
if range.startswith("bytes"):
range = range[6:]
range = range.split("/")[0]
# assert(int(range[0].split("-")[1]) - int(range[0].split("-")[0]) + 1 == int(range[1]))
jmsg.pop("jira")
cache_control = jmsg.pop("cc", "no-cache-control")
if isinstance(cache_control, list):
cache_control = ";".join(cache_control)
else:
cache_control = cache_control.replace(",", ";").replace(" ", "")
req_time = m.group("ts").strip()
req_time = datetime.datetime.strptime(req_time.split(".")[0], "%Y-%m-%dT%H:%M:%S")
expire_ttl = -1
expire = jmsg.pop("expire", "")
if not isinstance(expire, list):
expire = expire.strip()
if expire:
try:
expire = datetime.datetime.strptime(expire, "%a, %d %b %Y %H:%M:%S GMT")
expire_ttl = int((expire - req_time).total_seconds())
except Exception as e:
try:
expire_ttl = int(expire)
except Exception as e:
n_expire_err += 1
age = -1
last_modified = jmsg.pop("last_modified", "")
if not isinstance(last_modified, list):
last_modified = last_modified.strip()
if last_modified:
try:
last_modified = datetime.datetime.strptime(last_modified, "%a, %d %b %Y %H:%M:%S GMT")
age = int((req_time - last_modified).total_seconds())
except Exception as e:
n_last_modified_err += 1
extension = ""
if len(m.group("request").split()) > 1:
path = m.group("request").split()[1]
if '?' in path:
path = path[:path.find("?")]
if '.' in path:
extension = path.split(".")[-1]
if "?" in extension:
extension = extension[:extension.find("?")]
client = m.group("ip")
if client:
if client == '2a06:98c0:3600::103':
client = "cf"
try:
# client_country = ""
client_country = ip_database.country(client).country.iso_code
if client_country != None:
client = client_country
except Exception as e:
pass
node = m.group("node")
host = m.group("host")
if host:
host = host.split(":")[1].strip(' "')
host = str(int(hashlib.sha1(host.encode()).hexdigest(), 16) % (2**30))
else:
host = "-1"
assert len(jmsg) == 0, "jmsg is not empty" + str(jmsg)
chunked = "0"
if content_length == "":
chunked = "chunked"
if obody_sz == 0:
if cstatus not in ("HIT", "UPDATING", "noStatus"):
print("cstatus error ")
obody_sz = body_sz
elif body_sz != obody_sz:
# print(f"body size error {body_sz} {obody_sz}")
pass
has_query = "0"
n_param = "0"
if "?" in m.group("request"):
has_query = "1"
n_param = str(m.group("request").count("&") + 1)
n_level = "0"
try:
n_level = str(m.group("request").split(" ")[1].count("/") - 1)
except Exception as e:
pass
return node, client, src, ts, obj_id, body_sz, method, content_type, extension, n_level, expire_ttl, age, cstatus, zone, plan, chunked, has_query, n_param, cache_control, host, range
# print(f"{node}, {ts:16}, {body_sz:>8}, {method:>6}, {content_type:>6}, {cstatus:>6}, {plan:>4}, {src:>6}, {chunked}, {has_query}, {expire_ttl:>8}, {age:>8}, {extension:6}, {host}")
def parse_one_file(datapath, ofile_dict):
global n
ifile = open(datapath, errors="ignore")
for line in ifile:
n += 1
try:
t = parse_logline(line[:-1])
if not t:
continue
node, client, src, ts, obj_id, body_sz, method, content_type, extension, n_level, expire_ttl, age, cstatus, zone, plan, chunked, has_query, n_param, cache_control, host, http_range = t
ofile_dict[node].write(",".join([client, src, ts, obj_id, body_sz, method, content_type, extension, n_level, str(expire_ttl), str(age), cstatus, zone, plan, chunked, has_query, n_param, cache_control, host, http_range]) + "\n")
except Exception as e:
print(t)
print(e, line)
ifile.close()
def parse_one_file_parallel(datapath):
output_path_base = datapath.replace("raw", "data")
ifile = open(datapath, errors="ignore")
ofile_dict = {}
first_ts = -1
for line in ifile:
try:
t = parse_logline(line[:-1])
if not t:
continue
node, client, src, ts, obj_id, body_sz, method, content_type, extension, n_level, expire_ttl, age, cstatus, zone, plan, chunked, has_query, n_param, cache_control, host, http_range = t
if node not in ofile_dict:
ofile_dict[node] = open("{}_{}".format(output_path_base, node), "w")
ofile_dict[node].write(",".join([client, src, ts, obj_id, body_sz, method, content_type, extension, n_level, str(expire_ttl), str(age), cstatus, zone, plan, chunked, has_query, n_param, cache_control, host, http_range]) + "\n")
if first_ts == -1:
first_ts = ts
except Exception as e:
print(t)
print(e, line)
ifile.close()
for ofile in ofile_dict.values():
ofile.close()
print("{} time {} - {} ({}s)".format(datapath, first_ts, ts, ts - first_ts))
def run(colo, day):
ofile_dict = {}
for node in ("27m144", "27m376", "28m142", "28m480", "156m1", "156m2", "35m360", "35m780", "137m8", "137m18"):
if node.startswith(colo):
ofile_dict[node] = open("data/" + node, "a")
data = f"raw/colo{colo}_081923"
t = parse_one_file(data, ofile_dict)
for h in range(24):
if h < 10:
data = f"raw/colo{colo}_08{day}0{h}"
else:
data = f"raw/colo{colo}_08{day}{h}"
if not os.path.exists(data):
continue
t = parse_one_file(data, ofile_dict)
print("{:.0f} {}, {}, {} dynamic, {} expireEr, {} lastModifiedErr".format(time.time(), data, n, n_dynamic, n_expire_err, n_last_modified_err))
for ofile in ofile_dict.values():
ofile.close()
def run_parallel():
futures_dict = {}
with ProcessPoolExecutor(max_workers=80) as ppe:
for colo in (27, 28, 137, 156, 35):
for day in (20, 21, 22, 23, ):
data = f"raw/colo{colo}_08{day}"
# for h in range(24):
# if h < 10:
# data = f"raw/colo{colo}_08{day}0{h}"
# else:
# data = f"raw/colo{colo}_08{day}{h}"
# if not os.path.exists(data):
# continue
# parse_one_file_parallel(data)
futures_dict[ppe.submit(parse_one_file_parallel, data)] = data
for future in as_completed(futures_dict):
print("{} has finished running".format(futures_dict[future]))
if __name__ == "__main__":
# parse_one_file("27/081923")
# parse_test()
parse_logline(s)
# parse_one_file("raw/colo137_081923")
# run(sys.argv[1], 20)
# run_parallel()