provider.py 12 KB

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