provider.py 13 KB

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