-
Notifications
You must be signed in to change notification settings - Fork 1
Feature/matchy ntp #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
midgemacf
wants to merge
22
commits into
release/1.2.0
Choose a base branch
from
feature/matchy-ntp
base: release/1.2.0
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
22 commits
Select commit
Hold shift + click to select a range
c43a387
adding scaffolding
699f3b3
just my stuff
882569d
flexible
208c63e
remote collect worked
99f4033
ok loading works
d20bd09
doing some cleaning here
06a0e1b
some funkiness from calling as a class
2a5fba1
missed the extra metadata when loading direct (no file)
a5c2f2b
adding random
07f9190
removing the 2 suffix
82fb461
adding the geolocator stuff
e3618a1
hmm i think this is it
2d31e9a
so ruff out here
0edf9e5
fixing ntp specific names
1bedb8b
adding migration stuff
9d0d147
adding reference_probe view
45798ee
typosss
73b48f3
warning should only be on collision
1f617e4
ok, got that looking swanky
cf9dc32
adding initial pytest-postgresql functionality
3ba95cb
adding the other dash stuff
03ca8a0
small tweak
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,6 @@ | ||
| # OpenSAMPL data paths | ||
| archive/ | ||
| ntp-snapshots/ | ||
| # Byte-compiled / optimized / DLL files | ||
| __pycache__/ | ||
| *.py[cod] | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| """Associate NTP probes with ``castdb.locations`` for the geospatial Grafana dashboard.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import ipaddress | ||
| import json | ||
| import os | ||
| import socket | ||
| import urllib.request | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from loguru import logger | ||
|
|
||
| from opensampl.load.table_factory import TableFactory | ||
|
|
||
| if TYPE_CHECKING: | ||
| from sqlalchemy.orm import Session | ||
|
|
||
|
|
||
| _GEO_CACHE: dict[str, tuple[float, float, str]] = {} | ||
|
|
||
|
|
||
| def _env_bool(name: str, default: bool) -> bool: | ||
| v = os.getenv(name) | ||
| if v is None: | ||
| return default | ||
| return v.strip().lower() in ("1", "true", "yes", "on") | ||
|
|
||
|
|
||
| def _default_lab_coords() -> tuple[float, float]: | ||
| lat = float(os.getenv("DEFAULT_LAT", "35.9312")) | ||
| lon = float(os.getenv("DEFAULT_LON", "-84.3101")) | ||
| return lat, lon | ||
|
|
||
|
|
||
| def _is_private_or_loopback(ip: str) -> bool: | ||
| try: | ||
| addr = ipaddress.ip_address(ip) | ||
| except ValueError: | ||
| return True | ||
| return bool(addr.is_private or addr.is_loopback or addr.is_link_local or addr.is_reserved) | ||
|
|
||
|
|
||
| def _lookup_geo_ipapi(ip: str) -> tuple[float, float, str] | None: | ||
| if ip in _GEO_CACHE: | ||
| return _GEO_CACHE[ip] | ||
| url = f"http://ip-api.com/json/{ip}?fields=status,lat,lon,city,country" | ||
| try: | ||
| with urllib.request.urlopen(url, timeout=4.0) as resp: # noqa: S310 | ||
| body = json.loads(resp.read().decode("utf-8")) | ||
| except Exception as e: | ||
| logger.warning("ip-api geolocation failed for {}: {}", ip, e) | ||
| return None | ||
|
|
||
| if body.get("status") != "success" or body.get("lat") is None or body.get("lon") is None: | ||
| logger.warning("ip-api returned no coordinates for {}", ip) | ||
| return None | ||
|
|
||
| city = body.get("city") or "" | ||
| country = body.get("country") or "" | ||
| label = ", ".join(x for x in (city, country) if x) | ||
| out = (float(body["lat"]), float(body["lon"]), label or ip) | ||
| _GEO_CACHE[ip] = out | ||
| return out | ||
|
|
||
|
|
||
| def create_location(session: Session, geolocate_enabled: bool, ip_address: str, geo_override: dict) -> str | None: | ||
| """ | ||
| Set probe ``name``, ``public``, and ``location_uuid`` on NTP metadata before ``probe_metadata`` insert. | ||
|
|
||
| Uses ``additional_metadata.geo_override`` when present (lat/lon/label). Otherwise resolves the remote | ||
| host, uses RFC1918/loopback defaults from env, or ip-api.com for public IPs (HTTP, no API key). | ||
| """ | ||
| lat: float | None = None | ||
| lon: float | None = None | ||
| name: str | None = None | ||
|
|
||
| if isinstance(geo_override, dict) and geo_override.get("lat") is not None and geo_override.get("lon") is not None: | ||
| lat = float(geo_override["lat"]) | ||
| lon = float(geo_override["lon"]) | ||
|
|
||
| if isinstance(geo_override, dict) and geo_override.get("name") is not None: | ||
| name = geo_override["name"] | ||
|
|
||
| if geolocate_enabled and lat is None and lon is None: | ||
| ip_for_geo = ip_address | ||
| try: | ||
| ip_for_geo = socket.gethostbyname(ip_address) | ||
| except OSError as e: | ||
| logger.debug("Could not resolve {}: {}", ip_address, e) | ||
|
|
||
| if _is_private_or_loopback(ip_for_geo): | ||
| lat, lon = _default_lab_coords() | ||
| else: | ||
| geo = _lookup_geo_ipapi(ip_for_geo) | ||
| if geo: | ||
| lat, lon, _name = geo | ||
| name = name or _name | ||
| else: | ||
| lat, lon = _default_lab_coords() | ||
|
|
||
| loc_factory = TableFactory("locations", session=session) | ||
| loc = None | ||
| if name: | ||
| loc = loc_factory.find_existing({"name": name}) | ||
|
|
||
| if loc is None: | ||
| loc = loc_factory.write( | ||
| {"name": name, "lat": lat, "lon": lon, "public": True}, | ||
| if_exists="ignore", | ||
| ) | ||
|
|
||
| if loc: | ||
| return loc.uuid | ||
| return None |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
do we want to update all clock metadata to be used as a reference?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can get the information pretty easily from the tables, since any probe used as a reference will appear in the reference table.
I think i'll add a migration to add a view that joins our probe metadata against the reference table to make an easily accessible (and query-able) spot to get that info