-
-
Notifications
You must be signed in to change notification settings - Fork 23
Rucio replica sorting service using geolocation #896
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
Merged
Merged
Changes from 18 commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
74d4659
Working service but no callbacks from DID finder yet
ponyisi d0d6066
Fix lint
ponyisi 46bdbfc
Add CI action
ponyisi 944bf5c
More CI
ponyisi 03ba367
Sweep
ponyisi 1348faf
Updates for library replica sorter
ponyisi 0e5b9c8
lint fix
ponyisi 94dafd6
Remove another redundant thing
ponyisi e566f3f
Fix stupidity
ponyisi 832bd5d
poetry relock
ponyisi 86d0027
logger fix
ponyisi fe88aaa
Logging level, flake8 fixes
ponyisi f62d00d
Avoid download of GeoIP DB on each query
ponyisi 627e27d
Fix some spacing in the values.yaml
ponyisi afcc444
Sweep replica sorting by distance into this repo
ponyisi 801b066
Update lock
ponyisi e4c5d8e
Fix missing dependency
ponyisi 2c20d7b
Back out irrelevant change
ponyisi ccbece9
Respond to comments
ponyisi 8deb6b6
Fix bugs
ponyisi 3d576f5
Merge remote-tracking branch 'origin/develop' into replica_distance_s…
ponyisi 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
Large diffs are not rendered by default.
Oops, something went wrong.
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
159 changes: 159 additions & 0 deletions
159
did_finder_rucio/src/rucio_did_finder/replica_distance.py
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,159 @@ | ||
# Copyright (c) 2024, IRIS-HEP | ||
# All rights reserved. | ||
# | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are met: | ||
# | ||
# * Redistributions of source code must retain the above copyright notice, this | ||
# list of conditions and the following disclaimer. | ||
# | ||
# * Redistributions in binary form must reproduce the above copyright notice, | ||
# this list of conditions and the following disclaimer in the documentation | ||
# and/or other materials provided with the distribution. | ||
# | ||
# * Neither the name of the copyright holder nor the names of its | ||
# contributors may be used to endorse or promote products derived from | ||
# this software without specific prior written permission. | ||
# | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
import logging | ||
import os | ||
|
||
from typing import List, Mapping, Optional, Tuple | ||
from socket import gethostbyname | ||
import math | ||
from functools import lru_cache | ||
import tempfile | ||
from urllib.parse import urlparse | ||
import geoip2.database | ||
import geoip2.errors | ||
|
||
logger = logging.getLogger('ReplicaDistanceService') | ||
|
||
|
||
def _haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float): | ||
''' Assume inputs are in degrees; will convert to radians. Returns distance in radians ''' | ||
dellat = math.radians(lat2-lat1) | ||
dellon = math.radians(lon2-lon1) | ||
hav_theta = ((1-math.cos(dellat))/2 + | ||
math.cos(math.radians(lat1))*math.cos(math.radians(lat2))*(1-math.cos(dellon))/2) | ||
|
||
return 2*math.asin(math.sqrt(hav_theta)) | ||
|
||
|
||
@lru_cache | ||
def _get_distance(reader: Optional[geoip2.database.Reader], | ||
fqdn: str, my_lat: float, my_lon: float): | ||
""" | ||
Determine angular distance between server at fqdn and (my_lat, my_lon). | ||
If there is a failure of fdqn location lookup, will return pi | ||
""" | ||
if reader is None: | ||
return math.pi | ||
ponyisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
try: | ||
loc_data = reader.city(gethostbyname(fqdn)).location | ||
except geoip2.errors.AddressNotFoundError as e: | ||
logger.warning(f'Cannot geolocate {fqdn}, returning maximum distance.\nError: {e}') | ||
return math.pi | ||
site_lat, site_lon = loc_data.latitude, loc_data.longitude | ||
if site_lat is None or site_lon is None: | ||
return math.pi | ||
return _haversine_distance(site_lat, site_lon, my_lat, my_lon) | ||
|
||
|
||
class ReplicaSorter(object): | ||
_reader: Optional[geoip2.database.Reader] = None | ||
# we keep the temporary directory around so it won't get randomly deleted by the GC | ||
_tmpdir: Optional[tempfile.TemporaryDirectory] = None | ||
|
||
def __init__(self, db_url_tuple: Optional[Tuple[str, bool]] = None): | ||
""" | ||
Argument is an optional tuple of (URL, bool). | ||
The URL is assumed to be a file to download; the bool indicates whether | ||
it is ready to be used (True) or needs unpacking (False) | ||
""" | ||
if db_url_tuple is None: | ||
db_url_tuple = self.get_download_url_from_environment() | ||
self._download_data(db_url_tuple) | ||
|
||
def sort_replicas(self, replicas: List[str], location: Mapping[str, float]) -> List[str]: | ||
""" | ||
Main method of this class. | ||
replicas: list of strings which are the URLs for the replicas for a file | ||
location: dict of the form {'latitude': xxx, 'longitude': yyy} where xxx and yyy are floats | ||
ponyisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
giving the latitude and longitude in signed degrees | ||
""" | ||
if not self._reader: | ||
return replicas | ||
if len(replicas) == 1: | ||
return replicas | ||
fqdns = [(urlparse(replica).hostname, replica) for replica in replicas] | ||
distances = [(_get_distance(self._reader, fqdn, location['latitude'], | ||
ponyisi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
location['longitude']), | ||
replica) for fqdn, replica in fqdns] | ||
distances.sort() | ||
return [replica for _, replica in distances] | ||
|
||
@classmethod | ||
def get_download_url_from_key_and_edition(cls, license_key: str, edition: str): | ||
""" | ||
Construct the (url, unpacked) tuple to feed to the constructor from a license key | ||
and an edition of the MaxMind database. | ||
""" | ||
return (('https://download.maxmind.com/app/geoip_download?' | ||
f'edition_id={edition}&license_key={license_key}&suffix=tar.gz'), | ||
False) | ||
|
||
@classmethod | ||
def get_download_url_from_environment(cls) -> Optional[Tuple[str, bool]]: | ||
""" | ||
Based on environment variables, this will give a tuple of the URL and a bool which is | ||
True if the file from the URL is ready to use as is, False if needs to be unpacked | ||
""" | ||
if url := os.environ.get('GEOIP_DB_URL', ''): | ||
return (url, True) | ||
key = os.environ.get('GEOIP_DB_LICENSE_KEY', '') | ||
edition = os.environ.get('GEOIP_DB_EDITION', '') | ||
if (key and edition): | ||
return cls.get_download_url_from_key_and_edition(key, edition) | ||
else: | ||
return None | ||
|
||
def _download_data(self, db_url_tuple: Optional[Tuple[str, bool]]) -> None: | ||
""" | ||
Retrieves and unpacks the MaxMind databases and initializes the GeoIP reader | ||
""" | ||
from urllib.request import urlretrieve | ||
import tarfile | ||
import glob | ||
if db_url_tuple is None: | ||
return | ||
url, unpacked = db_url_tuple | ||
try: | ||
fname, _ = urlretrieve(url) | ||
except Exception as e: | ||
logger.error(f'Failure retrieving GeoIP database {url}.\nError: {e}') | ||
return | ||
try: | ||
if unpacked: | ||
self._reader = geoip2.database.Reader(fname) | ||
else: | ||
tarball = tarfile.open(fname) | ||
self._tmpdir = tempfile.TemporaryDirectory() | ||
tarball.extractall(self._tmpdir.name) | ||
self._reader = geoip2.database.Reader(glob.glob(os.path.join(self._tmpdir.name, | ||
'*/*mmdb') | ||
)[0]) | ||
except Exception as e: | ||
logger.error(f'Failure initializing the GeoIP database reader.\nError: {e}') | ||
self._reader = None | ||
return |
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,78 @@ | ||
# Copyright (c) 2024, IRIS-HEP | ||
# All rights reserved. | ||
# | ||
# Redistribution and use in source and binary forms, with or without | ||
# modification, are permitted provided that the following conditions are met: | ||
# | ||
# * Redistributions of source code must retain the above copyright notice, this | ||
# list of conditions and the following disclaimer. | ||
# | ||
# * Redistributions in binary form must reproduce the above copyright notice, | ||
# this list of conditions and the following disclaimer in the documentation | ||
# and/or other materials provided with the distribution. | ||
# | ||
# * Neither the name of the copyright holder nor the names of its | ||
# contributors may be used to endorse or promote products derived from | ||
# this software without specific prior written permission. | ||
# | ||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" | ||
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE | ||
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE | ||
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL | ||
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR | ||
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER | ||
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, | ||
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
||
GEOIP_URL = 'https://ponyisi.web.cern.ch/public/GeoLite2-City.mmdb' | ||
GEOIP_TGZ_URL = 'https://ponyisi.web.cern.ch/public/GeoLite2-City_20241015.tar.gz' | ||
|
||
# some URLs (real FQDNs, not real file paths) | ||
REPLICAS = ['https://ccxrootdatlas.in2p3.fr:1094//pnfs/DAOD_PHYSLITE.37020764._000004.pool.root.1', | ||
'root://fax.mwt2.org:1094//DAOD_PHYSLITE.37020764._000004.pool.root.1', | ||
'root://atlasdcache-kit.gridka.de:1094//DAOD_PHYSLITE.37020764._000004.pool.root.1'] | ||
|
||
SORTED_REPLICAS = ['root://fax.mwt2.org:1094//DAOD_PHYSLITE.37020764._000004.pool.root.1', | ||
'https://ccxrootdatlas.in2p3.fr:1094//pnfs/DAOD_PHYSLITE.37020764._000004.pool.root.1', # noqa: E501 | ||
'root://atlasdcache-kit.gridka.de:1094//DAOD_PHYSLITE.37020764._000004.pool.root.1'] # noqa: E501 | ||
|
||
JUNK_REPLICAS = ['https://junk.does.not.exist.org/', | ||
'root://fax.mwt2.org:1094//pnfs/uchicago.edu/'] | ||
SORTED_JUNK_REPLICAS = ['root://fax.mwt2.org:1094//pnfs/uchicago.edu/', | ||
'https://junk.does.not.exist.org/'] | ||
|
||
LOCATION = {'latitude': 41.78, 'longitude': -87.7} | ||
|
||
|
||
def test_sorting(): | ||
"""Also test unpacking tgz database""" | ||
from rucio_did_finder.replica_distance import ReplicaSorter | ||
rs = ReplicaSorter((GEOIP_TGZ_URL, False)) | ||
# Given location (Chicago) replicas should sort US, FR, DE | ||
sorted = rs.sort_replicas(REPLICAS, LOCATION) | ||
assert sorted == SORTED_REPLICAS | ||
# the nonexistent FQDN should sort at end | ||
sorted = rs.sort_replicas(JUNK_REPLICAS, LOCATION) | ||
assert sorted == SORTED_JUNK_REPLICAS | ||
|
||
|
||
def test_envvars(): | ||
"""Only tests unpacked DB download""" | ||
from rucio_did_finder.replica_distance import ReplicaSorter | ||
import os | ||
os.environ['GEOIP_DB_URL'] = GEOIP_URL | ||
rs = ReplicaSorter() | ||
sorted = rs.sort_replicas(REPLICAS, LOCATION) | ||
assert sorted == SORTED_REPLICAS | ||
del os.environ['GEOIP_DB_URL'] | ||
|
||
|
||
def test_bad_geodb(): | ||
"""Tests what happens when we have a bad DB URL""" | ||
from rucio_did_finder.replica_distance import ReplicaSorter | ||
rs = ReplicaSorter(('https://junk.does.not.exist.org', False)) | ||
assert rs._reader is None | ||
sorted = rs.sort_replicas(REPLICAS, LOCATION) | ||
assert sorted == REPLICAS |
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
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.
Uh oh!
There was an error while loading. Please reload this page.