|
| 1 | +# Copyright 2023 Neal Lathia |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +import json |
| 15 | +import os |
| 16 | +from typing import Optional |
| 17 | + |
| 18 | +from modelstore.metadata import metadata |
| 19 | +from modelstore.storage.blob_storage import BlobStorage |
| 20 | +from modelstore.storage.util.versions import sorted_by_created |
| 21 | +from modelstore.utils.log import logger |
| 22 | +from modelstore.utils.exceptions import FilePullFailedException |
| 23 | + |
| 24 | +try: |
| 25 | + import pydoop.hdfs as hdfs |
| 26 | + |
| 27 | + HDFS_EXISTS = True |
| 28 | +except ImportError: |
| 29 | + HDFS_EXISTS = False |
| 30 | + |
| 31 | + |
| 32 | +class HdfsStorage(BlobStorage): |
| 33 | + |
| 34 | + """ |
| 35 | + HDFS Storage |
| 36 | +
|
| 37 | + Assumes that you have `pydoop` installed |
| 38 | + https://crs4.github.io/pydoop/tutorial/hdfs_api.html#hdfs-api-tutorial |
| 39 | + """ |
| 40 | + |
| 41 | + NAME = "hdfs" |
| 42 | + BUILD_FROM_ENVIRONMENT = { |
| 43 | + "required": [], |
| 44 | + "optional": [ |
| 45 | + "MODEL_STORE_HDFS_ROOT_PREFIX", |
| 46 | + ], |
| 47 | + } |
| 48 | + |
| 49 | + def __init__(self, root_prefix: Optional[str] = None, create_directory: bool = False): |
| 50 | + super().__init__(["pydoop"], root_prefix, "MODEL_STORE_HDFS_ROOT_PREFIX") |
| 51 | + self._create_directory = create_directory |
| 52 | + |
| 53 | + def validate(self) -> bool: |
| 54 | + try: |
| 55 | + hdfs.ls(self.root_prefix) |
| 56 | + except FileNotFoundError: |
| 57 | + if not self._create_directory: |
| 58 | + raise |
| 59 | + logger.debug("creating root directory %s", self.root_prefix) |
| 60 | + hdfs.mkdir(self.root_prefix) |
| 61 | + return True |
| 62 | + |
| 63 | + def _push(self, file_path: str, prefix: str) -> str: |
| 64 | + logger.info("Uploading to: %s...", prefix) |
| 65 | + # This will raise an exception if the file already exists |
| 66 | + hdfs.put(file_path, prefix) |
| 67 | + return prefix |
| 68 | + |
| 69 | + def _pull(self, prefix: str, dir_path: str) -> str: |
| 70 | + try: |
| 71 | + logger.debug("Downloading from: %s...", prefix) |
| 72 | + file_name = os.path.split(prefix)[1] |
| 73 | + destination = os.path.join(dir_path, file_name) |
| 74 | + hdfs.get(prefix, destination) |
| 75 | + return destination |
| 76 | + except Exception as exc: |
| 77 | + logger.exception(exc) |
| 78 | + raise FilePullFailedException(exc) from exc |
| 79 | + |
| 80 | + def _remove(self, prefix: str) -> bool: |
| 81 | + """Removes a file from the destination path""" |
| 82 | + if hdfs.path.exists(prefix): |
| 83 | + logger.debug("Deleting: %s...", prefix) |
| 84 | + hdfs.rm(prefix) |
| 85 | + return True |
| 86 | + return False |
| 87 | + |
| 88 | + def _storage_location(self, prefix: str) -> metadata.Storage: |
| 89 | + """Returns a dict of the location the artifact was stored""" |
| 90 | + return metadata.Storage.from_path( |
| 91 | + storage_type="hdfs", |
| 92 | + root=self.root_prefix, |
| 93 | + path=prefix, |
| 94 | + ) |
| 95 | + |
| 96 | + def _get_storage_location(self, meta_data: metadata.Storage) -> str: |
| 97 | + """Extracts the storage location from a meta data dictionary""" |
| 98 | + return meta_data.path |
| 99 | + |
| 100 | + def _read_json_objects(self, prefix: str) -> list: |
| 101 | + logger.debug("Listing files in: %s", prefix) |
| 102 | + results = [] |
| 103 | + for obj in hdfs.ls(prefix): |
| 104 | + logger.debug("reading: %s", obj) |
| 105 | + if not hdfs.path.basename(obj).endswith(".json"): |
| 106 | + logger.debug("Skipping non-json file: %s", obj) |
| 107 | + continue |
| 108 | + parent = obj[obj.index(prefix):] |
| 109 | + if os.path.split(parent)[0] != prefix: |
| 110 | + # We don't want to read files in a sub-prefix |
| 111 | + logger.debug("Skipping file in sub-prefix: %s", obj) |
| 112 | + continue |
| 113 | + json_obj = self._read_json_object(obj) |
| 114 | + if json_obj is not None: |
| 115 | + results.append(json_obj) |
| 116 | + return sorted_by_created(results) |
| 117 | + |
| 118 | + def _read_json_object(self, prefix: str) -> dict: |
| 119 | + logger.debug("Reading: %s", prefix) |
| 120 | + lines = hdfs.load(prefix) |
| 121 | + if len(lines) == 0: |
| 122 | + return None |
| 123 | + try: |
| 124 | + return json.loads(lines) |
| 125 | + except json.JSONDecodeError as exc: |
| 126 | + logger.exception(exc) |
| 127 | + return None |
0 commit comments