provider.py 12 KB

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