|
| 1 | +# Copyright (c) 2024, IRIS-HEP |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# Redistribution and use in source and binary forms, with or without |
| 5 | +# modification, are permitted provided that the following conditions are met: |
| 6 | +# |
| 7 | +# * Redistributions of source code must retain the above copyright notice, this |
| 8 | +# list of conditions and the following disclaimer. |
| 9 | +# |
| 10 | +# * Redistributions in binary form must reproduce the above copyright notice, |
| 11 | +# this list of conditions and the following disclaimer in the documentation |
| 12 | +# and/or other materials provided with the distribution. |
| 13 | +# |
| 14 | +# * Neither the name of the copyright holder nor the names of its |
| 15 | +# contributors may be used to endorse or promote products derived from |
| 16 | +# this software without specific prior written permission. |
| 17 | +# |
| 18 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 19 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 20 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
| 21 | +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
| 22 | +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
| 23 | +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
| 24 | +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
| 25 | +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
| 26 | +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
| 27 | +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
| 28 | +import logging |
| 29 | +import os |
| 30 | + |
| 31 | +from typing import List, Mapping, Optional, Tuple |
| 32 | +from socket import gethostbyname |
| 33 | +import math |
| 34 | +from functools import lru_cache |
| 35 | +import tempfile |
| 36 | +from urllib.parse import urlparse |
| 37 | +import geoip2.database |
| 38 | +import geoip2.errors |
| 39 | +from collections import namedtuple |
| 40 | + |
| 41 | + |
| 42 | +Replica_distance = namedtuple('Replica_distance', 'replica distance') |
| 43 | +logger = logging.getLogger('ReplicaDistanceService') |
| 44 | + |
| 45 | + |
| 46 | +def _haversine_distance(lat1: float, lon1: float, lat2: float, lon2: float): |
| 47 | + ''' Assume inputs are in degrees; will convert to radians. Returns distance in radians ''' |
| 48 | + dellat = math.radians(lat2-lat1) |
| 49 | + dellon = math.radians(lon2-lon1) |
| 50 | + hav_theta = ((1-math.cos(dellat))/2 + |
| 51 | + math.cos(math.radians(lat1))*math.cos(math.radians(lat2))*(1-math.cos(dellon))/2) |
| 52 | + |
| 53 | + return 2*math.asin(math.sqrt(hav_theta)) |
| 54 | + |
| 55 | + |
| 56 | +@lru_cache |
| 57 | +def _get_distance(database: Optional[geoip2.database.Reader], |
| 58 | + fqdn: str, my_lat: float, my_lon: float): |
| 59 | + """ |
| 60 | + Determine angular distance between server at fqdn and (my_lat, my_lon). |
| 61 | + If there is a failure of fdqn location lookup, will return pi |
| 62 | + (the largest possible physical result) |
| 63 | + """ |
| 64 | + if database is None: |
| 65 | + return math.pi |
| 66 | + try: |
| 67 | + loc_data = database.city(gethostbyname(fqdn)).location |
| 68 | + except geoip2.errors.AddressNotFoundError as e: |
| 69 | + logger.warning(f'Cannot geolocate {fqdn}, returning maximum distance.\nError: {e}') |
| 70 | + return math.pi |
| 71 | + site_lat, site_lon = loc_data.latitude, loc_data.longitude |
| 72 | + if site_lat is None or site_lon is None: |
| 73 | + return math.pi |
| 74 | + return _haversine_distance(site_lat, site_lon, my_lat, my_lon) |
| 75 | + |
| 76 | + |
| 77 | +class ReplicaSorter(object): |
| 78 | + _database: Optional[geoip2.database.Reader] = None |
| 79 | + # we keep the temporary directory around so it won't get randomly deleted by the GC |
| 80 | + _tmpdir: Optional[tempfile.TemporaryDirectory] = None |
| 81 | + |
| 82 | + def __init__(self, db_url_tuple: Optional[Tuple[str, bool]] = None): |
| 83 | + """ |
| 84 | + Argument is an optional tuple of (URL, bool). |
| 85 | + The URL is assumed to be a file to download; the bool indicates whether |
| 86 | + it is ready to be used (True) or needs unpacking (False) |
| 87 | + """ |
| 88 | + if db_url_tuple is None: |
| 89 | + db_url_tuple = self.get_download_url_from_environment() |
| 90 | + self._download_data(db_url_tuple) |
| 91 | + |
| 92 | + def sort_replicas(self, replicas: List[str], location: Mapping[str, float]) -> List[str]: |
| 93 | + """ |
| 94 | + Main method of this class. |
| 95 | + replicas: list of strings which are the URLs for the replicas for a file |
| 96 | + location: dict of the form {'latitude': xxx, 'longitude': yyy} where xxx and yyy are floats |
| 97 | + giving the latitude and longitude in signed degrees |
| 98 | + """ |
| 99 | + if not self._database: |
| 100 | + return replicas |
| 101 | + if len(replicas) == 1: |
| 102 | + return replicas |
| 103 | + fqdns = [(urlparse(replica).hostname, replica) for replica in replicas] |
| 104 | + distances = [Replica_distance(replica=replica, |
| 105 | + distance=_get_distance(self._database, fqdn, |
| 106 | + location['latitude'], |
| 107 | + location['longitude'] |
| 108 | + ) |
| 109 | + ) |
| 110 | + for fqdn, replica in fqdns] |
| 111 | + distances.sort(key=lambda x: x.distance) |
| 112 | + return [_.replica for _ in distances] |
| 113 | + |
| 114 | + @classmethod |
| 115 | + def get_download_url_from_key_and_edition(cls, license_key: str, edition: str): |
| 116 | + """ |
| 117 | + Construct the (url, unpacked) tuple to feed to the constructor from a license key |
| 118 | + and an edition of the MaxMind database. |
| 119 | + """ |
| 120 | + return (('https://download.maxmind.com/app/geoip_download?' |
| 121 | + f'edition_id={edition}&license_key={license_key}&suffix=tar.gz'), |
| 122 | + False) |
| 123 | + |
| 124 | + @classmethod |
| 125 | + def get_download_url_from_environment(cls) -> Optional[Tuple[str, bool]]: |
| 126 | + """ |
| 127 | + Based on environment variables, this will give a tuple of the URL and a bool which is |
| 128 | + True if the file from the URL is ready to use as is, False if needs to be unpacked |
| 129 | + """ |
| 130 | + if url := os.environ.get('GEOIP_DB_URL', ''): |
| 131 | + return (url, True) |
| 132 | + key = os.environ.get('GEOIP_DB_LICENSE_KEY', '') |
| 133 | + edition = os.environ.get('GEOIP_DB_EDITION', '') |
| 134 | + if (key and edition): |
| 135 | + return cls.get_download_url_from_key_and_edition(key, edition) |
| 136 | + else: |
| 137 | + return None |
| 138 | + |
| 139 | + def _download_data(self, db_url_tuple: Optional[Tuple[str, bool]]) -> None: |
| 140 | + """ |
| 141 | + Retrieves and unpacks the MaxMind databases and initializes the GeoIP reader |
| 142 | + """ |
| 143 | + from urllib.request import urlretrieve |
| 144 | + import tarfile |
| 145 | + import glob |
| 146 | + if db_url_tuple is None: |
| 147 | + return |
| 148 | + url, unpacked = db_url_tuple |
| 149 | + try: |
| 150 | + fname, _ = urlretrieve(url) |
| 151 | + except Exception as e: |
| 152 | + logger.error(f'Failure retrieving GeoIP database {url}.\nError: {e}') |
| 153 | + return |
| 154 | + try: |
| 155 | + if unpacked: |
| 156 | + self._database = geoip2.database.Reader(fname) |
| 157 | + else: |
| 158 | + tarball = tarfile.open(fname) |
| 159 | + self._tmpdir = tempfile.TemporaryDirectory() |
| 160 | + tarball.extractall(self._tmpdir.name) |
| 161 | + self._database = geoip2.database.Reader(glob.glob(os.path.join(self._tmpdir.name, |
| 162 | + '*/*mmdb') |
| 163 | + )[0]) |
| 164 | + except Exception as e: |
| 165 | + logger.error(f'Failure initializing the GeoIP database reader.\nError: {e}') |
| 166 | + self._database = None |
| 167 | + return |
0 commit comments