provider.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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. STORAGE_PROVIDER,
  18. UPLOAD_DIR,
  19. )
  20. from google.cloud import storage
  21. from google.cloud.exceptions import GoogleCloudError, NotFound
  22. from open_webui.constants import ERROR_MESSAGES
  23. class StorageProvider(ABC):
  24. @abstractmethod
  25. def get_file(self, file_path: str) -> str:
  26. pass
  27. @abstractmethod
  28. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  29. pass
  30. @abstractmethod
  31. def delete_all_files(self) -> None:
  32. pass
  33. @abstractmethod
  34. def delete_file(self, file_path: str) -> None:
  35. pass
  36. class LocalStorageProvider(StorageProvider):
  37. @staticmethod
  38. def upload_file(file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  39. contents = file.read()
  40. if not contents:
  41. raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
  42. file_path = f"{UPLOAD_DIR}/{filename}"
  43. with open(file_path, "wb") as f:
  44. f.write(contents)
  45. return contents, file_path
  46. @staticmethod
  47. def get_file(file_path: str) -> str:
  48. """Handles downloading of the file from local storage."""
  49. return file_path
  50. @staticmethod
  51. def delete_file(file_path: str) -> None:
  52. """Handles deletion of the file from local storage."""
  53. filename = file_path.split("/")[-1]
  54. file_path = f"{UPLOAD_DIR}/{filename}"
  55. if os.path.isfile(file_path):
  56. os.remove(file_path)
  57. else:
  58. print(f"File {file_path} not found in local storage.")
  59. @staticmethod
  60. def delete_all_files() -> None:
  61. """Handles deletion of all files from local storage."""
  62. if os.path.exists(UPLOAD_DIR):
  63. for filename in os.listdir(UPLOAD_DIR):
  64. file_path = os.path.join(UPLOAD_DIR, filename)
  65. try:
  66. if os.path.isfile(file_path) or os.path.islink(file_path):
  67. os.unlink(file_path) # Remove the file or link
  68. elif os.path.isdir(file_path):
  69. shutil.rmtree(file_path) # Remove the directory
  70. except Exception as e:
  71. print(f"Failed to delete {file_path}. Reason: {e}")
  72. else:
  73. print(f"Directory {UPLOAD_DIR} not found in local storage.")
  74. class S3StorageProvider(StorageProvider):
  75. def __init__(self):
  76. self.s3_client = boto3.client(
  77. "s3",
  78. region_name=S3_REGION_NAME,
  79. endpoint_url=S3_ENDPOINT_URL,
  80. aws_access_key_id=S3_ACCESS_KEY_ID,
  81. aws_secret_access_key=S3_SECRET_ACCESS_KEY,
  82. )
  83. self.bucket_name = S3_BUCKET_NAME
  84. self.key_prefix = S3_KEY_PREFIX if S3_KEY_PREFIX else ""
  85. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  86. """Handles uploading of the file to S3 storage."""
  87. _, file_path = LocalStorageProvider.upload_file(file, filename)
  88. try:
  89. s3_key = os.path.join(self.key_prefix, filename)
  90. self.s3_client.upload_file(file_path, self.bucket_name, s3_key)
  91. return (
  92. open(file_path, "rb").read(),
  93. "s3://" + self.bucket_name + "/" + s3_key,
  94. )
  95. except ClientError as e:
  96. raise RuntimeError(f"Error uploading file to S3: {e}")
  97. def get_file(self, file_path: str) -> str:
  98. """Handles downloading of the file from S3 storage."""
  99. try:
  100. s3_key = self._extract_s3_key(file_path)
  101. local_file_path = self._get_local_file_path(s3_key)
  102. self.s3_client.download_file(self.bucket_name, s3_key, local_file_path)
  103. return local_file_path
  104. except ClientError as e:
  105. raise RuntimeError(f"Error downloading file from S3: {e}")
  106. def delete_file(self, file_path: str) -> None:
  107. """Handles deletion of the file from S3 storage."""
  108. try:
  109. s3_key = self._extract_s3_key(file_path)
  110. self.s3_client.delete_object(Bucket=self.bucket_name, Key=s3_key)
  111. except ClientError as e:
  112. raise RuntimeError(f"Error deleting file from S3: {e}")
  113. # Always delete from local storage
  114. LocalStorageProvider.delete_file(file_path)
  115. def delete_all_files(self) -> None:
  116. """Handles deletion of all files from S3 storage."""
  117. try:
  118. response = self.s3_client.list_objects_v2(Bucket=self.bucket_name)
  119. if "Contents" in response:
  120. for content in response["Contents"]:
  121. # Skip objects that were not uploaded from open-webui in the first place
  122. if not content["Key"].startswith(self.key_prefix):
  123. continue
  124. self.s3_client.delete_object(
  125. Bucket=self.bucket_name, Key=content["Key"]
  126. )
  127. except ClientError as e:
  128. raise RuntimeError(f"Error deleting all files from S3: {e}")
  129. # Always delete from local storage
  130. LocalStorageProvider.delete_all_files()
  131. # The s3 key is the name assigned to an object. It excludes the bucket name, but includes the internal path and the file name.
  132. def _extract_s3_key(self, full_file_path: str) -> str:
  133. return "/".join(full_file_path.split("//")[1].split("/")[1:])
  134. def _get_local_file_path(self, s3_key: str) -> str:
  135. return f"{UPLOAD_DIR}/{s3_key.split('/')[-1]}"
  136. class GCSStorageProvider(StorageProvider):
  137. def __init__(self):
  138. self.bucket_name = GCS_BUCKET_NAME
  139. if GOOGLE_APPLICATION_CREDENTIALS_JSON:
  140. self.gcs_client = storage.Client.from_service_account_info(
  141. info=json.loads(GOOGLE_APPLICATION_CREDENTIALS_JSON)
  142. )
  143. else:
  144. # if no credentials json is provided, credentials will be picked up from the environment
  145. # if running on local environment, credentials would be user credentials
  146. # if running on a Compute Engine instance, credentials would be from Google Metadata server
  147. self.gcs_client = storage.Client()
  148. self.bucket = self.gcs_client.bucket(GCS_BUCKET_NAME)
  149. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  150. """Handles uploading of the file to GCS storage."""
  151. contents, file_path = LocalStorageProvider.upload_file(file, filename)
  152. try:
  153. blob = self.bucket.blob(filename)
  154. blob.upload_from_filename(file_path)
  155. return contents, "gs://" + self.bucket_name + "/" + filename
  156. except GoogleCloudError as e:
  157. raise RuntimeError(f"Error uploading file to GCS: {e}")
  158. def get_file(self, file_path: str) -> str:
  159. """Handles downloading of the file from GCS storage."""
  160. try:
  161. filename = file_path.removeprefix("gs://").split("/")[1]
  162. local_file_path = f"{UPLOAD_DIR}/{filename}"
  163. blob = self.bucket.get_blob(filename)
  164. blob.download_to_filename(local_file_path)
  165. return local_file_path
  166. except NotFound as e:
  167. raise RuntimeError(f"Error downloading file from GCS: {e}")
  168. def delete_file(self, file_path: str) -> None:
  169. """Handles deletion of the file from GCS storage."""
  170. try:
  171. filename = file_path.removeprefix("gs://").split("/")[1]
  172. blob = self.bucket.get_blob(filename)
  173. blob.delete()
  174. except NotFound as e:
  175. raise RuntimeError(f"Error deleting file from GCS: {e}")
  176. # Always delete from local storage
  177. LocalStorageProvider.delete_file(file_path)
  178. def delete_all_files(self) -> None:
  179. """Handles deletion of all files from GCS storage."""
  180. try:
  181. blobs = self.bucket.list_blobs()
  182. for blob in blobs:
  183. blob.delete()
  184. except NotFound as e:
  185. raise RuntimeError(f"Error deleting all files from GCS: {e}")
  186. # Always delete from local storage
  187. LocalStorageProvider.delete_all_files()
  188. def get_storage_provider(storage_provider: str):
  189. if storage_provider == "local":
  190. Storage = LocalStorageProvider()
  191. elif storage_provider == "s3":
  192. Storage = S3StorageProvider()
  193. elif storage_provider == "gcs":
  194. Storage = GCSStorageProvider()
  195. else:
  196. raise RuntimeError(f"Unsupported storage provider: {storage_provider}")
  197. return Storage
  198. Storage = get_storage_provider(STORAGE_PROVIDER)