provider.py 7.9 KB

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