|
| 1 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +# or more contributor license agreements. See the NOTICE file |
| 3 | +# distributed with this work for additional information |
| 4 | +# regarding copyright ownership. The ASF licenses this file |
| 5 | +# to you under the Apache License, Version 2.0 (the |
| 6 | +# "License"); you may not use this file except in compliance |
| 7 | +# with the License. You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, |
| 12 | +# software distributed under the License is distributed on an |
| 13 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +# KIND, either express or implied. See the License for the |
| 15 | +# specific language governing permissions and limitations |
| 16 | +# under the License. |
| 17 | +import importlib |
| 18 | +import logging |
| 19 | +from abc import ABC, abstractmethod |
| 20 | +from typing import Optional |
| 21 | + |
| 22 | +import mmh3 |
| 23 | + |
| 24 | +from pyiceberg.partitioning import PartitionKey |
| 25 | +from pyiceberg.table import TableProperties |
| 26 | +from pyiceberg.typedef import Properties |
| 27 | +from pyiceberg.utils.properties import property_as_bool |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +class LocationProvider(ABC): |
| 33 | + """A base class for location providers, that provide data file locations for write tasks.""" |
| 34 | + |
| 35 | + table_location: str |
| 36 | + table_properties: Properties |
| 37 | + |
| 38 | + def __init__(self, table_location: str, table_properties: Properties): |
| 39 | + self.table_location = table_location |
| 40 | + self.table_properties = table_properties |
| 41 | + |
| 42 | + @abstractmethod |
| 43 | + def new_data_location(self, data_file_name: str, partition_key: Optional[PartitionKey] = None) -> str: |
| 44 | + """Return a fully-qualified data file location for the given filename. |
| 45 | +
|
| 46 | + Args: |
| 47 | + data_file_name (str): The name of the data file. |
| 48 | + partition_key (Optional[PartitionKey]): The data file's partition key. If None, the data is not partitioned. |
| 49 | +
|
| 50 | + Returns: |
| 51 | + str: A fully-qualified location URI for the data file. |
| 52 | + """ |
| 53 | + |
| 54 | + |
| 55 | +class SimpleLocationProvider(LocationProvider): |
| 56 | + def __init__(self, table_location: str, table_properties: Properties): |
| 57 | + super().__init__(table_location, table_properties) |
| 58 | + |
| 59 | + def new_data_location(self, data_file_name: str, partition_key: Optional[PartitionKey] = None) -> str: |
| 60 | + prefix = f"{self.table_location}/data" |
| 61 | + return f"{prefix}/{partition_key.to_path()}/{data_file_name}" if partition_key else f"{prefix}/{data_file_name}" |
| 62 | + |
| 63 | + |
| 64 | +class ObjectStoreLocationProvider(LocationProvider): |
| 65 | + HASH_BINARY_STRING_BITS = 20 |
| 66 | + ENTROPY_DIR_LENGTH = 4 |
| 67 | + ENTROPY_DIR_DEPTH = 3 |
| 68 | + |
| 69 | + _include_partition_paths: bool |
| 70 | + |
| 71 | + def __init__(self, table_location: str, table_properties: Properties): |
| 72 | + super().__init__(table_location, table_properties) |
| 73 | + self._include_partition_paths = property_as_bool( |
| 74 | + self.table_properties, |
| 75 | + TableProperties.WRITE_OBJECT_STORE_PARTITIONED_PATHS, |
| 76 | + TableProperties.WRITE_OBJECT_STORE_PARTITIONED_PATHS_DEFAULT, |
| 77 | + ) |
| 78 | + |
| 79 | + def new_data_location(self, data_file_name: str, partition_key: Optional[PartitionKey] = None) -> str: |
| 80 | + if self._include_partition_paths and partition_key: |
| 81 | + return self.new_data_location(f"{partition_key.to_path()}/{data_file_name}") |
| 82 | + |
| 83 | + prefix = f"{self.table_location}/data" |
| 84 | + hashed_path = self._compute_hash(data_file_name) |
| 85 | + |
| 86 | + return ( |
| 87 | + f"{prefix}/{hashed_path}/{data_file_name}" |
| 88 | + if self._include_partition_paths |
| 89 | + else f"{prefix}/{hashed_path}-{data_file_name}" |
| 90 | + ) |
| 91 | + |
| 92 | + @staticmethod |
| 93 | + def _compute_hash(data_file_name: str) -> str: |
| 94 | + # Bitwise AND to combat sign-extension; bitwise OR to preserve leading zeroes that `bin` would otherwise strip. |
| 95 | + top_mask = 1 << ObjectStoreLocationProvider.HASH_BINARY_STRING_BITS |
| 96 | + hash_code = mmh3.hash(data_file_name) & (top_mask - 1) | top_mask |
| 97 | + return ObjectStoreLocationProvider._dirs_from_hash(bin(hash_code)[-ObjectStoreLocationProvider.HASH_BINARY_STRING_BITS :]) |
| 98 | + |
| 99 | + @staticmethod |
| 100 | + def _dirs_from_hash(file_hash: str) -> str: |
| 101 | + """Divides hash into directories for optimized orphan removal operation using ENTROPY_DIR_DEPTH and ENTROPY_DIR_LENGTH.""" |
| 102 | + total_entropy_length = ObjectStoreLocationProvider.ENTROPY_DIR_DEPTH * ObjectStoreLocationProvider.ENTROPY_DIR_LENGTH |
| 103 | + |
| 104 | + hash_with_dirs = [] |
| 105 | + for i in range(0, total_entropy_length, ObjectStoreLocationProvider.ENTROPY_DIR_LENGTH): |
| 106 | + hash_with_dirs.append(file_hash[i : i + ObjectStoreLocationProvider.ENTROPY_DIR_LENGTH]) |
| 107 | + |
| 108 | + if len(file_hash) > total_entropy_length: |
| 109 | + hash_with_dirs.append(file_hash[total_entropy_length:]) |
| 110 | + |
| 111 | + return "/".join(hash_with_dirs) |
| 112 | + |
| 113 | + |
| 114 | +def _import_location_provider( |
| 115 | + location_provider_impl: str, table_location: str, table_properties: Properties |
| 116 | +) -> Optional[LocationProvider]: |
| 117 | + try: |
| 118 | + path_parts = location_provider_impl.split(".") |
| 119 | + if len(path_parts) < 2: |
| 120 | + raise ValueError( |
| 121 | + f"{TableProperties.WRITE_PY_LOCATION_PROVIDER_IMPL} should be full path (module.CustomLocationProvider), got: {location_provider_impl}" |
| 122 | + ) |
| 123 | + module_name, class_name = ".".join(path_parts[:-1]), path_parts[-1] |
| 124 | + module = importlib.import_module(module_name) |
| 125 | + class_ = getattr(module, class_name) |
| 126 | + return class_(table_location, table_properties) |
| 127 | + except ModuleNotFoundError: |
| 128 | + logger.warning("Could not initialize LocationProvider: %s", location_provider_impl) |
| 129 | + return None |
| 130 | + |
| 131 | + |
| 132 | +def load_location_provider(table_location: str, table_properties: Properties) -> LocationProvider: |
| 133 | + table_location = table_location.rstrip("/") |
| 134 | + |
| 135 | + if location_provider_impl := table_properties.get(TableProperties.WRITE_PY_LOCATION_PROVIDER_IMPL): |
| 136 | + if location_provider := _import_location_provider(location_provider_impl, table_location, table_properties): |
| 137 | + logger.info("Loaded LocationProvider: %s", location_provider_impl) |
| 138 | + return location_provider |
| 139 | + else: |
| 140 | + raise ValueError(f"Could not initialize LocationProvider: {location_provider_impl}") |
| 141 | + |
| 142 | + if property_as_bool(table_properties, TableProperties.OBJECT_STORE_ENABLED, TableProperties.OBJECT_STORE_ENABLED_DEFAULT): |
| 143 | + return ObjectStoreLocationProvider(table_location, table_properties) |
| 144 | + else: |
| 145 | + return SimpleLocationProvider(table_location, table_properties) |
0 commit comments