|
| 1 | +import argparse |
| 2 | +import gzip |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import sys |
| 6 | +from collections import defaultdict |
| 7 | +from datetime import datetime, timezone |
| 8 | + |
| 9 | +import arrow |
| 10 | +import requests |
| 11 | + |
| 12 | +from iyp import BaseCrawler, DataNotAvailableError |
| 13 | + |
| 14 | +# URL to AS2Org API |
| 15 | +URL = 'https://publicdata.caida.org/datasets/as-organizations/' |
| 16 | +ORG = 'CAIDA' |
| 17 | +NAME = 'caida.as2org' |
| 18 | + |
| 19 | + |
| 20 | +# (:AS)-[:MANAGED_BY]->(:Organization) // Most relevant |
| 21 | +# (:Organization)-[:COUNTRY]->(:Country) |
| 22 | +# (:Organization)-[:NAME]->(:Name) |
| 23 | + |
| 24 | +class Crawler(BaseCrawler): |
| 25 | + |
| 26 | + def __init__(self, organization, url, name): |
| 27 | + super().__init__(organization, url, name) |
| 28 | + self.reference['reference_url_info'] = 'https://publicdata.caida.org/datasets/as-organizations/README.txt' |
| 29 | + |
| 30 | + def __set_modification_time_from_metadata_line(self, date_str): |
| 31 | + try: |
| 32 | + date = datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S').replace(tzinfo=timezone.utc) |
| 33 | + self.reference['reference_time_modification'] = date |
| 34 | + except (json.JSONDecodeError, KeyError, ValueError) as e: |
| 35 | + logging.warning(f'Failed to get modification date from metadata line: {date_str.strip()}') |
| 36 | + logging.warning(e) |
| 37 | + logging.warning('Using date from filename.') |
| 38 | + |
| 39 | + def run(self): |
| 40 | + date = arrow.now() |
| 41 | + for _ in range(6): |
| 42 | + full_url = URL + f'{date.year}{date.month:02d}01.as-org2info.txt.gz' |
| 43 | + req = requests.head(full_url) |
| 44 | + |
| 45 | + # Found the latest file |
| 46 | + if req.status_code == 200: |
| 47 | + url = full_url |
| 48 | + break |
| 49 | + |
| 50 | + date = date.shift(months=-1) |
| 51 | + |
| 52 | + else: |
| 53 | + # for loop was not 'broken', no file available |
| 54 | + raise DataNotAvailableError('No recent CAIDA as2org file available') |
| 55 | + date = date.datetime.replace(day=1, hour=0, minute=0, second=0, microsecond=0, tzinfo=timezone.utc) |
| 56 | + self.reference['reference_time_modification'] = date |
| 57 | + self.reference['reference_url_data'] = url |
| 58 | + |
| 59 | + logging.info(f'Fetching data from: {url}') |
| 60 | + req = requests.get(self.url) |
| 61 | + req.raise_for_status() |
| 62 | + |
| 63 | + logging.info('Processing data...') |
| 64 | + |
| 65 | + data = gzip.decompress(req.content).decode() |
| 66 | + lines = data.split('\n') |
| 67 | + |
| 68 | + lines = [line for line in lines if line.strip()] |
| 69 | + |
| 70 | + orgs_mode = True |
| 71 | + asn_orgid = dict() |
| 72 | + name_country_orgids = defaultdict(lambda: defaultdict(set)) |
| 73 | + name_orgids = defaultdict(set) |
| 74 | + orgid_name = dict() |
| 75 | + countries = set() |
| 76 | + for line in lines: |
| 77 | + if line == '# format:org_id|changed|org_name|country|source': |
| 78 | + orgs_mode = True |
| 79 | + elif line == '# format:aut|changed|aut_name|org_id|opaque_id|source': |
| 80 | + orgs_mode = False |
| 81 | + elif 'program start time' in line: |
| 82 | + date = line.split('program start time:')[1] |
| 83 | + date = date.strip() |
| 84 | + self.__set_modification_time_from_metadata_line(date) |
| 85 | + |
| 86 | + if line.startswith('#'): |
| 87 | + continue |
| 88 | + |
| 89 | + fields = line.split('|') |
| 90 | + |
| 91 | + # extract org information with format: |
| 92 | + # org_id|changed|org_name|country|source |
| 93 | + # NB changed and source fields not used |
| 94 | + if orgs_mode: |
| 95 | + org_id = fields[0] |
| 96 | + if org_id.startswith('@del'): |
| 97 | + # There are some placeholder organizations with no name and IDs |
| 98 | + # starting with @del, which probably indicate some old relationship |
| 99 | + # that no longer exists. Does not make sense to model them, since |
| 100 | + # they all map to the same Organization node with an empty name. |
| 101 | + continue |
| 102 | + org_name = fields[2] |
| 103 | + country = fields[3] |
| 104 | + # Index by name, since this the identifier of the Organization node. |
| 105 | + # Keep track of which org ID is the source for a country. Some orgs have |
| 106 | + # multiple IDs mapping them to different countries, |
| 107 | + name_country_orgids[org_name][country].add(org_id) |
| 108 | + countries.add(country) |
| 109 | + # Some orgs (with the same name) map to multiple IDs. |
| 110 | + name_orgids[org_name].add(org_id) |
| 111 | + orgid_name[org_id] = org_name |
| 112 | + |
| 113 | + # extract org to as mapping with format: |
| 114 | + # aut|changed|aut_name|org_id|opaque_id|source |
| 115 | + # NB changed, aut_name, opaque_id, and source fields not used |
| 116 | + else: |
| 117 | + asn = int(fields[0]) |
| 118 | + org_id = fields[3] |
| 119 | + if org_id.startswith('@del'): |
| 120 | + continue |
| 121 | + asn_orgid[asn] = org_id |
| 122 | + |
| 123 | + names = set(name_orgids.keys()) |
| 124 | + org_ids = set(orgid_name.keys()) |
| 125 | + ases = set(asn_orgid.keys()) |
| 126 | + caida_org_id = self.iyp.batch_get_nodes_by_single_prop('CaidaOrgID', 'id', org_ids) |
| 127 | + as_id = self.iyp.batch_get_nodes_by_single_prop('AS', 'asn', ases) |
| 128 | + organization_id = self.iyp.batch_get_nodes_by_single_prop('Organization', 'name', names) |
| 129 | + name_id = self.iyp.batch_get_nodes_by_single_prop('Name', 'name', names) |
| 130 | + country_id = self.iyp.batch_get_nodes_by_single_prop('Country', 'country_code', countries) |
| 131 | + |
| 132 | + managed_links = list() |
| 133 | + for asn, org_id in asn_orgid.items(): |
| 134 | + org_qid = organization_id[orgid_name[org_id]] |
| 135 | + asn_qid = as_id[asn] |
| 136 | + managed_links.append({'src_id': asn_qid, 'dst_id': org_qid, |
| 137 | + 'props': [self.reference, {'org_id': org_id}]}) |
| 138 | + |
| 139 | + name_links = list() |
| 140 | + country_links = list() |
| 141 | + external_id_links = list() |
| 142 | + |
| 143 | + for name in name_orgids: |
| 144 | + org_ids = name_orgids[name] |
| 145 | + org_qid = organization_id[name] |
| 146 | + name_qid = name_id[name] |
| 147 | + |
| 148 | + name_links.append({'src_id': org_qid, 'dst_id': name_qid, |
| 149 | + 'props': [self.reference, {'org_ids': list(org_ids)}]}) |
| 150 | + |
| 151 | + for org_id in org_ids: |
| 152 | + caida_org_id_qid = caida_org_id[org_id] |
| 153 | + external_id_links.append({'src_id': org_qid, 'dst_id': caida_org_id_qid, 'props': [self.reference]}) |
| 154 | + |
| 155 | + for country, org_ids in name_country_orgids[name].items(): |
| 156 | + country_qid = country_id[country] |
| 157 | + country_links.append({'src_id': org_qid, 'dst_id': country_qid, |
| 158 | + 'props': [self.reference, {'org_ids': list(org_ids)}]}) |
| 159 | + |
| 160 | + self.iyp.batch_add_links('COUNTRY', country_links) |
| 161 | + self.iyp.batch_add_links('EXTERNAL_ID', external_id_links) |
| 162 | + self.iyp.batch_add_links('MANAGED_BY', managed_links) |
| 163 | + self.iyp.batch_add_links('NAME', name_links) |
| 164 | + |
| 165 | + def unit_test(self): |
| 166 | + return super().unit_test(['COUNTRY', 'EXTERNAL_ID', 'MANAGED_BY', 'NAME']) |
| 167 | + |
| 168 | + |
| 169 | +def main() -> None: |
| 170 | + parser = argparse.ArgumentParser() |
| 171 | + parser.add_argument('--unit-test', action='store_true') |
| 172 | + args = parser.parse_args() |
| 173 | + |
| 174 | + FORMAT = '%(asctime)s %(levelname)s %(message)s' |
| 175 | + logging.basicConfig( |
| 176 | + format=FORMAT, |
| 177 | + filename='log/' + NAME + '.log', |
| 178 | + level=logging.INFO, |
| 179 | + datefmt='%Y-%m-%d %H:%M:%S' |
| 180 | + ) |
| 181 | + |
| 182 | + logging.info(f'Started: {sys.argv}') |
| 183 | + |
| 184 | + crawler = Crawler(ORG, URL, NAME) |
| 185 | + if args.unit_test: |
| 186 | + crawler.unit_test() |
| 187 | + else: |
| 188 | + crawler.run() |
| 189 | + crawler.close() |
| 190 | + logging.info(f'Finished: {sys.argv}') |
| 191 | + |
| 192 | + |
| 193 | +if __name__ == '__main__': |
| 194 | + main() |
| 195 | + sys.exit(0) |
0 commit comments