provider.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import os
  2. import shutil
  3. import json
  4. from abc import ABC, abstractmethod
  5. from typing import BinaryIO, Tuple
  6. from io import BytesIO
  7. import boto3
  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_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. def upload_file(self, file: BinaryIO, filename: str) -> Tuple[bytes, str]:
  85. """Handles uploading of the file to S3 storage."""
  86. _, file_path = LocalStorageProvider.upload_file(file, filename)
  87. try:
  88. self.s3_client.upload_file(file_path, self.bucket_name, filename)
  89. return (
  90. open(file_path, "rb").read(),
  91. "s3://" + self.bucket_name + "/" + filename,
  92. )
  93. except ClientError as e:
  94. raise RuntimeError(f"Error uploading file to S3: {e}")
  95. def get_file(self, file_path: str) -> str:
  96. """Handles downloading of the file from S3 storage."""
  97. try:
  98. bucket_name, key = file_path.split("//")[1].split("/")
  99. local_file_path = f"{UPLOAD_DIR}/{key}"
  100. self.s3_client.download_file(bucket_name, key, local_file_path)
  101. return local_file_path
  102. except ClientError as e:
  103. raise RuntimeError(f"Error downloading file from S3: {e}")
  104. def delete_file(self, file_path: str) -> None:
  105. """Handles deletion of the file from S3 storage."""
  106. filename = file_path.split("/")[-1]
  107. try:
  108. self.s3_client.delete_object(Bucket=self.bucket_name, Key=filename)
  109. except ClientError as e:
  110. raise RuntimeError(f"Error deleting file from S3: {e}")
  111. # Always delete from local storage
  112. LocalStorageProvider.delete_file(file_path)
  113. def delete_all_files(self) -> None:
  114. """Handles deletion of all files from S3 storage."""
  115. try:
  116. response = self.s3_client.list_objects_v2(Bucket=self.bucket_name)
  117. if "Contents" in response:
  118. for content in response["Contents"]:
  119. self.s3_client.delete_object(
  120. Bucket=self.bucket_name, Key=content["Key"]
  121. )
  122. except ClientError as e:
  123. raise RuntimeError(f"Error deleting all files from S3: {e}")
  124. # Always delete from local storage
  125. LocalStorageProvider.delete_all_files()
  126. class GCSStorageProvider(StorageProvider):
  127. def __init__(self):
  128. self.gcs_client = storage.Client.from_service_account_info(info=json.loads(GOOGLE_APPLICATION_CREDENTIALS_JSON))
  129. self.bucket_name = self.gcs_client.bucket(GCS_BUCKET_NAME)
  130. def upload_file(self, file: BinaryIO, filename: str):
  131. """Handles uploading of the file to GCS storage."""
  132. contents, _ = LocalStorageProvider.upload_file(file, filename)
  133. try:
  134. # Get the blob (object in the bucket)
  135. blob = self.bucket_name.blob(filename)
  136. # Upload the file to the bucket
  137. blob.upload_from_file(BytesIO(contents))
  138. return contents, _
  139. except GoogleCloudError as e:
  140. raise RuntimeError(f"Error uploading file to GCS: {e}")
  141. def get_file(self, file_path:str) -> str:
  142. """Handles downloading of the file from GCS storage."""
  143. try:
  144. local_file_path=file_path.removeprefix(UPLOAD_DIR + "/")
  145. # Get the blob (object in the bucket)
  146. blob = self.bucket_name.blob(local_file_path)
  147. # Download the file to a local destination
  148. blob.download_to_filename(file_path)
  149. return file_path
  150. except NotFound as e:
  151. raise RuntimeError(f"Error downloading file from GCS: {e}")
  152. def delete_file(self, file_path:str) -> None:
  153. """Handles deletion of the file from GCS storage."""
  154. try:
  155. local_file_path = file_path.removeprefix(UPLOAD_DIR + "/")
  156. # Get the blob (object in the bucket)
  157. blob = self.bucket_name.blob(local_file_path)
  158. # Delete the file
  159. blob.delete()
  160. except NotFound as e:
  161. raise RuntimeError(f"Error deleting file from GCS: {e}")
  162. # Always delete from local storage
  163. LocalStorageProvider.delete_file(file_path)
  164. def delete_all_files(self) -> None:
  165. """Handles deletion of all files from GCS storage."""
  166. try:
  167. # List all objects in the bucket
  168. blobs = self.bucket_name.list_blobs()
  169. # Delete all files
  170. for blob in blobs:
  171. blob.delete()
  172. except NotFound as e:
  173. raise RuntimeError(f"Error deleting all files from GCS: {e}")
  174. # Always delete from local storage
  175. LocalStorageProvider.delete_all_files()
  176. def get_storage_provider(storage_provider: str):
  177. if storage_provider == "local":
  178. Storage = LocalStorageProvider()
  179. elif storage_provider == "s3":
  180. Storage = S3StorageProvider()
  181. elif storage_provider == "gcs":
  182. Storage = GCSStorageProvider()
  183. else:
  184. raise RuntimeError(f"Unsupported storage provider: {storage_provider}")
  185. return Storage
  186. Storage = get_storage_provider(STORAGE_PROVIDER)