provider.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. config = Config(
  90. s3={
  91. "use_accelerate_endpoint": S3_USE_ACCELERATE_ENDPOINT,
  92. "addressing_style": S3_ADDRESSING_STYLE,
  93. },
  94. )
  95. # If access key and secret are provided, use them for authentication
  96. if S3_ACCESS_KEY_ID and S3_SECRET_ACCESS_KEY:
  97. self.s3_client = boto3.client(
  98. "s3",
  99. region_name=S3_REGION_NAME,
  100. endpoint_url=S3_ENDPOINT_URL,
  101. aws_access_key_id=S3_ACCESS_KEY_ID,
  102. aws_secret_access_key=S3_SECRET_ACCESS_KEY,
  103. config=config,
  104. )
  105. else:
  106. # If no explicit credentials are provided, fall back to default AWS credentials
  107. # This supports workload identity (IAM roles for EC2, EKS, etc.)
  108. self.s3_client = boto3.client(
  109. "s3",
  110. region_name=S3_REGION_NAME,
  111. endpoint_url=S3_ENDPOINT_URL,
  112. config=config,
  113. )
  114. self.bucket_name = S3_BUCKET_NAME
  115. self.key_prefix = S3_KEY_PREFIX if S3_KEY_PREFIX else ""
  116. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  117. """Handles uploading of the file to S3 storage."""
  118. _, file_path = LocalStorageProvider.upload_file(file, filename)
  119. try:
  120. s3_key = os.path.join(self.key_prefix, filename)
  121. self.s3_client.upload_file(file_path, self.bucket_name, s3_key)
  122. return (
  123. open(file_path, "rb").read(),
  124. "s3://" + self.bucket_name + "/" + s3_key,
  125. )
  126. except ClientError as e:
  127. raise RuntimeError(f"Error uploading file to S3: {e}")
  128. def get_file(self, file_path: str) -> str:
  129. """Handles downloading of the file from S3 storage."""
  130. try:
  131. s3_key = self._extract_s3_key(file_path)
  132. local_file_path = self._get_local_file_path(s3_key)
  133. self.s3_client.download_file(self.bucket_name, s3_key, local_file_path)
  134. return local_file_path
  135. except ClientError as e:
  136. raise RuntimeError(f"Error downloading file from S3: {e}")
  137. def delete_file(self, file_path: str) -> None:
  138. """Handles deletion of the file from S3 storage."""
  139. try:
  140. s3_key = self._extract_s3_key(file_path)
  141. self.s3_client.delete_object(Bucket=self.bucket_name, Key=s3_key)
  142. except ClientError as e:
  143. raise RuntimeError(f"Error deleting file from S3: {e}")
  144. # Always delete from local storage
  145. LocalStorageProvider.delete_file(file_path)
  146. def delete_all_files(self) -> None:
  147. """Handles deletion of all files from S3 storage."""
  148. try:
  149. response = self.s3_client.list_objects_v2(Bucket=self.bucket_name)
  150. if "Contents" in response:
  151. for content in response["Contents"]:
  152. # Skip objects that were not uploaded from open-webui in the first place
  153. if not content["Key"].startswith(self.key_prefix):
  154. continue
  155. self.s3_client.delete_object(
  156. Bucket=self.bucket_name, Key=content["Key"]
  157. )
  158. except ClientError as e:
  159. raise RuntimeError(f"Error deleting all files from S3: {e}")
  160. # Always delete from local storage
  161. LocalStorageProvider.delete_all_files()
  162. # The s3 key is the name assigned to an object. It excludes the bucket name, but includes the internal path and the file name.
  163. def _extract_s3_key(self, full_file_path: str) -> str:
  164. return "/".join(full_file_path.split("//")[1].split("/")[1:])
  165. def _get_local_file_path(self, s3_key: str) -> str:
  166. return f"{UPLOAD_DIR}/{s3_key.split('/')[-1]}"
  167. class GCSStorageProvider(StorageProvider):
  168. def __init__(self):
  169. self.bucket_name = GCS_BUCKET_NAME
  170. if GOOGLE_APPLICATION_CREDENTIALS_JSON:
  171. self.gcs_client = storage.Client.from_service_account_info(
  172. info=json.loads(GOOGLE_APPLICATION_CREDENTIALS_JSON)
  173. )
  174. else:
  175. # if no credentials json is provided, credentials will be picked up from the environment
  176. # if running on local environment, credentials would be user credentials
  177. # if running on a Compute Engine instance, credentials would be from Google Metadata server
  178. self.gcs_client = storage.Client()
  179. self.bucket = self.gcs_client.bucket(GCS_BUCKET_NAME)
  180. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  181. """Handles uploading of the file to GCS storage."""
  182. contents, file_path = LocalStorageProvider.upload_file(file, filename)
  183. try:
  184. blob = self.bucket.blob(filename)
  185. blob.upload_from_filename(file_path)
  186. return contents, "gs://" + self.bucket_name + "/" + filename
  187. except GoogleCloudError as e:
  188. raise RuntimeError(f"Error uploading file to GCS: {e}")
  189. def get_file(self, file_path: str) -> str:
  190. """Handles downloading of the file from GCS storage."""
  191. try:
  192. filename = file_path.removeprefix("gs://").split("/")[1]
  193. local_file_path = f"{UPLOAD_DIR}/{filename}"
  194. blob = self.bucket.get_blob(filename)
  195. blob.download_to_filename(local_file_path)
  196. return local_file_path
  197. except NotFound as e:
  198. raise RuntimeError(f"Error downloading file from GCS: {e}")
  199. def delete_file(self, file_path: str) -> None:
  200. """Handles deletion of the file from GCS storage."""
  201. try:
  202. filename = file_path.removeprefix("gs://").split("/")[1]
  203. blob = self.bucket.get_blob(filename)
  204. blob.delete()
  205. except NotFound as e:
  206. raise RuntimeError(f"Error deleting file from GCS: {e}")
  207. # Always delete from local storage
  208. LocalStorageProvider.delete_file(file_path)
  209. def delete_all_files(self) -> None:
  210. """Handles deletion of all files from GCS storage."""
  211. try:
  212. blobs = self.bucket.list_blobs()
  213. for blob in blobs:
  214. blob.delete()
  215. except NotFound as e:
  216. raise RuntimeError(f"Error deleting all files from GCS: {e}")
  217. # Always delete from local storage
  218. LocalStorageProvider.delete_all_files()
  219. class AzureStorageProvider(StorageProvider):
  220. def __init__(self):
  221. self.endpoint = AZURE_STORAGE_ENDPOINT
  222. self.container_name = AZURE_STORAGE_CONTAINER_NAME
  223. storage_key = AZURE_STORAGE_KEY
  224. if storage_key:
  225. # Configure using the Azure Storage Account Endpoint and Key
  226. self.blob_service_client = BlobServiceClient(
  227. account_url=self.endpoint, credential=storage_key
  228. )
  229. else:
  230. # Configure using the Azure Storage Account Endpoint and DefaultAzureCredential
  231. # If the key is not configured, then the DefaultAzureCredential will be used to support Managed Identity authentication
  232. self.blob_service_client = BlobServiceClient(
  233. account_url=self.endpoint, credential=DefaultAzureCredential()
  234. )
  235. self.container_client = self.blob_service_client.get_container_client(
  236. self.container_name
  237. )
  238. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  239. """Handles uploading of the file to Azure Blob Storage."""
  240. contents, file_path = LocalStorageProvider.upload_file(file, filename)
  241. try:
  242. blob_client = self.container_client.get_blob_client(filename)
  243. blob_client.upload_blob(contents, overwrite=True)
  244. return contents, f"{self.endpoint}/{self.container_name}/{filename}"
  245. except Exception as e:
  246. raise RuntimeError(f"Error uploading file to Azure Blob Storage: {e}")
  247. def get_file(self, file_path: str) -> str:
  248. """Handles downloading of the file from Azure Blob Storage."""
  249. try:
  250. filename = file_path.split("/")[-1]
  251. local_file_path = f"{UPLOAD_DIR}/{filename}"
  252. blob_client = self.container_client.get_blob_client(filename)
  253. with open(local_file_path, "wb") as download_file:
  254. download_file.write(blob_client.download_blob().readall())
  255. return local_file_path
  256. except ResourceNotFoundError as e:
  257. raise RuntimeError(f"Error downloading file from Azure Blob Storage: {e}")
  258. def delete_file(self, file_path: str) -> None:
  259. """Handles deletion of the file from Azure Blob Storage."""
  260. try:
  261. filename = file_path.split("/")[-1]
  262. blob_client = self.container_client.get_blob_client(filename)
  263. blob_client.delete_blob()
  264. except ResourceNotFoundError as e:
  265. raise RuntimeError(f"Error deleting file from Azure Blob Storage: {e}")
  266. # Always delete from local storage
  267. LocalStorageProvider.delete_file(file_path)
  268. def delete_all_files(self) -> None:
  269. """Handles deletion of all files from Azure Blob Storage."""
  270. try:
  271. blobs = self.container_client.list_blobs()
  272. for blob in blobs:
  273. self.container_client.delete_blob(blob.name)
  274. except Exception as e:
  275. raise RuntimeError(f"Error deleting all files from Azure Blob Storage: {e}")
  276. # Always delete from local storage
  277. LocalStorageProvider.delete_all_files()
  278. def get_storage_provider(storage_provider: str):
  279. if storage_provider == "local":
  280. Storage = LocalStorageProvider()
  281. elif storage_provider == "s3":
  282. Storage = S3StorageProvider()
  283. elif storage_provider == "gcs":
  284. Storage = GCSStorageProvider()
  285. elif storage_provider == "azure":
  286. Storage = AzureStorageProvider()
  287. else:
  288. raise RuntimeError(f"Unsupported storage provider: {storage_provider}")
  289. return Storage
  290. Storage = get_storage_provider(STORAGE_PROVIDER)