provider.py 12 KB

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