provider.py 14 KB

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