provider.py 14 KB

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