|
| 1 | +######################################################################### |
| 2 | +# |
| 3 | +# Copyright (C) 2026 OSGeo |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 17 | +# |
| 18 | +######################################################################### |
| 19 | +import logging |
| 20 | +import requests |
| 21 | +from osgeo import gdal |
| 22 | + |
| 23 | +from geonode.layers.models import Dataset |
| 24 | +from geonode.upload.handlers.common.remote import BaseRemoteResourceHandler |
| 25 | +from geonode.upload.api.exceptions import ImportException |
| 26 | +from geonode.upload.orchestrator import orchestrator |
| 27 | + |
| 28 | +logger = logging.getLogger("importer") |
| 29 | + |
| 30 | + |
| 31 | +class RemoteCOGResourceHandler(BaseRemoteResourceHandler): |
| 32 | + |
| 33 | + @property |
| 34 | + def supported_file_extension_config(self): |
| 35 | + return {} |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def can_handle(_data) -> bool: |
| 39 | + """ |
| 40 | + This endpoint will return True or False if with the info provided |
| 41 | + the handler is able to handle the file or not |
| 42 | + """ |
| 43 | + if "url" in _data and "cog" in _data.get("type", "").lower(): |
| 44 | + return True |
| 45 | + return False |
| 46 | + |
| 47 | + @staticmethod |
| 48 | + def is_valid_url(url, **kwargs): |
| 49 | + """ |
| 50 | + Check if the URL is reachable and supports HTTP Range requests |
| 51 | + """ |
| 52 | + logger.debug(f"Checking COG URL validity (HEAD): {url}") |
| 53 | + try: |
| 54 | + # Reachability check using HEAD |
| 55 | + head_res = requests.head(url, timeout=10, allow_redirects=True) |
| 56 | + logger.debug(f"HTTP HEAD status: {head_res.status_code}") |
| 57 | + head_res.raise_for_status() |
| 58 | + |
| 59 | + accept_ranges = head_res.headers.get("Accept-Ranges", "").lower() |
| 60 | + |
| 61 | + # Check for range request support |
| 62 | + if accept_ranges == "bytes": |
| 63 | + logger.debug("Server explicitly supports Accept-Ranges: bytes") |
| 64 | + return True |
| 65 | + |
| 66 | + # Some servers might not return Accept-Ranges in HEAD, so we try a small range request |
| 67 | + logger.debug("Accept-Ranges header missing, trying a small Range GET...") |
| 68 | + range_res = requests.get(url, headers={"Range": "bytes=0-1"}, timeout=10, stream=True) |
| 69 | + logger.debug(f"Range GET status: {range_res.status_code}") |
| 70 | + try: |
| 71 | + if range_res.status_code != 206: |
| 72 | + raise ImportException( |
| 73 | + "The remote server does not support HTTP Range requests, which are required for COG." |
| 74 | + ) |
| 75 | + finally: |
| 76 | + range_res.close() |
| 77 | + except Exception as e: |
| 78 | + logger.debug(f"is_valid_url ERROR: {str(e)}") |
| 79 | + logger.exception(e) |
| 80 | + if isinstance(e, ImportException): |
| 81 | + raise e |
| 82 | + raise ImportException("Error checking COG URL") |
| 83 | + |
| 84 | + return True |
| 85 | + |
| 86 | + def create_geonode_resource( |
| 87 | + self, |
| 88 | + layer_name: str, |
| 89 | + alternate: str, |
| 90 | + execution_id: str, |
| 91 | + resource_type: Dataset = Dataset, |
| 92 | + asset=None, |
| 93 | + ): |
| 94 | + """ |
| 95 | + Base function to create the resource into geonode. |
| 96 | + """ |
| 97 | + logger.debug(f"Entering create_geonode_resource for {layer_name}") |
| 98 | + _exec = orchestrator.get_execution_object(execution_id) |
| 99 | + params = _exec.input_params.copy() |
| 100 | + url = params.get("url") |
| 101 | + |
| 102 | + # Extract metadata via GDAL VSICURL |
| 103 | + gdal.UseExceptions() |
| 104 | + logger.debug(f"Attempting to open COG with GDAL: /vsicurl/{url}") |
| 105 | + try: |
| 106 | + # Set GDAL config options for faster failure |
| 107 | + gdal.SetThreadLocalConfigOption("GDAL_HTTP_TIMEOUT", "15") |
| 108 | + gdal.SetThreadLocalConfigOption("GDAL_HTTP_MAX_RETRY", "1") |
| 109 | + |
| 110 | + vsiurl = f"/vsicurl/{url}" |
| 111 | + ds = gdal.OpenEx(vsiurl) |
| 112 | + if ds is None: |
| 113 | + logger.debug(f"GDAL failed to open dataset: {vsiurl}") |
| 114 | + raise ImportException(f"Could not open remote COG: {url}") |
| 115 | + |
| 116 | + if not ds.GetSpatialRef(): |
| 117 | + raise ImportException(f"Could not extract spatial reference from COG: {url}") |
| 118 | + |
| 119 | + srid = self.identify_authority(ds) |
| 120 | + |
| 121 | + # Get BBox |
| 122 | + gt = ds.GetGeoTransform() |
| 123 | + width = ds.RasterXSize |
| 124 | + height = ds.RasterYSize |
| 125 | + |
| 126 | + # Check for rotation |
| 127 | + is_rotated = gt[2] != 0 or gt[4] != 0 |
| 128 | + |
| 129 | + if is_rotated: |
| 130 | + logger.info("COG has rotation/skew - calculating envelope bbox") |
| 131 | + # Calculate all four corners |
| 132 | + corners = [ |
| 133 | + (gt[0], gt[3]), |
| 134 | + (gt[0] + width * gt[1], gt[3] + width * gt[4]), |
| 135 | + (gt[0] + width * gt[1] + height * gt[2], gt[3] + width * gt[4] + height * gt[5]), |
| 136 | + (gt[0] + height * gt[2], gt[3] + height * gt[5]), |
| 137 | + ] |
| 138 | + xs = [x for x, y in corners] |
| 139 | + ys = [y for x, y in corners] |
| 140 | + bbox = [min(xs), min(ys), max(xs), max(ys)] |
| 141 | + else: |
| 142 | + # Simple calculation for north-up images |
| 143 | + minx = gt[0] |
| 144 | + maxy = gt[3] |
| 145 | + maxx = gt[0] + width * gt[1] |
| 146 | + miny = gt[3] + height * gt[5] |
| 147 | + bbox = [minx, miny, maxx, maxy] |
| 148 | + |
| 149 | + ds = None # close dataset |
| 150 | + logger.debug("GDAL operations finished.") |
| 151 | + except Exception as e: |
| 152 | + logger.debug(f"GDAL ERROR: {str(e)}") |
| 153 | + logger.exception(e) |
| 154 | + if isinstance(e, ImportException): |
| 155 | + raise e |
| 156 | + raise ImportException(f"Failed to extract metadata from COG: {url}") |
| 157 | + resource = super().create_geonode_resource(layer_name, alternate, execution_id, resource_type, asset) |
| 158 | + resource.set_bbox_polygon(bbox, srid) |
| 159 | + return resource |
| 160 | + |
| 161 | + def generate_resource_payload(self, layer_name, alternate, asset, _exec, workspace, **kwargs): |
| 162 | + payload = super().generate_resource_payload(layer_name, alternate, asset, _exec, workspace, **kwargs) |
| 163 | + payload.update( |
| 164 | + { |
| 165 | + "name": alternate, |
| 166 | + } |
| 167 | + ) |
| 168 | + return payload |
0 commit comments