provider.py 13 KB

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