django-ixp-tracker 0.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.1
2
+ Name: django-ixp-tracker
3
+ Version: 0.3
4
+ Summary: Library to retrieve and manipulate data about IXPs
5
+ Author: Internet Society
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/InternetSociety/django-ixp-tracker
8
+ Project-URL: Changelog, https://github.com/InternetSociety/django-ixp-tracker/releases
9
+ Project-URL: Issues, https://github.com/InternetSociety/django-ixp-tracker/issues
10
+ Project-URL: CI, https://github.com/InternetSociety/django-ixp-tracker/actions
11
+ Classifier: License :: OSI Approved :: Apache Software License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Framework :: Django
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: django >4.2
19
+ Requires-Dist: django-countries >7.6
20
+ Requires-Dist: python-dateutil
21
+ Provides-Extra: test
22
+ Requires-Dist: django-stubs ; extra == 'test'
23
+ Requires-Dist: pre-commit ; extra == 'test'
24
+ Requires-Dist: pytest ; extra == 'test'
25
+ Requires-Dist: pytest-django ; extra == 'test'
26
+ Requires-Dist: responses ; extra == 'test'
27
+
28
+ # django-ixp-tracker
29
+
30
+ [![PyPI](https://img.shields.io/pypi/v/django-ixp-tracker.svg)](https://pypi.org/project/django-ixp-tracker/)
31
+ [![Tests](https://github.com/InternetSociety/django-ixp-tracker/actions/workflows/test.yml/badge.svg)](https://github.com/InternetSociety/django-ixp-tracker/actions/workflows/test.yml)
32
+ [![Changelog](https://img.shields.io/github/v/release/InternetSociety/django-ixp-tracker?include_prereleases&label=changelog)](https://github.com/InternetSociety/django-ixp-tracker/releases)
33
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/InternetSociety/django-ixp-tracker/blob/main/LICENSE)
34
+
35
+ Library to retrieve and manipulate data about IXPs
36
+
37
+ ## Installation
38
+
39
+ Install this library using `pip`:
40
+ ```bash
41
+ pip install django-ixp-tracker
42
+ ```
43
+ ## Usage
44
+
45
+ 1. Add to your INSTALLED_APPS setting like this:
46
+ ```
47
+ INSTALLED_APPS = [
48
+ ...,
49
+ "ixp_tracker",
50
+ ]
51
+ ```
52
+
53
+ Note: this app has no web-facing components so you don't need to add anything to `urls.py` etc
54
+
55
+ 2. Run `python manage.py migrate` to create the models.
56
+ 3. Add the relevant settings to your config. `IXP_TRACKER_PEERING_DB_URL` will use a default if you don't provide a value so you probably don't need that. But you will need to set `IXP_TRACKER_PEERING_DB_KEY` to authenticate against the API.
57
+ 4. Add `IXP_TRACKER_GEO_LOOKUP_FACTORY` to config with the path to your factory (see below).
58
+ 5. Run the management command to import the data: `python manage.py ixp_tracker_import` (This will sync the current data, if you want historical data you need to backfill first)
59
+
60
+ ## ASN country and status data
61
+
62
+ The lib uses an external component to look up the country of registration (why?) and the status of an ASN. This status is used for the logic to identify when members have left an IXP.
63
+
64
+ If you don't provide this service yourself, it will default to a noop version. This will mean you will get no country of registration data and the marking of members having left an IXP will not be as efficient.
65
+
66
+ In order to implement such a component yourself, you should implement the Protocol `ixp_tracker.importers.ASNGeoLookup` and provide a factory function for your class.
67
+
68
+ ## Backfilling data
69
+
70
+ You have the option of backfilling data from archived PeeringDb data. This can be done by running the import command with the `--backfill` option for each month you want to backfill:
71
+ ```shell
72
+ python manage.py ixp_tracker_import --backfill <YYYMM>
73
+ ```
74
+ The backfill currently process a single month at a time and will look for the earliest file for the relevant month at https://publicdata.caida.org/datasets/peeringdb/
75
+
76
+ IMPORTANT NOTE: due to the way the code tries to figure out when a member left an IXP, you should run the backfill strictly in date order and *before* syncing the current data.
77
+
78
+ ## IXP stats
79
+
80
+ The import process also generates monthly stats per IXP and per country. These are generated as of the 1st of the month used to import the data.
81
+
82
+ ## Running programmatically
83
+
84
+ If you'd like to run the import from code, rather than from the management command, you can call `importers.import_data()` directly.
85
+
86
+ It's not recommended to call any other functions yourself.
87
+
88
+ ## Development
89
+
90
+ To contribute to this library, first checkout the code. Then create a new virtual environment:
91
+ ```bash
92
+ cd django-ixp-tracker
93
+ python -m venv venv
94
+ source venv/bin/activate
95
+ ```
96
+ Now install the dependencies and test dependencies:
97
+ ```bash
98
+ pip install -e '.[test]'
99
+ ```
100
+ To run the tests:
101
+ ```bash
102
+ pytest
103
+ ```
104
+ We use [pre-commit](https://pre-commit.com/) for linting etc on push. Run:
105
+ ```bash
106
+ pre-commit install
107
+ ```
108
+ from the repo top-level dir to set it up.
109
+
110
+ ## Peering Db libraries
111
+
112
+ PeeringDb provide their own [vanilla Python](https://github.com/peeringdb/peeringdb-py) and [Django](https://github.com/peeringdb/django-peeringdb) libs, but we have decided not to use these.
113
+
114
+ Both libs are designed to keep a local copy of the current data and to keep that copy in sync with the central copy via the API.
115
+
116
+ As we need to keep a historical record (e.g. for IXP growth stats over time), we would have to provide some sort of wrapper over those libs anyway.
117
+
118
+ In addition to that, the [historical archives of PeeringDb data](https://publicdata.caida.org/datasets/peeringdb/) use flat lists of the different object types in json. We can retrieve the data from the API directly in the same way, so it makes it simpler to implement.
@@ -0,0 +1,20 @@
1
+ ixp_tracker/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ ixp_tracker/conf.py,sha256=SJqnTuVHgMb9rkJvkpvtd2qpz0j0P0rMlN5T_vN3j1g,1040
3
+ ixp_tracker/importers.py,sha256=ImOkQod81p1RBySjNO_IB2dWCS63ABf6_Zj3sCjE8k0,9176
4
+ ixp_tracker/models.py,sha256=Co8igLCP7qgyLXpUwxpoP63vd69fOwZChb6cYMq_HcM,3772
5
+ ixp_tracker/stats.py,sha256=2XNkrY-QsshoB7G41U-Plu7HZ5JUrzE0B8bWbIsn8yc,4182
6
+ ixp_tracker/management/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ ixp_tracker/management/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ ixp_tracker/management/commands/ixp_tracker_import.py,sha256=QToGoZ1YANBf9FZHoc7YZEm9g8nDq5Ogxaq-LfZ6Lbo,2581
9
+ ixp_tracker/migrations/0001_initial.py,sha256=1oGXDfnVW4U8-WXSfiqdrYhq4Cbg7RRHrewWKwq1bpY,1395
10
+ ixp_tracker/migrations/0002_asn_asn_unique_as_number.py,sha256=tSZOGg3AtoOiFjWPmiT288MGYoGp8eIoYjF_gMeYkmg,1446
11
+ ixp_tracker/migrations/0003_alter_asn_name.py,sha256=RgrazrOC4HWqahwvfiYhOuc9ODQ8YjvgH-3ZKPW64Ns,392
12
+ ixp_tracker/migrations/0004_ixpmember_ixpmember_unique_ixp_membership.py,sha256=GLtqSKWL7Xdj9nfSztsroBGTqthRGiAd6OZe22y7UZE,1408
13
+ ixp_tracker/migrations/0005_statspercountry_statsperixp_and_more.py,sha256=0Bz7Ii3jMSN3udSWYqrkVdFqd6ds9zgZV6bFWjuieTs,2104
14
+ ixp_tracker/migrations/0006_remove_statspercountry_ixp_tracker_unique_per_country_stats_and_more.py,sha256=CPnqRpNwewVKd1gi-YocN7L9I36mbTxB-ma4TgrA-TM,1085
15
+ ixp_tracker/migrations/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
+ django_ixp_tracker-0.3.dist-info/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
17
+ django_ixp_tracker-0.3.dist-info/METADATA,sha256=mXUebmy4rlGP3Exl5Vw3pJpPLw90mjsFlh8eSodGGh4,5521
18
+ django_ixp_tracker-0.3.dist-info/WHEEL,sha256=GV9aMThwP_4oNCtvEC2ec3qUYutgWeAzklro_0m4WJQ,91
19
+ django_ixp_tracker-0.3.dist-info/top_level.txt,sha256=-WM3VE8Krzl0pR87BeZyZYOD-QK06_Uz8zO-8IWghk8,12
20
+ django_ixp_tracker-0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ ixp_tracker
File without changes
ixp_tracker/conf.py ADDED
@@ -0,0 +1,25 @@
1
+ from django.conf import settings
2
+ from django.core.exceptions import ImproperlyConfigured
3
+
4
+ try:
5
+ IXP_TRACKER_GEO_LOOKUP_FACTORY = str(settings.IXP_TRACKER_GEO_LOOKUP_FACTORY)
6
+ except AttributeError:
7
+ IXP_TRACKER_GEO_LOOKUP_FACTORY = None
8
+ except(TypeError, ValueError):
9
+ raise ImproperlyConfigured("IXP_TRACKER_GEO_LOOKUP_FACTORY must be a string value")
10
+
11
+ try:
12
+ IXP_TRACKER_PEERING_DB_URL = str(settings.IXP_TRACKER_PEERING_DB_URL)
13
+ except AttributeError:
14
+ IXP_TRACKER_PEERING_DB_URL = "https://www.peeringdb.com/api"
15
+ except(TypeError, ValueError):
16
+ raise ImproperlyConfigured("IXP_TRACKER_PEERING_DB_URL must be a string value")
17
+
18
+ try:
19
+ IXP_TRACKER_PEERING_DB_KEY = str(settings.IXP_TRACKER_PEERING_DB_KEY)
20
+ except AttributeError:
21
+ IXP_TRACKER_PEERING_DB_KEY = None
22
+ except(TypeError, ValueError):
23
+ raise ImproperlyConfigured("IXP_TRACKER_PEERING_DB_KEY must be a string value")
24
+
25
+ DATA_ARCHIVE_URL = "https://publicdata.caida.org/datasets/peeringdb/{year}/{month:02d}/peeringdb_2_dump_{year}_{month:02d}_{day:02d}.json"
@@ -0,0 +1,212 @@
1
+ import ast
2
+ import json
3
+ from json.decoder import JSONDecodeError
4
+ import logging
5
+ from datetime import datetime, timedelta, timezone
6
+ from typing import Callable, List, Protocol
7
+
8
+ import requests
9
+ import dateutil.parser
10
+ from django_countries import countries
11
+
12
+ from ixp_tracker.conf import IXP_TRACKER_PEERING_DB_KEY, IXP_TRACKER_PEERING_DB_URL, DATA_ARCHIVE_URL
13
+ from ixp_tracker import models
14
+
15
+ logger = logging.getLogger("ixp_tracker")
16
+
17
+
18
+ class ASNGeoLookup(Protocol):
19
+
20
+ def get_iso2_country(self, asn: int, as_at: datetime) -> str:
21
+ pass
22
+
23
+ def get_status(self, asn: int, as_at: datetime) -> str:
24
+ pass
25
+
26
+ def get_asns_for_country(self, country: str, as_at: datetime) -> List[int]:
27
+ pass
28
+
29
+
30
+ def import_data(
31
+ geo_lookup: ASNGeoLookup,
32
+ reset: bool = False,
33
+ processing_date: datetime = None,
34
+ page_limit: int = 200
35
+ ):
36
+ if processing_date is None:
37
+ processing_date = datetime.utcnow().replace(tzinfo=timezone.utc)
38
+ import_ixps(processing_date)
39
+ logger.debug("Imported IXPs")
40
+ import_asns(geo_lookup, reset, page_limit)
41
+ logger.debug("Imported ASNs")
42
+ import_members(processing_date, geo_lookup)
43
+ logger.debug("Imported members")
44
+ else:
45
+ processing_date = processing_date.replace(day=1)
46
+ processing_month = processing_date.month
47
+ found = False
48
+ while processing_date.month == processing_month and not found:
49
+ url = DATA_ARCHIVE_URL.format(year=processing_date.year, month=processing_date.month, day=processing_date.day)
50
+ data = requests.get(url)
51
+ if data.status_code == 200:
52
+ found = True
53
+ else:
54
+ processing_date = processing_date + timedelta(days=1)
55
+ if not found:
56
+ logger.warning("Cannot find backfill data", extra={"backfill_date": processing_date})
57
+ return
58
+ backfill_raw = data.text
59
+ try:
60
+ backfill_data = json.loads(backfill_raw)
61
+ except JSONDecodeError:
62
+ # It seems some of the Peering dumps use single quotes so try and load using ast in this case
63
+ backfill_data = ast.literal_eval(backfill_raw)
64
+ ixp_data = backfill_data.get("ix", {"data": []}).get("data", [])
65
+ process_ixp_data(processing_date)(ixp_data)
66
+ asn_data = backfill_data.get("net", {"data": []}).get("data", [])
67
+ process_asn_data(geo_lookup)(asn_data)
68
+ member_data = backfill_data.get("netixlan", {"data": []}).get("data", [])
69
+ process_member_data(processing_date, geo_lookup)(member_data)
70
+
71
+
72
+ def get_data(endpoint: str, processor: Callable, limit: int = 0, last_updated: datetime = None) -> bool:
73
+ url = f"{IXP_TRACKER_PEERING_DB_URL}{endpoint}"
74
+ query_params = {}
75
+ if last_updated is not None:
76
+ query_params["updated__gte"] = last_updated.strftime("%Y-%m-%d")
77
+ if limit > 0:
78
+ query_params["limit"] = limit
79
+ query_params["skip"] = 0
80
+ finished = False
81
+ while finished is not True:
82
+ finished = True
83
+ data = requests.get(url, headers={"Authorization": f"Api-Key {IXP_TRACKER_PEERING_DB_KEY}"}, params=query_params)
84
+ if data.status_code >= 300:
85
+ logger.warning("Cannot retrieve data", extra={"status": data.status_code})
86
+ return False
87
+ try:
88
+ data = data.json().get("data", [])
89
+ processor(data)
90
+ if limit > 0 and len(data) > 0:
91
+ query_params["skip"] = query_params["skip"] + limit
92
+ finished = False
93
+ except JSONDecodeError:
94
+ logger.warning("Cannot decode json data")
95
+ return False
96
+ return True
97
+
98
+
99
+ def import_ixps(processing_date) -> bool:
100
+ return get_data("/ix", process_ixp_data(processing_date))
101
+
102
+
103
+ def process_ixp_data(processing_date: datetime):
104
+ def do_process_ixp_data(all_ixp_data):
105
+ for ixp_data in all_ixp_data:
106
+ country_data = countries.alpha2(ixp_data["country"])
107
+ if len(country_data) == 0:
108
+ logger.warning("Skipping IXP import as country code not found", extra={"country": ixp_data["country"], "id": ixp_data["id"]})
109
+ continue
110
+ try:
111
+ models.IXP.objects.update_or_create(
112
+ peeringdb_id=ixp_data["id"],
113
+ defaults={
114
+ "name": ixp_data["name"],
115
+ "long_name": ixp_data["name_long"],
116
+ "city": ixp_data["city"],
117
+ "website": ixp_data["website"],
118
+ "active_status": True,
119
+ "country_code": ixp_data["country"],
120
+ "created": ixp_data["created"],
121
+ "last_updated": ixp_data["updated"],
122
+ "last_active": processing_date,
123
+ }
124
+ )
125
+ logger.debug("Creating new IXP record", extra={"id": ixp_data["id"]})
126
+ except Exception as e:
127
+ logger.warning("Cannot import IXP data", extra={"error": str(e)})
128
+ return do_process_ixp_data
129
+
130
+
131
+ def import_asns(geo_lookup: ASNGeoLookup, reset: bool = False, page_limit: int = 200) -> bool:
132
+ logger.debug("Fetching ASN data")
133
+ updated_since = None
134
+ if not reset:
135
+ last_updated = models.ASN.objects.all().order_by("-last_updated").first()
136
+ if last_updated:
137
+ updated_since = last_updated.last_updated
138
+ return get_data("/net", process_asn_data(geo_lookup), limit=page_limit, last_updated=updated_since)
139
+
140
+
141
+ def process_asn_data(geo_lookup):
142
+ def process_asn_paged_data(all_asn_data):
143
+ for asn_data in all_asn_data:
144
+ try:
145
+ asn = int(asn_data["asn"])
146
+ last_updated = dateutil.parser.isoparse(asn_data["updated"])
147
+ models.ASN.objects.update_or_create(
148
+ peeringdb_id=asn_data["id"],
149
+ defaults={
150
+ "name": asn_data["name"],
151
+ "number": asn,
152
+ "network_type": asn_data["info_type"],
153
+ "registration_country_code": geo_lookup.get_iso2_country(asn, last_updated),
154
+ "created": asn_data["created"],
155
+ "last_updated": last_updated,
156
+ }
157
+ )
158
+ except Exception as e:
159
+ logger.warning("Cannot import ASN data", extra={"error": str(e)})
160
+ return True
161
+ return process_asn_paged_data
162
+
163
+
164
+ def import_members(processing_date: datetime, geo_lookup: ASNGeoLookup) -> bool:
165
+ logger.debug("Fetching IXP member data")
166
+ return get_data("/netixlan", process_member_data(processing_date, geo_lookup))
167
+
168
+
169
+ def process_member_data(processing_date: datetime, geo_lookup: ASNGeoLookup):
170
+
171
+ def do_process_member_data(all_member_data):
172
+ for member_data in all_member_data:
173
+ log_data = {"asn": member_data["asn"], "ixp": member_data["ix_id"]}
174
+ try:
175
+ ixp = models.IXP.objects.get(peeringdb_id=member_data["ix_id"])
176
+ except models.IXP.DoesNotExist:
177
+ logger.warning("Cannot find IXP")
178
+ continue
179
+ try:
180
+ asn = models.ASN.objects.get(number=member_data["asn"])
181
+ except models.ASN.DoesNotExist:
182
+ logger.warning("Cannot find ASN")
183
+ continue
184
+ models.IXPMember.objects.update_or_create(
185
+ ixp=ixp,
186
+ asn=asn,
187
+ defaults={
188
+ "member_since": dateutil.parser.isoparse(member_data["created"]).date(),
189
+ "last_updated": member_data["updated"],
190
+ "is_rs_peer": member_data["is_rs_peer"],
191
+ "speed": member_data["speed"],
192
+ "last_active": processing_date,
193
+ }
194
+ )
195
+ logger.debug("Imported IXP member record", extra=log_data)
196
+ start_of_month = processing_date.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
197
+ inactive = models.IXPMember.objects.filter(date_left=None, last_active__lt=start_of_month).all()
198
+ for member in inactive:
199
+ start_of_next_of_month = (member.last_active.replace(day=1) + timedelta(days=33)).replace(day=1)
200
+ end_of_month = start_of_next_of_month - timedelta(days=1)
201
+ member.date_left = end_of_month
202
+ member.save()
203
+ logger.debug("Member flagged as left due to inactivity", extra={"member": member.asn.number})
204
+ candidates = models.IXPMember.objects.filter(date_left=None, asn__registration_country_code="ZZ").all()
205
+ for candidate in candidates:
206
+ if geo_lookup.get_status(candidate.asn.number, processing_date) != "assigned":
207
+ end_of_last_month_active = (candidate.last_active.replace(day=1) - timedelta(days=1))
208
+ candidate.date_left = end_of_last_month_active
209
+ candidate.save()
210
+ logger.debug("Member flagged as left due to unassigned ASN", extra={"member": candidate.asn.number})
211
+ logger.info("Fixing members finished")
212
+ return do_process_member_data
File without changes
File without changes
@@ -0,0 +1,67 @@
1
+ import importlib
2
+ import logging
3
+ import traceback
4
+ from datetime import datetime, timezone
5
+ from typing import List
6
+
7
+ from django.core.management import BaseCommand
8
+
9
+ from ixp_tracker.conf import IXP_TRACKER_GEO_LOOKUP_FACTORY
10
+ from ixp_tracker.importers import ASNGeoLookup, import_data
11
+ from ixp_tracker.stats import generate_stats
12
+
13
+ logger = logging.getLogger("ixp_tracker")
14
+
15
+
16
+ class DefaultASNGeoLookup(ASNGeoLookup):
17
+
18
+ def get_iso2_country(self, asn: int, as_at: datetime) -> str:
19
+ return "ZZ"
20
+
21
+ def get_status(self, asn: int, as_at: datetime) -> str:
22
+ return "assigned"
23
+
24
+ def get_asns_for_country(self, country: str, as_at: datetime) -> List[int]:
25
+ pass
26
+
27
+
28
+ def load_geo_lookup(geo_lookup_name):
29
+ if geo_lookup_name is not None:
30
+ lookup_parts = geo_lookup_name.split(".")
31
+ factory_name = lookup_parts.pop()
32
+ module_name = ".".join(lookup_parts)
33
+ logger.debug("Trying to load geo lookup", extra={"module_name": module_name, "factory": factory_name})
34
+ if module_name and factory_name:
35
+ imported_module = importlib.import_module(module_name)
36
+ factory = getattr(imported_module, factory_name)
37
+ return factory()
38
+ return None
39
+
40
+
41
+ class Command(BaseCommand):
42
+ help = "Updates IXP data"
43
+
44
+ def add_arguments(self, parser):
45
+ parser.add_argument("--reset-asns", action="store_true", default=False, help="Do a full reset of ASNs rather than incremental update")
46
+ parser.add_argument("--backfill", type=str, default=None, help="The month you would like to backfill data for")
47
+
48
+ def handle(self, *args, **options):
49
+ try:
50
+ logger.debug("Importing IXP data")
51
+ geo_lookup = load_geo_lookup(IXP_TRACKER_GEO_LOOKUP_FACTORY) or DefaultASNGeoLookup()
52
+ reset = options["reset_asns"]
53
+ backfill_date = options["backfill"]
54
+ processing_date = None
55
+ if backfill_date is None:
56
+ import_data(geo_lookup, reset)
57
+ else:
58
+ processing_date = datetime.strptime(backfill_date, "%Y%m").replace(tzinfo=timezone.utc)
59
+ if reset:
60
+ logger.warning("The --reset option has no effect when running a backfill")
61
+ import_data(geo_lookup, False, processing_date)
62
+
63
+ logger.debug("Generating stats")
64
+ generate_stats(geo_lookup, processing_date)
65
+ logger.info("Import finished")
66
+ except Exception as e:
67
+ logging.error("Failed to import data", extra={"error": str(e), "trace": traceback.format_exc()})
@@ -0,0 +1,38 @@
1
+ # Generated by Django 5.0.8 on 2024-08-08 10:21
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ initial = True
9
+
10
+ dependencies = [
11
+ ]
12
+
13
+ operations = [
14
+ migrations.CreateModel(
15
+ name='IXP',
16
+ fields=[
17
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18
+ ('name', models.CharField(max_length=150)),
19
+ ('long_name', models.CharField(max_length=200)),
20
+ ('city', models.CharField(max_length=200)),
21
+ ('website', models.URLField(null=True)),
22
+ ('active_status', models.BooleanField(default=True)),
23
+ ('peeringdb_id', models.IntegerField(null=True)),
24
+ ('country', models.CharField(max_length=2)),
25
+ ('created', models.DateTimeField()),
26
+ ('last_updated', models.DateTimeField()),
27
+ ('last_active', models.DateTimeField(null=True)),
28
+ ],
29
+ options={
30
+ 'verbose_name': 'Internet Exchange Point',
31
+ 'verbose_name_plural': 'Internet Exchange Points',
32
+ },
33
+ ),
34
+ migrations.AddConstraint(
35
+ model_name='ixp',
36
+ constraint=models.UniqueConstraint(fields=('peeringdb_id',), name='ixp_tracker_unique_ixp_peeringdb_id'),
37
+ ),
38
+ ]
@@ -0,0 +1,34 @@
1
+ # Generated by Django 5.0.8 on 2024-08-08 12:33
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('ixp_tracker', '0001_initial'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.CreateModel(
14
+ name='ASN',
15
+ fields=[
16
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
17
+ ('name', models.CharField(max_length=200)),
18
+ ('number', models.IntegerField()),
19
+ ('peeringdb_id', models.IntegerField(null=True)),
20
+ ('network_type', models.CharField(choices=[('access', 'Access'), ('transit', 'Transit'), ('content', 'Content'), ('enterprise', 'Enterprise'), ('NREN', 'Research and Education'), ('non-profit', 'Non-profit'), ('not-disclosed', 'Not Disclosed'), ('other', 'Other')], default='not-disclosed', max_length=200)),
21
+ ('registration_country', models.CharField(max_length=2)),
22
+ ('created', models.DateTimeField()),
23
+ ('last_updated', models.DateTimeField()),
24
+ ],
25
+ options={
26
+ 'verbose_name': 'AS Number',
27
+ 'verbose_name_plural': 'AS Numbers',
28
+ },
29
+ ),
30
+ migrations.AddConstraint(
31
+ model_name='asn',
32
+ constraint=models.UniqueConstraint(fields=('number',), name='ixp_tracker_unique_as_number'),
33
+ ),
34
+ ]
@@ -0,0 +1,18 @@
1
+ # Generated by Django 5.0.8 on 2024-08-13 12:08
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('ixp_tracker', '0002_asn_asn_unique_as_number'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.AlterField(
14
+ model_name='asn',
15
+ name='name',
16
+ field=models.CharField(max_length=500),
17
+ ),
18
+ ]
@@ -0,0 +1,36 @@
1
+ # Generated by Django 5.0.8 on 2024-08-14 10:46
2
+
3
+ import django.db.models.deletion
4
+ from django.db import migrations, models
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ dependencies = [
10
+ ('ixp_tracker', '0003_alter_asn_name'),
11
+ ]
12
+
13
+ operations = [
14
+ migrations.CreateModel(
15
+ name='IXPMember',
16
+ fields=[
17
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18
+ ('member_since', models.DateField()),
19
+ ('last_updated', models.DateTimeField()),
20
+ ('is_rs_peer', models.BooleanField(default=False)),
21
+ ('speed', models.IntegerField(null=True)),
22
+ ('date_left', models.DateField(null=True)),
23
+ ('last_active', models.DateTimeField(null=True)),
24
+ ('asn', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ixp_tracker.asn')),
25
+ ('ixp', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ixp_tracker.ixp')),
26
+ ],
27
+ options={
28
+ 'verbose_name': 'IXP Member',
29
+ 'verbose_name_plural': 'IXP Members',
30
+ },
31
+ ),
32
+ migrations.AddConstraint(
33
+ model_name='ixpmember',
34
+ constraint=models.UniqueConstraint(fields=('ixp', 'asn'), name='ixp_tracker_unique_ixp_membership'),
35
+ ),
36
+ ]
@@ -0,0 +1,55 @@
1
+ # Generated by Django 5.0.8 on 2024-09-16 13:56
2
+
3
+ import django.db.models.deletion
4
+ from django.db import migrations, models
5
+
6
+
7
+ class Migration(migrations.Migration):
8
+
9
+ dependencies = [
10
+ ('ixp_tracker', '0004_ixpmember_ixpmember_unique_ixp_membership'),
11
+ ]
12
+
13
+ operations = [
14
+ migrations.CreateModel(
15
+ name='StatsPerCountry',
16
+ fields=[
17
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
18
+ ('country', models.CharField(max_length=2)),
19
+ ('stats_date', models.DateField()),
20
+ ('asn_count', models.IntegerField()),
21
+ ('member_count', models.IntegerField()),
22
+ ('asns_ixp_member_rate', models.FloatField()),
23
+ ('total_capacity', models.FloatField()),
24
+ ],
25
+ options={
26
+ 'verbose_name': 'Per-country stats',
27
+ },
28
+ ),
29
+ migrations.CreateModel(
30
+ name='StatsPerIXP',
31
+ fields=[
32
+ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
33
+ ('stats_date', models.DateField()),
34
+ ('capacity', models.FloatField()),
35
+ ('members', models.IntegerField()),
36
+ ('local_asns_members_rate', models.FloatField()),
37
+ ],
38
+ options={
39
+ 'verbose_name': 'IXP stats',
40
+ },
41
+ ),
42
+ migrations.AddConstraint(
43
+ model_name='statspercountry',
44
+ constraint=models.UniqueConstraint(fields=('country', 'stats_date'), name='ixp_tracker_unique_per_country_stats'),
45
+ ),
46
+ migrations.AddField(
47
+ model_name='statsperixp',
48
+ name='ixp',
49
+ field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='ixp_tracker.ixp'),
50
+ ),
51
+ migrations.AddConstraint(
52
+ model_name='statsperixp',
53
+ constraint=models.UniqueConstraint(fields=('ixp', 'stats_date'), name='ixp_tracker_unique_ixp_stats'),
54
+ ),
55
+ ]
@@ -0,0 +1,36 @@
1
+ # Generated by Django 5.0.8 on 2024-09-17 13:23
2
+
3
+ from django.db import migrations, models
4
+
5
+
6
+ class Migration(migrations.Migration):
7
+
8
+ dependencies = [
9
+ ('ixp_tracker', '0005_statspercountry_statsperixp_and_more'),
10
+ ]
11
+
12
+ operations = [
13
+ migrations.RemoveConstraint(
14
+ model_name='statspercountry',
15
+ name='ixp_tracker_unique_per_country_stats',
16
+ ),
17
+ migrations.RenameField(
18
+ model_name='asn',
19
+ old_name='registration_country',
20
+ new_name='registration_country_code',
21
+ ),
22
+ migrations.RenameField(
23
+ model_name='ixp',
24
+ old_name='country',
25
+ new_name='country_code',
26
+ ),
27
+ migrations.RenameField(
28
+ model_name='statspercountry',
29
+ old_name='country',
30
+ new_name='country_code',
31
+ ),
32
+ migrations.AddConstraint(
33
+ model_name='statspercountry',
34
+ constraint=models.UniqueConstraint(fields=('country_code', 'stats_date'), name='ixp_tracker_unique_per_country_stats'),
35
+ ),
36
+ ]
File without changes
ixp_tracker/models.py ADDED
@@ -0,0 +1,115 @@
1
+ from django.db import models
2
+ from django.utils.translation import gettext_lazy as _
3
+
4
+
5
+ class IXP(models.Model):
6
+ name = models.CharField(max_length=150)
7
+ long_name = models.CharField(max_length=200)
8
+ city = models.CharField(max_length=200)
9
+ website = models.URLField(null=True)
10
+ active_status = models.BooleanField(default=True)
11
+ peeringdb_id = models.IntegerField(null=True)
12
+ country_code = models.CharField(max_length=2)
13
+ created = models.DateTimeField()
14
+ last_updated = models.DateTimeField()
15
+ last_active = models.DateTimeField(null=True)
16
+
17
+ def __str__(self):
18
+ return self.name
19
+
20
+ class Meta:
21
+ verbose_name = _("Internet Exchange Point")
22
+ verbose_name_plural = _("Internet Exchange Points")
23
+
24
+ constraints = [
25
+ models.UniqueConstraint(fields=['peeringdb_id'], name='ixp_tracker_unique_ixp_peeringdb_id')
26
+ ]
27
+
28
+
29
+ class ASN(models.Model):
30
+ NETWORK_TYPE_CHOICES = [
31
+ ('access', 'Access'),
32
+ ('transit', 'Transit'),
33
+ ('content', 'Content'),
34
+ ('enterprise', 'Enterprise'),
35
+ ('NREN', 'Research and Education'),
36
+ ('non-profit', 'Non-profit'),
37
+ ('not-disclosed', 'Not Disclosed'),
38
+ ('other', 'Other'),
39
+ ]
40
+ name = models.CharField(max_length=500)
41
+ number = models.IntegerField()
42
+ peeringdb_id = models.IntegerField(null=True)
43
+ network_type = models.CharField(max_length=200, choices=NETWORK_TYPE_CHOICES, default='not-disclosed')
44
+ registration_country_code = models.CharField(max_length=2)
45
+ created = models.DateTimeField()
46
+ last_updated = models.DateTimeField()
47
+
48
+ def __str__(self):
49
+ return "AS" + str(self.number)
50
+
51
+ class Meta:
52
+ verbose_name = "AS Number"
53
+ verbose_name_plural = "AS Numbers"
54
+
55
+ constraints = [
56
+ models.UniqueConstraint(fields=['number'], name='ixp_tracker_unique_as_number')
57
+ ]
58
+
59
+
60
+ class IXPMember(models.Model):
61
+ ixp = models.ForeignKey(IXP, on_delete=models.CASCADE)
62
+ asn = models.ForeignKey(ASN, on_delete=models.CASCADE)
63
+ member_since = models.DateField()
64
+ last_updated = models.DateTimeField()
65
+ is_rs_peer = models.BooleanField(default=False)
66
+ speed = models.IntegerField(null=True)
67
+ date_left = models.DateField(null=True)
68
+ last_active = models.DateTimeField(null=True)
69
+
70
+ def __str__(self):
71
+ return f"{self.ixp.name} - {self.asn.name}"
72
+
73
+ class Meta:
74
+ verbose_name = "IXP Member"
75
+ verbose_name_plural = "IXP Members"
76
+
77
+ constraints = [
78
+ models.UniqueConstraint(fields=['ixp', 'asn'], name='ixp_tracker_unique_ixp_membership')
79
+ ]
80
+
81
+
82
+ class StatsPerIXP(models.Model):
83
+ ixp = models.ForeignKey(IXP, on_delete=models.CASCADE)
84
+ stats_date = models.DateField()
85
+ capacity = models.FloatField()
86
+ members = models.IntegerField()
87
+ local_asns_members_rate = models.FloatField()
88
+
89
+ def __str__(self):
90
+ return f"{self.ixp.name} - {self.stats_date}"
91
+
92
+ class Meta:
93
+ verbose_name = "IXP stats"
94
+
95
+ constraints = [
96
+ models.UniqueConstraint(fields=['ixp', 'stats_date'], name='ixp_tracker_unique_ixp_stats')
97
+ ]
98
+
99
+ class StatsPerCountry(models.Model):
100
+ country_code = models.CharField(max_length=2)
101
+ stats_date = models.DateField()
102
+ asn_count = models.IntegerField()
103
+ member_count = models.IntegerField()
104
+ asns_ixp_member_rate = models.FloatField()
105
+ total_capacity = models.FloatField()
106
+
107
+ def __str__(self):
108
+ return f"{self.country_code}-{self.stats_date}-{self.asn_count}-{self.member_count}"
109
+
110
+ class Meta:
111
+ verbose_name = "Per-country stats"
112
+
113
+ constraints = [
114
+ models.UniqueConstraint(fields=['country_code', 'stats_date'], name='ixp_tracker_unique_per_country_stats')
115
+ ]
ixp_tracker/stats.py ADDED
@@ -0,0 +1,91 @@
1
+ import logging
2
+ from datetime import datetime, timezone
3
+ from typing import Dict, List, TypedDict, Union
4
+
5
+ from django_countries import countries
6
+ from django.db.models import Q
7
+
8
+ from ixp_tracker.importers import ASNGeoLookup
9
+ from ixp_tracker.models import IXP, IXPMember, StatsPerCountry, StatsPerIXP
10
+
11
+ logger = logging.getLogger("ixp_tracker")
12
+
13
+
14
+ class CountryStats(TypedDict):
15
+ all_asns: Union[List[int], None]
16
+ member_asns: set
17
+ total_capacity: int
18
+
19
+
20
+ def generate_stats(geo_lookup: ASNGeoLookup, stats_date: datetime = None):
21
+ stats_date = stats_date or datetime.utcnow().replace(tzinfo=timezone.utc)
22
+ stats_date = stats_date.replace(day=1)
23
+ ixps = IXP.objects.filter(created__lte=stats_date).all()
24
+ all_members = (IXPMember.objects
25
+ .filter(member_since__lte=stats_date)
26
+ .filter(Q(date_left=None) | Q(date_left__gte=stats_date))).all()
27
+ all_stats_per_country: Dict[str, CountryStats] = {}
28
+ for code, _ in list(countries):
29
+ all_stats_per_country[code] = {
30
+ "all_asns": None,
31
+ "member_asns": set(),
32
+ "total_capacity": 0
33
+ }
34
+ for ixp in ixps:
35
+ logger.debug("Calculating growth stats for IXP", extra={"ixp": ixp.id})
36
+ members = [member for member in all_members if member.ixp == ixp]
37
+ member_count = len(members)
38
+ capacity = sum(member.speed for member in members)
39
+ ixp_country = ixp.country_code
40
+ country_stats = all_stats_per_country.get(ixp_country)
41
+ if country_stats is None:
42
+ logger.warning("Country not found", extra={"country": ixp_country})
43
+ country_stats = {
44
+ "all_asns": None,
45
+ "member_asns": set(),
46
+ "total_capacity": 0
47
+ }
48
+ all_stats_per_country[ixp_country] = country_stats
49
+ if country_stats.get("all_asns") is None:
50
+ all_stats_per_country[ixp_country]["all_asns"] = geo_lookup.get_asns_for_country(ixp_country, stats_date)
51
+ member_asns = [member.asn.number for member in members]
52
+ local_asns_members_rate = calculate_local_asns_members_rate(member_asns, all_stats_per_country[ixp_country]["all_asns"])
53
+ StatsPerIXP.objects.update_or_create(
54
+ ixp=ixp,
55
+ stats_date=stats_date.date(),
56
+ defaults={
57
+ "ixp": ixp,
58
+ "stats_date": stats_date.date(),
59
+ "members": member_count,
60
+ "capacity": (capacity/1000),
61
+ "local_asns_members_rate": local_asns_members_rate,
62
+ }
63
+ )
64
+ # We only count unique ASNs that are members of an IXP in a country
65
+ all_stats_per_country[ixp_country]["member_asns"] |= set(member_asns)
66
+ # But we count capacity for all members, i.e. an ASN member at 2 IXPs will have capacity at each included in the sum
67
+ all_stats_per_country[ixp_country]["total_capacity"] += capacity
68
+ for code, _ in list(countries):
69
+ country_stats = all_stats_per_country[code]
70
+ if country_stats.get("all_asns") is None:
71
+ country_stats["all_asns"] = geo_lookup.get_asns_for_country(code, stats_date)
72
+ local_asns_members_rate = calculate_local_asns_members_rate(country_stats["member_asns"], country_stats["all_asns"])
73
+ StatsPerCountry.objects.update_or_create(
74
+ country_code=code,
75
+ stats_date=stats_date.date(),
76
+ defaults={
77
+ "asn_count": len(country_stats["all_asns"]),
78
+ "member_count": len(country_stats["member_asns"]),
79
+ "asns_ixp_member_rate": local_asns_members_rate,
80
+ "total_capacity": (country_stats["total_capacity"]/1000),
81
+ }
82
+ )
83
+
84
+
85
+ def calculate_local_asns_members_rate(member_asns: List[int], country_asns: [int]) -> float:
86
+ if len(country_asns) == 0:
87
+ return 0
88
+ # Ignore the current country for a member ASN (as that might have changed) but just get all current members
89
+ # that are in the list of ASNs registered to the country at the time
90
+ members_in_country = [asn for asn in member_asns if asn in country_asns]
91
+ return len(members_in_country) / len(country_asns)