provider.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import os
  2. import shutil
  3. import json
  4. import logging
  5. from abc import ABC, abstractmethod
  6. from typing import BinaryIO, Tuple
  7. import boto3
  8. from botocore.exceptions import ClientError
  9. from open_webui.config import (
  10. S3_ACCESS_KEY_ID,
  11. S3_BUCKET_NAME,
  12. S3_ENDPOINT_URL,
  13. S3_KEY_PREFIX,
  14. S3_REGION_NAME,
  15. S3_SECRET_ACCESS_KEY,
  16. GCS_BUCKET_NAME,
  17. GOOGLE_APPLICATION_CREDENTIALS_JSON,
  18. AZURE_STORAGE_ENDPOINT,
  19. AZURE_STORAGE_CONTAINER_NAME,
  20. AZURE_STORAGE_KEY,
  21. STORAGE_PROVIDER,
  22. UPLOAD_DIR,
  23. )
  24. from google.cloud import storage
  25. from google.cloud.exceptions import GoogleCloudError, NotFound
  26. from open_webui.constants import ERROR_MESSAGES
  27. from azure.identity import DefaultAzureCredential
  28. from azure.storage.blob import BlobServiceClient
  29. from azure.core.exceptions import ResourceNotFoundError
  30. from open_webui.env import SRC_LOG_LEVELS
  31. log = logging.getLogger(__name__)
  32. log.setLevel(SRC_LOG_LEVELS["MAIN"])
  33. class StorageProvider(ABC):
  34. @abstractmethod
  35. def get_file(self, file_path: str) -> str:
  36. pass
  37. @abstractmethod
  38. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  39. pass
  40. @abstractmethod
  41. def delete_all_files(self) -> None:
  42. pass
  43. @abstractmethod
  44. def delete_file(self, file_path: str) -> None:
  45. pass
  46. class LocalStorageProvider(StorageProvider):
  47. @staticmethod
  48. def upload_file(file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  49. contents = file.read()
  50. if not contents:
  51. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  52. file_path = f"{UPLOAD_DIR}/{filename}"
  53. with open(file_path, "wb") as f:
  54. f.write(contents)
  55. return contents, file_path
  56. @staticmethod
  57. def get_file(file_path: str) -> str:
  58. """Handles downloading of the file from local storage."""
  59. return file_path
  60. @staticmethod
  61. def delete_file(file_path: str) -> None:
  62. """Handles deletion of the file from local storage."""
  63. filename = file_path.split("/")[-1]
  64. file_path = f"{UPLOAD_DIR}/{filename}"
  65. if os.path.isfile(file_path):
  66. os.remove(file_path)
  67. else:
  68. log.warning(f"File {file_path} not found in local storage.")
  69. @staticmethod
  70. def delete_all_files() -> None:
  71. """Handles deletion of all files from local storage."""
  72. if os.path.exists(UPLOAD_DIR):
  73. for filename in os.listdir(UPLOAD_DIR):
  74. file_path = os.path.join(UPLOAD_DIR, filename)
  75. try:
  76. if os.path.isfile(file_path) or os.path.islink(file_path):
  77. os.unlink(file_path) # Remove the file or link
  78. elif os.path.isdir(file_path):
  79. shutil.rmtree(file_path) # Remove the directory
  80. except Exception as e:
  81. log.exception(f"Failed to delete {file_path}. Reason: {e}")
  82. else:
  83. log.warning(f"Directory {UPLOAD_DIR} not found in local storage.")
  84. class S3StorageProvider(StorageProvider):
  85. def __init__(self):
  86. self.s3_client = boto3.client(
  87. "s3",
  88. region_name=S3_REGION_NAME,
  89. endpoint_url=S3_ENDPOINT_URL,
  90. aws_access_key_id=S3_ACCESS_KEY_ID,
  91. aws_secret_access_key=S3_SECRET_ACCESS_KEY,
  92. )
  93. self.bucket_name = S3_BUCKET_NAME
  94. self.key_prefix = S3_KEY_PREFIX if S3_KEY_PREFIX else ""
  95. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  96. """Handles uploading of the file to S3 storage."""
  97. _, file_path = LocalStorageProvider.upload_file(file, filename)
  98. try:
  99. s3_key = os.path.join(self.key_prefix, filename)
  100. self.s3_client.upload_file(file_path, self.bucket_name, s3_key)
  101. return (
  102. open(file_path, "rb").read(),
  103. "s3://" + self.bucket_name + "/" + s3_key,
  104. )
  105. except ClientError as e:
  106. raise RuntimeError(f"Error uploading file to S3: {e}")
  107. def get_file(self, file_path: str) -> str:
  108. """Handles downloading of the file from S3 storage."""
  109. try:
  110. s3_key = self._extract_s3_key(file_path)
  111. local_file_path = self._get_local_file_path(s3_key)
  112. self.s3_client.download_file(self.bucket_name, s3_key, local_file_path)
  113. return local_file_path
  114. except ClientError as e:
  115. raise RuntimeError(f"Error downloading file from S3: {e}")
  116. def delete_file(self, file_path: str) -> None:
  117. """Handles deletion of the file from S3 storage."""
  118. try:
  119. s3_key = self._extract_s3_key(file_path)
  120. self.s3_client.delete_object(Bucket=self.bucket_name, Key=s3_key)
  121. except ClientError as e:
  122. raise RuntimeError(f"Error deleting file from S3: {e}")
  123. # Always delete from local storage
  124. LocalStorageProvider.delete_file(file_path)
  125. def delete_all_files(self) -> None:
  126. """Handles deletion of all files from S3 storage."""
  127. try:
  128. response = self.s3_client.list_objects_v2(Bucket=self.bucket_name)
  129. if "Contents" in response:
  130. for content in response["Contents"]:
  131. # Skip objects that were not uploaded from open-webui in the first place
  132. if not content["Key"].startswith(self.key_prefix):
  133. continue
  134. self.s3_client.delete_object(
  135. Bucket=self.bucket_name, Key=content["Key"]
  136. )
  137. except ClientError as e:
  138. raise RuntimeError(f"Error deleting all files from S3: {e}")
  139. # Always delete from local storage
  140. LocalStorageProvider.delete_all_files()
  141. # The s3 key is the name assigned to an object. It excludes the bucket name, but includes the internal path and the file name.
  142. def _extract_s3_key(self, full_file_path: str) -> str:
  143. return "/".join(full_file_path.split("//")[1].split("/")[1:])
  144. def _get_local_file_path(self, s3_key: str) -> str:
  145. return f"{UPLOAD_DIR}/{s3_key.split('/')[-1]}"
  146. class GCSStorageProvider(StorageProvider):
  147. def __init__(self):
  148. self.bucket_name = GCS_BUCKET_NAME
  149. if GOOGLE_APPLICATION_CREDENTIALS_JSON:
  150. self.gcs_client = storage.Client.from_service_account_info(
  151. info=json.loads(GOOGLE_APPLICATION_CREDENTIALS_JSON)
  152. )
  153. else:
  154. # if no credentials json is provided, credentials will be picked up from the environment
  155. # if running on local environment, credentials would be user credentials
  156. # if running on a Compute Engine instance, credentials would be from Google Metadata server
  157. self.gcs_client = storage.Client()
  158. self.bucket = self.gcs_client.bucket(GCS_BUCKET_NAME)
  159. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  160. """Handles uploading of the file to GCS storage."""
  161. contents, file_path = LocalStorageProvider.upload_file(file, filename)
  162. try:
  163. blob = self.bucket.blob(filename)
  164. blob.upload_from_filename(file_path)
  165. return contents, "gs://" + self.bucket_name + "/" + filename
  166. except GoogleCloudError as e:
  167. raise RuntimeError(f"Error uploading file to GCS: {e}")
  168. def get_file(self, file_path: str) -> str:
  169. """Handles downloading of the file from GCS storage."""
  170. try:
  171. filename = file_path.removeprefix("gs://").split("/")[1]
  172. local_file_path = f"{UPLOAD_DIR}/{filename}"
  173. blob = self.bucket.get_blob(filename)
  174. blob.download_to_filename(local_file_path)
  175. return local_file_path
  176. except NotFound as e:
  177. raise RuntimeError(f"Error downloading file from GCS: {e}")
  178. def delete_file(self, file_path: str) -> None:
  179. """Handles deletion of the file from GCS storage."""
  180. try:
  181. filename = file_path.removeprefix("gs://").split("/")[1]
  182. blob = self.bucket.get_blob(filename)
  183. blob.delete()
  184. except NotFound as e:
  185. raise RuntimeError(f"Error deleting file from GCS: {e}")
  186. # Always delete from local storage
  187. LocalStorageProvider.delete_file(file_path)
  188. def delete_all_files(self) -> None:
  189. """Handles deletion of all files from GCS storage."""
  190. try:
  191. blobs = self.bucket.list_blobs()
  192. for blob in blobs:
  193. blob.delete()
  194. except NotFound as e:
  195. raise RuntimeError(f"Error deleting all files from GCS: {e}")
  196. # Always delete from local storage
  197. LocalStorageProvider.delete_all_files()
  198. class AzureStorageProvider(StorageProvider):
  199. def __init__(self):
  200. self.endpoint = AZURE_STORAGE_ENDPOINT
  201. self.container_name = AZURE_STORAGE_CONTAINER_NAME
  202. storage_key = AZURE_STORAGE_KEY
  203. if storage_key:
  204. # Configure using the Azure Storage Account Endpoint and Key
  205. self.blob_service_client = BlobServiceClient(
  206. account_url=self.endpoint, credential=storage_key
  207. )
  208. else:
  209. # Configure using the Azure Storage Account Endpoint and DefaultAzureCredential
  210. # If the key is not configured, then the DefaultAzureCredential will be used to support Managed Identity authentication
  211. self.blob_service_client = BlobServiceClient(
  212. account_url=self.endpoint, credential=DefaultAzureCredential()
  213. )
  214. self.container_client = self.blob_service_client.get_container_client(
  215. self.container_name
  216. )
  217. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  218. """Handles uploading of the file to Azure Blob Storage."""
  219. contents, file_path = LocalStorageProvider.upload_file(file, filename)
  220. try:
  221. blob_client = self.container_client.get_blob_client(filename)
  222. blob_client.upload_blob(contents, overwrite=True)
  223. return contents, f"{self.endpoint}/{self.container_name}/{filename}"
  224. except Exception as e:
  225. raise RuntimeError(f"Error uploading file to Azure Blob Storage: {e}")
  226. def get_file(self, file_path: str) -> str:
  227. """Handles downloading of the file from Azure Blob Storage."""
  228. try:
  229. filename = file_path.split("/")[-1]
  230. local_file_path = f"{UPLOAD_DIR}/{filename}"
  231. blob_client = self.container_client.get_blob_client(filename)
  232. with open(local_file_path, "wb") as download_file:
  233. download_file.write(blob_client.download_blob().readall())
  234. return local_file_path
  235. except ResourceNotFoundError as e:
  236. raise RuntimeError(f"Error downloading file from Azure Blob Storage: {e}")
  237. def delete_file(self, file_path: str) -> None:
  238. """Handles deletion of the file from Azure Blob Storage."""
  239. try:
  240. filename = file_path.split("/")[-1]
  241. blob_client = self.container_client.get_blob_client(filename)
  242. blob_client.delete_blob()
  243. except ResourceNotFoundError as e:
  244. raise RuntimeError(f"Error deleting file from Azure Blob Storage: {e}")
  245. # Always delete from local storage
  246. LocalStorageProvider.delete_file(file_path)
  247. def delete_all_files(self) -> None:
  248. """Handles deletion of all files from Azure Blob Storage."""
  249. try:
  250. blobs = self.container_client.list_blobs()
  251. for blob in blobs:
  252. self.container_client.delete_blob(blob.name)
  253. except Exception as e:
  254. raise RuntimeError(f"Error deleting all files from Azure Blob Storage: {e}")
  255. # Always delete from local storage
  256. LocalStorageProvider.delete_all_files()
  257. def get_storage_provider(storage_provider: str):
  258. if storage_provider == "local":
  259. Storage = LocalStorageProvider()
  260. elif storage_provider == "s3":
  261. Storage = S3StorageProvider()
  262. elif storage_provider == "gcs":
  263. Storage = GCSStorageProvider()
  264. elif storage_provider == "azure":
  265. Storage = AzureStorageProvider()
  266. else:
  267. raise RuntimeError(f"Unsupported storage provider: {storage_provider}")
  268. return Storage
  269. Storage = get_storage_provider(STORAGE_PROVIDER)